syntax.js 240 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Alexander Akait @alexander-akait
  4. */
  5. "use strict";
  6. // cspell:ignore yuku binop prec Prec
  7. const { Parser: BaseParser, tokTypes } = require("acorn");
  8. // acorn exports its token-context table but leaves it out of its public types
  9. const tokContexts =
  10. /** @type {Record<string, unknown>} */
  11. (
  12. /** @type {{ tokContexts: Record<string, unknown> }} */
  13. (/** @type {unknown} */ (require("acorn"))).tokContexts
  14. );
  15. /** @typedef {{ token: string, isExpr: boolean, preserveSpace?: boolean, override?: unknown }} TokContextShim acorn TokContext fields read by the owned tokenizer */
  16. // acorn's token contexts used by the inlined finishToken context updates
  17. const CTX_B_STAT = /** @type {TokContextShim} */ (tokContexts.b_stat);
  18. const CTX_B_EXPR = /** @type {TokContextShim} */ (tokContexts.b_expr);
  19. const CTX_P_STAT = /** @type {TokContextShim} */ (tokContexts.p_stat);
  20. const CTX_P_EXPR = /** @type {TokContextShim} */ (tokContexts.p_expr);
  21. const CTX_F_STAT = /** @type {TokContextShim} */ (tokContexts.f_stat);
  22. const CTX_F_EXPR = /** @type {TokContextShim} */ (tokContexts.f_expr);
  23. // acorn exports its keyword→TokenType map but leaves it out of its public
  24. // types; used by the word-classification lookups below.
  25. const keywordTypes =
  26. /** @type {Record<string, TokenType>} */
  27. (
  28. /** @type {{ keywordTypes: Record<string, TokenType> }} */
  29. (/** @type {unknown} */ (require("acorn"))).keywordTypes
  30. );
  31. // acorn exports these Unicode/character helpers at runtime but leaves them out
  32. // of its public types; the ported cold-path readers below reuse them so their
  33. // classification stays byte-identical to acorn's tokenizer.
  34. const {
  35. isIdentifierChar,
  36. isIdentifierStart,
  37. isNewLine,
  38. lineBreak,
  39. nonASCIIwhitespace
  40. } =
  41. /** @type {{ isIdentifierStart: (code: number, astral?: boolean) => boolean, isIdentifierChar: (code: number, astral?: boolean) => boolean, isNewLine: (code: number) => boolean, lineBreak: RegExp, nonASCIIwhitespace: RegExp }} */
  42. (/** @type {unknown} */ (require("acorn")));
  43. /**
  44. * @param {number} code code point
  45. * @returns {string} the string for a single code point
  46. */
  47. const codePointToString = (code) => String.fromCodePoint(code);
  48. /**
  49. * acorn's `stringToNumber`: legacy octal parses in base 8, everything else via
  50. * `parseFloat` after dropping `_` separators.
  51. * @param {string} str numeric literal text (may contain `_` separators)
  52. * @param {boolean} isLegacyOctal whether it is a legacy octal literal
  53. * @returns {number} numeric value
  54. */
  55. const stringToNumber = (str, isLegacyOctal) =>
  56. isLegacyOctal
  57. ? Number.parseInt(str, 8)
  58. : Number.parseFloat(str.replace(/_/g, ""));
  59. /**
  60. * acorn's `stringToBigInt`, minus the pre-BigInt fallback (every supported
  61. * Node has `BigInt`).
  62. * @param {string} str numeric literal text (may contain `_` separators)
  63. * @returns {bigint} bigint value
  64. */
  65. const stringToBigInt = (str) => BigInt(str.replace(/_/g, ""));
  66. /**
  67. * @import {
  68. * Options,
  69. * Position,
  70. * Node,
  71. * Identifier,
  72. * ImportAttribute,
  73. * ImportDefaultSpecifier,
  74. * ImportExpression,
  75. * Expression,
  76. * TokenType
  77. * } from "acorn"
  78. */
  79. /** @typedef {import("acorn").ImportSpecifier | import("acorn").ImportDefaultSpecifier | import("acorn").ImportNamespaceSpecifier} AnyImportSpecifier */
  80. /** @typedef {TokenType & { beforeExpr: boolean, isAssign?: boolean, prefix?: boolean, postfix?: boolean, binop: number | null, updateContext: ((prevType: TokenType) => void) | null }} TokenTypeInternal acorn's internal TokenType fields, absent from its public types */
  81. /** @typedef {[number, number]} Range */
  82. /** @typedef {"defer" | "source"} ImportPhase */
  83. /** @typedef {import("estree").Comment & { start: number, end: number }} CollectedComment comment as JavascriptParser exposes it */
  84. // Symbol-keyed so they stay out of for-in, Object.keys and JSON.stringify
  85. // over AST nodes.
  86. // Per-TokContext "the owned token loop must step aside" flag, cached on the
  87. // context itself so the hot guard reads one slot instead of two.
  88. const kSlowContext = Symbol("slow context");
  89. const kSource = Symbol("source");
  90. const kRange = Symbol("range");
  91. const kText = Symbol("text");
  92. const kTextStart = Symbol("text start");
  93. // Marks import attributes parsed from the legacy `assert {...}` syntax.
  94. const LEGACY_ASSERT_ATTRIBUTES = Symbol("assert");
  95. // acorn's binding types and scope flags, stable across acorn 8
  96. const BIND_NONE = 0;
  97. const BIND_VAR = 1;
  98. const BIND_LEXICAL = 2;
  99. const BIND_OUTSIDE = 5;
  100. const SCOPE_TOP = 1;
  101. const SCOPE_FUNCTION = 2;
  102. const SCOPE_ASYNC = 4;
  103. const SCOPE_GENERATOR = 8;
  104. const SCOPE_ARROW = 16;
  105. const SCOPE_SIMPLE_CATCH = 32;
  106. // SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK
  107. const SCOPE_SWITCH = 1024;
  108. const SCOPE_VAR = 0b100000011;
  109. // acorn's parseFunction statement bit flags
  110. const FUNC_STATEMENT = 1;
  111. const FUNC_HANGING_STATEMENT = 2;
  112. const FUNC_NULLABLE_ID = 4;
  113. // ASCII identifier-continuation chars ($ 0-9 A-Z _ a-z); css/html-style
  114. // Uint8Array table so the tokenizer fast path is one load per char
  115. const IDENT_CHAR = new Uint8Array(128);
  116. IDENT_CHAR[36] = 1;
  117. IDENT_CHAR[95] = 1;
  118. for (let i = 48; i <= 57; i++) IDENT_CHAR[i] = 1;
  119. for (let i = 65; i <= 90; i++) IDENT_CHAR[i] = 1;
  120. for (let i = 97; i <= 122; i++) IDENT_CHAR[i] = 1;
  121. // ASCII identifier-start chars (IDENT_CHAR minus 0-9), for token dispatch in
  122. // the owned `nextToken` loop.
  123. const IDENT_START = new Uint8Array(128);
  124. IDENT_START[36] = 1;
  125. IDENT_START[95] = 1;
  126. for (let i = 65; i <= 90; i++) IDENT_START[i] = 1;
  127. for (let i = 97; i <= 122; i++) IDENT_START[i] = 1;
  128. // Single-char punctuators that acorn's `getTokenFromCode` reads as just
  129. // `++pos; finishToken(type)` (no value, no operator state machine). Dispatching
  130. // them from `nextToken`'s char table skips the extra `getTokenFromCode` call and
  131. // its switch for the commonest tokens in JS ( ) { } [ ] ; , : — `0` is "not a
  132. // simple punctuator" since token types are truthy objects.
  133. const SIMPLE_PUNCT = Array.from({ length: 128 });
  134. SIMPLE_PUNCT[40] = tokTypes.parenL;
  135. SIMPLE_PUNCT[41] = tokTypes.parenR;
  136. SIMPLE_PUNCT[59] = tokTypes.semi;
  137. SIMPLE_PUNCT[44] = tokTypes.comma;
  138. SIMPLE_PUNCT[91] = tokTypes.bracketL;
  139. SIMPLE_PUNCT[93] = tokTypes.bracketR;
  140. SIMPLE_PUNCT[123] = tokTypes.braceL;
  141. SIMPLE_PUNCT[125] = tokTypes.braceR;
  142. SIMPLE_PUNCT[58] = tokTypes.colon;
  143. // Characters that can only start a token which cannot continue an expression,
  144. // so an atom directly followed by one is the whole expression (see
  145. // `parseMaybeAssign`'s fast path). `}` included: it only ever closes a block,
  146. // an object or a template substitution.
  147. const EXPRESSION_END_CHAR = new Uint8Array(128);
  148. EXPRESSION_END_CHAR[41] = 1; // )
  149. EXPRESSION_END_CHAR[44] = 1; // ,
  150. EXPRESSION_END_CHAR[58] = 1; // :
  151. EXPRESSION_END_CHAR[59] = 1; // ;
  152. EXPRESSION_END_CHAR[93] = 1; // ]
  153. EXPRESSION_END_CHAR[125] = 1; // }
  154. // Char classification for the owned `nextToken` (yuku's ws_class): one table
  155. // load steers both the whitespace skip loop and the token dispatch. Token
  156. // classes sort below CLS_SPACE so the skip loop exits on a single compare.
  157. const CLS_OTHER = 0;
  158. const CLS_IDENT = 1;
  159. const CLS_PUNCT = 2;
  160. const CLS_DOT = 3;
  161. const CLS_EQ = 4;
  162. const CLS_UNICODE = 5;
  163. const CLS_SPACE = 6;
  164. const CLS_NEWLINE = 7;
  165. const CLS_SLASH = 8;
  166. // Full `charCodeAt` range so the scan loop needs no `code > 127` branch per
  167. // character: every non-ASCII code unit classifies as CLS_UNICODE (which sorts
  168. // below CLS_SPACE, so the loop exits on the same single compare) and the
  169. // dispatch delegates it to acorn's unicode-aware paths.
  170. const CHAR_CLASS = new Uint8Array(0x10000).fill(CLS_UNICODE, 128);
  171. for (let i = 0; i < 128; i++) {
  172. if (IDENT_START[i] === 1 || i === 92) CHAR_CLASS[i] = CLS_IDENT;
  173. else if (SIMPLE_PUNCT[i] !== undefined) CHAR_CLASS[i] = CLS_PUNCT;
  174. }
  175. CHAR_CLASS[46] = CLS_DOT;
  176. CHAR_CLASS[61] = CLS_EQ;
  177. CHAR_CLASS[32] = CLS_SPACE;
  178. CHAR_CLASS[9] = CLS_SPACE;
  179. CHAR_CLASS[11] = CLS_SPACE;
  180. CHAR_CLASS[12] = CLS_SPACE;
  181. CHAR_CLASS[10] = CLS_NEWLINE;
  182. CHAR_CLASS[13] = CLS_NEWLINE;
  183. CHAR_CLASS[47] = CLS_SLASH;
  184. /**
  185. * Drop-in replacement for acorn's `Node` that materializes `loc` and `range`
  186. * on first access instead of allocating them during parsing. Most nodes never
  187. * get either read, which saves three objects and an array per node.
  188. */
  189. class LazyLocNode {
  190. /**
  191. * @param {number} pos start offset
  192. */
  193. constructor(pos) {
  194. this.type = "";
  195. this.start = pos;
  196. this.end = 0;
  197. }
  198. /**
  199. * Memoized in a symbol slot — a plain store is far cheaper than making the
  200. * property own via defineProperty, and the slot stays invisible to for-in,
  201. * Object.keys and JSON.stringify. No `loc` is served at all — locations
  202. * are derived from offsets via `JavascriptParser#getLocation`.
  203. * @returns {Range} source range
  204. */
  205. get range() {
  206. const cached = this[kRange];
  207. if (cached !== undefined) return cached;
  208. /** @type {Range} */
  209. const range = [this.start, this.end];
  210. if (this.end > 0) this[kRange] = range;
  211. return range;
  212. }
  213. /**
  214. * @param {Range} value source range
  215. */
  216. set range(value) {
  217. this[kRange] = value;
  218. }
  219. }
  220. /**
  221. * Single-shape `Identifier`, the most common node: all fields are assigned in
  222. * one constructor, so every instance is born on its final hidden class instead
  223. * of transitioning through acorn's start-empty-then-mutate construction.
  224. */
  225. class IdentifierNode {
  226. /**
  227. * @param {number} start start offset
  228. * @param {number} end end offset
  229. * @param {string} name identifier name
  230. */
  231. constructor(start, end, name) {
  232. this.type = "Identifier";
  233. this.start = start;
  234. this.end = end;
  235. this.name = name;
  236. }
  237. }
  238. /**
  239. * Single-shape `Literal`; `bigint` and `regex` stay post-construction
  240. * additions since both are rare.
  241. */
  242. class LiteralNode {
  243. /**
  244. * @param {number} start start offset
  245. * @param {number} end end offset
  246. * @param {unknown} value literal value
  247. * @param {string} raw literal source text
  248. */
  249. constructor(start, end, value, raw) {
  250. this.type = "Literal";
  251. this.start = start;
  252. this.end = end;
  253. this.value = value;
  254. this.raw = raw;
  255. }
  256. }
  257. /**
  258. * Single-shape `MemberExpression`. `optional` is a real field on every
  259. * instance since webpack always parses with `ecmaVersion >= 11`.
  260. */
  261. class MemberExpressionNode {
  262. /**
  263. * @param {number} start start offset
  264. * @param {number} end end offset
  265. * @param {Expression} object object expression
  266. * @param {Node} property property node
  267. * @param {boolean} computed whether the access is computed (`a[b]`)
  268. * @param {boolean} optional whether the access is optional (`a?.b`)
  269. */
  270. constructor(start, end, object, property, computed, optional) {
  271. this.type = "MemberExpression";
  272. this.start = start;
  273. this.end = end;
  274. this.object = object;
  275. this.property = property;
  276. this.computed = computed;
  277. this.optional = optional;
  278. }
  279. }
  280. /**
  281. * Single-shape `CallExpression`; `optional` as in `MemberExpressionNode`.
  282. */
  283. class CallExpressionNode {
  284. /**
  285. * @param {number} start start offset
  286. * @param {number} end end offset
  287. * @param {Expression} callee callee expression
  288. * @param {Node[]} args call arguments
  289. * @param {boolean} optional whether the call is optional (`a?.()`)
  290. */
  291. constructor(start, end, callee, args, optional) {
  292. this.type = "CallExpression";
  293. this.start = start;
  294. this.end = end;
  295. this.callee = callee;
  296. this.arguments = args;
  297. this.optional = optional;
  298. }
  299. }
  300. /**
  301. * Single-shape `ThisExpression`.
  302. */
  303. class ThisNode {
  304. /**
  305. * @param {number} start start offset
  306. * @param {number} end end offset
  307. */
  308. constructor(start, end) {
  309. this.type = "ThisExpression";
  310. this.start = start;
  311. this.end = end;
  312. }
  313. }
  314. /**
  315. * Single-shape `BinaryExpression`/`LogicalExpression` — identical field sets,
  316. * so both node types share one hidden class.
  317. */
  318. class BinaryNode {
  319. /**
  320. * @param {number} start start offset
  321. * @param {number} end end offset
  322. * @param {"BinaryExpression" | "LogicalExpression"} type node type
  323. * @param {Expression} left left operand
  324. * @param {string} operator operator text
  325. * @param {Expression} right right operand
  326. */
  327. constructor(start, end, type, left, operator, right) {
  328. this.type = type;
  329. this.start = start;
  330. this.end = end;
  331. this.left = left;
  332. this.operator = operator;
  333. this.right = right;
  334. }
  335. }
  336. /**
  337. * Single-shape `AssignmentExpression`.
  338. */
  339. class AssignmentNode {
  340. /**
  341. * @param {number} start start offset
  342. * @param {number} end end offset
  343. * @param {string} operator assignment operator text
  344. * @param {Node} left assignment target
  345. * @param {Expression} right assigned value
  346. */
  347. constructor(start, end, operator, left, right) {
  348. this.type = "AssignmentExpression";
  349. this.start = start;
  350. this.end = end;
  351. this.operator = operator;
  352. this.left = left;
  353. this.right = right;
  354. }
  355. }
  356. /**
  357. * Single-shape `UnaryExpression`/`UpdateExpression` — identical field sets,
  358. * so both node types share one hidden class.
  359. */
  360. class UnaryNode {
  361. /**
  362. * @param {number} start start offset
  363. * @param {number} end end offset
  364. * @param {"UnaryExpression" | "UpdateExpression"} type node type
  365. * @param {string} operator operator text
  366. * @param {boolean} prefix whether the operator is prefixed
  367. * @param {Expression} argument operand
  368. */
  369. constructor(start, end, type, operator, prefix, argument) {
  370. this.type = type;
  371. this.start = start;
  372. this.end = end;
  373. this.operator = operator;
  374. this.prefix = prefix;
  375. this.argument = argument;
  376. }
  377. }
  378. /**
  379. * Single-shape `VariableDeclaration` (statement position; `for` heads keep the
  380. * generic node since their caller finishes them).
  381. */
  382. class VariableDeclarationNode {
  383. /**
  384. * @param {number} start start offset
  385. * @param {number} end end offset
  386. * @param {Node[]} declarations declarators
  387. * @param {string} kind declaration kind (`var`/`let`/`const`/`using`)
  388. */
  389. constructor(start, end, declarations, kind) {
  390. this.type = "VariableDeclaration";
  391. this.start = start;
  392. this.end = end;
  393. this.declarations = declarations;
  394. this.kind = kind;
  395. }
  396. }
  397. /**
  398. * Single-shape `VariableDeclarator`.
  399. */
  400. class VariableDeclaratorNode {
  401. /**
  402. * @param {number} start start offset
  403. * @param {number} end end offset
  404. * @param {Node} id binding target
  405. * @param {Expression | null} init initializer
  406. */
  407. constructor(start, end, id, init) {
  408. this.type = "VariableDeclarator";
  409. this.start = start;
  410. this.end = end;
  411. this.id = id;
  412. this.init = init;
  413. }
  414. }
  415. /**
  416. * Single-shape `ExpressionStatement`.
  417. */
  418. class ExpressionStatementNode {
  419. /**
  420. * @param {number} start start offset
  421. * @param {number} end end offset
  422. * @param {Expression} expression the statement's expression
  423. */
  424. constructor(start, end, expression) {
  425. this.type = "ExpressionStatement";
  426. this.start = start;
  427. this.end = end;
  428. this.expression = expression;
  429. }
  430. }
  431. /**
  432. * Single-shape `BlockStatement`.
  433. */
  434. class BlockStatementNode {
  435. /**
  436. * @param {number} start start offset
  437. * @param {number} end end offset
  438. * @param {Node[]} body statements
  439. */
  440. constructor(start, end, body) {
  441. this.type = "BlockStatement";
  442. this.start = start;
  443. this.end = end;
  444. this.body = body;
  445. }
  446. }
  447. /**
  448. * Single-shape `IfStatement`.
  449. */
  450. class IfStatementNode {
  451. /**
  452. * @param {number} start start offset
  453. * @param {number} end end offset
  454. * @param {Expression} test condition
  455. * @param {Node} consequent then-branch
  456. * @param {Node | null} alternate else-branch
  457. */
  458. constructor(start, end, test, consequent, alternate) {
  459. this.type = "IfStatement";
  460. this.start = start;
  461. this.end = end;
  462. this.test = test;
  463. this.consequent = consequent;
  464. this.alternate = alternate;
  465. }
  466. }
  467. /**
  468. * Single-shape `ReturnStatement`.
  469. */
  470. class ReturnStatementNode {
  471. /**
  472. * @param {number} start start offset
  473. * @param {number} end end offset
  474. * @param {Expression | null} argument returned expression
  475. */
  476. constructor(start, end, argument) {
  477. this.type = "ReturnStatement";
  478. this.start = start;
  479. this.end = end;
  480. this.argument = argument;
  481. }
  482. }
  483. /**
  484. * Single-shape `ConditionalExpression`.
  485. */
  486. class ConditionalExpressionNode {
  487. /**
  488. * @param {number} start start offset
  489. * @param {number} end end offset
  490. * @param {Expression} test condition
  491. * @param {Expression} consequent then-value
  492. * @param {Expression} alternate else-value
  493. */
  494. constructor(start, end, test, consequent, alternate) {
  495. this.type = "ConditionalExpression";
  496. this.start = start;
  497. this.end = end;
  498. this.test = test;
  499. this.consequent = consequent;
  500. this.alternate = alternate;
  501. }
  502. }
  503. /**
  504. * Single-shape `NewExpression`.
  505. */
  506. class NewExpressionNode {
  507. /**
  508. * @param {number} start start offset
  509. * @param {number} end end offset
  510. * @param {Expression} callee constructed expression
  511. * @param {Expression[]} args constructor arguments
  512. */
  513. constructor(start, end, callee, args) {
  514. this.type = "NewExpression";
  515. this.start = start;
  516. this.end = end;
  517. this.callee = callee;
  518. this.arguments = args;
  519. }
  520. }
  521. /**
  522. * Single-shape `ArrayExpression`.
  523. */
  524. class ArrayExpressionNode {
  525. /**
  526. * @param {number} start start offset
  527. * @param {number} end end offset
  528. * @param {(Expression | null)[]} elements array elements (`null` for holes)
  529. */
  530. constructor(start, end, elements) {
  531. this.type = "ArrayExpression";
  532. this.start = start;
  533. this.end = end;
  534. this.elements = elements;
  535. }
  536. }
  537. /**
  538. * Single-shape `TemplateLiteral`.
  539. */
  540. class TemplateLiteralNode {
  541. /**
  542. * @param {number} start start offset
  543. * @param {number} end end offset
  544. * @param {Expression[]} expressions substitution expressions
  545. * @param {Node[]} quasis template chunks
  546. */
  547. constructor(start, end, expressions, quasis) {
  548. this.type = "TemplateLiteral";
  549. this.start = start;
  550. this.end = end;
  551. this.expressions = expressions;
  552. this.quasis = quasis;
  553. }
  554. }
  555. /**
  556. * Single-shape `TemplateElement`.
  557. */
  558. class TemplateElementNode {
  559. /**
  560. * @param {number} start start offset
  561. * @param {number} end end offset
  562. * @param {{ raw: string, cooked: string | null }} value chunk text
  563. * @param {boolean} tail whether this is the closing chunk
  564. */
  565. constructor(start, end, value, tail) {
  566. this.type = "TemplateElement";
  567. this.start = start;
  568. this.end = end;
  569. this.value = value;
  570. this.tail = tail;
  571. }
  572. }
  573. /**
  574. * Single-shape `ObjectExpression`/`ObjectPattern` — identical field sets, so
  575. * both node types share one hidden class.
  576. */
  577. class ObjectNode {
  578. /**
  579. * @param {number} start start offset
  580. * @param {number} end end offset
  581. * @param {"ObjectExpression" | "ObjectPattern"} type node type
  582. * @param {Node[]} properties properties
  583. */
  584. constructor(start, end, type, properties) {
  585. this.type = type;
  586. this.start = start;
  587. this.end = end;
  588. this.properties = properties;
  589. }
  590. }
  591. /**
  592. * Pre-shaped `Property`: acorn fills property nodes through shared
  593. * subroutines (`parsePropertyName`/`parsePropertyValue`), so instead of
  594. * rebuilding that flow the fields are all declared up-front and acorn's
  595. * writes land in existing slots — one hidden class, no transitions (yuku's
  596. * decoder emits `Property` with this fixed shape). Every non-throwing acorn
  597. * branch assigns `computed`, `key`, `value` and `kind`; `finishNode` sets
  598. * `type` and `end`.
  599. */
  600. class PropertyNode {
  601. /**
  602. * @param {number} start start offset
  603. */
  604. constructor(start) {
  605. this.type = "";
  606. this.start = start;
  607. this.end = 0;
  608. this.method = false;
  609. this.shorthand = false;
  610. this.computed = false;
  611. /** @type {Node | null} */
  612. this.key = null;
  613. /** @type {Node | null} */
  614. this.value = null;
  615. this.kind = "";
  616. }
  617. }
  618. /**
  619. * Single-shape `ForStatement`.
  620. */
  621. class ForStatementNode {
  622. /**
  623. * @param {number} start start offset
  624. * @param {number} end end offset
  625. * @param {Node | null} init init statement or expression
  626. * @param {Expression | null} test loop condition
  627. * @param {Expression | null} update update expression
  628. * @param {Node} body loop body
  629. */
  630. constructor(start, end, init, test, update, body) {
  631. this.type = "ForStatement";
  632. this.start = start;
  633. this.end = end;
  634. this.init = init;
  635. this.test = test;
  636. this.update = update;
  637. this.body = body;
  638. }
  639. }
  640. /**
  641. * Single-shape `ForInStatement` (no `await` slot, matching acorn).
  642. */
  643. class ForInStatementNode {
  644. /**
  645. * @param {number} start start offset
  646. * @param {number} end end offset
  647. * @param {Node} left loop target
  648. * @param {Expression} right iterated expression
  649. * @param {Node} body loop body
  650. */
  651. constructor(start, end, left, right, body) {
  652. this.type = "ForInStatement";
  653. this.start = start;
  654. this.end = end;
  655. this.left = left;
  656. this.right = right;
  657. this.body = body;
  658. }
  659. }
  660. /**
  661. * Single-shape `ForOfStatement`; `await` leads, matching acorn's write order.
  662. */
  663. class ForOfStatementNode {
  664. /**
  665. * @param {number} start start offset
  666. * @param {number} end end offset
  667. * @param {boolean} isAwait whether this is `for await`
  668. * @param {Node} left loop target
  669. * @param {Expression} right iterated expression
  670. * @param {Node} body loop body
  671. */
  672. constructor(start, end, isAwait, left, right, body) {
  673. this.type = "ForOfStatement";
  674. this.start = start;
  675. this.end = end;
  676. this.await = isAwait;
  677. this.left = left;
  678. this.right = right;
  679. this.body = body;
  680. }
  681. }
  682. /**
  683. * Single-shape `WhileStatement`.
  684. */
  685. class WhileStatementNode {
  686. /**
  687. * @param {number} start start offset
  688. * @param {number} end end offset
  689. * @param {Expression} test loop condition
  690. * @param {Node} body loop body
  691. */
  692. constructor(start, end, test, body) {
  693. this.type = "WhileStatement";
  694. this.start = start;
  695. this.end = end;
  696. this.test = test;
  697. this.body = body;
  698. }
  699. }
  700. /**
  701. * Single-shape `SwitchStatement`.
  702. */
  703. class SwitchStatementNode {
  704. /**
  705. * @param {number} start start offset
  706. * @param {number} end end offset
  707. * @param {Expression} discriminant switched expression
  708. * @param {Node[]} cases case clauses
  709. */
  710. constructor(start, end, discriminant, cases) {
  711. this.type = "SwitchStatement";
  712. this.start = start;
  713. this.end = end;
  714. this.discriminant = discriminant;
  715. this.cases = cases;
  716. }
  717. }
  718. /**
  719. * Pre-shaped `SwitchCase`: filled in acorn's write order (`consequent` before
  720. * `test`), finished via `finishNode` like acorn's.
  721. */
  722. class SwitchCaseNode {
  723. /**
  724. * @param {number} start start offset
  725. */
  726. constructor(start) {
  727. this.type = "";
  728. this.start = start;
  729. this.end = 0;
  730. /** @type {Node[] | null} */
  731. this.consequent = null;
  732. /** @type {Expression | null} */
  733. this.test = null;
  734. }
  735. }
  736. /**
  737. * Single-shape `ThrowStatement`.
  738. */
  739. class ThrowStatementNode {
  740. /**
  741. * @param {number} start start offset
  742. * @param {number} end end offset
  743. * @param {Expression} argument thrown expression
  744. */
  745. constructor(start, end, argument) {
  746. this.type = "ThrowStatement";
  747. this.start = start;
  748. this.end = end;
  749. this.argument = argument;
  750. }
  751. }
  752. /**
  753. * Single-shape `BreakStatement`/`ContinueStatement` — identical field sets, so
  754. * both node types share one hidden class.
  755. */
  756. class BreakContinueNode {
  757. /**
  758. * @param {number} start start offset
  759. * @param {number} end end offset
  760. * @param {"BreakStatement" | "ContinueStatement"} type node type
  761. * @param {Identifier | null} label target label
  762. */
  763. constructor(start, end, type, label) {
  764. this.type = type;
  765. this.start = start;
  766. this.end = end;
  767. this.label = label;
  768. }
  769. }
  770. /**
  771. * Single-shape `TryStatement`.
  772. */
  773. class TryStatementNode {
  774. /**
  775. * @param {number} start start offset
  776. * @param {number} end end offset
  777. * @param {Node} block try block
  778. * @param {Node | null} handler catch clause
  779. * @param {Node | null} finalizer finally block
  780. */
  781. constructor(start, end, block, handler, finalizer) {
  782. this.type = "TryStatement";
  783. this.start = start;
  784. this.end = end;
  785. this.block = block;
  786. this.handler = handler;
  787. this.finalizer = finalizer;
  788. }
  789. }
  790. /**
  791. * Single-shape `CatchClause`.
  792. */
  793. class CatchClauseNode {
  794. /**
  795. * @param {number} start start offset
  796. * @param {number} end end offset
  797. * @param {Node | null} param catch parameter
  798. * @param {Node} body catch block
  799. */
  800. constructor(start, end, param, body) {
  801. this.type = "CatchClause";
  802. this.start = start;
  803. this.end = end;
  804. this.param = param;
  805. this.body = body;
  806. }
  807. }
  808. /**
  809. * Pre-shaped `FunctionDeclaration`/`FunctionExpression`/
  810. * `ArrowFunctionExpression`: acorn fills function nodes through shared
  811. * subroutines (`parseFunctionParams`/`parseFunctionBody`), so like
  812. * `PropertyNode` the fields are all declared up-front — in acorn's exact write
  813. * order (`initFunction` assigns `expression` before `generator`) so JSON key
  814. * order is unchanged — and acorn's writes land in existing slots: one hidden
  815. * class for all three function node types, no transitions.
  816. */
  817. class FunctionNode {
  818. /**
  819. * @param {number} start start offset
  820. */
  821. constructor(start) {
  822. this.type = "";
  823. this.start = start;
  824. this.end = 0;
  825. /** @type {Identifier | null} */
  826. this.id = null;
  827. this.expression = false;
  828. this.generator = false;
  829. this.async = false;
  830. /** @type {Node[] | null} */
  831. this.params = null;
  832. /** @type {Node | null} */
  833. this.body = null;
  834. }
  835. }
  836. /**
  837. * Single-shape `SpreadElement`/`RestElement` — identical field sets, so both
  838. * node types share one hidden class.
  839. */
  840. class RestSpreadNode {
  841. /**
  842. * @param {number} start start offset
  843. * @param {number} end end offset
  844. * @param {"SpreadElement" | "RestElement"} type node type
  845. * @param {Node} argument spread/rest argument
  846. */
  847. constructor(start, end, type, argument) {
  848. this.type = type;
  849. this.start = start;
  850. this.end = end;
  851. this.argument = argument;
  852. }
  853. }
  854. // Mirrors of acorn's module-level `loopLabel`/`switchLabel`.
  855. const LOOP_LABEL = { kind: "loop" };
  856. const SWITCH_LABEL = { kind: "switch" };
  857. // Shared zero-length arguments array for `new X` without parens, mirroring
  858. // acorn's module-level `empty`.
  859. /** @type {Expression[]} */
  860. const EMPTY_NEW_ARGS = [];
  861. /**
  862. * Mirror of acorn's module-level `isLocalVariableAccess`.
  863. * @param {Node} node checked node
  864. * @returns {boolean} whether the node reads a local variable
  865. */
  866. const isLocalVariableAccess = (node) =>
  867. node.type === "Identifier" ||
  868. (node.type === "ParenthesizedExpression" &&
  869. isLocalVariableAccess(
  870. /** @type {Node} */ (
  871. /** @type {Node & { expression?: Node }} */ (node).expression
  872. )
  873. ));
  874. /**
  875. * Mirror of acorn's module-level `isPrivateFieldAccess`.
  876. * @param {Node} node checked node
  877. * @returns {boolean} whether the node accesses a private field
  878. */
  879. const isPrivateFieldAccess = (node) =>
  880. (node.type === "MemberExpression" &&
  881. /** @type {Node} */ (
  882. /** @type {Node & { property?: Node }} */ (node).property
  883. ).type === "PrivateIdentifier") ||
  884. (node.type === "ChainExpression" &&
  885. isPrivateFieldAccess(
  886. /** @type {Node} */ (
  887. /** @type {Node & { expression?: Node }} */ (node).expression
  888. )
  889. )) ||
  890. (node.type === "ParenthesizedExpression" &&
  891. isPrivateFieldAccess(
  892. /** @type {Node} */ (
  893. /** @type {Node & { expression?: Node }} */ (node).expression
  894. )
  895. ));
  896. // the dedicated node classes serve `range` exactly like LazyLocNode
  897. for (const NodeClass of [
  898. IdentifierNode,
  899. LiteralNode,
  900. MemberExpressionNode,
  901. CallExpressionNode,
  902. ThisNode,
  903. BinaryNode,
  904. AssignmentNode,
  905. UnaryNode,
  906. VariableDeclarationNode,
  907. VariableDeclaratorNode,
  908. ExpressionStatementNode,
  909. BlockStatementNode,
  910. IfStatementNode,
  911. ReturnStatementNode,
  912. ConditionalExpressionNode,
  913. NewExpressionNode,
  914. ArrayExpressionNode,
  915. TemplateLiteralNode,
  916. TemplateElementNode,
  917. ObjectNode,
  918. PropertyNode,
  919. RestSpreadNode,
  920. FunctionNode,
  921. ForStatementNode,
  922. ForInStatementNode,
  923. ForOfStatementNode,
  924. WhileStatementNode,
  925. SwitchStatementNode,
  926. SwitchCaseNode,
  927. ThrowStatementNode,
  928. BreakContinueNode,
  929. TryStatementNode,
  930. CatchClauseNode
  931. ]) {
  932. for (const key of ["range"]) {
  933. Object.defineProperty(
  934. NodeClass.prototype,
  935. key,
  936. /** @type {PropertyDescriptor} */
  937. (Object.getOwnPropertyDescriptor(LazyLocNode.prototype, key))
  938. );
  939. }
  940. }
  941. /**
  942. * Comment collected without slicing its text out of the source: only magic
  943. * comments and pure annotations ever get their text read, and only binary
  944. * searches around magic-comment sites read `range`, so the text slice and the
  945. * range array are both deferred to first access and memoized like `loc`.
  946. */
  947. class LazyComment {
  948. /**
  949. * @param {boolean} block whether this is a block comment
  950. * @param {number} textStart offset right after the comment opener
  951. * @param {number} start start offset
  952. * @param {number} end end offset
  953. * @param {string} source full source text for the lazy `value` slice
  954. */
  955. constructor(block, textStart, start, end, source) {
  956. /** @type {"Block" | "Line"} */
  957. this.type = block ? "Block" : "Line";
  958. this.start = start;
  959. this.end = end;
  960. this[kSource] = source;
  961. this[kTextStart] = textStart;
  962. }
  963. /**
  964. * Memoized like `LazyLocNode#range`; offsets are final at construction so
  965. * the slot is cached unconditionally.
  966. * @returns {Range} source range
  967. */
  968. get range() {
  969. const cached = this[kRange];
  970. if (cached !== undefined) return cached;
  971. /** @type {Range} */
  972. const range = [this.start, this.end];
  973. return (this[kRange] = range);
  974. }
  975. /**
  976. * @param {Range} value source range
  977. */
  978. set range(value) {
  979. this[kRange] = value;
  980. }
  981. /**
  982. * @returns {string} comment text without the delimiters
  983. */
  984. get value() {
  985. const cached = this[kText];
  986. if (cached !== undefined) return cached;
  987. return (this[kText] = this[kSource].slice(
  988. this[kTextStart],
  989. this.type === "Block" ? this.end - 2 : this.end
  990. ));
  991. }
  992. /**
  993. * @param {string} value comment text
  994. */
  995. set value(value) {
  996. this[kText] = value;
  997. }
  998. }
  999. /**
  1000. * Replaces acorn's array-backed `Scope`: membership checks in `declareName`
  1001. * are `indexOf` there, which goes quadratic on files with thousands of
  1002. * bindings per scope (bundled or minified inputs). The three Sets are
  1003. * allocated lazily — most scopes declare into only one (module `functions` is
  1004. * always empty), so ~⅔ of the Sets are never needed.
  1005. */
  1006. class Scope {
  1007. /**
  1008. * @param {number} flags scope flags
  1009. */
  1010. constructor(flags) {
  1011. this.flags = flags;
  1012. /** @type {Set<string> | undefined} */
  1013. this.var = undefined;
  1014. /** @type {Set<string> | undefined} */
  1015. this.lexical = undefined;
  1016. /** @type {Set<string> | undefined} */
  1017. this.functions = undefined;
  1018. // first lexically-declared name; stands in for acorn's `lexical[0]`
  1019. // (the catch parameter of a simple catch scope)
  1020. /** @type {string | undefined} */
  1021. this.firstLexical = undefined;
  1022. }
  1023. }
  1024. /**
  1025. * Acorn's methods and state used by `WebpackParser` but missing from its
  1026. * public types, plus `WebpackParser`'s own fields, so overridden methods can
  1027. * declare `this` precisely.
  1028. * @typedef {import("acorn").Parser & {
  1029. * type: TokenType,
  1030. * value: unknown,
  1031. * start: number,
  1032. * startLoc?: Position,
  1033. * containsEsc: boolean,
  1034. * exprAllowed: boolean,
  1035. * options: Options,
  1036. * end: number,
  1037. * lastTokEnd: number,
  1038. * canInsertSemicolon: () => boolean,
  1039. * nextToken: () => void,
  1040. * next: (ignoreEscapeSequenceInKeyword?: boolean) => void,
  1041. * eat: (type: TokenType) => boolean,
  1042. * expect: (type: TokenType) => void,
  1043. * afterTrailingComma: (type: TokenType, notNext?: boolean) => boolean,
  1044. * unexpected: (pos?: number) => never,
  1045. * raise: (pos: number, message: string) => never,
  1046. * raiseRecoverable: (pos: number, message: string) => void,
  1047. * isContextual: (name: string) => boolean,
  1048. * parseIdent: (liberal?: boolean) => Identifier,
  1049. * parseLiteral: (value: unknown) => Node,
  1050. * awaitIdentPos: number,
  1051. * lastTokStart: number,
  1052. * lastTokStartLoc?: Position,
  1053. * yieldPos: number,
  1054. * awaitPos: number,
  1055. * parseExpression: (forInit?: boolean | string, refDestructuringErrors?: DestructuringErrorsShim | null) => Expression,
  1056. * parseSpread: (refDestructuringErrors?: DestructuringErrorsShim | null) => Node,
  1057. * braceIsBlock: (prevType: TokenType) => boolean,
  1058. * _gapHasNewline: () => boolean,
  1059. * parseExprList: (close: TokenType, allowTrailingComma: boolean, allowEmpty: boolean, refDestructuringErrors?: DestructuringErrorsShim | null) => Expression[],
  1060. * parsePrivateIdent: () => Node,
  1061. * parseTemplate: (opts: { isTagged: boolean }) => Node,
  1062. * shouldParseAsyncArrow: () => boolean,
  1063. * parseSubscriptAsyncArrow: (startPos: number, startLoc: Position | undefined, exprList: Expression[], forInit: boolean | string) => Expression,
  1064. * checkPatternErrors: (refDestructuringErrors: DestructuringErrorsShim, isAssign: boolean) => void,
  1065. * checkYieldAwaitInDefaultParams: () => void,
  1066. * checkExpressionErrors: (refDestructuringErrors?: DestructuringErrorsShim | null, andThrow?: boolean) => boolean,
  1067. * parseSubscript: (base: Expression, startPos: number, startLoc: Position | undefined, noCalls: boolean | undefined, maybeAsyncArrow: boolean, optionalChained: boolean, forInit?: boolean | string) => Expression,
  1068. * parseExprAtom: (refDestructuringErrors?: DestructuringErrorsShim | null, forInit?: boolean | string, forNew?: boolean) => Expression,
  1069. * buildBinary: (startPos: number, startLoc: Position | undefined, left: Expression, right: Expression, op: string, logical: boolean) => Expression,
  1070. * parseMaybeAssign: (forInit?: boolean | string, refDestructuringErrors?: DestructuringErrorsShim | null, afterLeftParse?: (this: unknown, left: Expression, startPos: number, startLoc?: Position) => Expression) => Expression,
  1071. * _parseTrivialAtom: (forInit?: boolean | string) => Expression | null,
  1072. * parseMaybeConditional: (forInit?: boolean | string, refDestructuringErrors?: DestructuringErrorsShim | null) => Expression,
  1073. * parseMaybeUnary: (refDestructuringErrors: DestructuringErrorsShim | null, sawUnary: boolean, incDec: boolean, forInit?: boolean | string) => Expression,
  1074. * parseExprSubscripts: (refDestructuringErrors?: DestructuringErrorsShim | null, forInit?: boolean | string) => Expression,
  1075. * parseAwait: (forInit?: boolean | string) => Expression,
  1076. * canAwait: boolean,
  1077. * privateNameStack: unknown[],
  1078. * semicolon: () => void,
  1079. * exitScope: () => void,
  1080. * parseStatement: (context: string | null, topLevel?: boolean, exports?: unknown) => Node,
  1081. * parseBindingAtom: () => Node,
  1082. * parseVarStatement: (node: Node, kind: string, allowMissingInitializer?: boolean) => Node,
  1083. * parseVar: (node: Node, isFor: boolean, kind: string, allowMissingInitializer?: boolean) => Node,
  1084. * parseExpressionStatement: (node: Node, expr: Expression) => Node,
  1085. * parseParenExpression: () => Expression,
  1086. * parseIfStatement: (node: Node) => Node,
  1087. * parseReturnStatement: (node: Node) => Node,
  1088. * insertSemicolon: () => boolean,
  1089. * allowReturn: boolean,
  1090. * allowNewDotTarget: boolean,
  1091. * parseExprOps: (forInit?: boolean | string, refDestructuringErrors?: DestructuringErrorsShim | null) => Expression,
  1092. * parseExprOp: (left: Expression, leftStartPos: number, leftStartLoc: Position | undefined, minPrec: number, forInit?: boolean | string) => Expression,
  1093. * _deStack: DestructuringErrorsShim[],
  1094. * _deDepth: number,
  1095. * _ecmaVersion: number,
  1096. * _noLocations: boolean,
  1097. * _validRegexpFlags: string,
  1098. * _propHashFastPath: boolean,
  1099. * _propHashStack: { proto: boolean }[],
  1100. * _propHashDepth: number,
  1101. * _acquireDestructuringErrors: () => DestructuringErrorsShim,
  1102. * _releaseDestructuringErrors: () => void,
  1103. * _arrStack: EXPECTED_ANY[][],
  1104. * _arrDepth: number,
  1105. * _acquireScratch: () => EXPECTED_ANY[],
  1106. * _releaseScratch: (scratch: EXPECTED_ANY[], count: number) => EXPECTED_ANY[],
  1107. * parseRestBinding: () => Node,
  1108. * parseBindingListItem: (param: Node) => Node,
  1109. * parseAssignableListItem: (allowModifiers?: boolean) => Node,
  1110. * parseParenItem: (item: Expression | Node) => Expression,
  1111. * shouldParseArrow: (exprList: Expression[]) => boolean,
  1112. * parseParenArrowList: (startPos: number, startLoc: Position | undefined, exprList: Expression[], forInit?: boolean | string) => Expression,
  1113. * finishNodeAt: (node: Node, type: string, pos: number, loc?: Position) => Node,
  1114. * parseParenAndDistinguishExpression: (canBeArrow: boolean, forInit?: boolean | string) => Expression,
  1115. * parseSubscripts: (base: Expression, startPos: number, startLoc: Position | undefined, noCalls?: boolean, forInit?: boolean | string) => Expression,
  1116. * parseNew: () => Expression,
  1117. * parseTemplateElement: (opts: { isTagged: boolean }) => Node,
  1118. * parseBlock: (createNewLexicalScope?: boolean, node?: Node, exitStrict?: boolean) => Node,
  1119. * parseYield: (forInit?: boolean | string) => Expression,
  1120. * toAssignable: (node: Node, isBinding?: boolean, refDestructuringErrors?: DestructuringErrorsShim | null) => Node,
  1121. * checkLValPattern: (expr: Node, bindingType?: number, checkClashes?: unknown) => void,
  1122. * checkUnreserved: (ref: Identifier) => void,
  1123. * enterScope: (flags: number) => void,
  1124. * readRegexp: () => void,
  1125. * potentialArrowAt: number,
  1126. * potentialArrowInForAwait: boolean,
  1127. * overrideContext: (tokenCtx: unknown) => void,
  1128. * parseFunction: (node: Node, statement: number, allowExpressionBody?: boolean, isAsync?: boolean, forInit?: boolean | string) => Expression,
  1129. * parseArrowExpression: (node: Node, params: Node[], isAsync: boolean, forInit?: boolean | string) => Expression,
  1130. * _subscriptFastPath: boolean,
  1131. * checkLValSimple: (expr: Node, bindingType?: number, checkClashes?: Record<string, boolean> | null) => void,
  1132. * checkLValInnerPattern: (expr: Node, bindingType?: number, checkClashes?: Record<string, boolean> | null) => void,
  1133. * declareName: (name: string, bindingType: number, pos: number) => void,
  1134. * startNode: () => Node,
  1135. * startNodeAt: (pos: number, loc?: Position) => Node,
  1136. * finishNode: (node: Node, type: string) => Node,
  1137. * readWord1: () => string,
  1138. * readWord: () => void,
  1139. * readToken: (code: number) => void,
  1140. * getTokenFromCode: (code: number) => void,
  1141. * fullCharCodeAtPos: () => number,
  1142. * skipSpace: () => void,
  1143. * skipLineComment: (startSkip: number) => void,
  1144. * skipBlockComment: () => void,
  1145. * readString: (quote: number) => void,
  1146. * readNumber: (startsWithDot: boolean) => void,
  1147. * readRadixNumber: (radix: number) => void,
  1148. * readTmplToken: () => void,
  1149. * invalidStringToken: (position: number, message: string) => void,
  1150. * _readInt: (radix: number, len?: number, maybeLegacyOctal?: boolean) => number | null,
  1151. * _readCodePoint: () => number,
  1152. * _readHexChar: (len: number) => number,
  1153. * _readEscapedChar: (inTemplate: boolean) => string,
  1154. * _readStringCold: (quote: number) => void,
  1155. * _readTmplTokenCold: () => void,
  1156. * _readNumberCold: (startsWithDot: boolean) => void,
  1157. * _readRadixNumber: (radix: number) => void,
  1158. * _readWord1Cold: () => string,
  1159. * _finishWordSlow: (word: string) => void,
  1160. * _skipSpaceCold: () => void,
  1161. * _getUnknownOrPrivate: (code: number) => void,
  1162. * finishToken: (type: TokenType, value?: unknown) => void,
  1163. * context: TokContextShim[],
  1164. * pos: number,
  1165. * input: string,
  1166. * scopeStack: Scope[],
  1167. * currentScope: () => Scope,
  1168. * currentThisScope: () => Scope,
  1169. * currentVarScope: () => Scope,
  1170. * keywords: RegExp,
  1171. * reservedWords: RegExp,
  1172. * reservedWordsStrict: RegExp,
  1173. * reservedWordsStrictBind: RegExp,
  1174. * strict: boolean,
  1175. * inGenerator: boolean,
  1176. * inGeneratorContext: () => boolean,
  1177. * inAsync: boolean,
  1178. * inClassStaticBlock: boolean,
  1179. * _wordLookups: WordLookups,
  1180. * treatFunctionsAsVar: boolean,
  1181. * treatFunctionsAsVarInScope: (scope: Scope) => boolean,
  1182. * inModule: boolean,
  1183. * undefinedExports: Record<string, Node>,
  1184. * parseObj: (isPattern: boolean, refDestructuringErrors?: DestructuringErrorsShim | null) => Node,
  1185. * parseProperty: (isPattern: boolean, refDestructuringErrors?: DestructuringErrorsShim | null) => Node,
  1186. * parsePropertyName: (prop: Node) => Node,
  1187. * parsePropertyValue: (prop: Node, isPattern: boolean, isGenerator: boolean, isAsync: boolean, startPos: number | undefined, startLoc: Position | undefined, refDestructuringErrors: DestructuringErrorsShim | null | undefined, containsEsc: boolean) => void,
  1188. * isAsyncProp: (prop: Node) => boolean,
  1189. * checkPropClash: (prop: Node, propHash: Record<string, unknown>, refDestructuringErrors?: DestructuringErrorsShim | null) => void,
  1190. * parseImport: (node: Node) => Node,
  1191. * parseExport: (node: Node, exports: unknown) => Node,
  1192. * parseImportSpecifiers: () => AnyImportSpecifier[],
  1193. * parseImportAttribute: () => ImportAttribute,
  1194. * parseExprImport: (forNew: boolean) => Expression,
  1195. * parseImportMeta: (node: Node) => Expression,
  1196. * parseDynamicImport: (node: Node) => Expression,
  1197. * updateContext: (prevType: TokenType) => void,
  1198. * finishOp: (type: TokenType, size: number) => void,
  1199. * readToken_dot: () => void,
  1200. * readToken_slash: () => void,
  1201. * readToken_mult_modulo_exp: (code: number) => void,
  1202. * readToken_pipe_amp: (code: number) => void,
  1203. * readToken_caret: () => void,
  1204. * readToken_plus_min: (code: number) => void,
  1205. * readToken_lt_gt: (code: number) => void,
  1206. * readToken_eq_excl: (code: number) => void,
  1207. * readToken_question: () => void,
  1208. * readToken_numberSign: () => void,
  1209. * _tokenFastPath: boolean,
  1210. * _inlineFinish: boolean,
  1211. * _lazy: boolean,
  1212. * _importPhase: ImportPhase | null,
  1213. * _importPhasesEnabled: boolean,
  1214. * _lazyComments: CollectedComment[] | undefined,
  1215. * _newlineBefore: 0 | 1 | 2,
  1216. * _fullTokenFastPath: boolean,
  1217. * _stmtFastPath: boolean,
  1218. * _lastArrow: Expression | null,
  1219. * _arrowFastPath: boolean,
  1220. * labels: { kind?: string | null, name?: string, statementStart?: number }[],
  1221. * initFunction: (node: Node) => void,
  1222. * parseFunctionStatement: (node: Node, isAsync: boolean, declarationPosition: boolean) => Node,
  1223. * parseFunctionBody: (node: Node, isArrowFunction: boolean, isMethod: boolean, forInit?: boolean | string) => void,
  1224. * parseFunctionParams: (node: Node) => void,
  1225. * isSimpleParamList: (params: Node[]) => boolean,
  1226. * checkParams: (node: Node, allowDuplicates: boolean) => void,
  1227. * adaptDirectivePrologue: (statements: Node[]) => void,
  1228. * toAssignableList: (exprList: Node[], isBinding: boolean) => Node[],
  1229. * parseBindingList: (close: TokenType, allowEmpty: boolean, allowTrailingComma: boolean, allowModifiers?: boolean) => Node[],
  1230. * strictDirective: (start: number) => boolean,
  1231. * _funcFastPath: boolean,
  1232. * _funcStmtOwn: boolean,
  1233. * _parseFunctionAt: (start: number, statement: number, allowExpressionBody: boolean, isAsync: boolean, forInit?: boolean | string) => Expression,
  1234. * isLet: (context?: string | null) => boolean,
  1235. * parseLabeledStatement: (node: Node, maybeName: string, expr: Identifier, context: string | null) => Node,
  1236. * _parseVarInto: (declarations: Node[], isFor: boolean, kind: string, allowMissingInitializer?: boolean) => number,
  1237. * _parseVarStatementAt: (start: number, kind: string, allowMissingInitializer?: boolean) => Node,
  1238. * _parseIfStatementAt: (start: number) => Node,
  1239. * _parseReturnStatementAt: (start: number) => Node,
  1240. * _parseExpressionStatementAt: (start: number, expr: Expression) => Node,
  1241. * eatContextual: (name: string) => boolean,
  1242. * isUsing: (isFor: boolean) => boolean,
  1243. * isAwaitUsing: (isFor: boolean) => boolean,
  1244. * parseForStatement: (node: Node) => Node,
  1245. * parseFor: (node: Node, init: Node | null) => Node,
  1246. * parseForIn: (node: Node, init: Node) => Node,
  1247. * parseForAfterInit: (node: Node, init: Node, awaitAt: number) => Node,
  1248. * parseWhileStatement: (node: Node) => Node,
  1249. * parseSwitchStatement: (node: Node) => Node,
  1250. * parseThrowStatement: (node: Node) => Node,
  1251. * parseTryStatement: (node: Node) => Node,
  1252. * parseBreakContinueStatement: (node: Node, keyword: string) => Node,
  1253. * parseCatchClauseParam: () => Node,
  1254. * _stmt2FastPath: boolean,
  1255. * _exprFastPath: boolean,
  1256. * _parseForStatementAt: (start: number) => Node,
  1257. * _parseForAt: (start: number, init: Node | null) => Node,
  1258. * _parseForInAt: (start: number, isAwait: boolean, init: Node) => Node,
  1259. * _parseForAfterInitAt: (start: number, init: Node, awaitAt: number) => Node,
  1260. * _parseWhileStatementAt: (start: number) => Node,
  1261. * _parseSwitchStatementAt: (start: number) => Node,
  1262. * _parseThrowStatementAt: (start: number) => Node,
  1263. * _parseTryStatementAt: (start: number) => Node,
  1264. * _parseBreakContinueStatementAt: (start: number, keyword: string) => Node,
  1265. * _moduleFallback: boolean,
  1266. * _moduleSyntaxSeen: boolean,
  1267. * _tryModuleFallback: () => boolean,
  1268. * }} ParserInternals
  1269. */
  1270. // internal methods are absent from acorn's types, so super calls do not
  1271. // type-check; call through a typed view of the base prototype instead
  1272. const base = /** @type {ParserInternals} */ (
  1273. /** @type {unknown} */ (BaseParser.prototype)
  1274. );
  1275. /**
  1276. * Acorn's internal destructuring-errors record; the class itself is not
  1277. * exported. Owned methods must create records with the same hidden class the
  1278. * rest of the expression parser reads, or every record field access there
  1279. * turns polymorphic.
  1280. * @typedef {{ shorthandAssign: number, trailingComma: number, parenthesizedAssign: number, parenthesizedBind: number, doubleProto: number }} DestructuringErrorsShim
  1281. */
  1282. // Capture the class at module load: parse one expression through a probe
  1283. // whose `checkExpressionErrors` sees the record the base parser created.
  1284. /** @type {{ new (): DestructuringErrorsShim } | null} */
  1285. const DestructuringErrorsClass = (() => {
  1286. /** @type {{ new (): DestructuringErrorsShim } | null} */
  1287. let captured = null;
  1288. class Probe extends BaseParser {
  1289. /**
  1290. * @param {DestructuringErrorsShim | null} refDestructuringErrors record to inspect
  1291. * @param {boolean=} andThrow whether to throw on error
  1292. * @returns {boolean} whether an error position was set
  1293. */
  1294. checkExpressionErrors(refDestructuringErrors, andThrow) {
  1295. if (refDestructuringErrors) {
  1296. captured =
  1297. /** @type {{ new (): DestructuringErrorsShim }} */
  1298. (refDestructuringErrors.constructor);
  1299. }
  1300. return /** @type {ParserInternals} */ (
  1301. /** @type {unknown} */ (base)
  1302. ).checkExpressionErrors.call(this, refDestructuringErrors, andThrow);
  1303. }
  1304. }
  1305. Probe.parse("a", { ecmaVersion: 2020 });
  1306. // cast: the closure assignment above is invisible to control-flow analysis
  1307. return /** @type {{ new (): DestructuringErrorsShim } | null} */ (captured);
  1308. })();
  1309. /**
  1310. * @returns {DestructuringErrorsShim} fresh destructuring-errors record on acorn's own class (plain-object fallback if the capture ever fails)
  1311. */
  1312. const createDestructuringErrors = () => {
  1313. const DestructuringErrors = DestructuringErrorsClass;
  1314. return DestructuringErrors !== null
  1315. ? new DestructuringErrors()
  1316. : {
  1317. shorthandAssign: -1,
  1318. trailingComma: -1,
  1319. parenthesizedAssign: -1,
  1320. parenthesizedBind: -1,
  1321. doubleProto: -1
  1322. };
  1323. };
  1324. /**
  1325. * Reserved-word classification for `checkUnreserved`'s single lookup:
  1326. * `1` keyword, `2` reserved in sloppy and strict mode, `3` reserved in strict
  1327. * mode only.
  1328. * @typedef {1 | 2 | 3} ReservedKind
  1329. */
  1330. /**
  1331. * @typedef {object} WordLookups
  1332. * @property {Map<string, TokenType>} keywords keyword name → token type
  1333. * @property {Map<string, ReservedKind>} reservedKinds identifier name → reserved kind
  1334. * @property {number} reservedMaxLen longest key in `reservedKinds`
  1335. * @property {{ test: (name: string) => boolean }} reservedBindTest strict-mode binding check, a Set-backed stand-in for acorn's `reservedWordsStrictBind` regexp
  1336. * @property {Set<string>} reservedBindSet strict-mode binding-reserved names
  1337. * @property {number} reservedBindMinLen shortest key in `reservedBindSet`
  1338. * @property {number} reservedBindMaxLen longest key in `reservedBindSet`
  1339. * @property {number} id owner tag for the shared `WORD_TYPES` classification memo
  1340. */
  1341. // One entry per distinct keyword/reserved-word set; webpack parses with a
  1342. // single option set, making this effectively a one-time build shared across
  1343. // every parse.
  1344. /** @type {Map<string, WordLookups>} */
  1345. const wordLookupsCache = new Map();
  1346. // Direct-mapped identifier cache for `readWord1`: one slot per hash, verified
  1347. // by char compare, overwritten on collision. Shared across parses — hits are
  1348. // content-checked, so a stale entry is merely a miss. Only words short enough
  1349. // to be flat V8 strings (never slices retaining their whole source) are stored.
  1350. const WORD_CACHE_MASK = 0x1fff;
  1351. /** @type {(string | null)[]} */
  1352. const WORD_CACHE = Array.from({ length: WORD_CACHE_MASK + 1 }, () => null);
  1353. const WORD_CACHE_MAX_LEN = 12;
  1354. // Classification memo parallel to `WORD_CACHE`, same slot: every cache write
  1355. // also writes the word's token type plus the id of the keyword set that
  1356. // classified it, so a hit skips `classifyWord` and another option set (or a
  1357. // `readWord1` write, owner 0) invalidates instead of mis-classifying. Keying
  1358. // by the cache's own slot adds no extra string references — the memo can
  1359. // never retain a word the cache itself dropped.
  1360. /** @type {(TokenType | null)[]} */
  1361. const WORD_TYPES = Array.from({ length: WORD_CACHE_MASK + 1 }, () => null);
  1362. const WORD_TYPE_OWNERS = new Int32Array(WORD_CACHE_MASK + 1);
  1363. let nextWordLookupsId = 1;
  1364. /**
  1365. * Keyword-or-name classification: pure in (word, keywords), so it can be
  1366. * memoized per `WORD_CACHE` slot.
  1367. * @param {string} word word
  1368. * @param {Map<string, TokenType>} keywords keyword name → token type
  1369. * @returns {TokenType} token type for `word`
  1370. */
  1371. const classifyWord = (word, keywords) => {
  1372. const len = word.length;
  1373. // every acorn keyword is 2-10 lowercase ASCII chars (`do`…`instanceof`)
  1374. if (len >= 2 && len <= 10) {
  1375. const first = word.charCodeAt(0);
  1376. if (first >= 97 && first <= 122) return keywords.get(word) || tokTypes.name;
  1377. }
  1378. return tokTypes.name;
  1379. };
  1380. // Multi-char operator strings for `finishOp` (`=>`, `===`, `&&=`, …), keyed by
  1381. // their char codes packed 7 bits apart — collision-free for ASCII operators up
  1382. // to acorn's maximum of 4 chars (`>>>=`), so the set stays ~40 entries.
  1383. /** @type {Map<number, string>} */
  1384. const OP_CACHE = new Map();
  1385. // The regexp flag whitelist depends only on the ecmaVersion, so build one
  1386. // string per version instead of a fresh one in every parser constructor.
  1387. /** @type {Map<number, string>} */
  1388. const VALID_REGEXP_FLAGS = new Map();
  1389. /**
  1390. * @param {number} ecmaVersion normalized acorn ecmaVersion
  1391. * @returns {string} the regexp flags allowed at `ecmaVersion`
  1392. */
  1393. const getValidRegexpFlags = (ecmaVersion) => {
  1394. let flags = VALID_REGEXP_FLAGS.get(ecmaVersion);
  1395. if (flags === undefined) {
  1396. flags = `gim${ecmaVersion >= 6 ? "uy" : ""}${ecmaVersion >= 9 ? "s" : ""}${
  1397. ecmaVersion >= 13 ? "d" : ""
  1398. }${ecmaVersion >= 15 ? "v" : ""}`;
  1399. VALID_REGEXP_FLAGS.set(ecmaVersion, flags);
  1400. }
  1401. return flags;
  1402. };
  1403. // Sticky mirrors of acorn's `skipWhiteSpace` / string-literal / `lineBreak`
  1404. // regexes for the owned `strictDirective` (they scan at an offset, no slice).
  1405. const STRICT_SKIP_WS = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  1406. const STRICT_LITERAL = /(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/y;
  1407. const STRICT_LINE_BREAK = /\r\n?|\n|\u2028|\u2029/;
  1408. /**
  1409. * @param {RegExp} re acorn `wordsRegexp` output (`^(?:a|b|c)$`)
  1410. * @returns {Set<string>} the alternation's words
  1411. */
  1412. const wordsRegexpToSet = (re) => {
  1413. const match = /^\^\(\?:(.*)\)\$$/.exec(re.source);
  1414. const body = match ? match[1] : "";
  1415. return new Set(body ? body.split("|") : []);
  1416. };
  1417. // One-entry identity memo in front of the string-keyed cache: acorn's
  1418. // `wordsRegexp` interns its regexps, so identity captures the whole word set,
  1419. // and builds construct thousands of parsers with one option set — this makes
  1420. // the per-construction lookup three compares instead of a long key concat.
  1421. /** @type {RegExp | undefined} */
  1422. let lastKeywordsRe;
  1423. /** @type {RegExp | undefined} */
  1424. let lastReservedRe;
  1425. /** @type {RegExp | undefined} */
  1426. let lastReservedStrictRe;
  1427. /** @type {WordLookups | undefined} */
  1428. let lastWordLookups;
  1429. /**
  1430. * Mirrors acorn's `keywords` / `reservedWords` / `reservedWordsStrict` regexps
  1431. * as Map/Set lookups. Membership is the hot per-word test in `readWord` and
  1432. * `checkUnreserved`, and a hash lookup beats an anchored alternation regexp.
  1433. * @param {ParserInternals} parser parser instance
  1434. * @returns {WordLookups} lookups for this parser's keyword set
  1435. */
  1436. const getWordLookups = (parser) => {
  1437. if (
  1438. parser.keywords === lastKeywordsRe &&
  1439. parser.reservedWords === lastReservedRe &&
  1440. parser.reservedWordsStrict === lastReservedStrictRe
  1441. ) {
  1442. return /** @type {WordLookups} */ (lastWordLookups);
  1443. }
  1444. // module vs script share a keyword set but differ in reserved words, so the
  1445. // key must cover all three regexps
  1446. const key = `${parser.keywords.source}\n${parser.reservedWords.source}\n${parser.reservedWordsStrict.source}`;
  1447. lastKeywordsRe = parser.keywords;
  1448. lastReservedRe = parser.reservedWords;
  1449. lastReservedStrictRe = parser.reservedWordsStrict;
  1450. const cached = wordLookupsCache.get(key);
  1451. if (cached !== undefined) {
  1452. lastWordLookups = cached;
  1453. return cached;
  1454. }
  1455. /** @type {Map<string, TokenType>} */
  1456. const keywords = new Map();
  1457. // acorn's keyword regexp is a subset of keywordTypes for the ecmaVersion
  1458. for (const name of Object.keys(keywordTypes)) {
  1459. if (parser.keywords.test(name)) keywords.set(name, keywordTypes[name]);
  1460. }
  1461. const reserved = wordsRegexpToSet(parser.reservedWords);
  1462. /** @type {Map<string, ReservedKind>} */
  1463. const reservedKinds = new Map();
  1464. for (const name of reserved) reservedKinds.set(name, 2);
  1465. for (const name of wordsRegexpToSet(parser.reservedWordsStrict)) {
  1466. if (!reserved.has(name)) reservedKinds.set(name, 3);
  1467. }
  1468. // keyword classification wins, matching acorn's keyword-first check
  1469. for (const name of keywords.keys()) reservedKinds.set(name, 1);
  1470. const reservedBind = wordsRegexpToSet(parser.reservedWordsStrictBind);
  1471. // length bounds so the owned checkLValSimple can skip the Set probe for
  1472. // most identifiers
  1473. let reservedBindMinLen = 0x7fffffff;
  1474. let reservedBindMaxLen = 0;
  1475. for (const name of reservedBind) {
  1476. if (name.length < reservedBindMinLen) reservedBindMinLen = name.length;
  1477. if (name.length > reservedBindMaxLen) reservedBindMaxLen = name.length;
  1478. }
  1479. let reservedMaxLen = 0;
  1480. for (const name of reservedKinds.keys()) {
  1481. if (name.length > reservedMaxLen) reservedMaxLen = name.length;
  1482. }
  1483. /** @type {WordLookups} */
  1484. const lookups = {
  1485. keywords,
  1486. reservedKinds,
  1487. reservedMaxLen,
  1488. reservedBindTest: { test: (name) => reservedBind.has(name) },
  1489. reservedBindSet: reservedBind,
  1490. reservedBindMinLen,
  1491. reservedBindMaxLen,
  1492. id: nextWordLookupsId++
  1493. };
  1494. wordLookupsCache.set(key, lookups);
  1495. lastWordLookups = lookups;
  1496. return lookups;
  1497. };
  1498. /**
  1499. * webpack's parser: acorn plus lazy `range` (no `loc` at all), Set-based scopes,
  1500. * tokenizer fast paths, import attributes and import phases (with acorn's
  1501. * `!forNew` guard, unlike the former `acorn-import-phases` package).
  1502. */
  1503. class WebpackParser extends BaseParser {
  1504. /**
  1505. * @param {Options & { lazyNodes?: boolean, lazyComments?: CollectedComment[], importPhases?: boolean, moduleFallback?: boolean }} options options
  1506. * @param {string} input source code
  1507. * @param {number=} startPos start position
  1508. */
  1509. constructor(options, input, startPos) {
  1510. const lazy = options.lazyNodes === true;
  1511. // JavascriptParser._parse pre-disables acorn's tracking, so the
  1512. // defensive copy only runs for direct callers
  1513. if (lazy && (options.locations || options.ranges)) {
  1514. options = { ...options, locations: false, ranges: false };
  1515. }
  1516. super(options, input, startPos);
  1517. // acorn sets this.keywords/reservedWords in its constructor; parsing
  1518. // (and thus readWord) only starts later in parse(), so this is ready
  1519. this._wordLookups = getWordLookups(
  1520. /** @type {ParserInternals} */ (/** @type {unknown} */ (this))
  1521. );
  1522. // acorn only calls `.test()` on reservedWordsStrictBind (in
  1523. // checkLValSimple); swap its regexp for the Set-backed check
  1524. /** @type {{ reservedWordsStrictBind: { test: (name: string) => boolean } }} */
  1525. (/** @type {unknown} */ (this)).reservedWordsStrictBind =
  1526. this._wordLookups.reservedBindTest;
  1527. // per-token option probes cached once: acorn normalizes options in
  1528. // `getOptions` before the constructor body runs and never mutates them
  1529. const normalizedOptions = /** @type {ParserInternals} */ (
  1530. /** @type {unknown} */ (this)
  1531. ).options;
  1532. this._ecmaVersion = /** @type {number} */ (normalizedOptions.ecmaVersion);
  1533. this._noLocations = !normalizedOptions.locations;
  1534. // lazy mode: nodes get only offsets, gating the owned tokenizer and
  1535. // statement fast paths
  1536. this._lazy = lazy;
  1537. // lazy comment collection must not race a user-provided onComment
  1538. /** @type {CollectedComment[] | undefined} */
  1539. this._lazyComments =
  1540. lazy && !options.onComment ? options.lazyComments : undefined;
  1541. // acorn skips a hashbang inside its constructor, before `_lazyComments`
  1542. // above exists — reconstruct the comment the override missed
  1543. if (
  1544. this._lazyComments !== undefined &&
  1545. !startPos &&
  1546. this.options.allowHashBang &&
  1547. input.startsWith("#!")
  1548. ) {
  1549. this._lazyComments.push(
  1550. new LazyComment(
  1551. false,
  1552. 2,
  1553. 0,
  1554. /** @type {ParserInternals} */ (/** @type {unknown} */ (this)).pos,
  1555. input
  1556. )
  1557. );
  1558. }
  1559. /** @type {ImportPhase | null} */
  1560. this._importPhase = null;
  1561. this._importPhasesEnabled = options.importPhases === true;
  1562. // auto source type: parse as module first, downgrade to script in place
  1563. // (instead of a second full parse) when script-only syntax is hit
  1564. this._moduleFallback = options.moduleFallback === true;
  1565. // set once a module-only construct is parsed; blocks the downgrade
  1566. this._moduleSyntaxSeen = false;
  1567. // the owned parseSubscript assumes optional chaining exists (it bakes
  1568. // `optional` into the node shape), so gate it on the normalized version
  1569. this._subscriptFastPath = lazy && this._ecmaVersion >= 11;
  1570. const proto = WebpackParser.prototype;
  1571. const self = /** @type {ParserInternals} */ (/** @type {unknown} */ (this));
  1572. // the owned per-token loop (nextToken/finishToken/next) also serves the
  1573. // public non-lazy tokenizer(): locations off, no onToken, and none of the
  1574. // acorn tokenizer methods it inlines or skips overridden by a plugin
  1575. // (`nextToken`'s punct/dot/eq shortcuts bypass `getTokenFromCode`,
  1576. // `finishOp`, `readToken_dot` and `readToken_eq_excl` even when the full
  1577. // token path below is off, so their overrides must gate this loop too)
  1578. this._tokenFastPath =
  1579. lazy ||
  1580. (this._noLocations &&
  1581. !normalizedOptions.onToken &&
  1582. this.nextToken === proto.nextToken &&
  1583. this.finishToken === proto.finishToken &&
  1584. this.next === proto.next &&
  1585. this.skipSpace === proto.skipSpace &&
  1586. this.getTokenFromCode === proto.getTokenFromCode &&
  1587. this.finishOp === proto.finishOp &&
  1588. self.readToken === base.readToken &&
  1589. self.updateContext === base.updateContext &&
  1590. self.readToken_dot === base.readToken_dot &&
  1591. self.readToken_eq_excl === base.readToken_eq_excl);
  1592. // the owned getTokenFromCode bakes in every ES2021 operator (?., ??=,
  1593. // &&=, ...), so it needs at least that version; outside lazy mode it also
  1594. // bypasses acorn's readToken_* family, so any override there turns it off
  1595. this._fullTokenFastPath =
  1596. this._ecmaVersion >= 12 &&
  1597. (lazy ||
  1598. (this._tokenFastPath &&
  1599. self.readToken_slash === base.readToken_slash &&
  1600. self.readToken_mult_modulo_exp === base.readToken_mult_modulo_exp &&
  1601. self.readToken_pipe_amp === base.readToken_pipe_amp &&
  1602. self.readToken_caret === base.readToken_caret &&
  1603. self.readToken_plus_min === base.readToken_plus_min &&
  1604. self.readToken_lt_gt === base.readToken_lt_gt &&
  1605. self.readToken_question === base.readToken_question &&
  1606. self.readToken_numberSign === base.readToken_numberSign &&
  1607. self.readRadixNumber === base.readRadixNumber));
  1608. // the owned nextToken/readWord finish the commonest tokens in place,
  1609. // which skips this.finishToken: needs the fast token loop (readWord runs
  1610. // in every mode) and no finishToken override by a plugin
  1611. this._inlineFinish =
  1612. this._tokenFastPath &&
  1613. this.finishToken === WebpackParser.prototype.finishToken;
  1614. // whether the gap before the current token holds a line terminator:
  1615. // 0 no, 1 yes, 2 unknown (canInsertSemicolon then scans the gap)
  1616. /** @type {0 | 1 | 2} */
  1617. this._newlineBefore = 2;
  1618. // LIFO pool for call-scoped destructuring-errors records; depth resets
  1619. // implicitly since a raise aborts the whole parse
  1620. /** @type {DestructuringErrorsShim[]} */
  1621. this._deStack = [];
  1622. this._deDepth = 0;
  1623. // LIFO pool for `parseObj`'s prop-clash records: acorn's ES6+
  1624. // `checkPropClash` only ever touches `.proto`, so one record per nesting
  1625. // depth suffices; an overriding subclass gets the fresh `{}` acorn expects
  1626. this._propHashFastPath =
  1627. /** @type {ParserInternals} */ (/** @type {unknown} */ (this))
  1628. .checkPropClash === base.checkPropClash;
  1629. /** @type {{ proto: boolean }[]} */
  1630. this._propHashStack = [];
  1631. this._propHashDepth = 0;
  1632. // LIFO pool of scratch arrays for list productions: elements are written
  1633. // by index, then copied out exactly sized — a push-grown array retains
  1634. // ~17 slots of capacity slack per list otherwise
  1635. /** @type {unknown[][]} */
  1636. this._arrStack = [];
  1637. this._arrDepth = 0;
  1638. // `readRegexp`'s flag whitelist depends only on the ecmaVersion
  1639. this._validRegexpFlags = getValidRegexpFlags(this._ecmaVersion);
  1640. // the owned parseStatement inlines these methods, so a parser plugin
  1641. // overriding any of them turns the statement fast path off
  1642. this._stmtFastPath =
  1643. lazy &&
  1644. this.parseVarStatement === proto.parseVarStatement &&
  1645. this.parseVar === proto.parseVar &&
  1646. this.parseIfStatement === proto.parseIfStatement &&
  1647. this.parseReturnStatement === proto.parseReturnStatement &&
  1648. this.parseExpressionStatement === proto.parseExpressionStatement;
  1649. // last arrow finished by parseArrowExpression: `expr === this._lastArrow`
  1650. // replaces the megamorphic `expr.type === "ArrowFunctionExpression"`
  1651. // probes on the expression spine (arrows are created in exactly one place
  1652. // and never backtracked, so identity captures the type test)
  1653. /** @type {Expression | null} */
  1654. this._lastArrow = null;
  1655. // arrows must flow through parseArrowExpression for the identity probe;
  1656. // a plugin overriding it falls back to the type-based probes
  1657. this._arrowFastPath =
  1658. lazy && this.parseArrowExpression === proto.parseArrowExpression;
  1659. // the owned parseFunction/parseFunctionBody inline initFunction and
  1660. // isSimpleParamList; a plugin overriding either turns the fast path off
  1661. const internals = /** @type {ParserInternals} */ (
  1662. /** @type {unknown} */ (this)
  1663. );
  1664. this._funcFastPath =
  1665. lazy &&
  1666. this._ecmaVersion >= 9 &&
  1667. internals.initFunction === base.initFunction &&
  1668. internals.isSimpleParamList === base.isSimpleParamList;
  1669. // the owned parseStatement inlines parseFunctionStatement's body
  1670. this._funcStmtOwn =
  1671. this._funcFastPath &&
  1672. internals.parseFunctionStatement === base.parseFunctionStatement &&
  1673. this.parseFunction === proto.parseFunction;
  1674. // the owned parseStatement inlines these statement parsers too; any
  1675. // override falls back to acorn's dispatch for these heads
  1676. this._stmt2FastPath =
  1677. lazy &&
  1678. this._ecmaVersion >= 9 &&
  1679. internals.parseForStatement === base.parseForStatement &&
  1680. internals.parseFor === base.parseFor &&
  1681. internals.parseForIn === base.parseForIn &&
  1682. internals.parseForAfterInit === base.parseForAfterInit &&
  1683. this.parseVar === proto.parseVar &&
  1684. internals.parseWhileStatement === base.parseWhileStatement &&
  1685. internals.parseSwitchStatement === base.parseSwitchStatement &&
  1686. internals.parseThrowStatement === base.parseThrowStatement &&
  1687. internals.parseTryStatement === base.parseTryStatement &&
  1688. internals.parseBreakContinueStatement ===
  1689. base.parseBreakContinueStatement;
  1690. // `parseMaybeAssign`'s trivial-atom fast path returns the atom without
  1691. // descending the seven-layer expression chain, so every layer it skips
  1692. // must be the owned one
  1693. this._exprFastPath =
  1694. lazy &&
  1695. this.parseMaybeConditional === proto.parseMaybeConditional &&
  1696. this.parseExprOps === proto.parseExprOps &&
  1697. this.parseExprOp === proto.parseExprOp &&
  1698. this.parseMaybeUnary === proto.parseMaybeUnary &&
  1699. this.parseExprSubscripts === proto.parseExprSubscripts &&
  1700. this.parseSubscripts === proto.parseSubscripts &&
  1701. this.parseSubscript === proto.parseSubscript &&
  1702. this.parseExprAtom === proto.parseExprAtom &&
  1703. this.checkExpressionErrors === proto.checkExpressionErrors &&
  1704. internals.isContextual === base.isContextual;
  1705. }
  1706. /**
  1707. * Fetches a destructuring-errors record from the pool: acorn allocates one
  1708. * per expression parse and drops it at the end of the call, so strictly
  1709. * call-scoped users can reuse records instead. Pair every acquire with a
  1710. * `_releaseDestructuringErrors` on each non-throwing exit.
  1711. * @returns {DestructuringErrorsShim} reset record
  1712. * @this {ParserInternals}
  1713. */
  1714. _acquireDestructuringErrors() {
  1715. const stack = this._deStack;
  1716. const depth = this._deDepth++;
  1717. const cached = stack[depth];
  1718. if (cached !== undefined) {
  1719. cached.shorthandAssign =
  1720. cached.trailingComma =
  1721. cached.parenthesizedAssign =
  1722. cached.parenthesizedBind =
  1723. cached.doubleProto =
  1724. -1;
  1725. return cached;
  1726. }
  1727. return (stack[depth] = createDestructuringErrors());
  1728. }
  1729. /**
  1730. * @returns {void}
  1731. * @this {ParserInternals}
  1732. */
  1733. _releaseDestructuringErrors() {
  1734. this._deDepth--;
  1735. }
  1736. /**
  1737. * Fetches a scratch array for a list production: write elements by index,
  1738. * then materialize with `_releaseScratch`. Entries past the caller's write
  1739. * index are stale and meaningless.
  1740. * @returns {EXPECTED_ANY[]} scratch array
  1741. * @this {ParserInternals}
  1742. */
  1743. _acquireScratch() {
  1744. const stack = this._arrStack;
  1745. const depth = this._arrDepth++;
  1746. const cached = stack[depth];
  1747. if (cached !== undefined) return cached;
  1748. return (stack[depth] = []);
  1749. }
  1750. /**
  1751. * @param {EXPECTED_ANY[]} scratch scratch array from `_acquireScratch`
  1752. * @param {number} count number of elements written
  1753. * @returns {EXPECTED_ANY[]} exactly-sized copy of the first `count` entries
  1754. * @this {ParserInternals}
  1755. */
  1756. _releaseScratch(scratch, count) {
  1757. this._arrDepth--;
  1758. return scratch.slice(0, count);
  1759. }
  1760. // ----- tokenizer fast paths -----
  1761. /**
  1762. * Owned per-token loop: acorn's `nextToken` chains `skipSpace` →
  1763. * `fullCharCodeAtPos` → `readToken` → `isIdentifierStart` with a dead
  1764. * `locations` check at each step. For the common non-template context of
  1765. * `_tokenFastPath` mode (lazy, or locations-off with no tokenizer overrides)
  1766. * this folds whitespace and comment skipping and the ASCII token dispatch
  1767. * into one function so nothing re-enters acorn's per-step option checks.
  1768. * Template/`preserveSpace` contexts and other modes use acorn's tokenizer.
  1769. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  1770. * @returns {void}
  1771. * @this {ParserInternals}
  1772. */
  1773. nextToken() {
  1774. const context = this.context;
  1775. const curContext = context[context.length - 1];
  1776. let slow;
  1777. if (curContext !== undefined) {
  1778. const flagged =
  1779. /** @type {TokContextShim & { [kSlowContext]?: boolean }} */
  1780. (curContext);
  1781. slow = flagged[kSlowContext];
  1782. if (slow === undefined) {
  1783. slow = flagged[kSlowContext] = Boolean(
  1784. curContext.preserveSpace || curContext.override
  1785. );
  1786. }
  1787. }
  1788. if (!this._tokenFastPath || curContext === undefined || slow) {
  1789. this._newlineBefore = 2;
  1790. return base.nextToken.call(this);
  1791. }
  1792. const input = this.input;
  1793. const len = input.length;
  1794. let pos = this.pos;
  1795. // line terminators are flagged while skipping (yuku's
  1796. // `line_terminator_before`), so ASI checks need no gap re-scan. A
  1797. // delegated path (acorn's html-comment handling) may have consumed part
  1798. // of the gap before re-entering — start at "unknown" then.
  1799. /** @type {0 | 1 | 2} */
  1800. let newline = pos === this.lastTokEnd ? 0 : 2;
  1801. // one CHAR_CLASS load classifies each char for both the skip loop and
  1802. // the token dispatch below (yuku's ws_class/ident/punct tables in one)
  1803. let code = 0;
  1804. let cls = CLS_OTHER;
  1805. while (pos < len) {
  1806. code = input.charCodeAt(pos);
  1807. cls = CHAR_CLASS[code];
  1808. if (cls < CLS_SPACE) {
  1809. if (cls === CLS_UNICODE) {
  1810. // unicode whitespace / line terminators: the cold reader consumes them
  1811. this.pos = pos;
  1812. this._skipSpaceCold();
  1813. pos = this.pos;
  1814. if (newline === 0) newline = 2;
  1815. code = pos < len ? input.charCodeAt(pos) : 0;
  1816. cls = CHAR_CLASS[code];
  1817. }
  1818. break;
  1819. }
  1820. if (cls === CLS_SPACE) {
  1821. // space, tab, VT, FF (no CRLF/line bookkeeping in lazy mode)
  1822. pos++;
  1823. } else if (cls === CLS_NEWLINE) {
  1824. newline = 1;
  1825. pos++;
  1826. } else {
  1827. const next = input.charCodeAt(pos + 1);
  1828. if (next === 42) {
  1829. this.pos = pos;
  1830. this.skipBlockComment();
  1831. pos = this.pos;
  1832. // the comment body may hold a line terminator
  1833. if (newline === 0) newline = 2;
  1834. } else if (next === 47) {
  1835. this.pos = pos;
  1836. this.skipLineComment(2);
  1837. pos = this.pos;
  1838. } else {
  1839. // a division/regexp token, not a comment
  1840. cls = CLS_OTHER;
  1841. break;
  1842. }
  1843. }
  1844. }
  1845. this._newlineBefore = newline;
  1846. this.pos = pos;
  1847. this.start = pos;
  1848. if (pos >= len) return this.finishToken(tokTypes.eof);
  1849. switch (cls) {
  1850. case CLS_IDENT:
  1851. return this.readWord();
  1852. case CLS_PUNCT: {
  1853. const type = /** @type {TokenType} */ (SIMPLE_PUNCT[code]);
  1854. this.pos = pos + 1;
  1855. if (!this._inlineFinish) return this.finishToken(type);
  1856. // finishToken inlined for the simple punctuators (no value, and
  1857. // their context updates are per-char static)
  1858. this.end = pos + 1;
  1859. const prevType = this.type;
  1860. this.type = type;
  1861. this.value = undefined;
  1862. switch (code) {
  1863. case 41:
  1864. case 125: {
  1865. // parenR/braceR.updateContext, inlined
  1866. if (context.length === 1) {
  1867. this.exprAllowed = true;
  1868. break;
  1869. }
  1870. let out = /** @type {TokContextShim} */ (context.pop());
  1871. if (
  1872. out === CTX_B_STAT &&
  1873. /** @type {TokContextShim} */ (context[context.length - 1])
  1874. .token === "function"
  1875. ) {
  1876. out = /** @type {TokContextShim} */ (context.pop());
  1877. }
  1878. this.exprAllowed = !out.isExpr;
  1879. break;
  1880. }
  1881. case 123:
  1882. // braceL.updateContext, inlined
  1883. context.push(this.braceIsBlock(prevType) ? CTX_B_STAT : CTX_B_EXPR);
  1884. this.exprAllowed = true;
  1885. break;
  1886. case 40: {
  1887. // parenL.updateContext, inlined
  1888. const statementParens =
  1889. prevType === tokTypes._if ||
  1890. prevType === tokTypes._for ||
  1891. prevType === tokTypes._with ||
  1892. prevType === tokTypes._while;
  1893. context.push(statementParens ? CTX_P_STAT : CTX_P_EXPR);
  1894. this.exprAllowed = true;
  1895. break;
  1896. }
  1897. case 58:
  1898. // colon.updateContext, inlined
  1899. if (
  1900. /** @type {TokContextShim} */ (context[context.length - 1])
  1901. .token === "function"
  1902. ) {
  1903. context.pop();
  1904. }
  1905. this.exprAllowed = true;
  1906. break;
  1907. case 93:
  1908. // bracketR: no context hook, beforeExpr is false
  1909. this.exprAllowed = false;
  1910. break;
  1911. default:
  1912. // semi, comma, bracketL: no context hook, beforeExpr is true
  1913. this.exprAllowed = true;
  1914. }
  1915. return;
  1916. }
  1917. case CLS_DOT: {
  1918. // `.` not starting `.5` or `...`: skip readToken_dot's re-dispatch
  1919. const next = input.charCodeAt(pos + 1);
  1920. if ((next < 48 || next > 57) && next !== 46) {
  1921. this.pos = pos + 1;
  1922. return this.finishToken(tokTypes.dot);
  1923. }
  1924. return this.getTokenFromCode(code);
  1925. }
  1926. case CLS_EQ: {
  1927. // `=` not starting `==` or `=>`: skip readToken_eq_excl + finishOp slice
  1928. const next = input.charCodeAt(pos + 1);
  1929. if (next !== 61 && next !== 62) {
  1930. this.pos = pos + 1;
  1931. return this.finishToken(tokTypes.eq, "=");
  1932. }
  1933. return this.getTokenFromCode(code);
  1934. }
  1935. case CLS_UNICODE:
  1936. return this.readToken(this.fullCharCodeAtPos());
  1937. default:
  1938. return this.getTokenFromCode(code);
  1939. }
  1940. }
  1941. /**
  1942. * `_tokenFastPath` `finishToken`: acorn probes `options.locations` for a
  1943. * dead `endLoc` write on every token and reaches `updateContext` through an
  1944. * extra method call. Skip the probe and inline acorn's `updateContext` body —
  1945. * this runs once per token. Other modes use acorn's.
  1946. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  1947. * @param {TokenType} type token type
  1948. * @param {unknown=} value token value
  1949. * @returns {void}
  1950. * @this {ParserInternals}
  1951. */
  1952. finishToken(type, value) {
  1953. if (!this._tokenFastPath) {
  1954. return base.finishToken.call(this, type, value);
  1955. }
  1956. this.end = this.pos;
  1957. const prevType = this.type;
  1958. this.type = type;
  1959. this.value = value;
  1960. const internal = /** @type {TokenTypeInternal} */ (type);
  1961. // acorn's updateContext, inlined: keyword-after-dot forbids an expression,
  1962. // else the token type's own context hook runs, else `exprAllowed` follows
  1963. // the type's `beforeExpr` (the branch that makes `/` after a value divide)
  1964. if (type === tokTypes.name) {
  1965. // name.updateContext, inlined for the commonest token: only `of` /
  1966. // `yield` (outside a `.` access, ES6+) can re-allow an expression
  1967. this.exprAllowed =
  1968. ((value === "of" && !this.exprAllowed) ||
  1969. (value === "yield" && this.inGeneratorContext())) &&
  1970. prevType !== tokTypes.dot &&
  1971. this._ecmaVersion >= 6;
  1972. } else {
  1973. const update = internal.updateContext;
  1974. if (update === null) {
  1975. // no context hook (most punctuation, operators, literals and
  1976. // keywords): acorn's keyword-after-dot probe, else `beforeExpr` —
  1977. // checked first so this majority skips the per-type compares below
  1978. this.exprAllowed =
  1979. prevType === tokTypes.dot && internal.keyword !== undefined
  1980. ? false
  1981. : internal.beforeExpr;
  1982. } else if (type === tokTypes.parenR || type === tokTypes.braceR) {
  1983. // parenR/braceR.updateContext, inlined
  1984. const context = this.context;
  1985. if (context.length === 1) {
  1986. this.exprAllowed = true;
  1987. } else {
  1988. let out = /** @type {TokContextShim} */ (context.pop());
  1989. if (
  1990. out === CTX_B_STAT &&
  1991. /** @type {TokContextShim} */ (context[context.length - 1])
  1992. .token === "function"
  1993. ) {
  1994. out = /** @type {TokContextShim} */ (context.pop());
  1995. }
  1996. this.exprAllowed = !out.isExpr;
  1997. }
  1998. } else if (type === tokTypes.braceL) {
  1999. // braceL.updateContext, inlined
  2000. this.context.push(
  2001. this.braceIsBlock(prevType) ? CTX_B_STAT : CTX_B_EXPR
  2002. );
  2003. this.exprAllowed = true;
  2004. } else if (type === tokTypes.parenL) {
  2005. // parenL.updateContext, inlined
  2006. const statementParens =
  2007. prevType === tokTypes._if ||
  2008. prevType === tokTypes._for ||
  2009. prevType === tokTypes._with ||
  2010. prevType === tokTypes._while;
  2011. this.context.push(statementParens ? CTX_P_STAT : CTX_P_EXPR);
  2012. this.exprAllowed = true;
  2013. } else if (internal.keyword !== undefined && prevType === tokTypes.dot) {
  2014. // `.function` etc.: keyword-after-dot wins over the type's own hook
  2015. this.exprAllowed = false;
  2016. } else {
  2017. update.call(this, prevType);
  2018. }
  2019. }
  2020. }
  2021. /**
  2022. * Owned `braceIsBlock`, acorn's verbatim except the line-terminator probe:
  2023. * acorn slices the inter-token gap and runs a regexp; `_gapHasNewline`
  2024. * answers from the tokenizer's newline flag (scanning only when unknown).
  2025. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokencontext.js
  2026. * @param {TokenType} prevType type of the previous token
  2027. * @returns {boolean} whether a `{` opens a block in this context
  2028. * @this {ParserInternals}
  2029. */
  2030. braceIsBlock(prevType) {
  2031. const context = this.context;
  2032. const parent = /** @type {TokContextShim} */ (context[context.length - 1]);
  2033. if (parent === CTX_F_EXPR || parent === CTX_F_STAT) return true;
  2034. if (
  2035. prevType === tokTypes.colon &&
  2036. (parent === CTX_B_STAT || parent === CTX_B_EXPR)
  2037. ) {
  2038. return !parent.isExpr;
  2039. }
  2040. // after `return`, or after `yield`/`of` (name with exprAllowed), a line
  2041. // terminator decides between block and expression
  2042. if (
  2043. prevType === tokTypes._return ||
  2044. (prevType === tokTypes.name && this.exprAllowed)
  2045. ) {
  2046. return this._gapHasNewline();
  2047. }
  2048. if (
  2049. prevType === tokTypes._else ||
  2050. prevType === tokTypes.semi ||
  2051. prevType === tokTypes.eof ||
  2052. prevType === tokTypes.parenR ||
  2053. prevType === tokTypes.arrow
  2054. ) {
  2055. return true;
  2056. }
  2057. if (prevType === tokTypes.braceL) return parent === CTX_B_STAT;
  2058. if (
  2059. prevType === tokTypes._var ||
  2060. prevType === tokTypes._const ||
  2061. prevType === tokTypes.name
  2062. ) {
  2063. return false;
  2064. }
  2065. return !this.exprAllowed;
  2066. }
  2067. /**
  2068. * Whether the gap before the current token holds a line terminator, served
  2069. * from the owned tokenizer's flag when known.
  2070. * @returns {boolean} whether a line terminator precedes the current token
  2071. * @this {ParserInternals}
  2072. */
  2073. _gapHasNewline() {
  2074. const newlineBefore = this._newlineBefore;
  2075. if (newlineBefore !== 2) return newlineBefore === 1;
  2076. const input = this.input;
  2077. const end = this.start;
  2078. for (let i = this.lastTokEnd; i < end; i++) {
  2079. const ch = input.charCodeAt(i);
  2080. // LF, CR, LS, PS — acorn's `lineBreak` alternation
  2081. if (ch === 10 || ch === 13 || ch === 0x2028 || ch === 0x2029) {
  2082. // memoize: the gap is fixed until the next token is read, and
  2083. // `nextToken` rewrites the flag — ASI probes often repeat per token
  2084. // (e.g. name atoms behind a /*#__PURE__*/ comment)
  2085. this._newlineBefore = 1;
  2086. return true;
  2087. }
  2088. }
  2089. this._newlineBefore = 0;
  2090. return false;
  2091. }
  2092. /**
  2093. * Owned per-token advance: acorn's `next` writes `lastTokEndLoc`/
  2094. * `lastTokStartLoc` and probes `options.onToken` on every token, both dead in
  2095. * `_tokenFastPath` mode (locations off, no token stream), leaving only the
  2096. * two offset writes and the keyword-escape guard. Other modes use acorn's.
  2097. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2098. * @param {boolean=} ignoreEscapeSequenceInKeyword whether an escape in a keyword is allowed here
  2099. * @returns {void}
  2100. * @this {ParserInternals}
  2101. */
  2102. next(ignoreEscapeSequenceInKeyword) {
  2103. if (!this._tokenFastPath) {
  2104. return base.next.call(this, ignoreEscapeSequenceInKeyword);
  2105. }
  2106. const type = this.type;
  2107. // `containsEsc` is a parser field and almost always false; testing it first
  2108. // keeps the TokenType load off the common path.
  2109. if (this.containsEsc && !ignoreEscapeSequenceInKeyword && type.keyword) {
  2110. this.raiseRecoverable(
  2111. this.start,
  2112. `Escape sequence in keyword ${type.keyword}`
  2113. );
  2114. }
  2115. this.lastTokEnd = this.end;
  2116. this.lastTokStart = this.start;
  2117. this.nextToken();
  2118. }
  2119. /**
  2120. * Owned `finishOp`: acorn slices the operator text out of the source for
  2121. * every operator token, allocating a fresh 2-4 char string per `=>`, `===`,
  2122. * `&&` etc. Serve those from `OP_CACHE` instead; single-char operators keep
  2123. * the direct slice, which V8 serves from its single-character table.
  2124. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2125. * @param {TokenType} type token type
  2126. * @param {number} size operator length
  2127. * @returns {void}
  2128. * @this {ParserInternals}
  2129. */
  2130. finishOp(type, size) {
  2131. const pos = this.pos;
  2132. const input = this.input;
  2133. if (size === 1) {
  2134. this.pos = pos + 1;
  2135. return this.finishToken(type, input.slice(pos, pos + 1));
  2136. }
  2137. let key = input.charCodeAt(pos) | (input.charCodeAt(pos + 1) << 7);
  2138. if (size > 2) {
  2139. key |= input.charCodeAt(pos + 2) << 14;
  2140. if (size > 3) key |= input.charCodeAt(pos + 3) << 21;
  2141. }
  2142. let str = OP_CACHE.get(key);
  2143. if (str === undefined) {
  2144. str = input.slice(pos, pos + size);
  2145. OP_CACHE.set(key, str);
  2146. }
  2147. this.pos = pos + size;
  2148. return this.finishToken(type, str);
  2149. }
  2150. /**
  2151. * Owned `getTokenFromCode`: acorn dispatches operators through per-family
  2152. * `readToken_*` methods that each end in `finishOp`'s source slice. Resolve
  2153. * every operator by direct char peeks to a static string instead (yuku's
  2154. * `scanPunctuation`) — no method chain, no slice, no `OP_CACHE` probe. The
  2155. * HTML-comment forms (`<!--`, `-->`) inline acorn's line-comment handling;
  2156. * `#` and unknown chars use the owned cold reader.
  2157. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2158. * @param {number} code current char code
  2159. * @returns {void}
  2160. * @this {ParserInternals}
  2161. */
  2162. getTokenFromCode(code) {
  2163. if (!this._fullTokenFastPath) {
  2164. return base.getTokenFromCode.call(this, code);
  2165. }
  2166. const input = this.input;
  2167. const pos = this.pos;
  2168. switch (code) {
  2169. case 46: {
  2170. // '.': number, ellipsis or plain dot
  2171. const next = input.charCodeAt(pos + 1);
  2172. if (next >= 48 && next <= 57) return this.readNumber(true);
  2173. if (next === 46 && input.charCodeAt(pos + 2) === 46) {
  2174. this.pos = pos + 3;
  2175. return this.finishToken(tokTypes.ellipsis);
  2176. }
  2177. this.pos = pos + 1;
  2178. return this.finishToken(tokTypes.dot);
  2179. }
  2180. case 47: {
  2181. // '/': regexp in expression position, otherwise /= or /
  2182. if (this.exprAllowed) {
  2183. this.pos = pos + 1;
  2184. return this.readRegexp();
  2185. }
  2186. if (input.charCodeAt(pos + 1) === 61) {
  2187. this.pos = pos + 2;
  2188. return this.finishToken(tokTypes.assign, "/=");
  2189. }
  2190. this.pos = pos + 1;
  2191. return this.finishToken(tokTypes.slash, "/");
  2192. }
  2193. case 37: {
  2194. // '%': %= or %
  2195. if (input.charCodeAt(pos + 1) === 61) {
  2196. this.pos = pos + 2;
  2197. return this.finishToken(tokTypes.assign, "%=");
  2198. }
  2199. this.pos = pos + 1;
  2200. return this.finishToken(tokTypes.modulo, "%");
  2201. }
  2202. case 42: {
  2203. // '*': **=, **, *= or *
  2204. const next = input.charCodeAt(pos + 1);
  2205. if (next === 42) {
  2206. if (input.charCodeAt(pos + 2) === 61) {
  2207. this.pos = pos + 3;
  2208. return this.finishToken(tokTypes.assign, "**=");
  2209. }
  2210. this.pos = pos + 2;
  2211. return this.finishToken(tokTypes.starstar, "**");
  2212. }
  2213. if (next === 61) {
  2214. this.pos = pos + 2;
  2215. return this.finishToken(tokTypes.assign, "*=");
  2216. }
  2217. this.pos = pos + 1;
  2218. return this.finishToken(tokTypes.star, "*");
  2219. }
  2220. case 124: {
  2221. // '|': ||=, ||, |= or |
  2222. const next = input.charCodeAt(pos + 1);
  2223. if (next === 124) {
  2224. if (input.charCodeAt(pos + 2) === 61) {
  2225. this.pos = pos + 3;
  2226. return this.finishToken(tokTypes.assign, "||=");
  2227. }
  2228. this.pos = pos + 2;
  2229. return this.finishToken(tokTypes.logicalOR, "||");
  2230. }
  2231. if (next === 61) {
  2232. this.pos = pos + 2;
  2233. return this.finishToken(tokTypes.assign, "|=");
  2234. }
  2235. this.pos = pos + 1;
  2236. return this.finishToken(tokTypes.bitwiseOR, "|");
  2237. }
  2238. case 38: {
  2239. // '&': &&=, &&, &= or &
  2240. const next = input.charCodeAt(pos + 1);
  2241. if (next === 38) {
  2242. if (input.charCodeAt(pos + 2) === 61) {
  2243. this.pos = pos + 3;
  2244. return this.finishToken(tokTypes.assign, "&&=");
  2245. }
  2246. this.pos = pos + 2;
  2247. return this.finishToken(tokTypes.logicalAND, "&&");
  2248. }
  2249. if (next === 61) {
  2250. this.pos = pos + 2;
  2251. return this.finishToken(tokTypes.assign, "&=");
  2252. }
  2253. this.pos = pos + 1;
  2254. return this.finishToken(tokTypes.bitwiseAND, "&");
  2255. }
  2256. case 94: {
  2257. // '^': ^= or ^
  2258. if (input.charCodeAt(pos + 1) === 61) {
  2259. this.pos = pos + 2;
  2260. return this.finishToken(tokTypes.assign, "^=");
  2261. }
  2262. this.pos = pos + 1;
  2263. return this.finishToken(tokTypes.bitwiseXOR, "^");
  2264. }
  2265. case 43: {
  2266. // '+': ++, += or +
  2267. const next = input.charCodeAt(pos + 1);
  2268. if (next === 43) {
  2269. this.pos = pos + 2;
  2270. return this.finishToken(tokTypes.incDec, "++");
  2271. }
  2272. if (next === 61) {
  2273. this.pos = pos + 2;
  2274. return this.finishToken(tokTypes.assign, "+=");
  2275. }
  2276. this.pos = pos + 1;
  2277. return this.finishToken(tokTypes.plusMin, "+");
  2278. }
  2279. case 45: {
  2280. // '-': --, -= or -; `-->` may open an HTML line comment
  2281. const next = input.charCodeAt(pos + 1);
  2282. if (next === 45) {
  2283. // `-->` opens an HTML line comment only at the start of a line
  2284. // (acorn readToken_plus_min): https://github.com/acornjs/acorn/blob/8.15.0/acorn/src/tokenize.js#L599-L618
  2285. if (
  2286. input.charCodeAt(pos + 2) === 62 &&
  2287. !this.inModule &&
  2288. (this.lastTokEnd === 0 ||
  2289. lineBreak.test(input.slice(this.lastTokEnd, pos)))
  2290. ) {
  2291. this.skipLineComment(3);
  2292. this.skipSpace();
  2293. return this.nextToken();
  2294. }
  2295. this.pos = pos + 2;
  2296. return this.finishToken(tokTypes.incDec, "--");
  2297. }
  2298. if (next === 61) {
  2299. this.pos = pos + 2;
  2300. return this.finishToken(tokTypes.assign, "-=");
  2301. }
  2302. this.pos = pos + 1;
  2303. return this.finishToken(tokTypes.plusMin, "-");
  2304. }
  2305. case 60: {
  2306. // '<': <<=, <<, <= or <; `<!--` opens an HTML line comment
  2307. const next = input.charCodeAt(pos + 1);
  2308. if (next === 60) {
  2309. if (input.charCodeAt(pos + 2) === 61) {
  2310. this.pos = pos + 3;
  2311. return this.finishToken(tokTypes.assign, "<<=");
  2312. }
  2313. this.pos = pos + 2;
  2314. return this.finishToken(tokTypes.bitShift, "<<");
  2315. }
  2316. if (
  2317. next === 33 &&
  2318. !this.inModule &&
  2319. input.charCodeAt(pos + 2) === 45 &&
  2320. input.charCodeAt(pos + 3) === 45
  2321. ) {
  2322. // `<!--` opens an HTML line comment (acorn readToken_lt_gt):
  2323. // https://github.com/acornjs/acorn/blob/8.15.0/acorn/src/tokenize.js#L620-L649
  2324. this.skipLineComment(4);
  2325. this.skipSpace();
  2326. return this.nextToken();
  2327. }
  2328. if (next === 61) {
  2329. this.pos = pos + 2;
  2330. return this.finishToken(tokTypes.relational, "<=");
  2331. }
  2332. this.pos = pos + 1;
  2333. return this.finishToken(tokTypes.relational, "<");
  2334. }
  2335. case 62: {
  2336. // '>': >>>=, >>>, >>=, >>, >= or >
  2337. const next = input.charCodeAt(pos + 1);
  2338. if (next === 62) {
  2339. if (input.charCodeAt(pos + 2) === 62) {
  2340. if (input.charCodeAt(pos + 3) === 61) {
  2341. this.pos = pos + 4;
  2342. return this.finishToken(tokTypes.assign, ">>>=");
  2343. }
  2344. this.pos = pos + 3;
  2345. return this.finishToken(tokTypes.bitShift, ">>>");
  2346. }
  2347. if (input.charCodeAt(pos + 2) === 61) {
  2348. this.pos = pos + 3;
  2349. return this.finishToken(tokTypes.assign, ">>=");
  2350. }
  2351. this.pos = pos + 2;
  2352. return this.finishToken(tokTypes.bitShift, ">>");
  2353. }
  2354. if (next === 61) {
  2355. this.pos = pos + 2;
  2356. return this.finishToken(tokTypes.relational, ">=");
  2357. }
  2358. this.pos = pos + 1;
  2359. return this.finishToken(tokTypes.relational, ">");
  2360. }
  2361. case 61: {
  2362. // '=': ===, ==, => or =
  2363. const next = input.charCodeAt(pos + 1);
  2364. if (next === 61) {
  2365. if (input.charCodeAt(pos + 2) === 61) {
  2366. this.pos = pos + 3;
  2367. return this.finishToken(tokTypes.equality, "===");
  2368. }
  2369. this.pos = pos + 2;
  2370. return this.finishToken(tokTypes.equality, "==");
  2371. }
  2372. if (next === 62) {
  2373. this.pos = pos + 2;
  2374. return this.finishToken(tokTypes.arrow);
  2375. }
  2376. this.pos = pos + 1;
  2377. return this.finishToken(tokTypes.eq, "=");
  2378. }
  2379. case 33: {
  2380. // '!': !==, != or !
  2381. const next = input.charCodeAt(pos + 1);
  2382. if (next === 61) {
  2383. if (input.charCodeAt(pos + 2) === 61) {
  2384. this.pos = pos + 3;
  2385. return this.finishToken(tokTypes.equality, "!==");
  2386. }
  2387. this.pos = pos + 2;
  2388. return this.finishToken(tokTypes.equality, "!=");
  2389. }
  2390. this.pos = pos + 1;
  2391. return this.finishToken(tokTypes.prefix, "!");
  2392. }
  2393. case 63: {
  2394. // '?': ?. (not before a digit), ??=, ?? or ?
  2395. const next = input.charCodeAt(pos + 1);
  2396. if (next === 46) {
  2397. const next2 = input.charCodeAt(pos + 2);
  2398. if (next2 < 48 || next2 > 57) {
  2399. this.pos = pos + 2;
  2400. return this.finishToken(tokTypes.questionDot, "?.");
  2401. }
  2402. }
  2403. if (next === 63) {
  2404. if (input.charCodeAt(pos + 2) === 61) {
  2405. this.pos = pos + 3;
  2406. return this.finishToken(tokTypes.assign, "??=");
  2407. }
  2408. this.pos = pos + 2;
  2409. return this.finishToken(tokTypes.coalesce, "??");
  2410. }
  2411. this.pos = pos + 1;
  2412. return this.finishToken(tokTypes.question, "?");
  2413. }
  2414. case 126: {
  2415. // '~'
  2416. this.pos = pos + 1;
  2417. return this.finishToken(tokTypes.prefix, "~");
  2418. }
  2419. case 96: {
  2420. // '`'
  2421. this.pos = pos + 1;
  2422. return this.finishToken(tokTypes.backQuote);
  2423. }
  2424. case 48: {
  2425. // '0': radix literals split off before the decimal reader
  2426. const next = input.charCodeAt(pos + 1);
  2427. if (next === 120 || next === 88) return this._readRadixNumber(16);
  2428. if (next === 111 || next === 79) return this._readRadixNumber(8);
  2429. if (next === 98 || next === 66) return this._readRadixNumber(2);
  2430. return this.readNumber(false);
  2431. }
  2432. case 49:
  2433. case 50:
  2434. case 51:
  2435. case 52:
  2436. case 53:
  2437. case 54:
  2438. case 55:
  2439. case 56:
  2440. case 57:
  2441. return this.readNumber(false);
  2442. case 34:
  2443. case 39:
  2444. return this.readString(code);
  2445. default:
  2446. return this._getUnknownOrPrivate(code);
  2447. }
  2448. }
  2449. /**
  2450. * ASCII fast path for acorn's `readWord1`, which pays a surrogate-aware
  2451. * method call and a range-check helper per character. Escapes, non-ASCII
  2452. * and astral input restart the owned cold reader from the word start.
  2453. * Words are deduplicated through `WORD_CACHE` so repeated identifiers —
  2454. * which dominate real code — reuse one string instead of slicing a fresh
  2455. * one per occurrence; sharing also keeps their cached string hashes warm
  2456. * for the keyword/scope Map lookups downstream.
  2457. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2458. * @this {ParserInternals}
  2459. * @returns {string} the word
  2460. */
  2461. readWord1() {
  2462. const input = this.input;
  2463. const start = this.pos;
  2464. const len = input.length;
  2465. // djb2-style hash folded into the scan loop (yuku scans each lexeme in
  2466. // one pass); computing it for the rare over-long words is cheaper than
  2467. // re-walking every word in a second pass
  2468. let hash = 0;
  2469. let pos = start;
  2470. while (pos < len) {
  2471. const ch = input.charCodeAt(pos);
  2472. if (ch < 128) {
  2473. if (IDENT_CHAR[ch] === 0) {
  2474. // backslash escape: restart cold so escape rules see the word
  2475. if (ch === 92) return this._readWord1Cold();
  2476. break;
  2477. }
  2478. hash = (Math.imul(hash, 33) + ch) | 0;
  2479. pos++;
  2480. } else {
  2481. return this._readWord1Cold();
  2482. }
  2483. }
  2484. this.containsEsc = false;
  2485. this.pos = pos;
  2486. const wordLen = pos - start;
  2487. // Single-char words skip the cache (V8 serves those slices from its
  2488. // single-character table without allocating); long words skip it too.
  2489. if (wordLen >= 2 && wordLen <= WORD_CACHE_MAX_LEN) {
  2490. const slot = hash & WORD_CACHE_MASK;
  2491. const cached = WORD_CACHE[slot];
  2492. if (
  2493. cached !== null &&
  2494. cached.length === wordLen &&
  2495. // length already matched, so a prefix test is an exact compare —
  2496. // one builtin instead of a charCodeAt loop per cached character
  2497. input.startsWith(cached, start)
  2498. ) {
  2499. return cached;
  2500. }
  2501. const word = input.slice(start, pos);
  2502. WORD_CACHE[slot] = word;
  2503. WORD_TYPE_OWNERS[slot] = 0;
  2504. return word;
  2505. }
  2506. return input.slice(start, pos);
  2507. }
  2508. /**
  2509. * String fast path: one scan finds the closing quote and cooks the common
  2510. * single-char escapes (`\n \t \\ \" \'` …) and line continuations inline.
  2511. * Hex/unicode/octal escapes (`\x`, `\u`, `\0`-`\9`) restart the owned cold
  2512. * reader, which owns their readers and strict-mode errors; old ecmaVersions
  2513. * (LS/PS terminate strings there) and location tracking use acorn's own.
  2514. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2515. * @this {ParserInternals}
  2516. * @param {number} quote quote char code
  2517. * @returns {void}
  2518. */
  2519. readString(quote) {
  2520. if (!this._noLocations || this._ecmaVersion < 10) {
  2521. return base.readString.call(this, quote);
  2522. }
  2523. const input = this.input;
  2524. const len = input.length;
  2525. const quotePos = this.pos;
  2526. const start = quotePos + 1;
  2527. let pos = start;
  2528. // spans between escapes accumulate here; a plain string never touches
  2529. // `out` and slices once at the end
  2530. let out = "";
  2531. let chunkStart = start;
  2532. for (;;) {
  2533. if (pos >= len) this.raise(this.start, "Unterminated string constant");
  2534. const ch = input.charCodeAt(pos);
  2535. if (ch === quote) break;
  2536. if (ch === 92) {
  2537. const esc = input.charCodeAt(pos + 1);
  2538. // hex/unicode/octal escapes (and a trailing `\`) need the cold
  2539. // reader's escape handling; restart from the quote (this.pos unmoved)
  2540. if (
  2541. pos + 1 >= len ||
  2542. esc === 120 ||
  2543. esc === 117 ||
  2544. (esc >= 48 && esc <= 57)
  2545. ) {
  2546. this.pos = quotePos;
  2547. return this._readStringCold(quote);
  2548. }
  2549. let rep;
  2550. let advance = 2;
  2551. switch (esc) {
  2552. case 110:
  2553. rep = "\n";
  2554. break;
  2555. case 114:
  2556. rep = "\r";
  2557. break;
  2558. case 116:
  2559. rep = "\t";
  2560. break;
  2561. case 98:
  2562. rep = "\b";
  2563. break;
  2564. case 102:
  2565. rep = "\f";
  2566. break;
  2567. case 118:
  2568. rep = "\u000B";
  2569. break;
  2570. case 13:
  2571. // `\` + CR(LF): line continuation cooked away
  2572. rep = "";
  2573. if (input.charCodeAt(pos + 2) === 10) advance = 3;
  2574. break;
  2575. case 10:
  2576. case 0x2028:
  2577. case 0x2029:
  2578. rep = "";
  2579. break;
  2580. default:
  2581. // any other escape is the escaped code unit verbatim (`\\`, `\q`)
  2582. rep = input[pos + 1];
  2583. }
  2584. out += input.slice(chunkStart, pos) + rep;
  2585. pos += advance;
  2586. chunkStart = pos;
  2587. } else if (ch === 10 || ch === 13) {
  2588. // bare LF/CR is unterminated; LS/PS stay valid at ES2019+
  2589. this.raise(this.start, "Unterminated string constant");
  2590. } else {
  2591. pos++;
  2592. }
  2593. }
  2594. this.pos = pos + 1;
  2595. if (chunkStart === start) {
  2596. return this.finishToken(tokTypes.string, input.slice(start, pos));
  2597. }
  2598. this.finishToken(tokTypes.string, out + input.slice(chunkStart, pos));
  2599. }
  2600. /**
  2601. * Number fast path: plain integer literals (no leading zero, up to 15
  2602. * digits so the float is exact) are accumulated numerically — no slice,
  2603. * no parseFloat, no separator handling. Everything else (dots, exponents,
  2604. * bigints, separators, octal forms) restarts the owned cold reader.
  2605. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2606. * @this {ParserInternals}
  2607. * @param {boolean} startsWithDot whether the number started with a dot
  2608. * @returns {void}
  2609. */
  2610. readNumber(startsWithDot) {
  2611. if (startsWithDot) return this._readNumberCold(startsWithDot);
  2612. const input = this.input;
  2613. const start = this.pos;
  2614. const len = input.length;
  2615. const first = input.charCodeAt(start);
  2616. let pos;
  2617. if (first === 48) {
  2618. const c1 = start + 1 < len ? input.charCodeAt(start + 1) : 0;
  2619. if (c1 === 46) {
  2620. // `0.<digits>`
  2621. pos = start + 1;
  2622. } else if (c1 > 127 || IDENT_CHAR[c1] === 1) {
  2623. // 0x/0o/0b, 0e…, 0n, 0_, legacy `0NN`, or `0`+identifier: acorn
  2624. return this._readNumberCold(startsWithDot);
  2625. } else {
  2626. // bare `0` before punctuation/operator/whitespace/EOF
  2627. this.pos = start + 1;
  2628. return this.finishToken(tokTypes.num, 0);
  2629. }
  2630. } else if (first > 48 && first <= 57) {
  2631. // integer digits, accumulated numerically for the integer-only case
  2632. let value = first - 48;
  2633. pos = start + 1;
  2634. while (pos < len) {
  2635. const ch = input.charCodeAt(pos);
  2636. if (ch >= 48 && ch <= 57) {
  2637. value = value * 10 + (ch - 48);
  2638. pos++;
  2639. } else {
  2640. break;
  2641. }
  2642. }
  2643. const after = pos < len ? input.charCodeAt(pos) : 0;
  2644. if (after !== 46) {
  2645. // no fraction: exponent, separator, bigint suffix or a trailing
  2646. // identifier char all need acorn's full handling and exact errors
  2647. if (
  2648. after === 101 ||
  2649. after === 69 ||
  2650. after === 95 ||
  2651. after === 110 ||
  2652. after > 127 ||
  2653. IDENT_CHAR[after] === 1
  2654. ) {
  2655. return this._readNumberCold(startsWithDot);
  2656. }
  2657. // 15 digits always fit exactly into a double
  2658. if (pos - start > 15) {
  2659. return this._readNumberCold(startsWithDot);
  2660. }
  2661. this.pos = pos;
  2662. return this.finishToken(tokTypes.num, value);
  2663. }
  2664. // a fraction follows the integer part
  2665. } else {
  2666. return this._readNumberCold(startsWithDot);
  2667. }
  2668. // decimal fraction: `pos` is at the '.'
  2669. pos++;
  2670. while (pos < len) {
  2671. const ch = input.charCodeAt(pos);
  2672. if (ch >= 48 && ch <= 57) pos++;
  2673. else break;
  2674. }
  2675. const after = pos < len ? input.charCodeAt(pos) : 0;
  2676. // exponent, a second dot, separator, bigint suffix or trailing identifier
  2677. if (
  2678. after === 46 ||
  2679. after === 101 ||
  2680. after === 69 ||
  2681. after === 95 ||
  2682. after === 110 ||
  2683. after > 127 ||
  2684. IDENT_CHAR[after] === 1
  2685. ) {
  2686. return this._readNumberCold(startsWithDot);
  2687. }
  2688. this.pos = pos;
  2689. this.finishToken(tokTypes.num, Number.parseFloat(input.slice(start, pos)));
  2690. }
  2691. /**
  2692. * Owned `strictDirective`: acorn's runs an anchored literal regex over
  2693. * `this.input.slice(start)` — a fresh sliced string per (sloppy-mode)
  2694. * function body. Sticky regexes at the offset scan the same grammar with no
  2695. * slice. Same directive-prologue semantics, including the ASI tail checks.
  2696. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/parseutil.js
  2697. * @param {number} start offset of the function body's first statement
  2698. * @returns {boolean} true when a 'use strict' directive leads the prologue
  2699. * @this {ParserInternals & { input: string, options: { ecmaVersion: number } }}
  2700. */
  2701. strictDirective(start) {
  2702. if (/** @type {number} */ (this.options.ecmaVersion) < 5) return false;
  2703. const input = this.input;
  2704. for (;;) {
  2705. // Skip whitespace and comments (acorn's `skipWhiteSpace`, sticky).
  2706. STRICT_SKIP_WS.lastIndex = start;
  2707. start += /** @type {RegExpExecArray} */ (STRICT_SKIP_WS.exec(input))[0]
  2708. .length;
  2709. STRICT_LITERAL.lastIndex = start;
  2710. const match = STRICT_LITERAL.exec(input);
  2711. if (!match) return false;
  2712. if ((match[1] || match[2]) === "use strict") {
  2713. STRICT_SKIP_WS.lastIndex = start + match[0].length;
  2714. const spaceAfter = /** @type {RegExpExecArray} */ (
  2715. STRICT_SKIP_WS.exec(input)
  2716. );
  2717. const end = spaceAfter.index + spaceAfter[0].length;
  2718. const next = input.charAt(end);
  2719. return (
  2720. next === ";" ||
  2721. next === "}" ||
  2722. (STRICT_LINE_BREAK.test(spaceAfter[0]) &&
  2723. !(
  2724. /[(`.[+\-/*%<>=,?^&]/.test(next) ||
  2725. (next === "!" && input.charAt(end + 1) === "=")
  2726. ))
  2727. );
  2728. }
  2729. start += match[0].length;
  2730. // Skip semicolon, if any.
  2731. STRICT_SKIP_WS.lastIndex = start;
  2732. start += /** @type {RegExpExecArray} */ (STRICT_SKIP_WS.exec(input))[0]
  2733. .length;
  2734. if (input[start] === ";") start++;
  2735. }
  2736. }
  2737. /**
  2738. * Template fast path: when the chunk contains no backslash and no CR, the
  2739. * cooked value is one slice (LF/LS/PS cook to themselves). Escapes and CR
  2740. * normalization restart the owned cold reader (its exact errors); location
  2741. * tracking uses acorn's own.
  2742. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2743. * @this {ParserInternals}
  2744. * @returns {void}
  2745. */
  2746. readTmplToken() {
  2747. if (!this._noLocations) return base.readTmplToken.call(this);
  2748. const input = this.input;
  2749. const start = this.pos;
  2750. const len = input.length;
  2751. let pos = start;
  2752. while (pos < len) {
  2753. const ch = input.charCodeAt(pos);
  2754. if (ch === 96 || (ch === 36 && input.charCodeAt(pos + 1) === 123)) {
  2755. if (
  2756. pos === this.start &&
  2757. (this.type === tokTypes.template ||
  2758. this.type === tokTypes.invalidTemplate)
  2759. ) {
  2760. if (ch === 36) {
  2761. this.pos = pos + 2;
  2762. return this.finishToken(tokTypes.dollarBraceL);
  2763. }
  2764. this.pos = pos + 1;
  2765. return this.finishToken(tokTypes.backQuote);
  2766. }
  2767. this.pos = pos;
  2768. return this.finishToken(tokTypes.template, input.slice(start, pos));
  2769. }
  2770. // backslash and CR need the cooked-string building of the cold reader
  2771. if (ch === 92 || ch === 13) {
  2772. return this._readTmplTokenCold();
  2773. }
  2774. pos++;
  2775. }
  2776. this.raise(this.start, "Unterminated template");
  2777. }
  2778. /**
  2779. * Fast path for the common run of plain ASCII whitespace; comments and
  2780. * unicode whitespace use the owned cold reader, location tracking acorn's.
  2781. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2782. * @this {ParserInternals & { pos: number }}
  2783. * @returns {void}
  2784. */
  2785. skipSpace() {
  2786. if (!this._noLocations) return base.skipSpace.call(this);
  2787. const input = this.input;
  2788. const len = input.length;
  2789. let pos = this.pos;
  2790. while (pos < len) {
  2791. const ch = input.charCodeAt(pos);
  2792. // 9-13 and 32 cover tab, LF, VT, FF, CR and space
  2793. if (ch === 32 || (ch > 8 && ch < 14)) {
  2794. pos++;
  2795. } else if (ch === 47 || ch > 127) {
  2796. // comments or unicode whitespace: hand off to the cold reader
  2797. this.pos = pos;
  2798. return this._skipSpaceCold();
  2799. } else {
  2800. break;
  2801. }
  2802. }
  2803. this.pos = pos;
  2804. }
  2805. // ----- cold-path readers (ported from acorn's tokenizer, reached only from
  2806. // the lazy fast paths above; non-lazy mode keeps acorn's own prototype
  2807. // methods so plugins that patch them still see acorn's tokenizer) -----
  2808. /**
  2809. * acorn `readInt`: reads `radix`-base digits (optionally exactly `len` of
  2810. * them), honoring ES2021 `_` separators.
  2811. * https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2812. * @this {ParserInternals}
  2813. * @param {number} radix numeric radix
  2814. * @param {number=} len fixed digit count (for escapes), else read greedily
  2815. * @param {boolean=} maybeLegacyOctal whether a leading zero disallows separators
  2816. * @returns {number | null} the integer value, or null when no digits matched
  2817. */
  2818. _readInt(radix, len, maybeLegacyOctal) {
  2819. const input = this.input;
  2820. const allowSeparators = this._ecmaVersion >= 12 && len === undefined;
  2821. const isLegacyOctal =
  2822. maybeLegacyOctal === true && input.charCodeAt(this.pos) === 48;
  2823. const start = this.pos;
  2824. let total = 0;
  2825. let lastCode = 0;
  2826. for (
  2827. let i = 0, e = len === undefined ? Infinity : len;
  2828. i < e;
  2829. ++i, ++this.pos
  2830. ) {
  2831. const code = input.charCodeAt(this.pos);
  2832. let val;
  2833. if (allowSeparators && code === 95) {
  2834. if (isLegacyOctal) {
  2835. this.raiseRecoverable(
  2836. this.pos,
  2837. "Numeric separator is not allowed in legacy octal numeric literals"
  2838. );
  2839. }
  2840. if (lastCode === 95) {
  2841. this.raiseRecoverable(
  2842. this.pos,
  2843. "Numeric separator must be exactly one underscore"
  2844. );
  2845. }
  2846. if (i === 0) {
  2847. this.raiseRecoverable(
  2848. this.pos,
  2849. "Numeric separator is not allowed at the first of digits"
  2850. );
  2851. }
  2852. lastCode = code;
  2853. continue;
  2854. }
  2855. if (code >= 97) val = code - 97 + 10;
  2856. else if (code >= 65) val = code - 65 + 10;
  2857. else if (code >= 48 && code <= 57) val = code - 48;
  2858. else val = Infinity;
  2859. if (val >= radix) break;
  2860. lastCode = code;
  2861. total = total * radix + val;
  2862. }
  2863. if (allowSeparators && lastCode === 95) {
  2864. this.raiseRecoverable(
  2865. this.pos - 1,
  2866. "Numeric separator is not allowed at the last of digits"
  2867. );
  2868. }
  2869. if (this.pos === start || (len !== undefined && this.pos - start !== len)) {
  2870. return null;
  2871. }
  2872. return total;
  2873. }
  2874. /**
  2875. * acorn `readRadixNumber`: `0x`/`0o`/`0b` integer or bigint literals.
  2876. * https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2877. * @this {ParserInternals}
  2878. * @param {number} radix numeric radix (2/8/16)
  2879. * @returns {void}
  2880. */
  2881. _readRadixNumber(radix) {
  2882. const input = this.input;
  2883. const start = this.pos;
  2884. this.pos += 2;
  2885. let val = this._readInt(radix);
  2886. if (val === null) {
  2887. this.raise(this.start + 2, `Expected number in radix ${radix}`);
  2888. }
  2889. if (this._ecmaVersion >= 11 && input.charCodeAt(this.pos) === 110) {
  2890. val = /** @type {EXPECTED_ANY} */ (
  2891. stringToBigInt(input.slice(start, this.pos))
  2892. );
  2893. ++this.pos;
  2894. } else if (isIdentifierStart(this.fullCharCodeAtPos())) {
  2895. this.raise(this.pos, "Identifier directly after number");
  2896. }
  2897. return this.finishToken(tokTypes.num, val);
  2898. }
  2899. /**
  2900. * acorn `readNumber`: decimal/float/legacy-octal/bigint literals (the fast
  2901. * path handles only plain integers and simple fractions).
  2902. * https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2903. * @this {ParserInternals}
  2904. * @param {boolean} startsWithDot whether the literal started with `.`
  2905. * @returns {void}
  2906. */
  2907. _readNumberCold(startsWithDot) {
  2908. const input = this.input;
  2909. const start = this.pos;
  2910. if (!startsWithDot && this._readInt(10, undefined, true) === null) {
  2911. this.raise(start, "Invalid number");
  2912. }
  2913. let octal = this.pos - start >= 2 && input.charCodeAt(start) === 48;
  2914. if (octal && this.strict) this.raise(start, "Invalid number");
  2915. let next = input.charCodeAt(this.pos);
  2916. if (!octal && !startsWithDot && this._ecmaVersion >= 11 && next === 110) {
  2917. const val = stringToBigInt(input.slice(start, this.pos));
  2918. ++this.pos;
  2919. if (isIdentifierStart(this.fullCharCodeAtPos())) {
  2920. this.raise(this.pos, "Identifier directly after number");
  2921. }
  2922. return this.finishToken(tokTypes.num, /** @type {EXPECTED_ANY} */ (val));
  2923. }
  2924. if (octal && /[89]/.test(input.slice(start, this.pos))) octal = false;
  2925. if (next === 46 && !octal) {
  2926. ++this.pos;
  2927. this._readInt(10);
  2928. next = input.charCodeAt(this.pos);
  2929. }
  2930. if ((next === 69 || next === 101) && !octal) {
  2931. next = input.charCodeAt(++this.pos);
  2932. if (next === 43 || next === 45) ++this.pos;
  2933. if (this._readInt(10) === null) this.raise(start, "Invalid number");
  2934. }
  2935. if (isIdentifierStart(this.fullCharCodeAtPos())) {
  2936. this.raise(this.pos, "Identifier directly after number");
  2937. }
  2938. const val = stringToNumber(input.slice(start, this.pos), octal);
  2939. return this.finishToken(tokTypes.num, val);
  2940. }
  2941. /**
  2942. * acorn `readCodePoint`: a `\u{...}` or `\uXXXX` escape.
  2943. * https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2944. * @this {ParserInternals}
  2945. * @returns {number} the escaped code point
  2946. */
  2947. _readCodePoint() {
  2948. const input = this.input;
  2949. const ch = input.charCodeAt(this.pos);
  2950. let code;
  2951. if (ch === 123) {
  2952. if (this._ecmaVersion < 6) this.unexpected();
  2953. const codePos = ++this.pos;
  2954. code = this._readHexChar(input.indexOf("}", this.pos) - this.pos);
  2955. ++this.pos;
  2956. if (code > 0x10ffff) {
  2957. this.invalidStringToken(codePos, "Code point out of bounds");
  2958. }
  2959. } else {
  2960. code = this._readHexChar(4);
  2961. }
  2962. return code;
  2963. }
  2964. /**
  2965. * acorn `readHexChar`: exactly `len` hex digits.
  2966. * https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2967. * @this {ParserInternals}
  2968. * @param {number} len number of hex digits
  2969. * @returns {number} the parsed code
  2970. */
  2971. _readHexChar(len) {
  2972. const codePos = this.pos;
  2973. const n = this._readInt(16, len);
  2974. if (n === null) {
  2975. this.invalidStringToken(codePos, "Bad character escape sequence");
  2976. }
  2977. return /** @type {number} */ (n);
  2978. }
  2979. /**
  2980. * acorn `readString`: the escape-bearing string reader (the fast path cooks
  2981. * only the common single-char escapes inline).
  2982. * https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  2983. * @this {ParserInternals}
  2984. * @param {number} quote quote char code
  2985. * @returns {void}
  2986. */
  2987. _readStringCold(quote) {
  2988. const input = this.input;
  2989. let out = "";
  2990. let chunkStart = ++this.pos;
  2991. for (;;) {
  2992. if (this.pos >= input.length) {
  2993. this.raise(this.start, "Unterminated string constant");
  2994. }
  2995. const ch = input.charCodeAt(this.pos);
  2996. if (ch === quote) break;
  2997. if (ch === 92) {
  2998. out += input.slice(chunkStart, this.pos);
  2999. out += this._readEscapedChar(false);
  3000. chunkStart = this.pos;
  3001. } else if (ch === 0x2028 || ch === 0x2029) {
  3002. if (this._ecmaVersion < 10) {
  3003. this.raise(this.start, "Unterminated string constant");
  3004. }
  3005. ++this.pos;
  3006. } else {
  3007. if (isNewLine(ch)) {
  3008. this.raise(this.start, "Unterminated string constant");
  3009. }
  3010. ++this.pos;
  3011. }
  3012. }
  3013. out += input.slice(chunkStart, this.pos++);
  3014. return this.finishToken(tokTypes.string, out);
  3015. }
  3016. /**
  3017. * acorn `readTmplToken`: the escape/CR-normalizing template reader. Invalid
  3018. * escapes throw acorn's sentinel via `invalidStringToken`, which acorn's own
  3019. * `tryReadTemplateToken` (not overridden here) catches to re-read raw.
  3020. * https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  3021. * @this {ParserInternals}
  3022. * @returns {void}
  3023. */
  3024. _readTmplTokenCold() {
  3025. const input = this.input;
  3026. let out = "";
  3027. let chunkStart = this.pos;
  3028. for (;;) {
  3029. if (this.pos >= input.length) {
  3030. this.raise(this.start, "Unterminated template");
  3031. }
  3032. const ch = input.charCodeAt(this.pos);
  3033. if (ch === 96 || (ch === 36 && input.charCodeAt(this.pos + 1) === 123)) {
  3034. if (
  3035. this.pos === this.start &&
  3036. (this.type === tokTypes.template ||
  3037. this.type === tokTypes.invalidTemplate)
  3038. ) {
  3039. if (ch === 36) {
  3040. this.pos += 2;
  3041. return this.finishToken(tokTypes.dollarBraceL);
  3042. }
  3043. ++this.pos;
  3044. return this.finishToken(tokTypes.backQuote);
  3045. }
  3046. out += input.slice(chunkStart, this.pos);
  3047. return this.finishToken(tokTypes.template, out);
  3048. }
  3049. if (ch === 92) {
  3050. out += input.slice(chunkStart, this.pos);
  3051. out += this._readEscapedChar(true);
  3052. chunkStart = this.pos;
  3053. } else if (isNewLine(ch)) {
  3054. out += input.slice(chunkStart, this.pos);
  3055. ++this.pos;
  3056. if (ch === 13 && input.charCodeAt(this.pos) === 10) ++this.pos;
  3057. out += "\n";
  3058. chunkStart = this.pos;
  3059. } else {
  3060. ++this.pos;
  3061. }
  3062. }
  3063. }
  3064. /**
  3065. * acorn `readEscapedChar`: cooks one backslash escape in a string/template.
  3066. * https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  3067. * @this {ParserInternals}
  3068. * @param {boolean} inTemplate whether the escape is in a template literal
  3069. * @returns {string} the cooked replacement (may be `""`)
  3070. */
  3071. _readEscapedChar(inTemplate) {
  3072. const input = this.input;
  3073. let ch = input.charCodeAt(++this.pos);
  3074. ++this.pos;
  3075. switch (ch) {
  3076. case 110:
  3077. return "\n";
  3078. case 114:
  3079. return "\r";
  3080. case 120:
  3081. return String.fromCharCode(this._readHexChar(2));
  3082. case 117:
  3083. return codePointToString(this._readCodePoint());
  3084. case 116:
  3085. return "\t";
  3086. case 98:
  3087. return "\b";
  3088. case 118:
  3089. return "\u000B";
  3090. case 102:
  3091. return "\f";
  3092. case 13:
  3093. if (input.charCodeAt(this.pos) === 10) ++this.pos;
  3094. // falls through
  3095. case 10:
  3096. return "";
  3097. case 56:
  3098. case 57:
  3099. if (this.strict) {
  3100. this.invalidStringToken(this.pos - 1, "Invalid escape sequence");
  3101. }
  3102. if (inTemplate) {
  3103. this.invalidStringToken(
  3104. this.pos - 1,
  3105. "Invalid escape sequence in template string"
  3106. );
  3107. }
  3108. // falls through
  3109. default:
  3110. if (ch >= 48 && ch <= 55) {
  3111. let octalStr = /** @type {RegExpMatchArray} */ (
  3112. input.slice(this.pos - 1, this.pos + 2).match(/^[0-7]+/)
  3113. )[0];
  3114. let octal = Number.parseInt(octalStr, 8);
  3115. if (octal > 255) {
  3116. octalStr = octalStr.slice(0, -1);
  3117. octal = Number.parseInt(octalStr, 8);
  3118. }
  3119. this.pos += octalStr.length - 1;
  3120. ch = input.charCodeAt(this.pos);
  3121. if (
  3122. (octalStr !== "0" || ch === 56 || ch === 57) &&
  3123. (this.strict || inTemplate)
  3124. ) {
  3125. this.invalidStringToken(
  3126. this.pos - 1 - octalStr.length,
  3127. inTemplate
  3128. ? "Octal literal in template string"
  3129. : "Octal literal in strict mode"
  3130. );
  3131. }
  3132. return String.fromCharCode(octal);
  3133. }
  3134. if (isNewLine(ch)) return "";
  3135. return String.fromCharCode(ch);
  3136. }
  3137. }
  3138. /**
  3139. * acorn `readWord1`: the escape-/astral-aware identifier reader (the fast
  3140. * path handles pure-ASCII words).
  3141. * https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  3142. * @this {ParserInternals}
  3143. * @returns {string} the (possibly escape-cooked) word
  3144. */
  3145. _readWord1Cold() {
  3146. const input = this.input;
  3147. this.containsEsc = false;
  3148. let word = "";
  3149. let first = true;
  3150. let chunkStart = this.pos;
  3151. const astral = this._ecmaVersion >= 6;
  3152. while (this.pos < input.length) {
  3153. const ch = this.fullCharCodeAtPos();
  3154. if (isIdentifierChar(ch, astral)) {
  3155. this.pos += ch <= 0xffff ? 1 : 2;
  3156. } else if (ch === 92) {
  3157. this.containsEsc = true;
  3158. word += input.slice(chunkStart, this.pos);
  3159. const escStart = this.pos;
  3160. if (input.charCodeAt(++this.pos) !== 117) {
  3161. this.invalidStringToken(
  3162. this.pos,
  3163. "Expecting Unicode escape sequence \\uXXXX"
  3164. );
  3165. }
  3166. ++this.pos;
  3167. const esc = this._readCodePoint();
  3168. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) {
  3169. this.invalidStringToken(escStart, "Invalid Unicode escape");
  3170. }
  3171. word += codePointToString(esc);
  3172. chunkStart = this.pos;
  3173. } else {
  3174. break;
  3175. }
  3176. first = false;
  3177. }
  3178. return word + input.slice(chunkStart, this.pos);
  3179. }
  3180. /**
  3181. * acorn `skipSpace` (location-free): unicode whitespace and comments. Only
  3182. * reached from the lazy fast paths, which keep no line bookkeeping.
  3183. * https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  3184. * @this {ParserInternals}
  3185. * @returns {void}
  3186. */
  3187. _skipSpaceCold() {
  3188. const input = this.input;
  3189. const len = input.length;
  3190. loop: while (this.pos < len) {
  3191. const ch = input.charCodeAt(this.pos);
  3192. switch (ch) {
  3193. case 32:
  3194. case 160:
  3195. ++this.pos;
  3196. break;
  3197. case 13:
  3198. if (input.charCodeAt(this.pos + 1) === 10) ++this.pos;
  3199. // falls through
  3200. case 10:
  3201. case 8232:
  3202. case 8233:
  3203. ++this.pos;
  3204. break;
  3205. case 47:
  3206. switch (input.charCodeAt(this.pos + 1)) {
  3207. case 42:
  3208. this.skipBlockComment();
  3209. break;
  3210. case 47:
  3211. this.skipLineComment(2);
  3212. break;
  3213. default:
  3214. break loop;
  3215. }
  3216. break;
  3217. default:
  3218. if (
  3219. (ch > 8 && ch < 14) ||
  3220. (ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch)))
  3221. ) {
  3222. ++this.pos;
  3223. } else {
  3224. break loop;
  3225. }
  3226. }
  3227. }
  3228. }
  3229. /**
  3230. * acorn `readToken_numberSign` plus `getTokenFromCode`'s default: a private
  3231. * identifier (`#x`) or an unexpected-character error.
  3232. * https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  3233. * @this {ParserInternals}
  3234. * @param {number} code current char code
  3235. * @returns {void}
  3236. */
  3237. _getUnknownOrPrivate(code) {
  3238. if (code === 35 && this._ecmaVersion >= 13) {
  3239. ++this.pos;
  3240. const next = this.fullCharCodeAtPos();
  3241. if (isIdentifierStart(next, true) || next === 92) {
  3242. return this.finishToken(tokTypes.privateId, this.readWord1());
  3243. }
  3244. this.raise(this.pos, `Unexpected character '${codePointToString(next)}'`);
  3245. }
  3246. this.raise(this.pos, `Unexpected character '${codePointToString(code)}'`);
  3247. }
  3248. // ----- word classification (Map/Set lookups, replaces acorn's regexps) -----
  3249. /**
  3250. * Replaces acorn's `readWord`: `readWord1`'s ASCII fast path inlined so the
  3251. * token type can be memoized per `WORD_CACHE` slot (classification is pure in
  3252. * the word and the per-option keyword set) — a cache hit serves the type by
  3253. * identity compare instead of a keywords Map probe.
  3254. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  3255. * @this {ParserInternals}
  3256. * @returns {void}
  3257. */
  3258. readWord() {
  3259. const input = this.input;
  3260. const start = this.pos;
  3261. const len = input.length;
  3262. let hash = 0;
  3263. let pos = start;
  3264. while (pos < len) {
  3265. const ch = input.charCodeAt(pos);
  3266. if (ch < 128) {
  3267. if (IDENT_CHAR[ch] === 0) {
  3268. // backslash escape: restart cold so escape rules see the word
  3269. if (ch === 92) return this._finishWordSlow(this._readWord1Cold());
  3270. break;
  3271. }
  3272. hash = (Math.imul(hash, 33) + ch) | 0;
  3273. pos++;
  3274. } else {
  3275. return this._finishWordSlow(this._readWord1Cold());
  3276. }
  3277. }
  3278. this.containsEsc = false;
  3279. this.pos = pos;
  3280. const wordLen = pos - start;
  3281. if (wordLen >= 2 && wordLen <= WORD_CACHE_MAX_LEN) {
  3282. const slot = hash & WORD_CACHE_MASK;
  3283. const lookups = this._wordLookups;
  3284. const owner = lookups.id;
  3285. const cached = WORD_CACHE[slot];
  3286. /** @type {string} */
  3287. let word;
  3288. /** @type {TokenType} */
  3289. let type;
  3290. if (
  3291. cached !== null &&
  3292. cached.length === wordLen &&
  3293. // length already matched, so a prefix test is an exact compare —
  3294. // one builtin instead of a charCodeAt loop per cached character
  3295. input.startsWith(cached, start)
  3296. ) {
  3297. word = cached;
  3298. if (WORD_TYPE_OWNERS[slot] === owner) {
  3299. type = /** @type {TokenType} */ (WORD_TYPES[slot]);
  3300. } else {
  3301. type = classifyWord(cached, lookups.keywords);
  3302. WORD_TYPES[slot] = type;
  3303. WORD_TYPE_OWNERS[slot] = owner;
  3304. }
  3305. } else {
  3306. word = input.slice(start, pos);
  3307. WORD_CACHE[slot] = word;
  3308. type = classifyWord(word, lookups.keywords);
  3309. WORD_TYPES[slot] = type;
  3310. WORD_TYPE_OWNERS[slot] = owner;
  3311. }
  3312. if (type === tokTypes.name && this._inlineFinish) {
  3313. // finishToken(name) inlined: offset/type/value stores plus
  3314. // name.updateContext (as in the owned finishToken)
  3315. this.end = pos;
  3316. const prevType = this.type;
  3317. this.type = type;
  3318. this.value = word;
  3319. this.exprAllowed =
  3320. ((word === "of" && !this.exprAllowed) ||
  3321. (word === "yield" && this.inGeneratorContext())) &&
  3322. prevType !== tokTypes.dot &&
  3323. this._ecmaVersion >= 6;
  3324. return;
  3325. }
  3326. return this.finishToken(type, word);
  3327. }
  3328. // Every keyword is 2-10 chars, so a word outside the cacheable range is a
  3329. // plain name and can be neither `of` nor `yield`.
  3330. if (this._inlineFinish) {
  3331. this.end = pos;
  3332. this.type = tokTypes.name;
  3333. this.value = input.slice(start, pos);
  3334. this.exprAllowed = false;
  3335. return;
  3336. }
  3337. return this._finishWordSlow(input.slice(start, pos));
  3338. }
  3339. /**
  3340. * Uncached tail of `readWord`: escaped/non-ASCII, 1-char and over-long words.
  3341. * @this {ParserInternals}
  3342. * @param {string} word the word
  3343. * @returns {void}
  3344. */
  3345. _finishWordSlow(word) {
  3346. this.finishToken(classifyWord(word, this._wordLookups.keywords), word);
  3347. }
  3348. /**
  3349. * Mirror of acorn's `checkUnreserved` with its two per-identifier regexp
  3350. * tests (`keywords` and `reservedWords`/`reservedWordsStrict`) folded into a
  3351. * single `reservedKinds` lookup — one hash probe instead of two, and the
  3352. * common plain identifier misses it and returns. Branches and error
  3353. * messages match acorn exactly.
  3354. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  3355. * @param {Identifier} ref identifier node
  3356. * @this {ParserInternals}
  3357. */
  3358. checkUnreserved(ref) {
  3359. const { start, end, name } = ref;
  3360. // every reserved word and special name below is short lowercase ASCII, so
  3361. // most identifiers exit on this shape gate before any string compare
  3362. // (`yield`/`await`/`arguments` all pass it: lengths 5/5/9 ≤ reservedMaxLen,
  3363. // which keywords like `instanceof` keep at ≥ 10)
  3364. const lookups = this._wordLookups;
  3365. const nameLen = name.length;
  3366. if (nameLen < 2 || nameLen > lookups.reservedMaxLen) return;
  3367. const firstCC = name.charCodeAt(0);
  3368. if (firstCC < 97 || firstCC > 122) return;
  3369. // name-first ordering: acorn's `inGenerator`/`inAsync` are getters that
  3370. // walk the scope stack, so gate them behind the cheap string compare —
  3371. // a plain identifier never triggers them
  3372. if (name === "yield" && this.inGenerator) {
  3373. this.raiseRecoverable(
  3374. start,
  3375. "Cannot use 'yield' as identifier inside a generator"
  3376. );
  3377. } else if (name === "await" && this.inAsync) {
  3378. this.raiseRecoverable(
  3379. start,
  3380. "Cannot use 'await' as identifier inside an async function"
  3381. );
  3382. }
  3383. if (name === "arguments" && !(this.currentThisScope().flags & SCOPE_VAR)) {
  3384. this.raiseRecoverable(
  3385. start,
  3386. "Cannot use 'arguments' in class field initializer"
  3387. );
  3388. }
  3389. if ((name === "arguments" || name === "await") && this.inClassStaticBlock) {
  3390. this.raise(
  3391. start,
  3392. `Cannot use ${name} in class static initialization block`
  3393. );
  3394. }
  3395. const kind = lookups.reservedKinds.get(name);
  3396. if (kind === undefined) return;
  3397. if (kind === 1) {
  3398. this.raise(start, `Unexpected keyword '${name}'`);
  3399. }
  3400. if (
  3401. /** @type {number} */ (this.options.ecmaVersion) < 6 &&
  3402. this.input.slice(start, end).includes("\\")
  3403. ) {
  3404. return;
  3405. }
  3406. if (kind === 2 || (kind === 3 && this.strict)) {
  3407. if (name === "await" && !this.inAsync) {
  3408. this.raiseRecoverable(
  3409. start,
  3410. "Cannot use keyword 'await' outside an async function"
  3411. );
  3412. }
  3413. this.raiseRecoverable(start, `The keyword '${name}' is reserved`);
  3414. }
  3415. }
  3416. /**
  3417. * Owned `checkLValSimple`, an exact-semantics copy of acorn 8's with the
  3418. * strict-bind probe inlined: the constructor-installed Set stand-in is one
  3419. * `has` behind a length gate instead of a closure call per checked name.
  3420. * A runtime-replaced `reservedWordsStrictBind` falls back to `.test()`.
  3421. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/lval.js
  3422. * @param {Node} expr assignment/binding target
  3423. * @param {number=} bindingType acorn BIND_* binding type
  3424. * @param {Record<string, boolean> | null=} checkClashes param-name clash record
  3425. * @returns {void}
  3426. * @this {ParserInternals}
  3427. */
  3428. checkLValSimple(expr, bindingType, checkClashes) {
  3429. if (bindingType === undefined) bindingType = BIND_NONE;
  3430. const isBind = bindingType !== BIND_NONE;
  3431. const type = expr.type;
  3432. if (type === "Identifier") {
  3433. const name = /** @type {Identifier} */ (expr).name;
  3434. if (this.strict) {
  3435. const lookups = this._wordLookups;
  3436. let reserved;
  3437. if (this.reservedWordsStrictBind === lookups.reservedBindTest) {
  3438. const len = name.length;
  3439. reserved =
  3440. len >= lookups.reservedBindMinLen &&
  3441. len <= lookups.reservedBindMaxLen &&
  3442. lookups.reservedBindSet.has(name);
  3443. } else {
  3444. reserved = this.reservedWordsStrictBind.test(name);
  3445. }
  3446. if (reserved) {
  3447. this.raiseRecoverable(
  3448. expr.start,
  3449. `${isBind ? "Binding " : "Assigning to "}${name} in strict mode`
  3450. );
  3451. }
  3452. }
  3453. if (isBind) {
  3454. if (bindingType === BIND_LEXICAL && name === "let") {
  3455. this.raiseRecoverable(
  3456. expr.start,
  3457. "let is disallowed as a lexically bound name"
  3458. );
  3459. }
  3460. if (checkClashes) {
  3461. if (Object.prototype.hasOwnProperty.call(checkClashes, name)) {
  3462. this.raiseRecoverable(expr.start, "Argument name clash");
  3463. }
  3464. checkClashes[name] = true;
  3465. }
  3466. if (bindingType !== BIND_OUTSIDE) {
  3467. this.declareName(name, bindingType, expr.start);
  3468. }
  3469. }
  3470. return;
  3471. }
  3472. if (type === "ChainExpression") {
  3473. this.raiseRecoverable(
  3474. expr.start,
  3475. "Optional chaining cannot appear in left-hand side"
  3476. );
  3477. return;
  3478. }
  3479. if (type === "MemberExpression") {
  3480. if (isBind) {
  3481. this.raiseRecoverable(expr.start, "Binding member expression");
  3482. }
  3483. return;
  3484. }
  3485. if (type === "ParenthesizedExpression") {
  3486. if (isBind) {
  3487. this.raiseRecoverable(expr.start, "Binding parenthesized expression");
  3488. }
  3489. return this.checkLValSimple(
  3490. /** @type {Node} */ (
  3491. /** @type {Node & { expression?: Node }} */ (expr).expression
  3492. ),
  3493. bindingType,
  3494. checkClashes
  3495. );
  3496. }
  3497. this.raise(expr.start, `${isBind ? "Binding" : "Assigning to"} rvalue`);
  3498. }
  3499. /**
  3500. * Owned `checkLValPattern`, acorn's verbatim, so declarator/assignment
  3501. * targets stay on owned code down to `checkLValSimple`/`declareName`.
  3502. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/lval.js
  3503. * @param {Node} expr binding pattern
  3504. * @param {number=} bindingType acorn BIND_* binding type
  3505. * @param {Record<string, boolean> | null=} checkClashes param-name clash record
  3506. * @returns {void}
  3507. * @this {ParserInternals}
  3508. */
  3509. checkLValPattern(expr, bindingType, checkClashes) {
  3510. const type = expr.type;
  3511. if (type === "ObjectPattern") {
  3512. const properties = /** @type {Node & { properties: Node[] }} */ (expr)
  3513. .properties;
  3514. for (let i = 0; i < properties.length; i++) {
  3515. this.checkLValInnerPattern(properties[i], bindingType, checkClashes);
  3516. }
  3517. } else if (type === "ArrayPattern") {
  3518. const elements = /** @type {Node & { elements: (Node | null)[] }} */ (
  3519. expr
  3520. ).elements;
  3521. for (let i = 0; i < elements.length; i++) {
  3522. const element = elements[i];
  3523. if (element) {
  3524. this.checkLValInnerPattern(element, bindingType, checkClashes);
  3525. }
  3526. }
  3527. } else {
  3528. this.checkLValSimple(expr, bindingType, checkClashes);
  3529. }
  3530. }
  3531. /**
  3532. * Owned `checkLValInnerPattern`, acorn's verbatim.
  3533. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/lval.js
  3534. * @param {Node} expr pattern element
  3535. * @param {number=} bindingType acorn BIND_* binding type
  3536. * @param {Record<string, boolean> | null=} checkClashes param-name clash record
  3537. * @returns {void}
  3538. * @this {ParserInternals}
  3539. */
  3540. checkLValInnerPattern(expr, bindingType, checkClashes) {
  3541. const type = expr.type;
  3542. if (type === "Property") {
  3543. // AssignmentProperty has type === "Property"
  3544. this.checkLValInnerPattern(
  3545. /** @type {Node} */ (
  3546. /** @type {Node & { value?: Node }} */ (expr).value
  3547. ),
  3548. bindingType,
  3549. checkClashes
  3550. );
  3551. } else if (type === "AssignmentPattern") {
  3552. this.checkLValPattern(
  3553. /** @type {Node} */ (/** @type {Node & { left?: Node }} */ (expr).left),
  3554. bindingType,
  3555. checkClashes
  3556. );
  3557. } else if (type === "RestElement") {
  3558. this.checkLValPattern(
  3559. /** @type {Node} */ (
  3560. /** @type {Node & { argument?: Node }} */ (expr).argument
  3561. ),
  3562. bindingType,
  3563. checkClashes
  3564. );
  3565. } else {
  3566. this.checkLValPattern(expr, bindingType, checkClashes);
  3567. }
  3568. }
  3569. /**
  3570. * Replaces acorn's `canInsertSemicolon`, whose line-break check slices the
  3571. * inter-token gap and runs a regexp on it for every ASI decision (hundreds
  3572. * of thousands per file). Scan the gap for a line terminator instead — no
  3573. * slice, no regexp.
  3574. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/parseutil.js
  3575. * @returns {boolean} whether a semicolon may be inserted here
  3576. * @this {ParserInternals}
  3577. */
  3578. canInsertSemicolon() {
  3579. if (this.type === tokTypes.eof || this.type === tokTypes.braceR) {
  3580. return true;
  3581. }
  3582. // the owned nextToken already classified the gap; 2 (comment/unicode in
  3583. // the gap, or a token from acorn's tokenizer) falls back to the scan
  3584. return this._gapHasNewline();
  3585. }
  3586. // ----- comment collection without eager text slicing -----
  3587. /**
  3588. * Replaces acorn's `skipLineComment` when comments are collected lazily:
  3589. * the same scan, but no text slice and no position objects. Acorn calls
  3590. * this for `//`, hashbangs and HTML-style comments (varying `startSkip`).
  3591. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  3592. * @this {ParserInternals}
  3593. * @param {number} startSkip length of the comment opener
  3594. * @returns {void}
  3595. */
  3596. skipLineComment(startSkip) {
  3597. const comments = this._lazyComments;
  3598. if (comments === undefined) {
  3599. return base.skipLineComment.call(this, startSkip);
  3600. }
  3601. const input = this.input;
  3602. const start = this.pos;
  3603. const len = input.length;
  3604. let pos = start + startSkip;
  3605. while (pos < len) {
  3606. const ch = input.charCodeAt(pos);
  3607. // LF, CR, LS, PS terminate the comment but are not part of it
  3608. if (ch === 10 || ch === 13 || ch === 0x2028 || ch === 0x2029) break;
  3609. pos++;
  3610. }
  3611. this.pos = pos;
  3612. comments.push(new LazyComment(false, start + startSkip, start, pos, input));
  3613. }
  3614. /**
  3615. * Replaces acorn's `skipBlockComment` when comments are collected lazily.
  3616. * Locations are always off in lazy mode, so line breaks need no handling.
  3617. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  3618. * @this {ParserInternals}
  3619. * @returns {void}
  3620. */
  3621. skipBlockComment() {
  3622. const comments = this._lazyComments;
  3623. if (comments === undefined) {
  3624. return base.skipBlockComment.call(this);
  3625. }
  3626. const start = this.pos;
  3627. const end = this.input.indexOf("*/", (this.pos += 2));
  3628. if (end === -1) this.raise(this.pos - 2, "Unterminated comment");
  3629. this.pos = end + 2;
  3630. comments.push(
  3631. new LazyComment(true, start + 2, start, this.pos, this.input)
  3632. );
  3633. }
  3634. // ----- lazy range -----
  3635. /**
  3636. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/node.js
  3637. * @returns {Node} new node
  3638. * @this {ParserInternals}
  3639. */
  3640. startNode() {
  3641. if (!this._lazy) return base.startNode.call(this);
  3642. return new LazyLocNode(this.start);
  3643. }
  3644. /**
  3645. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/node.js
  3646. * @param {number} pos start offset
  3647. * @param {Position=} loc start position when acorn tracks locations
  3648. * @returns {Node} new node
  3649. * @this {ParserInternals}
  3650. */
  3651. startNodeAt(pos, loc) {
  3652. if (!this._lazy) return base.startNodeAt.call(this, pos, loc);
  3653. return new LazyLocNode(pos);
  3654. }
  3655. /**
  3656. * Lazy-mode `finishNode`: acorn's `locations`/`ranges` writes are dead when
  3657. * `range` is served lazily and `loc` not at all, so skip them and the `finishNodeAt`
  3658. * indirection. Runs once per node.
  3659. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/node.js
  3660. * @param {Node} node node to finish
  3661. * @param {string} type node type
  3662. * @returns {Node} the finished node
  3663. * @this {ParserInternals}
  3664. */
  3665. finishNode(node, type) {
  3666. if (!this._lazy) return base.finishNode.call(this, node, type);
  3667. node.type = type;
  3668. node.end = this.lastTokEnd;
  3669. return node;
  3670. }
  3671. /**
  3672. * Mirror of acorn's `copyNode`, which bypasses `startNodeAt` via
  3673. * `new Node(...)` and would otherwise produce non-lazy nodes.
  3674. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/node.js
  3675. * @param {Node} node node to copy
  3676. * @returns {Node} copied node
  3677. * @this {ParserInternals}
  3678. */
  3679. copyNode(node) {
  3680. const newNode = this.startNodeAt(node.start, this.startLoc);
  3681. const from = /** @type {Record<string, unknown>} */ (
  3682. /** @type {unknown} */ (node)
  3683. );
  3684. const to = /** @type {Record<string, unknown>} */ (
  3685. /** @type {unknown} */ (newNode)
  3686. );
  3687. for (const prop in from) to[prop] = from[prop];
  3688. return newNode;
  3689. }
  3690. // ----- owned node construction (single-shape nodes, replaces acorn's
  3691. // start-empty-then-mutate flow one node type at a time) -----
  3692. /**
  3693. * Owned `parseIdent` for the common name-token case: builds the finished
  3694. * `IdentifierNode` directly, skipping acorn's `parseIdentNode`/`startNode`/
  3695. * `finishNode` chain and its keyword branches. Keyword-as-identifier
  3696. * (`obj.class`) and non-lazy mode delegate to acorn.
  3697. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  3698. * @param {boolean=} liberal whether reserved words are allowed
  3699. * @returns {Identifier} identifier node
  3700. * @this {ParserInternals}
  3701. */
  3702. parseIdent(liberal) {
  3703. if (this.type !== tokTypes.name || !this._lazy) {
  3704. return base.parseIdent.call(this, liberal);
  3705. }
  3706. const node = /** @type {Identifier} */ (
  3707. /** @type {unknown} */ (
  3708. new IdentifierNode(
  3709. this.start,
  3710. this.end,
  3711. /** @type {string} */ (this.value)
  3712. )
  3713. )
  3714. );
  3715. this.next(Boolean(liberal));
  3716. if (!liberal) {
  3717. this.checkUnreserved(node);
  3718. if (node.name === "await" && !this.awaitIdentPos) {
  3719. this.awaitIdentPos = node.start;
  3720. }
  3721. }
  3722. return node;
  3723. }
  3724. /**
  3725. * Owned `parseSubscripts`, an exact-semantics copy of acorn 8's with the
  3726. * async-arrow-head probe reordered cheapest-first (all operands are pure)
  3727. * and the arrow exit probe served by `_lastArrow` identity instead of the
  3728. * megamorphic `.type` load. Delegates when either fast path is off.
  3729. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  3730. * @param {Expression} baseExpr subscript base
  3731. * @param {number} startPos expression start offset
  3732. * @param {Position | undefined} startLoc expression start position
  3733. * @param {boolean=} noCalls whether calls are forbidden (`new` callee)
  3734. * @param {boolean | string=} forInit for-init context flag
  3735. * @returns {Expression} expression with subscripts applied
  3736. * @this {ParserInternals}
  3737. */
  3738. parseSubscripts(baseExpr, startPos, startLoc, noCalls, forInit) {
  3739. if (!this._subscriptFastPath || !this._arrowFastPath) {
  3740. return base.parseSubscripts.call(
  3741. this,
  3742. baseExpr,
  3743. startPos,
  3744. startLoc,
  3745. noCalls,
  3746. forInit
  3747. );
  3748. }
  3749. // acorn's probe order is (ecmaVersion, type, name, offsets, ASI,
  3750. // potentialArrowAt); every operand is pure, so the SMI compares run
  3751. // first and the megamorphic `.type` load only when `async` matched
  3752. const maybeAsyncArrow =
  3753. baseExpr.start === this.potentialArrowAt &&
  3754. baseExpr.end - baseExpr.start === 5 &&
  3755. this.lastTokEnd === baseExpr.end &&
  3756. this._ecmaVersion >= 8 &&
  3757. /** @type {Identifier} */ (baseExpr).name === "async" &&
  3758. baseExpr.type === "Identifier" &&
  3759. !this.canInsertSemicolon();
  3760. let optionalChained = false;
  3761. for (;;) {
  3762. const element = this.parseSubscript(
  3763. baseExpr,
  3764. startPos,
  3765. startLoc,
  3766. noCalls,
  3767. maybeAsyncArrow,
  3768. optionalChained,
  3769. forInit
  3770. );
  3771. if (
  3772. /** @type {Expression & { optional?: boolean }} */ (element).optional
  3773. ) {
  3774. optionalChained = true;
  3775. }
  3776. if (element === baseExpr || element === this._lastArrow) {
  3777. if (optionalChained) {
  3778. const chainNode =
  3779. /** @type {Node & { expression?: Expression }} */
  3780. (this.startNodeAt(startPos, startLoc));
  3781. chainNode.expression = element;
  3782. return /** @type {Expression} */ (
  3783. /** @type {unknown} */ (
  3784. this.finishNode(
  3785. /** @type {Node} */ (chainNode),
  3786. "ChainExpression"
  3787. )
  3788. )
  3789. );
  3790. }
  3791. return element;
  3792. }
  3793. baseExpr = element;
  3794. }
  3795. }
  3796. /**
  3797. * Owned `parseSubscript`, an exact-semantics copy of acorn 8's with the
  3798. * node construction replaced: member and call nodes are built fully-formed
  3799. * after their property/arguments parse (the half-built node was never
  3800. * reachable during it), landing on `MemberExpressionNode`/
  3801. * `CallExpressionNode`'s single shapes. Pre-optional-chaining ecmaVersions
  3802. * and non-lazy mode delegate to acorn.
  3803. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  3804. * @param {Expression} baseExpr subscript base
  3805. * @param {number} startPos expression start offset
  3806. * @param {Position | undefined} startLoc expression start position
  3807. * @param {boolean | undefined} noCalls whether calls are forbidden (`new` callee)
  3808. * @param {boolean} maybeAsyncArrow whether this may be an async arrow head
  3809. * @param {boolean} optionalChained whether the chain is already optional
  3810. * @param {boolean | string} forInit for-init context flag
  3811. * @returns {Expression} subscript element or `baseExpr` when done
  3812. * @this {ParserInternals}
  3813. */
  3814. parseSubscript(
  3815. baseExpr,
  3816. startPos,
  3817. startLoc,
  3818. noCalls,
  3819. maybeAsyncArrow,
  3820. optionalChained,
  3821. forInit
  3822. ) {
  3823. if (!this._subscriptFastPath) {
  3824. return base.parseSubscript.call(
  3825. this,
  3826. baseExpr,
  3827. startPos,
  3828. startLoc,
  3829. noCalls,
  3830. maybeAsyncArrow,
  3831. optionalChained,
  3832. forInit
  3833. );
  3834. }
  3835. const optional = this.eat(tokTypes.questionDot);
  3836. if (noCalls && optional) {
  3837. this.raise(
  3838. this.lastTokStart,
  3839. "Optional chaining cannot appear in the callee of new expressions"
  3840. );
  3841. }
  3842. const computed = this.eat(tokTypes.bracketL);
  3843. if (
  3844. computed ||
  3845. (optional &&
  3846. this.type !== tokTypes.parenL &&
  3847. this.type !== tokTypes.backQuote) ||
  3848. this.eat(tokTypes.dot)
  3849. ) {
  3850. /** @type {Node} */
  3851. let property;
  3852. if (computed) {
  3853. property = this.parseExpression();
  3854. this.expect(tokTypes.bracketR);
  3855. } else if (
  3856. this.type === tokTypes.privateId &&
  3857. /** @type {string} */ (baseExpr.type) !== "Super"
  3858. ) {
  3859. property = this.parsePrivateIdent();
  3860. } else {
  3861. property = this.parseIdent(this.options.allowReserved !== "never");
  3862. }
  3863. return /** @type {Expression} */ (
  3864. /** @type {unknown} */ (
  3865. new MemberExpressionNode(
  3866. startPos,
  3867. this.lastTokEnd,
  3868. baseExpr,
  3869. property,
  3870. computed,
  3871. optional
  3872. )
  3873. )
  3874. );
  3875. } else if (!noCalls && this.eat(tokTypes.parenL)) {
  3876. const refDestructuringErrors = this._acquireDestructuringErrors();
  3877. const oldYieldPos = this.yieldPos;
  3878. const oldAwaitPos = this.awaitPos;
  3879. const oldAwaitIdentPos = this.awaitIdentPos;
  3880. this.yieldPos = 0;
  3881. this.awaitPos = 0;
  3882. this.awaitIdentPos = 0;
  3883. const exprList = this.parseExprList(
  3884. tokTypes.parenR,
  3885. true,
  3886. false,
  3887. refDestructuringErrors
  3888. );
  3889. if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {
  3890. this.checkPatternErrors(refDestructuringErrors, false);
  3891. this._releaseDestructuringErrors();
  3892. this.checkYieldAwaitInDefaultParams();
  3893. if (this.awaitIdentPos > 0) {
  3894. this.raise(
  3895. this.awaitIdentPos,
  3896. "Cannot use 'await' as identifier inside an async function"
  3897. );
  3898. }
  3899. this.yieldPos = oldYieldPos;
  3900. this.awaitPos = oldAwaitPos;
  3901. this.awaitIdentPos = oldAwaitIdentPos;
  3902. return this.parseSubscriptAsyncArrow(
  3903. startPos,
  3904. startLoc,
  3905. exprList,
  3906. forInit
  3907. );
  3908. }
  3909. this.checkExpressionErrors(refDestructuringErrors, true);
  3910. this._releaseDestructuringErrors();
  3911. this.yieldPos = oldYieldPos || this.yieldPos;
  3912. this.awaitPos = oldAwaitPos || this.awaitPos;
  3913. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  3914. return /** @type {Expression} */ (
  3915. /** @type {unknown} */ (
  3916. new CallExpressionNode(
  3917. startPos,
  3918. this.lastTokEnd,
  3919. baseExpr,
  3920. exprList,
  3921. optional
  3922. )
  3923. )
  3924. );
  3925. } else if (this.type === tokTypes.backQuote) {
  3926. if (optional || optionalChained) {
  3927. this.raise(
  3928. this.start,
  3929. "Optional chaining cannot appear in the tag of tagged template expressions"
  3930. );
  3931. }
  3932. const node = this.startNodeAt(startPos, startLoc);
  3933. /** @type {Node & { tag?: Expression, quasi?: Node }} */
  3934. (node).tag = baseExpr;
  3935. /** @type {Node & { tag?: Expression, quasi?: Node }} */
  3936. (node).quasi = this.parseTemplate({ isTagged: true });
  3937. return /** @type {Expression} */ (
  3938. /** @type {unknown} */ (
  3939. this.finishNode(node, "TaggedTemplateExpression")
  3940. )
  3941. );
  3942. }
  3943. return baseExpr;
  3944. }
  3945. /**
  3946. * Owned `parseStatement` for the hot statement heads: acorn starts a node
  3947. * before dispatching, but the owned statement parsers build their own
  3948. * single-shape nodes, so that started node was one discarded allocation per
  3949. * statement. Dispatch the common heads (`var`/`let`/`const`, `if`, `return`,
  3950. * blocks and plain expression statements) without it; everything rarer, the
  3951. * `name`-token ambiguities (`let`/`async`/`using`/`await` heads) and
  3952. * plugin-overridden parsers delegate to acorn.
  3953. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  3954. * @param {string | null} context statement context
  3955. * @param {boolean=} topLevel whether parsing top-level statements
  3956. * @param {unknown=} exports export tracking object
  3957. * @returns {Node} statement
  3958. * @this {ParserInternals}
  3959. */
  3960. parseStatement(context, topLevel, exports) {
  3961. if (!this._stmtFastPath) {
  3962. return base.parseStatement.call(this, context, topLevel, exports);
  3963. }
  3964. const startType = this.type;
  3965. switch (startType) {
  3966. case tokTypes._var:
  3967. case tokTypes._const: {
  3968. const kind = /** @type {string} */ (this.value);
  3969. if (context && kind !== "var") this.unexpected();
  3970. return this._parseVarStatementAt(this.start, kind);
  3971. }
  3972. case tokTypes._if:
  3973. return this._parseIfStatementAt(this.start);
  3974. case tokTypes._return:
  3975. return this._parseReturnStatementAt(this.start);
  3976. case tokTypes.braceL:
  3977. // the owned parseBlock never reads the started node
  3978. return this.parseBlock(true);
  3979. case tokTypes._function: {
  3980. if (!this._funcStmtOwn) {
  3981. return base.parseStatement.call(this, context, topLevel, exports);
  3982. }
  3983. // acorn's hanging-function guard (context = single-statement position)
  3984. if (
  3985. context &&
  3986. (this.strict || (context !== "if" && context !== "label"))
  3987. ) {
  3988. this.unexpected();
  3989. }
  3990. // parseFunctionStatement, inlined without the started node
  3991. const start = this.start;
  3992. this.next();
  3993. return this._parseFunctionAt(
  3994. start,
  3995. FUNC_STATEMENT | (context ? FUNC_HANGING_STATEMENT : 0),
  3996. false,
  3997. false,
  3998. undefined
  3999. );
  4000. }
  4001. case tokTypes._break:
  4002. case tokTypes._continue:
  4003. if (!this._stmt2FastPath) {
  4004. return base.parseStatement.call(this, context, topLevel, exports);
  4005. }
  4006. return this._parseBreakContinueStatementAt(
  4007. this.start,
  4008. /** @type {string} */ (startType.keyword)
  4009. );
  4010. case tokTypes._for:
  4011. if (!this._stmt2FastPath) {
  4012. return base.parseStatement.call(this, context, topLevel, exports);
  4013. }
  4014. return this._parseForStatementAt(this.start);
  4015. case tokTypes._switch:
  4016. if (!this._stmt2FastPath) {
  4017. return base.parseStatement.call(this, context, topLevel, exports);
  4018. }
  4019. return this._parseSwitchStatementAt(this.start);
  4020. case tokTypes._throw:
  4021. if (!this._stmt2FastPath) {
  4022. return base.parseStatement.call(this, context, topLevel, exports);
  4023. }
  4024. return this._parseThrowStatementAt(this.start);
  4025. case tokTypes._try:
  4026. if (!this._stmt2FastPath) {
  4027. return base.parseStatement.call(this, context, topLevel, exports);
  4028. }
  4029. return this._parseTryStatementAt(this.start);
  4030. case tokTypes._while:
  4031. if (!this._stmt2FastPath) {
  4032. return base.parseStatement.call(this, context, topLevel, exports);
  4033. }
  4034. return this._parseWhileStatementAt(this.start);
  4035. case tokTypes._debugger:
  4036. case tokTypes._do:
  4037. case tokTypes._class:
  4038. case tokTypes._with:
  4039. case tokTypes.semi:
  4040. case tokTypes._export:
  4041. case tokTypes._import:
  4042. return base.parseStatement.call(this, context, topLevel, exports);
  4043. default: {
  4044. if (startType === tokTypes.name) {
  4045. const value = this.value;
  4046. if (value === "let") {
  4047. if (this.isLet(context)) {
  4048. // mirrors acorn's `context && kind !== "var"` rejection
  4049. if (context) this.unexpected();
  4050. return this._parseVarStatementAt(this.start, "let");
  4051. }
  4052. // `let` as a plain identifier: expression/label tail below
  4053. } else if (
  4054. value === "async" ||
  4055. value === "using" ||
  4056. value === "await"
  4057. ) {
  4058. // async functions and using declarations keep acorn's
  4059. // lookahead-heavy classification
  4060. return base.parseStatement.call(this, context, topLevel, exports);
  4061. }
  4062. }
  4063. // unambiguous expression statement, with acorn's label tail
  4064. const start = this.start;
  4065. const maybeName = this.value;
  4066. const expr = this.parseExpression();
  4067. if (
  4068. startType === tokTypes.name &&
  4069. expr.type === "Identifier" &&
  4070. this.eat(tokTypes.colon)
  4071. ) {
  4072. // labels are rare enough to pay for the started node
  4073. return this.parseLabeledStatement(
  4074. this.startNodeAt(start),
  4075. /** @type {string} */ (maybeName),
  4076. /** @type {Identifier} */ (expr),
  4077. context
  4078. );
  4079. }
  4080. return this._parseExpressionStatementAt(start, expr);
  4081. }
  4082. }
  4083. }
  4084. /**
  4085. * Owned `parseVarStatement`: the passed started node is filled by
  4086. * `parseVar` as acorn expects, then the finished statement lands on
  4087. * `VariableDeclarationNode`'s single shape. Non-lazy mode delegates.
  4088. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4089. * @param {Node} node started statement node from `parseStatement`
  4090. * @param {string} kind declaration kind
  4091. * @param {boolean=} allowMissingInitializer whether `const x;` is allowed
  4092. * @returns {Node} variable declaration
  4093. * @this {ParserInternals}
  4094. */
  4095. parseVarStatement(node, kind, allowMissingInitializer) {
  4096. if (!this._lazy) {
  4097. return base.parseVarStatement.call(
  4098. this,
  4099. node,
  4100. kind,
  4101. allowMissingInitializer
  4102. );
  4103. }
  4104. return this._parseVarStatementAt(node.start, kind, allowMissingInitializer);
  4105. }
  4106. /**
  4107. * Statement-position `var`/`let`/`const` without a started node: the
  4108. * declaration lands directly on `VariableDeclarationNode`'s single shape.
  4109. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4110. * @param {number} start statement start offset
  4111. * @param {string} kind declaration kind
  4112. * @param {boolean=} allowMissingInitializer whether `const x;` is allowed
  4113. * @returns {Node} variable declaration
  4114. * @this {ParserInternals}
  4115. */
  4116. _parseVarStatementAt(start, kind, allowMissingInitializer) {
  4117. this.next();
  4118. const scratch = this._acquireScratch();
  4119. const count = this._parseVarInto(
  4120. scratch,
  4121. false,
  4122. kind,
  4123. allowMissingInitializer
  4124. );
  4125. const declarations = this._releaseScratch(scratch, count);
  4126. this.semicolon();
  4127. return /** @type {Node} */ (
  4128. /** @type {unknown} */ (
  4129. new VariableDeclarationNode(start, this.lastTokEnd, declarations, kind)
  4130. )
  4131. );
  4132. }
  4133. /**
  4134. * Owned `parseVar`, an exact-semantics copy of acorn 8's that builds each
  4135. * declarator fully-formed on `VariableDeclaratorNode`'s single shape. The
  4136. * passed node keeps receiving `declarations`/`kind` because
  4137. * `parseForStatement` finishes it itself. Non-lazy mode delegates.
  4138. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4139. * @param {Node} node declaration node to fill
  4140. * @param {boolean} isFor whether parsing a `for` head
  4141. * @param {string} kind declaration kind
  4142. * @param {boolean=} allowMissingInitializer whether `const x;` is allowed
  4143. * @returns {Node} the filled node
  4144. * @this {ParserInternals}
  4145. */
  4146. parseVar(node, isFor, kind, allowMissingInitializer) {
  4147. if (!this._lazy) {
  4148. return base.parseVar.call(
  4149. this,
  4150. node,
  4151. isFor,
  4152. kind,
  4153. allowMissingInitializer
  4154. );
  4155. }
  4156. const target =
  4157. /** @type {Node & { declarations: Node[] | null, kind: string }} */ (
  4158. node
  4159. );
  4160. // null placeholder keeps acorn's declarations-then-kind key order while
  4161. // the list is built in scratch (the node is a local in every caller
  4162. // until this returns, so the placeholder is unobservable)
  4163. target.declarations = null;
  4164. target.kind = kind;
  4165. const scratch = this._acquireScratch();
  4166. const count = this._parseVarInto(
  4167. scratch,
  4168. isFor,
  4169. kind,
  4170. allowMissingInitializer
  4171. );
  4172. target.declarations = this._releaseScratch(scratch, count);
  4173. return node;
  4174. }
  4175. /**
  4176. * The declarator loop of the owned `parseVar`, shared with the owned
  4177. * `parseStatement`'s node-free statement path.
  4178. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4179. * @param {Node[]} declarations scratch array for the declarators
  4180. * @param {boolean} isFor whether parsing a `for` head
  4181. * @param {string} kind declaration kind
  4182. * @param {boolean=} allowMissingInitializer whether `const x;` is allowed
  4183. * @returns {number} number of declarators written
  4184. * @this {ParserInternals}
  4185. */
  4186. _parseVarInto(declarations, isFor, kind, allowMissingInitializer) {
  4187. const ecmaVersion = this._ecmaVersion;
  4188. const usingKind = kind === "using" || kind === "await using";
  4189. let count = 0;
  4190. for (;;) {
  4191. const declStart = this.start;
  4192. const id = usingKind ? this.parseIdent() : this.parseBindingAtom();
  4193. this.checkLValPattern(
  4194. id,
  4195. kind === "var" ? BIND_VAR : BIND_LEXICAL,
  4196. false
  4197. );
  4198. /** @type {Expression | null} */
  4199. let init = null;
  4200. if (this.eat(tokTypes.eq)) {
  4201. init = this.parseMaybeAssign(isFor);
  4202. } else if (
  4203. !allowMissingInitializer &&
  4204. kind === "const" &&
  4205. !(
  4206. this.type === tokTypes._in ||
  4207. (ecmaVersion >= 6 && this.isContextual("of"))
  4208. )
  4209. ) {
  4210. this.unexpected();
  4211. } else if (
  4212. !allowMissingInitializer &&
  4213. usingKind &&
  4214. ecmaVersion >= 17 &&
  4215. this.type !== tokTypes._in &&
  4216. !this.isContextual("of")
  4217. ) {
  4218. this.raise(
  4219. this.lastTokEnd,
  4220. `Missing initializer in ${kind} declaration`
  4221. );
  4222. } else if (
  4223. !allowMissingInitializer &&
  4224. id.type !== "Identifier" &&
  4225. !(isFor && (this.type === tokTypes._in || this.isContextual("of")))
  4226. ) {
  4227. this.raise(
  4228. this.lastTokEnd,
  4229. "Complex binding patterns require an initialization value"
  4230. );
  4231. }
  4232. declarations[count++] = /** @type {Node} */ (
  4233. /** @type {unknown} */ (
  4234. new VariableDeclaratorNode(declStart, this.lastTokEnd, id, init)
  4235. )
  4236. );
  4237. if (!this.eat(tokTypes.comma)) break;
  4238. }
  4239. return count;
  4240. }
  4241. /**
  4242. * Owned `parseExpressionStatement`: the statement lands on
  4243. * `ExpressionStatementNode`'s single shape (the passed started node is
  4244. * discarded, matching acorn's observable output). Non-lazy mode delegates.
  4245. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4246. * @param {Node} node started statement node from `parseStatement`
  4247. * @param {Expression} expr the parsed expression
  4248. * @returns {Node} expression statement
  4249. * @this {ParserInternals}
  4250. */
  4251. parseExpressionStatement(node, expr) {
  4252. if (!this._lazy) {
  4253. return base.parseExpressionStatement.call(this, node, expr);
  4254. }
  4255. return this._parseExpressionStatementAt(node.start, expr);
  4256. }
  4257. /**
  4258. * `parseExpressionStatement` without a started node.
  4259. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4260. * @param {number} start statement start offset
  4261. * @param {Expression} expr the parsed expression
  4262. * @returns {Node} expression statement
  4263. * @this {ParserInternals}
  4264. */
  4265. _parseExpressionStatementAt(start, expr) {
  4266. this.semicolon();
  4267. return /** @type {Node} */ (
  4268. /** @type {unknown} */ (
  4269. new ExpressionStatementNode(start, this.lastTokEnd, expr)
  4270. )
  4271. );
  4272. }
  4273. /**
  4274. * Owned `parseBlock`, an exact-semantics copy of acorn 8's landing on
  4275. * `BlockStatementNode`'s single shape. Non-lazy mode delegates.
  4276. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4277. * @param {boolean=} createNewLexicalScope whether the block opens a scope
  4278. * @param {Node=} node started statement node, when called from `parseStatement`
  4279. * @param {boolean=} exitStrict whether to restore sloppy mode at the end
  4280. * @returns {Node} block statement
  4281. * @this {ParserInternals}
  4282. */
  4283. parseBlock(createNewLexicalScope, node, exitStrict) {
  4284. if (!this._lazy) {
  4285. return base.parseBlock.call(
  4286. this,
  4287. createNewLexicalScope,
  4288. node,
  4289. exitStrict
  4290. );
  4291. }
  4292. if (createNewLexicalScope === undefined) createNewLexicalScope = true;
  4293. const start = this.start;
  4294. const scratch = this._acquireScratch();
  4295. let count = 0;
  4296. this.expect(tokTypes.braceL);
  4297. if (createNewLexicalScope) this.enterScope(0);
  4298. while (this.type !== tokTypes.braceR) {
  4299. scratch[count++] = this.parseStatement(null);
  4300. }
  4301. if (exitStrict) this.strict = false;
  4302. this.next();
  4303. if (createNewLexicalScope) this.exitScope();
  4304. return /** @type {Node} */ (
  4305. /** @type {unknown} */ (
  4306. new BlockStatementNode(
  4307. start,
  4308. this.lastTokEnd,
  4309. this._releaseScratch(scratch, count)
  4310. )
  4311. )
  4312. );
  4313. }
  4314. /**
  4315. * Owned `parseIfStatement` landing on `IfStatementNode`'s single shape.
  4316. * Non-lazy mode delegates to acorn.
  4317. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4318. * @param {Node} node started statement node from `parseStatement`
  4319. * @returns {Node} if statement
  4320. * @this {ParserInternals}
  4321. */
  4322. parseIfStatement(node) {
  4323. if (!this._lazy) return base.parseIfStatement.call(this, node);
  4324. return this._parseIfStatementAt(node.start);
  4325. }
  4326. /**
  4327. * `parseIfStatement` without a started node.
  4328. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4329. * @param {number} start statement start offset
  4330. * @returns {Node} if statement
  4331. * @this {ParserInternals}
  4332. */
  4333. _parseIfStatementAt(start) {
  4334. this.next();
  4335. const test = this.parseParenExpression();
  4336. // function declarations are allowed in branches outside strict mode
  4337. const consequent = this.parseStatement("if");
  4338. const alternate = this.eat(tokTypes._else)
  4339. ? this.parseStatement("if")
  4340. : null;
  4341. return /** @type {Node} */ (
  4342. /** @type {unknown} */ (
  4343. new IfStatementNode(start, this.lastTokEnd, test, consequent, alternate)
  4344. )
  4345. );
  4346. }
  4347. /**
  4348. * Owned `parseReturnStatement` landing on `ReturnStatementNode`'s single
  4349. * shape. Non-lazy mode delegates to acorn.
  4350. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4351. * @param {Node} node started statement node from `parseStatement`
  4352. * @returns {Node} return statement
  4353. * @this {ParserInternals}
  4354. */
  4355. parseReturnStatement(node) {
  4356. if (!this._lazy) {
  4357. if (!this.allowReturn) this._tryModuleFallback();
  4358. return base.parseReturnStatement.call(this, node);
  4359. }
  4360. return this._parseReturnStatementAt(node.start);
  4361. }
  4362. /**
  4363. * In `auto` source type a top-level `return` is script-only syntax. When the
  4364. * strict module parse reaches it with no module construct seen yet, downgrade
  4365. * to a sloppy script in place: the prefix parsed under stricter rules stays a
  4366. * valid sloppy prefix, so the second full parse is avoided.
  4367. * @returns {boolean} true when the parse was downgraded to script
  4368. * @this {ParserInternals}
  4369. */
  4370. _tryModuleFallback() {
  4371. if (
  4372. !this._moduleFallback ||
  4373. this._moduleSyntaxSeen ||
  4374. !(this.currentVarScope().flags & SCOPE_TOP)
  4375. ) {
  4376. return false;
  4377. }
  4378. this.options.allowReturnOutsideFunction = true;
  4379. // acorn stamps Program.sourceType from this at parseTopLevel's end
  4380. this.options.sourceType = "script";
  4381. this.strict = false;
  4382. this.inModule = false;
  4383. this._moduleFallback = false;
  4384. return true;
  4385. }
  4386. /**
  4387. * `parseReturnStatement` without a started node.
  4388. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4389. * @param {number} start statement start offset
  4390. * @returns {Node} return statement
  4391. * @this {ParserInternals}
  4392. */
  4393. _parseReturnStatementAt(start) {
  4394. if (!this.allowReturn && !this._tryModuleFallback()) {
  4395. this.raise(this.start, "'return' outside of function");
  4396. }
  4397. this.next();
  4398. /** @type {Expression | null} */
  4399. let argument = null;
  4400. // `return` takes an optional argument, so eagerly look for a semicolon
  4401. if (!(this.eat(tokTypes.semi) || this.insertSemicolon())) {
  4402. argument = this.parseExpression();
  4403. this.semicolon();
  4404. }
  4405. return /** @type {Node} */ (
  4406. /** @type {unknown} */ (
  4407. new ReturnStatementNode(start, this.lastTokEnd, argument)
  4408. )
  4409. );
  4410. }
  4411. /**
  4412. * `parseBreakContinueStatement` without a started node, landing on
  4413. * `BreakContinueNode`'s single shape.
  4414. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4415. * @param {number} start statement start offset
  4416. * @param {string} keyword `break` or `continue`
  4417. * @returns {Node} break or continue statement
  4418. * @this {ParserInternals}
  4419. */
  4420. _parseBreakContinueStatementAt(start, keyword) {
  4421. const isBreak = keyword === "break";
  4422. this.next();
  4423. /** @type {Identifier | null} */
  4424. let label = null;
  4425. if (this.eat(tokTypes.semi) || this.insertSemicolon()) {
  4426. // no label
  4427. } else if (this.type !== tokTypes.name) {
  4428. this.unexpected();
  4429. } else {
  4430. label = this.parseIdent();
  4431. this.semicolon();
  4432. }
  4433. // verify there is an actual destination to break or continue to
  4434. const labels = this.labels;
  4435. let i = 0;
  4436. for (; i < labels.length; ++i) {
  4437. const lab = labels[i];
  4438. if (label === null || lab.name === label.name) {
  4439. if (
  4440. lab.kind !== null &&
  4441. lab.kind !== undefined &&
  4442. (isBreak || lab.kind === "loop")
  4443. ) {
  4444. break;
  4445. }
  4446. if (label && isBreak) break;
  4447. }
  4448. }
  4449. if (i === labels.length) this.raise(start, `Unsyntactic ${keyword}`);
  4450. return /** @type {Node} */ (
  4451. /** @type {unknown} */ (
  4452. new BreakContinueNode(
  4453. start,
  4454. this.lastTokEnd,
  4455. isBreak ? "BreakStatement" : "ContinueStatement",
  4456. label
  4457. )
  4458. )
  4459. );
  4460. }
  4461. /**
  4462. * `parseForStatement` without a started node (fast-path gate guarantees
  4463. * `ecmaVersion >= 9`, folding acorn's version probes).
  4464. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4465. * @param {number} start statement start offset
  4466. * @returns {Node} for/for-in/for-of statement
  4467. * @this {ParserInternals}
  4468. */
  4469. _parseForStatementAt(start) {
  4470. this.next();
  4471. const awaitAt =
  4472. this.canAwait && this.eatContextual("await") ? this.lastTokStart : -1;
  4473. this.labels.push(LOOP_LABEL);
  4474. this.enterScope(0);
  4475. this.expect(tokTypes.parenL);
  4476. if (this.type === tokTypes.semi) {
  4477. if (awaitAt > -1) this.unexpected(awaitAt);
  4478. return this._parseForAt(start, null);
  4479. }
  4480. const isLet = this.isLet();
  4481. if (this.type === tokTypes._var || this.type === tokTypes._const || isLet) {
  4482. const initStart = this.start;
  4483. const kind = isLet ? "let" : /** @type {string} */ (this.value);
  4484. this.next();
  4485. const scratch = this._acquireScratch();
  4486. const count = this._parseVarInto(scratch, true, kind);
  4487. const declarations = this._releaseScratch(scratch, count);
  4488. const init = /** @type {Node} */ (
  4489. /** @type {unknown} */ (
  4490. new VariableDeclarationNode(
  4491. initStart,
  4492. this.lastTokEnd,
  4493. declarations,
  4494. kind
  4495. )
  4496. )
  4497. );
  4498. return this._parseForAfterInitAt(start, init, awaitAt);
  4499. }
  4500. const startsWithLet = this.isContextual("let");
  4501. let isForOf = false;
  4502. const usingKind = this.isUsing(true)
  4503. ? "using"
  4504. : this.isAwaitUsing(true)
  4505. ? "await using"
  4506. : null;
  4507. if (usingKind) {
  4508. const initStart = this.start;
  4509. this.next();
  4510. if (usingKind === "await using") {
  4511. if (!this.canAwait) {
  4512. this.raise(
  4513. this.start,
  4514. "Await using cannot appear outside of async function"
  4515. );
  4516. }
  4517. this.next();
  4518. }
  4519. const scratch = this._acquireScratch();
  4520. const count = this._parseVarInto(scratch, true, usingKind);
  4521. const declarations = this._releaseScratch(scratch, count);
  4522. const init = /** @type {Node} */ (
  4523. /** @type {unknown} */ (
  4524. new VariableDeclarationNode(
  4525. initStart,
  4526. this.lastTokEnd,
  4527. declarations,
  4528. usingKind
  4529. )
  4530. )
  4531. );
  4532. return this._parseForAfterInitAt(start, init, awaitAt);
  4533. }
  4534. const containsEsc = this.containsEsc;
  4535. const refDestructuringErrors = this._acquireDestructuringErrors();
  4536. const initPos = this.start;
  4537. const init =
  4538. awaitAt > -1
  4539. ? this.parseExprSubscripts(refDestructuringErrors, "await")
  4540. : this.parseExpression(true, refDestructuringErrors);
  4541. if (this.type === tokTypes._in || (isForOf = this.isContextual("of"))) {
  4542. let isAwait = false;
  4543. if (awaitAt > -1) {
  4544. if (this.type === tokTypes._in) this.unexpected(awaitAt);
  4545. isAwait = true;
  4546. } else if (
  4547. isForOf &&
  4548. init.start === initPos &&
  4549. !containsEsc &&
  4550. init.type === "Identifier" &&
  4551. /** @type {Identifier} */ (init).name === "async"
  4552. ) {
  4553. this.unexpected();
  4554. }
  4555. if (startsWithLet && isForOf) {
  4556. this.raise(
  4557. init.start,
  4558. "The left-hand side of a for-of loop may not start with 'let'."
  4559. );
  4560. }
  4561. this.toAssignable(init, false, refDestructuringErrors);
  4562. this.checkLValPattern(init);
  4563. this._releaseDestructuringErrors();
  4564. return this._parseForInAt(start, isAwait, /** @type {Node} */ (init));
  4565. }
  4566. this.checkExpressionErrors(refDestructuringErrors, true);
  4567. this._releaseDestructuringErrors();
  4568. if (awaitAt > -1) this.unexpected(awaitAt);
  4569. return this._parseForAt(start, /** @type {Node} */ (init));
  4570. }
  4571. /**
  4572. * `parseForAfterInit` without a started node.
  4573. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4574. * @param {number} start statement start offset
  4575. * @param {Node} init parsed variable declaration
  4576. * @param {number} awaitAt offset of a consumed `await`, or -1
  4577. * @returns {Node} for/for-in/for-of statement
  4578. * @this {ParserInternals}
  4579. */
  4580. _parseForAfterInitAt(start, init, awaitAt) {
  4581. const target =
  4582. /** @type {Node & { declarations: Node[], kind: string }} */ (init);
  4583. if (
  4584. (this.type === tokTypes._in || this.isContextual("of")) &&
  4585. target.declarations.length === 1
  4586. ) {
  4587. if (this.type === tokTypes._in) {
  4588. if (
  4589. (target.kind === "using" || target.kind === "await using") &&
  4590. !(
  4591. /** @type {Node & { init: Node | null }} */ (target.declarations[0])
  4592. .init
  4593. )
  4594. ) {
  4595. this.raise(
  4596. this.start,
  4597. "Using declaration is not allowed in for-in loops"
  4598. );
  4599. }
  4600. if (awaitAt > -1) this.unexpected(awaitAt);
  4601. return this._parseForInAt(start, false, init);
  4602. }
  4603. return this._parseForInAt(start, awaitAt > -1, init);
  4604. }
  4605. if (awaitAt > -1) this.unexpected(awaitAt);
  4606. return this._parseForAt(start, init);
  4607. }
  4608. /**
  4609. * `parseFor` without a started node, landing on `ForStatementNode`'s
  4610. * single shape.
  4611. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4612. * @param {number} start statement start offset
  4613. * @param {Node | null} init init clause
  4614. * @returns {Node} for statement
  4615. * @this {ParserInternals}
  4616. */
  4617. _parseForAt(start, init) {
  4618. this.expect(tokTypes.semi);
  4619. const test = this.type === tokTypes.semi ? null : this.parseExpression();
  4620. this.expect(tokTypes.semi);
  4621. const update =
  4622. this.type === tokTypes.parenR ? null : this.parseExpression();
  4623. this.expect(tokTypes.parenR);
  4624. const body = this.parseStatement("for");
  4625. this.exitScope();
  4626. this.labels.pop();
  4627. return /** @type {Node} */ (
  4628. /** @type {unknown} */ (
  4629. new ForStatementNode(start, this.lastTokEnd, init, test, update, body)
  4630. )
  4631. );
  4632. }
  4633. /**
  4634. * `parseForIn` without a started node, landing on `ForInStatementNode`/
  4635. * `ForOfStatementNode`'s single shapes.
  4636. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4637. * @param {number} start statement start offset
  4638. * @param {boolean} isAwait whether this is `for await`
  4639. * @param {Node} init loop target
  4640. * @returns {Node} for-in or for-of statement
  4641. * @this {ParserInternals}
  4642. */
  4643. _parseForInAt(start, isAwait, init) {
  4644. const isForIn = this.type === tokTypes._in;
  4645. this.next();
  4646. if (
  4647. init.type === "VariableDeclaration" &&
  4648. /** @type {Node & { init: Node | null }} */ (
  4649. /** @type {Node & { declarations: Node[] }} */ (init).declarations[0]
  4650. ).init !== null &&
  4651. (!isForIn ||
  4652. this.strict ||
  4653. /** @type {Node & { kind: string }} */ (init).kind !== "var" ||
  4654. /** @type {Node & { id: Node }} */ (
  4655. /** @type {Node & { declarations: Node[] }} */ (init).declarations[0]
  4656. ).id.type !== "Identifier")
  4657. ) {
  4658. this.raise(
  4659. init.start,
  4660. `${
  4661. isForIn ? "for-in" : "for-of"
  4662. } loop variable declaration may not have an initializer`
  4663. );
  4664. }
  4665. const right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  4666. this.expect(tokTypes.parenR);
  4667. const body = this.parseStatement("for");
  4668. this.exitScope();
  4669. this.labels.pop();
  4670. return /** @type {Node} */ (
  4671. /** @type {unknown} */ (
  4672. isForIn
  4673. ? new ForInStatementNode(start, this.lastTokEnd, init, right, body)
  4674. : new ForOfStatementNode(
  4675. start,
  4676. this.lastTokEnd,
  4677. isAwait,
  4678. init,
  4679. right,
  4680. body
  4681. )
  4682. )
  4683. );
  4684. }
  4685. /**
  4686. * `parseSwitchStatement` without a started node, landing on
  4687. * `SwitchStatementNode`'s single shape with pre-shaped `SwitchCaseNode`s.
  4688. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4689. * @param {number} start statement start offset
  4690. * @returns {Node} switch statement
  4691. * @this {ParserInternals}
  4692. */
  4693. _parseSwitchStatementAt(start) {
  4694. this.next();
  4695. const discriminant = this.parseParenExpression();
  4696. /** @type {Node[]} */
  4697. const cases = [];
  4698. this.expect(tokTypes.braceL);
  4699. this.labels.push(SWITCH_LABEL);
  4700. this.enterScope(SCOPE_SWITCH);
  4701. /** @type {SwitchCaseNode | undefined} */
  4702. let cur;
  4703. for (let sawDefault = false; this.type !== tokTypes.braceR;) {
  4704. if (this.type === tokTypes._case || this.type === tokTypes._default) {
  4705. const isCase = this.type === tokTypes._case;
  4706. if (cur) this.finishNode(/** @type {Node} */ (cur), "SwitchCase");
  4707. cur = new SwitchCaseNode(this.start);
  4708. cases.push(/** @type {Node} */ (cur));
  4709. cur.consequent = [];
  4710. this.next();
  4711. if (isCase) {
  4712. cur.test = this.parseExpression();
  4713. } else {
  4714. if (sawDefault) {
  4715. this.raiseRecoverable(
  4716. this.lastTokStart,
  4717. "Multiple default clauses"
  4718. );
  4719. }
  4720. sawDefault = true;
  4721. cur.test = null;
  4722. }
  4723. this.expect(tokTypes.colon);
  4724. } else {
  4725. if (!cur) this.unexpected();
  4726. /** @type {Node[]} */ (
  4727. /** @type {SwitchCaseNode} */ (cur).consequent
  4728. ).push(this.parseStatement(null));
  4729. }
  4730. }
  4731. this.exitScope();
  4732. if (cur) this.finishNode(/** @type {Node} */ (cur), "SwitchCase");
  4733. this.next(); // closing brace
  4734. this.labels.pop();
  4735. return /** @type {Node} */ (
  4736. /** @type {unknown} */ (
  4737. new SwitchStatementNode(start, this.lastTokEnd, discriminant, cases)
  4738. )
  4739. );
  4740. }
  4741. /**
  4742. * `parseThrowStatement` without a started node; the illegal-newline probe
  4743. * runs on the tokenizer's newline flag instead of acorn's gap slice+regexp.
  4744. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4745. * @param {number} start statement start offset
  4746. * @returns {Node} throw statement
  4747. * @this {ParserInternals}
  4748. */
  4749. _parseThrowStatementAt(start) {
  4750. this.next();
  4751. if (this._gapHasNewline()) {
  4752. this.raise(this.lastTokEnd, "Illegal newline after throw");
  4753. }
  4754. const argument = this.parseExpression();
  4755. this.semicolon();
  4756. return /** @type {Node} */ (
  4757. /** @type {unknown} */ (
  4758. new ThrowStatementNode(start, this.lastTokEnd, argument)
  4759. )
  4760. );
  4761. }
  4762. /**
  4763. * `parseTryStatement` without a started node, landing on
  4764. * `TryStatementNode`/`CatchClauseNode`'s single shapes.
  4765. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4766. * @param {number} start statement start offset
  4767. * @returns {Node} try statement
  4768. * @this {ParserInternals}
  4769. */
  4770. _parseTryStatementAt(start) {
  4771. this.next();
  4772. const block = this.parseBlock();
  4773. /** @type {Node | null} */
  4774. let handler = null;
  4775. if (this.type === tokTypes._catch) {
  4776. const clauseStart = this.start;
  4777. this.next();
  4778. /** @type {Node | null} */
  4779. let param;
  4780. if (this.eat(tokTypes.parenL)) {
  4781. param = this.parseCatchClauseParam();
  4782. } else {
  4783. if (this._ecmaVersion < 10) this.unexpected();
  4784. param = null;
  4785. this.enterScope(0);
  4786. }
  4787. const body = this.parseBlock(false);
  4788. this.exitScope();
  4789. handler = /** @type {Node} */ (
  4790. /** @type {unknown} */ (
  4791. new CatchClauseNode(clauseStart, this.lastTokEnd, param, body)
  4792. )
  4793. );
  4794. }
  4795. const finalizer = this.eat(tokTypes._finally) ? this.parseBlock() : null;
  4796. if (!handler && !finalizer) {
  4797. this.raise(start, "Missing catch or finally clause");
  4798. }
  4799. return /** @type {Node} */ (
  4800. /** @type {unknown} */ (
  4801. new TryStatementNode(start, this.lastTokEnd, block, handler, finalizer)
  4802. )
  4803. );
  4804. }
  4805. /**
  4806. * `parseWhileStatement` without a started node, landing on
  4807. * `WhileStatementNode`'s single shape.
  4808. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4809. * @param {number} start statement start offset
  4810. * @returns {Node} while statement
  4811. * @this {ParserInternals}
  4812. */
  4813. _parseWhileStatementAt(start) {
  4814. this.next();
  4815. const test = this.parseParenExpression();
  4816. this.labels.push(LOOP_LABEL);
  4817. const body = this.parseStatement("while");
  4818. this.labels.pop();
  4819. return /** @type {Node} */ (
  4820. /** @type {unknown} */ (
  4821. new WhileStatementNode(start, this.lastTokEnd, test, body)
  4822. )
  4823. );
  4824. }
  4825. /**
  4826. * Owned `parseSpread` landing on `RestSpreadNode`'s single shape.
  4827. * Non-lazy mode delegates.
  4828. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/lval.js
  4829. * @param {DestructuringErrorsShim | null=} refDestructuringErrors destructuring errors to fill
  4830. * @returns {Node} spread element
  4831. * @this {ParserInternals}
  4832. */
  4833. parseSpread(refDestructuringErrors) {
  4834. if (!this._lazy) {
  4835. return base.parseSpread.call(this, refDestructuringErrors);
  4836. }
  4837. const start = this.start;
  4838. this.next();
  4839. const argument = this.parseMaybeAssign(false, refDestructuringErrors);
  4840. return /** @type {Node} */ (
  4841. /** @type {unknown} */ (
  4842. new RestSpreadNode(start, this.lastTokEnd, "SpreadElement", argument)
  4843. )
  4844. );
  4845. }
  4846. /**
  4847. * Owned `parseMaybeConditional` landing on
  4848. * `ConditionalExpressionNode`'s single shape. Non-lazy mode delegates.
  4849. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  4850. * @param {boolean | string=} forInit for-init context flag
  4851. * @param {DestructuringErrorsShim | null=} refDestructuringErrors destructuring errors to fill
  4852. * @returns {Expression} expression node
  4853. * @this {ParserInternals}
  4854. */
  4855. parseMaybeConditional(forInit, refDestructuringErrors) {
  4856. if (!this._lazy) {
  4857. return base.parseMaybeConditional.call(
  4858. this,
  4859. forInit,
  4860. refDestructuringErrors
  4861. );
  4862. }
  4863. const startPos = this.start;
  4864. const expr = this.parseExprOps(forInit, refDestructuringErrors);
  4865. if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
  4866. const isArrowAtStart = this._arrowFastPath
  4867. ? expr === this._lastArrow && expr.start === startPos
  4868. : expr.type === "ArrowFunctionExpression" && expr.start === startPos;
  4869. if (!isArrowAtStart && this.eat(tokTypes.question)) {
  4870. const consequent = this.parseMaybeAssign();
  4871. this.expect(tokTypes.colon);
  4872. const alternate = this.parseMaybeAssign(forInit);
  4873. return /** @type {Expression} */ (
  4874. /** @type {unknown} */ (
  4875. new ConditionalExpressionNode(
  4876. startPos,
  4877. this.lastTokEnd,
  4878. expr,
  4879. consequent,
  4880. alternate
  4881. )
  4882. )
  4883. );
  4884. }
  4885. return expr;
  4886. }
  4887. /**
  4888. * acorn's `parseArrowExpression` plus `_lastArrow` tracking — arrows are
  4889. * created and returned only here, so the expression-spine probes can test
  4890. * node identity instead of the megamorphic `.type` load. A plugin fabricating
  4891. * arrow nodes in an overridden `parseExprAtom` bypasses the gate (same
  4892. * acceptance class as `_stmtFastPath`).
  4893. * @param {Node} node started node
  4894. * @param {Node[]} params parameter expressions
  4895. * @param {boolean} isAsync async arrow
  4896. * @param {boolean | string=} forInit for-init context flag
  4897. * @returns {Expression} arrow function expression
  4898. * @this {ParserInternals}
  4899. */
  4900. parseArrowExpression(node, params, isAsync, forInit) {
  4901. if (!this._funcFastPath) {
  4902. const result = base.parseArrowExpression.call(
  4903. this,
  4904. node,
  4905. params,
  4906. isAsync,
  4907. forInit
  4908. );
  4909. this._lastArrow = result;
  4910. return result;
  4911. }
  4912. // acorn's body with the started node replaced by the pre-shaped
  4913. // FunctionNode (initFunction's writes are its constructor defaults)
  4914. const functionNode = /** @type {Node} */ (
  4915. /** @type {unknown} */ (new FunctionNode(node.start))
  4916. );
  4917. const oldYieldPos = this.yieldPos;
  4918. const oldAwaitPos = this.awaitPos;
  4919. const oldAwaitIdentPos = this.awaitIdentPos;
  4920. this.enterScope(SCOPE_FUNCTION | (isAsync ? SCOPE_ASYNC : 0) | SCOPE_ARROW);
  4921. /** @type {Node & { async: boolean, params?: Node[] }} */ (
  4922. functionNode
  4923. ).async = Boolean(isAsync);
  4924. this.yieldPos = 0;
  4925. this.awaitPos = 0;
  4926. this.awaitIdentPos = 0;
  4927. /** @type {Node & { params?: Node[] }} */ (functionNode).params =
  4928. /** @type {Node[]} */ (this.toAssignableList(params, true));
  4929. this.parseFunctionBody(functionNode, true, false, forInit);
  4930. this.yieldPos = oldYieldPos;
  4931. this.awaitPos = oldAwaitPos;
  4932. this.awaitIdentPos = oldAwaitIdentPos;
  4933. const result = /** @type {Expression} */ (
  4934. /** @type {unknown} */ (
  4935. this.finishNode(functionNode, "ArrowFunctionExpression")
  4936. )
  4937. );
  4938. this._lastArrow = result;
  4939. return result;
  4940. }
  4941. /**
  4942. * Owned `parseFunction`, an exact-semantics copy of acorn 8's landing on
  4943. * `FunctionNode`'s pre-declared shape (the passed started node is discarded,
  4944. * matching acorn's observable output; `initFunction`'s writes are the
  4945. * constructor defaults). Non-lazy mode and plugin overrides delegate.
  4946. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4947. * @param {Node} node started node from the caller
  4948. * @param {number} statement FUNC_* statement bit flags
  4949. * @param {boolean=} allowExpressionBody whether an expression body is allowed
  4950. * @param {boolean=} isAsync whether the function is async
  4951. * @param {boolean | string=} forInit for-init context flag
  4952. * @returns {Expression} function declaration or expression
  4953. * @this {ParserInternals}
  4954. */
  4955. parseFunction(node, statement, allowExpressionBody, isAsync, forInit) {
  4956. if (!this._funcFastPath) {
  4957. return base.parseFunction.call(
  4958. this,
  4959. node,
  4960. statement,
  4961. allowExpressionBody,
  4962. isAsync,
  4963. forInit
  4964. );
  4965. }
  4966. return this._parseFunctionAt(
  4967. node.start,
  4968. statement,
  4969. allowExpressionBody === true,
  4970. isAsync === true,
  4971. forInit
  4972. );
  4973. }
  4974. /**
  4975. * `parseFunction` without a started node (fast-path gate guarantees
  4976. * `ecmaVersion >= 9`, folding acorn's version probes).
  4977. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  4978. * @param {number} start function start offset
  4979. * @param {number} statement FUNC_* statement bit flags
  4980. * @param {boolean} allowExpressionBody whether an expression body is allowed
  4981. * @param {boolean} isAsync whether the function is async
  4982. * @param {boolean | string=} forInit for-init context flag
  4983. * @returns {Expression} function declaration or expression
  4984. * @this {ParserInternals}
  4985. */
  4986. _parseFunctionAt(start, statement, allowExpressionBody, isAsync, forInit) {
  4987. const node =
  4988. /** @type {Node & { id: Identifier | null, generator: boolean, async: boolean }} */ (
  4989. /** @type {unknown} */ (new FunctionNode(start))
  4990. );
  4991. if (this.type === tokTypes.star && statement & FUNC_HANGING_STATEMENT) {
  4992. this.unexpected();
  4993. }
  4994. node.generator = this.eat(tokTypes.star);
  4995. node.async = isAsync;
  4996. if (statement & FUNC_STATEMENT) {
  4997. node.id =
  4998. statement & FUNC_NULLABLE_ID && this.type !== tokTypes.name
  4999. ? null
  5000. : this.parseIdent();
  5001. if (node.id && !(statement & FUNC_HANGING_STATEMENT)) {
  5002. // Annex B: sloppy-mode function declarations bind like vars
  5003. this.checkLValSimple(
  5004. node.id,
  5005. this.strict || node.generator || node.async
  5006. ? this.treatFunctionsAsVar
  5007. ? BIND_VAR
  5008. : BIND_LEXICAL
  5009. : /* BIND_FUNCTION */ 3
  5010. );
  5011. }
  5012. }
  5013. const oldYieldPos = this.yieldPos;
  5014. const oldAwaitPos = this.awaitPos;
  5015. const oldAwaitIdentPos = this.awaitIdentPos;
  5016. this.yieldPos = 0;
  5017. this.awaitPos = 0;
  5018. this.awaitIdentPos = 0;
  5019. this.enterScope(
  5020. SCOPE_FUNCTION |
  5021. (node.async ? SCOPE_ASYNC : 0) |
  5022. (node.generator ? SCOPE_GENERATOR : 0)
  5023. );
  5024. if (!(statement & FUNC_STATEMENT)) {
  5025. node.id = this.type === tokTypes.name ? this.parseIdent() : null;
  5026. }
  5027. this.parseFunctionParams(node);
  5028. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  5029. this.yieldPos = oldYieldPos;
  5030. this.awaitPos = oldAwaitPos;
  5031. this.awaitIdentPos = oldAwaitIdentPos;
  5032. return /** @type {Expression} */ (
  5033. /** @type {unknown} */ (
  5034. this.finishNode(
  5035. node,
  5036. statement & FUNC_STATEMENT
  5037. ? "FunctionDeclaration"
  5038. : "FunctionExpression"
  5039. )
  5040. )
  5041. );
  5042. }
  5043. /**
  5044. * Owned `parseFunctionBody`, an exact-semantics copy of acorn 8's with
  5045. * `isSimpleParamList` inlined and computed once (acorn walks the params
  5046. * twice) — the fast-path gate pins it to acorn's own implementation.
  5047. * Non-lazy mode and plugin overrides delegate.
  5048. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  5049. * @param {Node} node function node being filled
  5050. * @param {boolean} isArrowFunction whether this is an arrow function
  5051. * @param {boolean} isMethod whether this is an object/class method
  5052. * @param {boolean | string=} forInit for-init context flag
  5053. * @returns {void}
  5054. * @this {ParserInternals}
  5055. */
  5056. parseFunctionBody(node, isArrowFunction, isMethod, forInit) {
  5057. if (!this._funcFastPath) {
  5058. return base.parseFunctionBody.call(
  5059. this,
  5060. node,
  5061. isArrowFunction,
  5062. isMethod,
  5063. forInit
  5064. );
  5065. }
  5066. const target =
  5067. /** @type {Node & { id: Identifier | null, params: Node[], body: Node, expression: boolean }} */ (
  5068. node
  5069. );
  5070. const isExpression = isArrowFunction && this.type !== tokTypes.braceL;
  5071. const oldStrict = this.strict;
  5072. let useStrict = false;
  5073. if (isExpression) {
  5074. target.body = this.parseMaybeAssign(forInit);
  5075. target.expression = true;
  5076. this.checkParams(node, false);
  5077. } else {
  5078. // acorn's isSimpleParamList, inlined and shared by both its call sites
  5079. const params = target.params;
  5080. let simpleParams = true;
  5081. for (let i = 0; i < params.length; i++) {
  5082. if (params[i].type !== "Identifier") {
  5083. simpleParams = false;
  5084. break;
  5085. }
  5086. }
  5087. if (!oldStrict || !simpleParams) {
  5088. useStrict = this.strictDirective(this.end);
  5089. if (useStrict && !simpleParams) {
  5090. this.raiseRecoverable(
  5091. node.start,
  5092. "Illegal 'use strict' directive in function with non-simple parameter list"
  5093. );
  5094. }
  5095. }
  5096. const oldLabels = this.labels;
  5097. this.labels = [];
  5098. if (useStrict) this.strict = true;
  5099. this.checkParams(
  5100. node,
  5101. !oldStrict &&
  5102. !useStrict &&
  5103. !isArrowFunction &&
  5104. !isMethod &&
  5105. simpleParams
  5106. );
  5107. if (this.strict && target.id) {
  5108. this.checkLValSimple(target.id, BIND_OUTSIDE);
  5109. }
  5110. target.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  5111. target.expression = false;
  5112. this.adaptDirectivePrologue(
  5113. /** @type {Node & { body: Node[] }} */ (target.body).body
  5114. );
  5115. this.labels = oldLabels;
  5116. }
  5117. this.exitScope();
  5118. }
  5119. /**
  5120. * Owned `parseBindingAtom`: acorn's exact dispatch minus the per-call
  5121. * normalized-options read. Non-lazy mode and pre-ES6 delegate.
  5122. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/lval.js
  5123. * @returns {Node} binding atom (identifier or pattern)
  5124. * @this {ParserInternals}
  5125. */
  5126. parseBindingAtom() {
  5127. if (!this._lazy || this._ecmaVersion < 6) {
  5128. return base.parseBindingAtom.call(this);
  5129. }
  5130. const type = this.type;
  5131. if (type === tokTypes.bracketL) {
  5132. const node = /** @type {Node & { elements?: Node[] }} */ (
  5133. this.startNode()
  5134. );
  5135. this.next();
  5136. node.elements = this.parseBindingList(tokTypes.bracketR, true, true);
  5137. return this.finishNode(node, "ArrayPattern");
  5138. }
  5139. if (type === tokTypes.braceL) return this.parseObj(true);
  5140. return this.parseIdent();
  5141. }
  5142. /**
  5143. * Owned `parseExprSubscripts`, an exact copy of acorn 8's with the arrow
  5144. * probe served by `_lastArrow` identity. Delegates when the fast path is off.
  5145. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  5146. * @param {DestructuringErrorsShim | null=} refDestructuringErrors destructuring errors to fill
  5147. * @param {boolean | string=} forInit for-init context flag
  5148. * @returns {Expression} expression node
  5149. * @this {ParserInternals}
  5150. */
  5151. parseExprSubscripts(refDestructuringErrors, forInit) {
  5152. if (!this._arrowFastPath) {
  5153. return base.parseExprSubscripts.call(
  5154. this,
  5155. refDestructuringErrors,
  5156. forInit
  5157. );
  5158. }
  5159. const startPos = this.start;
  5160. const startLoc = this.startLoc;
  5161. const expr = this.parseExprAtom(refDestructuringErrors, forInit);
  5162. if (
  5163. expr === this._lastArrow &&
  5164. this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"
  5165. ) {
  5166. return expr;
  5167. }
  5168. const result = this.parseSubscripts(
  5169. expr,
  5170. startPos,
  5171. startLoc,
  5172. false,
  5173. forInit
  5174. );
  5175. if (refDestructuringErrors && result.type === "MemberExpression") {
  5176. if (refDestructuringErrors.parenthesizedAssign >= result.start) {
  5177. refDestructuringErrors.parenthesizedAssign = -1;
  5178. }
  5179. if (refDestructuringErrors.parenthesizedBind >= result.start) {
  5180. refDestructuringErrors.parenthesizedBind = -1;
  5181. }
  5182. if (refDestructuringErrors.trailingComma >= result.start) {
  5183. refDestructuringErrors.trailingComma = -1;
  5184. }
  5185. }
  5186. return result;
  5187. }
  5188. /**
  5189. * Owned `parseExprList`, an exact-semantics copy of acorn 8's built in a
  5190. * scratch array and materialized exactly sized. Non-lazy mode delegates.
  5191. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  5192. * @param {TokenType} close closing token type
  5193. * @param {boolean} allowTrailingComma whether a trailing comma is allowed
  5194. * @param {boolean} allowEmpty whether holes are allowed
  5195. * @param {DestructuringErrorsShim | null=} refDestructuringErrors destructuring errors to fill
  5196. * @returns {Expression[]} parsed elements (`null` for holes)
  5197. * @this {ParserInternals}
  5198. */
  5199. parseExprList(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  5200. if (!this._lazy) {
  5201. return base.parseExprList.call(
  5202. this,
  5203. close,
  5204. allowTrailingComma,
  5205. allowEmpty,
  5206. refDestructuringErrors
  5207. );
  5208. }
  5209. const scratch = this._acquireScratch();
  5210. let count = 0;
  5211. let first = true;
  5212. while (!this.eat(close)) {
  5213. if (!first) {
  5214. this.expect(tokTypes.comma);
  5215. if (allowTrailingComma && this.afterTrailingComma(close)) break;
  5216. } else {
  5217. first = false;
  5218. }
  5219. let elt;
  5220. if (allowEmpty && this.type === tokTypes.comma) {
  5221. elt = null;
  5222. } else if (this.type === tokTypes.ellipsis) {
  5223. elt = this.parseSpread(refDestructuringErrors);
  5224. if (
  5225. refDestructuringErrors &&
  5226. this.type === tokTypes.comma &&
  5227. refDestructuringErrors.trailingComma < 0
  5228. ) {
  5229. refDestructuringErrors.trailingComma = this.start;
  5230. }
  5231. } else {
  5232. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  5233. }
  5234. scratch[count++] = elt;
  5235. }
  5236. return this._releaseScratch(scratch, count);
  5237. }
  5238. /**
  5239. * Owned `parseBindingList`, an exact-semantics copy of acorn 8's built in a
  5240. * scratch array and materialized exactly sized. Non-lazy mode delegates.
  5241. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/lval.js
  5242. * @param {TokenType} close closing token type
  5243. * @param {boolean} allowEmpty whether holes are allowed
  5244. * @param {boolean} allowTrailingComma whether a trailing comma is allowed
  5245. * @param {boolean=} allowModifiers passed through to `parseAssignableListItem`
  5246. * @returns {Node[]} parsed bindings (`null` for holes)
  5247. * @this {ParserInternals}
  5248. */
  5249. parseBindingList(close, allowEmpty, allowTrailingComma, allowModifiers) {
  5250. if (!this._lazy) {
  5251. return base.parseBindingList.call(
  5252. this,
  5253. close,
  5254. allowEmpty,
  5255. allowTrailingComma,
  5256. allowModifiers
  5257. );
  5258. }
  5259. const scratch = this._acquireScratch();
  5260. let count = 0;
  5261. let first = true;
  5262. while (!this.eat(close)) {
  5263. if (first) first = false;
  5264. else this.expect(tokTypes.comma);
  5265. if (allowEmpty && this.type === tokTypes.comma) {
  5266. scratch[count++] = null;
  5267. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  5268. break;
  5269. } else if (this.type === tokTypes.ellipsis) {
  5270. const rest = this.parseRestBinding();
  5271. this.parseBindingListItem(rest);
  5272. scratch[count++] = rest;
  5273. if (this.type === tokTypes.comma) {
  5274. this.raiseRecoverable(
  5275. this.start,
  5276. "Comma is not permitted after the rest element"
  5277. );
  5278. }
  5279. this.expect(close);
  5280. break;
  5281. } else {
  5282. scratch[count++] = this.parseAssignableListItem(allowModifiers);
  5283. }
  5284. }
  5285. return this._releaseScratch(scratch, count);
  5286. }
  5287. /**
  5288. * Owned `parseParenAndDistinguishExpression`, an exact-semantics copy of
  5289. * acorn 8's with the per-paren `DestructuringErrors` record pooled and the
  5290. * expression list built in a scratch array. Non-lazy mode delegates (the
  5291. * copy assumes ES6+, which `_lazy` guarantees via `ecmaVersion: "latest"`).
  5292. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  5293. * @param {boolean} canBeArrow whether this may be an arrow head
  5294. * @param {boolean | string} forInit for-init context flag
  5295. * @returns {Expression} expression node
  5296. * @this {ParserInternals}
  5297. */
  5298. parseParenAndDistinguishExpression(canBeArrow, forInit) {
  5299. if (!this._lazy || this._ecmaVersion < 6) {
  5300. return base.parseParenAndDistinguishExpression.call(
  5301. this,
  5302. canBeArrow,
  5303. forInit
  5304. );
  5305. }
  5306. const startPos = this.start;
  5307. const startLoc = this.startLoc;
  5308. const allowTrailingComma = this._ecmaVersion >= 8;
  5309. this.next();
  5310. const innerStartPos = this.start;
  5311. const innerStartLoc = this.startLoc;
  5312. const scratch = this._acquireScratch();
  5313. let count = 0;
  5314. let first = true;
  5315. let lastIsComma = false;
  5316. const refDestructuringErrors = this._acquireDestructuringErrors();
  5317. const oldYieldPos = this.yieldPos;
  5318. const oldAwaitPos = this.awaitPos;
  5319. let spreadStart;
  5320. this.yieldPos = 0;
  5321. this.awaitPos = 0;
  5322. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  5323. while (this.type !== tokTypes.parenR) {
  5324. if (first) first = false;
  5325. else this.expect(tokTypes.comma);
  5326. if (
  5327. allowTrailingComma &&
  5328. this.afterTrailingComma(tokTypes.parenR, true)
  5329. ) {
  5330. lastIsComma = true;
  5331. break;
  5332. } else if (this.type === tokTypes.ellipsis) {
  5333. spreadStart = this.start;
  5334. scratch[count++] = this.parseParenItem(this.parseRestBinding());
  5335. if (this.type === tokTypes.comma) {
  5336. this.raiseRecoverable(
  5337. this.start,
  5338. "Comma is not permitted after the rest element"
  5339. );
  5340. }
  5341. break;
  5342. } else {
  5343. scratch[count++] = this.parseMaybeAssign(
  5344. false,
  5345. refDestructuringErrors,
  5346. this.parseParenItem
  5347. );
  5348. }
  5349. }
  5350. const exprList = this._releaseScratch(scratch, count);
  5351. const innerEndPos = this.lastTokEnd;
  5352. this.expect(tokTypes.parenR);
  5353. if (
  5354. canBeArrow &&
  5355. this.shouldParseArrow(exprList) &&
  5356. this.eat(tokTypes.arrow)
  5357. ) {
  5358. this.checkPatternErrors(refDestructuringErrors, false);
  5359. this.checkYieldAwaitInDefaultParams();
  5360. // last read of the pooled record was above, so the arrow body parse
  5361. // below can already reuse its pool slot
  5362. this._releaseDestructuringErrors();
  5363. this.yieldPos = oldYieldPos;
  5364. this.awaitPos = oldAwaitPos;
  5365. return this.parseParenArrowList(startPos, startLoc, exprList, forInit);
  5366. }
  5367. if (exprList.length === 0 || lastIsComma) {
  5368. this.unexpected(this.lastTokStart);
  5369. }
  5370. if (spreadStart) this.unexpected(spreadStart);
  5371. this.checkExpressionErrors(refDestructuringErrors, true);
  5372. this._releaseDestructuringErrors();
  5373. this.yieldPos = oldYieldPos || this.yieldPos;
  5374. this.awaitPos = oldAwaitPos || this.awaitPos;
  5375. /** @type {Expression} */
  5376. let val;
  5377. if (exprList.length > 1) {
  5378. const seq = /** @type {Node & { expressions?: Expression[] }} */ (
  5379. this.startNodeAt(innerStartPos, innerStartLoc)
  5380. );
  5381. seq.expressions = exprList;
  5382. this.finishNodeAt(
  5383. /** @type {Node} */ (seq),
  5384. "SequenceExpression",
  5385. innerEndPos,
  5386. undefined
  5387. );
  5388. val = /** @type {Expression} */ (/** @type {unknown} */ (seq));
  5389. } else {
  5390. val = exprList[0];
  5391. }
  5392. if (this.options.preserveParens) {
  5393. const par = /** @type {Node & { expression?: Expression }} */ (
  5394. this.startNodeAt(startPos, startLoc)
  5395. );
  5396. par.expression = val;
  5397. return /** @type {Expression} */ (
  5398. /** @type {unknown} */ (
  5399. this.finishNode(/** @type {Node} */ (par), "ParenthesizedExpression")
  5400. )
  5401. );
  5402. }
  5403. return val;
  5404. }
  5405. /**
  5406. * Owned `afterTrailingComma`, acorn's verbatim (mode-independent), so the
  5407. * owned list parsers do not bounce through the dist for each element.
  5408. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/parseutil.js
  5409. * @param {TokenType} tokType closing token type
  5410. * @param {boolean=} notNext whether to leave the closing token unconsumed
  5411. * @returns {boolean} true when the list ended on a trailing comma
  5412. * @this {ParserInternals}
  5413. */
  5414. afterTrailingComma(tokType, notNext) {
  5415. if (this.type === tokType) {
  5416. const onTrailingComma =
  5417. /** @type {Options & { onTrailingComma?: (pos: number, loc?: Position) => void }} */
  5418. (this.options).onTrailingComma;
  5419. if (onTrailingComma) {
  5420. onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
  5421. }
  5422. if (!notNext) this.next();
  5423. return true;
  5424. }
  5425. return false;
  5426. }
  5427. /**
  5428. * Owned `checkExpressionErrors`, acorn's verbatim (mode-independent): it
  5429. * runs several times per expression from the owned spine.
  5430. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/parseutil.js
  5431. * @param {DestructuringErrorsShim | null=} refDestructuringErrors record to inspect
  5432. * @param {boolean=} andThrow whether to throw on error
  5433. * @returns {boolean} whether an error position was set
  5434. * @this {ParserInternals}
  5435. */
  5436. checkExpressionErrors(refDestructuringErrors, andThrow) {
  5437. if (!refDestructuringErrors) return false;
  5438. const shorthandAssign = refDestructuringErrors.shorthandAssign;
  5439. const doubleProto = refDestructuringErrors.doubleProto;
  5440. if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
  5441. if (shorthandAssign >= 0) {
  5442. this.raise(
  5443. shorthandAssign,
  5444. "Shorthand property assignments are valid only in destructuring patterns"
  5445. );
  5446. }
  5447. if (doubleProto >= 0) {
  5448. this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property");
  5449. }
  5450. return false;
  5451. }
  5452. /**
  5453. * Owned `parseExpression`: acorn wraps every call in `catchStackOverflow`,
  5454. * allocating a fresh closure per expression; inline the try/catch instead
  5455. * (same overflow-message translation, no closure). Non-lazy mode delegates.
  5456. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  5457. * @param {boolean | string=} forInit for-init context flag
  5458. * @param {DestructuringErrorsShim | null=} refDestructuringErrors destructuring errors to fill
  5459. * @returns {Expression} expression node
  5460. * @this {ParserInternals}
  5461. */
  5462. parseExpression(forInit, refDestructuringErrors) {
  5463. if (!this._lazy) {
  5464. return base.parseExpression.call(this, forInit, refDestructuringErrors);
  5465. }
  5466. try {
  5467. const startPos = this.start;
  5468. const startLoc = this.startLoc;
  5469. const expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  5470. if (this.type === tokTypes.comma) {
  5471. const node =
  5472. /** @type {Node & { expressions?: Expression[] }} */
  5473. (this.startNodeAt(startPos, startLoc));
  5474. node.expressions = [expr];
  5475. while (this.eat(tokTypes.comma)) {
  5476. node.expressions.push(
  5477. this.parseMaybeAssign(forInit, refDestructuringErrors)
  5478. );
  5479. }
  5480. return /** @type {Expression} */ (
  5481. /** @type {unknown} */ (this.finishNode(node, "SequenceExpression"))
  5482. );
  5483. }
  5484. return expr;
  5485. } catch (err) {
  5486. // acorn's catchStackOverflow: translate an engine stack-overflow error
  5487. if (
  5488. err instanceof Error &&
  5489. (/\bstack\b.*\b(exceeded|overflow)\b/i.test(err.message) ||
  5490. /\btoo much recursion\b/i.test(err.message))
  5491. ) {
  5492. this.raise(this.start, "Not enough stack space to parse input");
  5493. }
  5494. throw err;
  5495. }
  5496. }
  5497. /**
  5498. * Owned `parseNew`, an exact-semantics copy of acorn 8's: `NewExpression`
  5499. * lands on `NewExpressionNode`'s single shape (zero-argument calls share
  5500. * one empty array like acorn's `empty`); the rare `new.target` path keeps
  5501. * the generic node. Non-lazy mode delegates.
  5502. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  5503. * @returns {Expression} new expression or meta property
  5504. * @this {ParserInternals}
  5505. */
  5506. parseNew() {
  5507. if (!this._lazy) return base.parseNew.call(this);
  5508. if (this.containsEsc) {
  5509. this.raiseRecoverable(this.start, "Escape sequence in keyword new");
  5510. }
  5511. const nodeStart = this.start;
  5512. this.next();
  5513. if (this._ecmaVersion >= 6 && this.type === tokTypes.dot) {
  5514. const node =
  5515. /** @type {Node & { meta?: Node, property?: Identifier }} */
  5516. (this.startNodeAt(nodeStart, undefined));
  5517. const meta =
  5518. /** @type {Node & { name?: string }} */
  5519. (this.startNodeAt(nodeStart, undefined));
  5520. meta.name = "new";
  5521. node.meta = this.finishNode(/** @type {Node} */ (meta), "Identifier");
  5522. this.next();
  5523. const containsEsc = this.containsEsc;
  5524. node.property = this.parseIdent(true);
  5525. if (node.property.name !== "target") {
  5526. this.raiseRecoverable(
  5527. node.property.start,
  5528. "The only valid meta property for new is 'new.target'"
  5529. );
  5530. }
  5531. if (containsEsc) {
  5532. this.raiseRecoverable(
  5533. nodeStart,
  5534. "'new.target' must not contain escaped characters"
  5535. );
  5536. }
  5537. if (!this.allowNewDotTarget) {
  5538. this.raiseRecoverable(
  5539. nodeStart,
  5540. "'new.target' can only be used in functions and class static block"
  5541. );
  5542. }
  5543. return /** @type {Expression} */ (
  5544. /** @type {unknown} */ (this.finishNode(node, "MetaProperty"))
  5545. );
  5546. }
  5547. const startPos = this.start;
  5548. const startLoc = this.startLoc;
  5549. const callee = this.parseSubscripts(
  5550. this.parseExprAtom(null, false, true),
  5551. startPos,
  5552. startLoc,
  5553. true,
  5554. false
  5555. );
  5556. if (/** @type {string} */ (callee.type) === "Super") {
  5557. this.raiseRecoverable(startPos, "Invalid use of 'super'");
  5558. }
  5559. /** @type {Expression[]} */
  5560. const args = this.eat(tokTypes.parenL)
  5561. ? this.parseExprList(tokTypes.parenR, true, false)
  5562. : EMPTY_NEW_ARGS;
  5563. return /** @type {Expression} */ (
  5564. /** @type {unknown} */ (
  5565. new NewExpressionNode(nodeStart, this.lastTokEnd, callee, args)
  5566. )
  5567. );
  5568. }
  5569. /**
  5570. * Owned `parseTemplateElement` landing on `TemplateElementNode`'s single
  5571. * shape; matches acorn's CRLF normalization and invalid-escape handling.
  5572. * Non-lazy mode delegates.
  5573. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  5574. * @param {{ isTagged: boolean }} opts whether the template is tagged
  5575. * @returns {Node} template element
  5576. * @this {ParserInternals}
  5577. */
  5578. parseTemplateElement(opts) {
  5579. if (!this._lazy) return base.parseTemplateElement.call(this, opts);
  5580. const start = this.start;
  5581. /** @type {{ raw: string, cooked: string | null }} */
  5582. let value;
  5583. if (this.type === tokTypes.invalidTemplate) {
  5584. if (!opts.isTagged) {
  5585. this.raiseRecoverable(
  5586. this.start,
  5587. "Bad escape sequence in untagged template literal"
  5588. );
  5589. }
  5590. value = {
  5591. raw: /** @type {string} */ (this.value).replace(/\r\n?/g, "\n"),
  5592. cooked: null
  5593. };
  5594. } else {
  5595. const cooked = /** @type {string} */ (this.value);
  5596. // Every escape cooks strictly shorter and CRLF shortens, while a lone CR
  5597. // cooks to the LF the raw normalization would produce — so an
  5598. // equal-length cooked string IS the normalized raw. That covers every
  5599. // fast-path chunk (no backslash, no CR): raw and cooked share one string.
  5600. value = {
  5601. raw:
  5602. cooked.length === this.end - this.start
  5603. ? cooked
  5604. : this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  5605. cooked
  5606. };
  5607. }
  5608. this.next();
  5609. return /** @type {Node} */ (
  5610. /** @type {unknown} */ (
  5611. new TemplateElementNode(
  5612. start,
  5613. this.lastTokEnd,
  5614. value,
  5615. this.type === tokTypes.backQuote
  5616. )
  5617. )
  5618. );
  5619. }
  5620. /**
  5621. * Owned `parseTemplate` landing on `TemplateLiteralNode`'s single shape.
  5622. * Non-lazy mode delegates.
  5623. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  5624. * @param {{ isTagged?: boolean }=} opts whether the template is tagged
  5625. * @returns {Node} template literal
  5626. * @this {ParserInternals}
  5627. */
  5628. parseTemplate(opts) {
  5629. if (!this._lazy) {
  5630. return base.parseTemplate.call(
  5631. this,
  5632. /** @type {{ isTagged: boolean }} */ (opts)
  5633. );
  5634. }
  5635. const isTagged = (opts !== undefined && opts.isTagged) === true;
  5636. const start = this.start;
  5637. this.next();
  5638. const exprScratch = this._acquireScratch();
  5639. const quasiScratch = this._acquireScratch();
  5640. let exprCount = 0;
  5641. let quasiCount = 0;
  5642. // one options object for all chunks (only `isTagged` is ever read)
  5643. const eltOpts = { isTagged };
  5644. let curElt = /** @type {Node & { tail?: boolean }} */ (
  5645. this.parseTemplateElement(eltOpts)
  5646. );
  5647. quasiScratch[quasiCount++] = curElt;
  5648. while (!curElt.tail) {
  5649. if (this.type === tokTypes.eof) {
  5650. this.raise(this.pos, "Unterminated template literal");
  5651. }
  5652. this.expect(tokTypes.dollarBraceL);
  5653. exprScratch[exprCount++] = this.parseExpression();
  5654. this.expect(tokTypes.braceR);
  5655. curElt = /** @type {Node & { tail?: boolean }} */ (
  5656. this.parseTemplateElement(eltOpts)
  5657. );
  5658. quasiScratch[quasiCount++] = curElt;
  5659. }
  5660. this.next();
  5661. const quasis = this._releaseScratch(quasiScratch, quasiCount);
  5662. const expressions = this._releaseScratch(exprScratch, exprCount);
  5663. return /** @type {Node} */ (
  5664. /** @type {unknown} */ (
  5665. new TemplateLiteralNode(start, this.lastTokEnd, expressions, quasis)
  5666. )
  5667. );
  5668. }
  5669. /**
  5670. * Owned `parseMaybeUnary`, an exact-semantics copy of acorn 8's: prefix
  5671. * unary/update and postfix update nodes are built fully-formed on
  5672. * `UnaryNode`'s shared single shape. Non-lazy mode delegates to acorn.
  5673. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  5674. * @param {DestructuringErrorsShim | null} refDestructuringErrors destructuring errors to fill
  5675. * @param {boolean} sawUnary whether a unary operator was already consumed
  5676. * @param {boolean} incDec whether the caller was an update operator
  5677. * @param {boolean | string=} forInit for-init context flag
  5678. * @returns {Expression} expression node
  5679. * @this {ParserInternals}
  5680. */
  5681. parseMaybeUnary(refDestructuringErrors, sawUnary, incDec, forInit) {
  5682. if (!this._lazy) {
  5683. return base.parseMaybeUnary.call(
  5684. this,
  5685. refDestructuringErrors,
  5686. sawUnary,
  5687. incDec,
  5688. forInit
  5689. );
  5690. }
  5691. const startPos = this.start;
  5692. const startLoc = this.startLoc;
  5693. /** @type {Expression} */
  5694. let expr;
  5695. if (this.isContextual("await") && this.canAwait) {
  5696. expr = this.parseAwait(forInit);
  5697. sawUnary = true;
  5698. } else if (/** @type {TokenTypeInternal} */ (this.type).prefix) {
  5699. const update = this.type === tokTypes.incDec;
  5700. const operator = /** @type {string} */ (this.value);
  5701. this.next();
  5702. const argument = this.parseMaybeUnary(null, true, update, forInit);
  5703. this.checkExpressionErrors(refDestructuringErrors, true);
  5704. if (update) {
  5705. this.checkLValSimple(argument);
  5706. } else if (
  5707. this.strict &&
  5708. operator === "delete" &&
  5709. isLocalVariableAccess(argument)
  5710. ) {
  5711. this.raiseRecoverable(
  5712. startPos,
  5713. "Deleting local variable in strict mode"
  5714. );
  5715. } else if (operator === "delete" && isPrivateFieldAccess(argument)) {
  5716. this.raiseRecoverable(startPos, "Private fields can not be deleted");
  5717. } else {
  5718. sawUnary = true;
  5719. }
  5720. expr = /** @type {Expression} */ (
  5721. /** @type {unknown} */ (
  5722. new UnaryNode(
  5723. startPos,
  5724. this.lastTokEnd,
  5725. update ? "UpdateExpression" : "UnaryExpression",
  5726. operator,
  5727. true,
  5728. argument
  5729. )
  5730. )
  5731. );
  5732. } else if (!sawUnary && this.type === tokTypes.privateId) {
  5733. if (
  5734. (forInit || this.privateNameStack.length === 0) &&
  5735. this.options.checkPrivateFields
  5736. ) {
  5737. this.unexpected();
  5738. }
  5739. expr = /** @type {Expression} */ (
  5740. /** @type {unknown} */ (this.parsePrivateIdent())
  5741. );
  5742. // a private name is only valid as `#x in obj`
  5743. if (this.type !== tokTypes._in) this.unexpected();
  5744. } else {
  5745. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  5746. if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
  5747. while (
  5748. /** @type {TokenTypeInternal} */ (this.type).postfix &&
  5749. !this.canInsertSemicolon()
  5750. ) {
  5751. const operator = /** @type {string} */ (this.value);
  5752. this.checkLValSimple(expr);
  5753. this.next();
  5754. expr = /** @type {Expression} */ (
  5755. /** @type {unknown} */ (
  5756. new UnaryNode(
  5757. startPos,
  5758. this.lastTokEnd,
  5759. "UpdateExpression",
  5760. operator,
  5761. false,
  5762. expr
  5763. )
  5764. )
  5765. );
  5766. }
  5767. }
  5768. if (!incDec && this.eat(tokTypes.starstar)) {
  5769. if (sawUnary) {
  5770. this.unexpected(this.lastTokStart);
  5771. } else {
  5772. return this.buildBinary(
  5773. startPos,
  5774. startLoc,
  5775. expr,
  5776. this.parseMaybeUnary(null, false, false, forInit),
  5777. "**",
  5778. false
  5779. );
  5780. }
  5781. }
  5782. return expr;
  5783. }
  5784. /**
  5785. * Collapses the commonest expression shape — a name/number/string/keyword
  5786. * literal or `this` whose next source character can only begin a token that
  5787. * cannot continue an expression — into the atom, skipping the seven-layer
  5788. * `parseMaybeAssign` → `parseExprAtom` descent and its destructuring-error
  5789. * bookkeeping (which is a net no-op for a bare atom).
  5790. * @param {boolean | string=} forInit for-init context flag
  5791. * @returns {Expression | null} the atom, or `null` when the shape does not apply
  5792. * @this {ParserInternals}
  5793. */
  5794. _parseTrivialAtom(forInit) {
  5795. const code = this.input.charCodeAt(this.end);
  5796. if (code >= 128 || EXPRESSION_END_CHAR[code] !== 1) return null;
  5797. const type = this.type;
  5798. if (type === tokTypes.name) {
  5799. // both steer the chain themselves (`yield x`, `await x`)
  5800. const name = /** @type {string} */ (this.value);
  5801. if (name === "yield" || name === "await") return null;
  5802. this.potentialArrowAt = this.start;
  5803. this.potentialArrowInForAwait = forInit === "await";
  5804. return /** @type {Expression} */ (
  5805. /** @type {unknown} */ (this.parseIdent(false))
  5806. );
  5807. }
  5808. if (type === tokTypes.num || type === tokTypes.string) {
  5809. return /** @type {Expression} */ (
  5810. /** @type {unknown} */ (this.parseLiteral(this.value))
  5811. );
  5812. }
  5813. if (type === tokTypes._this) {
  5814. const node = new ThisNode(this.start, this.end);
  5815. this.next();
  5816. return /** @type {Expression} */ (/** @type {unknown} */ (node));
  5817. }
  5818. if (
  5819. type === tokTypes._null ||
  5820. type === tokTypes._true ||
  5821. type === tokTypes._false
  5822. ) {
  5823. const node = new LiteralNode(
  5824. this.start,
  5825. this.end,
  5826. type === tokTypes._null ? null : type === tokTypes._true,
  5827. /** @type {string} */ (type.keyword)
  5828. );
  5829. this.next();
  5830. return /** @type {Expression} */ (/** @type {unknown} */ (node));
  5831. }
  5832. return null;
  5833. }
  5834. /**
  5835. * Owned `parseMaybeAssign`, an exact-semantics copy of acorn 8's: the
  5836. * operator is captured before `next()` and the `AssignmentExpression` is
  5837. * built fully-formed on `AssignmentNode`'s single shape after the
  5838. * right-hand parse. Yield and non-lazy mode delegate to acorn.
  5839. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  5840. * @param {boolean | string=} forInit for-init context flag
  5841. * @param {DestructuringErrorsShim | null=} refDestructuringErrors destructuring errors to fill
  5842. * @param {((this: unknown, left: Expression, startPos: number, startLoc?: Position) => Expression)=} afterLeftParse hook applied to the parsed left side
  5843. * @returns {Expression} expression node
  5844. * @this {ParserInternals}
  5845. */
  5846. parseMaybeAssign(forInit, refDestructuringErrors, afterLeftParse) {
  5847. if (!this._lazy) {
  5848. return base.parseMaybeAssign.call(
  5849. this,
  5850. forInit,
  5851. refDestructuringErrors,
  5852. afterLeftParse
  5853. );
  5854. }
  5855. if (this._exprFastPath && afterLeftParse === undefined) {
  5856. const atom = this._parseTrivialAtom(forInit);
  5857. if (atom !== null) return atom;
  5858. }
  5859. if (this.isContextual("yield")) {
  5860. if (this.inGenerator) return this.parseYield(forInit);
  5861. // the tokenizer assumed an expression follows `yield`, but this
  5862. // isn't that kind of yield
  5863. this.exprAllowed = false;
  5864. }
  5865. let ownDestructuringErrors = false;
  5866. let oldParenAssign = -1;
  5867. let oldTrailingComma = -1;
  5868. let oldDoubleProto = -1;
  5869. if (refDestructuringErrors) {
  5870. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  5871. oldTrailingComma = refDestructuringErrors.trailingComma;
  5872. oldDoubleProto = refDestructuringErrors.doubleProto;
  5873. refDestructuringErrors.parenthesizedAssign =
  5874. refDestructuringErrors.trailingComma = -1;
  5875. } else {
  5876. refDestructuringErrors = this._acquireDestructuringErrors();
  5877. ownDestructuringErrors = true;
  5878. }
  5879. const startPos = this.start;
  5880. const startLoc = this.startLoc;
  5881. if (this.type === tokTypes.parenL || this.type === tokTypes.name) {
  5882. this.potentialArrowAt = this.start;
  5883. this.potentialArrowInForAwait = forInit === "await";
  5884. }
  5885. let left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  5886. if (afterLeftParse) {
  5887. left = afterLeftParse.call(this, left, startPos, startLoc);
  5888. }
  5889. if (/** @type {TokenTypeInternal} */ (this.type).isAssign) {
  5890. const operator = /** @type {string} */ (this.value);
  5891. if (this.type === tokTypes.eq) {
  5892. left = /** @type {Expression} */ (
  5893. this.toAssignable(left, false, refDestructuringErrors)
  5894. );
  5895. }
  5896. if (!ownDestructuringErrors) {
  5897. refDestructuringErrors.parenthesizedAssign =
  5898. refDestructuringErrors.trailingComma =
  5899. refDestructuringErrors.doubleProto =
  5900. -1;
  5901. }
  5902. if (refDestructuringErrors.shorthandAssign >= left.start) {
  5903. // shorthand default was used correctly
  5904. refDestructuringErrors.shorthandAssign = -1;
  5905. }
  5906. if (this.type === tokTypes.eq) this.checkLValPattern(left);
  5907. else this.checkLValSimple(left);
  5908. // the own record's last read was above, so the nested right-side
  5909. // parse below can already reuse its pool slot
  5910. if (ownDestructuringErrors) this._releaseDestructuringErrors();
  5911. this.next();
  5912. const right = this.parseMaybeAssign(forInit);
  5913. if (oldDoubleProto > -1) {
  5914. refDestructuringErrors.doubleProto = oldDoubleProto;
  5915. }
  5916. return /** @type {Expression} */ (
  5917. /** @type {unknown} */ (
  5918. new AssignmentNode(startPos, this.lastTokEnd, operator, left, right)
  5919. )
  5920. );
  5921. } else if (ownDestructuringErrors) {
  5922. this.checkExpressionErrors(refDestructuringErrors, true);
  5923. this._releaseDestructuringErrors();
  5924. }
  5925. if (oldParenAssign > -1) {
  5926. refDestructuringErrors.parenthesizedAssign = oldParenAssign;
  5927. }
  5928. if (oldTrailingComma > -1) {
  5929. refDestructuringErrors.trailingComma = oldTrailingComma;
  5930. }
  5931. return left;
  5932. }
  5933. /**
  5934. * Owned `parseExprOps`, an exact copy of acorn 8's, so the hot expression
  5935. * spine (`parseMaybeAssign` → here → `parseMaybeUnary`) stays monomorphic
  5936. * on owned code. Non-lazy mode delegates.
  5937. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  5938. * @param {boolean | string=} forInit for-init context flag
  5939. * @param {DestructuringErrorsShim | null=} refDestructuringErrors destructuring errors to fill
  5940. * @returns {Expression} expression node
  5941. * @this {ParserInternals}
  5942. */
  5943. parseExprOps(forInit, refDestructuringErrors) {
  5944. if (!this._lazy) {
  5945. return base.parseExprOps.call(this, forInit, refDestructuringErrors);
  5946. }
  5947. const startPos = this.start;
  5948. const startLoc = this.startLoc;
  5949. const expr = this.parseMaybeUnary(
  5950. refDestructuringErrors || null,
  5951. false,
  5952. false,
  5953. forInit
  5954. );
  5955. if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
  5956. const isArrow = this._arrowFastPath
  5957. ? expr === this._lastArrow && expr.start === startPos
  5958. : expr.start === startPos && expr.type === "ArrowFunctionExpression";
  5959. return isArrow
  5960. ? expr
  5961. : this.parseExprOp(expr, startPos, startLoc, -1, forInit);
  5962. }
  5963. /**
  5964. * Owned `parseExprOp`, an exact-semantics copy of acorn 8's with the
  5965. * same-precedence continuation turned from tail recursion into a loop —
  5966. * `a + b + c + d` runs one frame instead of one per operator. Non-lazy mode
  5967. * delegates.
  5968. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  5969. * @param {Expression} left left operand
  5970. * @param {number} leftStartPos expression start offset
  5971. * @param {Position | undefined} leftStartLoc expression start position
  5972. * @param {number} minPrec minimal binding precedence to continue
  5973. * @param {boolean | string=} forInit for-init context flag (excludes `in`)
  5974. * @returns {Expression} expression node
  5975. * @this {ParserInternals}
  5976. */
  5977. parseExprOp(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  5978. if (!this._lazy) {
  5979. return base.parseExprOp.call(
  5980. this,
  5981. left,
  5982. leftStartPos,
  5983. leftStartLoc,
  5984. minPrec,
  5985. forInit
  5986. );
  5987. }
  5988. for (;;) {
  5989. const type = /** @type {TokenTypeInternal} */ (this.type);
  5990. let prec = type.binop;
  5991. // acorn's TokenType sets binop to null (never undefined) when absent
  5992. if (
  5993. prec === null ||
  5994. prec <= minPrec ||
  5995. (forInit && type === tokTypes._in)
  5996. ) {
  5997. return left;
  5998. }
  5999. const logical =
  6000. type === tokTypes.logicalOR || type === tokTypes.logicalAND;
  6001. const coalesce = type === tokTypes.coalesce;
  6002. if (coalesce) {
  6003. // acorn parses `??`'s right at logical precedence so the mixing
  6004. // check below sees any unparenthesized `&&`/`||` as a sibling
  6005. prec = /** @type {number} */ (
  6006. /** @type {TokenTypeInternal} */ (tokTypes.logicalAND).binop
  6007. );
  6008. }
  6009. const op = /** @type {string} */ (this.value);
  6010. this.next();
  6011. const startPos = this.start;
  6012. const right = this.parseExprOp(
  6013. this.parseMaybeUnary(null, false, false, forInit),
  6014. startPos,
  6015. this.startLoc,
  6016. prec,
  6017. forInit
  6018. );
  6019. left = this.buildBinary(
  6020. leftStartPos,
  6021. leftStartLoc,
  6022. left,
  6023. right,
  6024. op,
  6025. logical || coalesce
  6026. );
  6027. if (
  6028. (logical && this.type === tokTypes.coalesce) ||
  6029. (coalesce &&
  6030. (this.type === tokTypes.logicalOR ||
  6031. this.type === tokTypes.logicalAND))
  6032. ) {
  6033. this.raiseRecoverable(
  6034. this.start,
  6035. "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"
  6036. );
  6037. }
  6038. }
  6039. }
  6040. /**
  6041. * Owned `buildBinary` (acorn calls it only from `parseExprOp`): binary and
  6042. * logical nodes are built fully-formed on `BinaryNode`'s single shape.
  6043. * Non-lazy mode delegates to acorn.
  6044. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  6045. * @param {number} startPos expression start offset
  6046. * @param {Position | undefined} startLoc expression start position
  6047. * @param {Expression} left left operand
  6048. * @param {Expression} right right operand
  6049. * @param {string} op operator text
  6050. * @param {boolean} logical whether this is a logical/coalesce expression
  6051. * @returns {Expression} binary or logical expression node
  6052. * @this {ParserInternals}
  6053. */
  6054. buildBinary(startPos, startLoc, left, right, op, logical) {
  6055. if (!this._lazy) {
  6056. return base.buildBinary.call(
  6057. this,
  6058. startPos,
  6059. startLoc,
  6060. left,
  6061. right,
  6062. op,
  6063. logical
  6064. );
  6065. }
  6066. const rightNode = /** @type {Node} */ (/** @type {unknown} */ (right));
  6067. if (rightNode.type === "PrivateIdentifier") {
  6068. this.raise(
  6069. rightNode.start,
  6070. "Private identifier can only be left side of binary expression"
  6071. );
  6072. }
  6073. return /** @type {Expression} */ (
  6074. /** @type {unknown} */ (
  6075. new BinaryNode(
  6076. startPos,
  6077. this.lastTokEnd,
  6078. logical ? "LogicalExpression" : "BinaryExpression",
  6079. left,
  6080. op,
  6081. right
  6082. )
  6083. )
  6084. );
  6085. }
  6086. /**
  6087. * Owned `parseExprAtom` for the hot atoms: identifiers (with acorn's exact
  6088. * async-function/async-arrow detection), number/string literals, keyword
  6089. * literals (`true`/`false`/`null` — on the same `LiteralNode` shape as the
  6090. * rest) and `this`. Everything else, and non-lazy mode, delegates to acorn.
  6091. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  6092. * @param {DestructuringErrorsShim | null=} refDestructuringErrors destructuring errors to fill
  6093. * @param {boolean | string=} forInit for-init context flag
  6094. * @param {boolean=} forNew whether parsed as a `new` callee
  6095. * @returns {Expression} expression atom
  6096. * @this {ParserInternals}
  6097. */
  6098. parseExprAtom(refDestructuringErrors, forInit, forNew) {
  6099. if (!this._lazy) {
  6100. return base.parseExprAtom.call(
  6101. this,
  6102. refDestructuringErrors,
  6103. forInit,
  6104. forNew
  6105. );
  6106. }
  6107. // division in expression position: the tokenizer got confused, force a
  6108. // regexp re-read (mirrors the top of acorn's parseExprAtom)
  6109. if (this.type === tokTypes.slash) this.readRegexp();
  6110. const type = this.type;
  6111. if (type === tokTypes.name) {
  6112. const canBeArrow = this.potentialArrowAt === this.start;
  6113. const startPos = this.start;
  6114. const startLoc = this.startLoc;
  6115. const containsEsc = this.containsEsc;
  6116. let id = this.parseIdent(false);
  6117. // `async` compare first — almost every identifier fails it, skipping
  6118. // the version probe (all operands are pure)
  6119. if (
  6120. id.name === "async" &&
  6121. !containsEsc &&
  6122. this._ecmaVersion >= 8 &&
  6123. !this.canInsertSemicolon() &&
  6124. this.eat(tokTypes._function)
  6125. ) {
  6126. this.overrideContext(tokContexts.f_expr);
  6127. return this.parseFunction(
  6128. this.startNodeAt(startPos, startLoc),
  6129. 0,
  6130. false,
  6131. true,
  6132. forInit
  6133. );
  6134. }
  6135. if (canBeArrow && !this.canInsertSemicolon()) {
  6136. if (this.eat(tokTypes.arrow)) {
  6137. return this.parseArrowExpression(
  6138. this.startNodeAt(startPos, startLoc),
  6139. [id],
  6140. false,
  6141. forInit
  6142. );
  6143. }
  6144. if (
  6145. id.name === "async" &&
  6146. !containsEsc &&
  6147. this._ecmaVersion >= 8 &&
  6148. this.type === tokTypes.name &&
  6149. (!this.potentialArrowInForAwait ||
  6150. this.value !== "of" ||
  6151. this.containsEsc)
  6152. ) {
  6153. id = this.parseIdent(false);
  6154. if (this.canInsertSemicolon() || !this.eat(tokTypes.arrow)) {
  6155. this.unexpected();
  6156. }
  6157. return this.parseArrowExpression(
  6158. this.startNodeAt(startPos, startLoc),
  6159. [id],
  6160. true,
  6161. forInit
  6162. );
  6163. }
  6164. }
  6165. return id;
  6166. }
  6167. if (type === tokTypes.num || type === tokTypes.string) {
  6168. return /** @type {Expression} */ (
  6169. /** @type {unknown} */ (this.parseLiteral(this.value))
  6170. );
  6171. }
  6172. if (
  6173. type === tokTypes._null ||
  6174. type === tokTypes._true ||
  6175. type === tokTypes._false
  6176. ) {
  6177. const node = new LiteralNode(
  6178. this.start,
  6179. this.end,
  6180. type === tokTypes._null ? null : type === tokTypes._true,
  6181. /** @type {string} */ (type.keyword)
  6182. );
  6183. this.next();
  6184. return /** @type {Expression} */ (/** @type {unknown} */ (node));
  6185. }
  6186. if (type === tokTypes._this) {
  6187. const node = new ThisNode(this.start, this.end);
  6188. this.next();
  6189. return /** @type {Expression} */ (/** @type {unknown} */ (node));
  6190. }
  6191. if (type === tokTypes.bracketL) {
  6192. const start = this.start;
  6193. this.next();
  6194. const elements = this.parseExprList(
  6195. tokTypes.bracketR,
  6196. true,
  6197. true,
  6198. refDestructuringErrors
  6199. );
  6200. return /** @type {Expression} */ (
  6201. /** @type {unknown} */ (
  6202. new ArrayExpressionNode(start, this.lastTokEnd, elements)
  6203. )
  6204. );
  6205. }
  6206. return base.parseExprAtom.call(
  6207. this,
  6208. refDestructuringErrors,
  6209. forInit,
  6210. forNew
  6211. );
  6212. }
  6213. /**
  6214. * Owned `parseObj`, an exact-semantics copy of acorn 8's landing on
  6215. * `ObjectNode`'s single shape (the ES5 trailing-comma gate is dropped —
  6216. * the fast path requires ES11+). Non-lazy mode delegates.
  6217. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  6218. * @param {boolean} isPattern whether parsing a binding pattern
  6219. * @param {DestructuringErrorsShim | null=} refDestructuringErrors destructuring errors to fill
  6220. * @returns {Node} object expression or pattern
  6221. * @this {ParserInternals}
  6222. */
  6223. parseObj(isPattern, refDestructuringErrors) {
  6224. if (!this._subscriptFastPath) {
  6225. return base.parseObj.call(this, isPattern, refDestructuringErrors);
  6226. }
  6227. const start = this.start;
  6228. let first = true;
  6229. // acorn's ES6+ `checkPropClash` only ever reads/writes `.proto`, so the
  6230. // record is pooled by nesting depth (like `_deStack`); a subclass override
  6231. // might write arbitrary keys and gets a fresh `{}` instead. Depth resets
  6232. // implicitly since a raise aborts the whole parse.
  6233. const pooled = this._propHashFastPath;
  6234. /** @type {Record<string, unknown>} */
  6235. let propHash;
  6236. if (pooled) {
  6237. const stack = this._propHashStack;
  6238. const depth = this._propHashDepth++;
  6239. const cached = stack[depth];
  6240. if (cached !== undefined) {
  6241. cached.proto = false;
  6242. propHash = cached;
  6243. } else {
  6244. propHash = stack[depth] = { proto: false };
  6245. }
  6246. } else {
  6247. propHash = {};
  6248. }
  6249. const scratch = this._acquireScratch();
  6250. let count = 0;
  6251. this.next();
  6252. while (!this.eat(tokTypes.braceR)) {
  6253. if (!first) {
  6254. this.expect(tokTypes.comma);
  6255. if (this.afterTrailingComma(tokTypes.braceR)) break;
  6256. } else {
  6257. first = false;
  6258. }
  6259. const prop = this.parseProperty(isPattern, refDestructuringErrors);
  6260. if (!isPattern) {
  6261. this.checkPropClash(prop, propHash, refDestructuringErrors);
  6262. }
  6263. scratch[count++] = prop;
  6264. }
  6265. if (pooled) this._propHashDepth--;
  6266. return /** @type {Node} */ (
  6267. /** @type {unknown} */ (
  6268. new ObjectNode(
  6269. start,
  6270. this.lastTokEnd,
  6271. isPattern ? "ObjectPattern" : "ObjectExpression",
  6272. this._releaseScratch(scratch, count)
  6273. )
  6274. )
  6275. );
  6276. }
  6277. /**
  6278. * Owned `parseProperty`, an exact-semantics copy of acorn 8's: spread/rest
  6279. * land fully-formed on `RestSpreadNode` and properties start pre-shaped on
  6280. * `PropertyNode`, which acorn's shared `parsePropertyName`/
  6281. * `parsePropertyValue` then fill in place (ES9+ semantics assumed via the
  6282. * ES11 fast-path gate). Non-lazy mode delegates.
  6283. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  6284. * @param {boolean} isPattern whether parsing a binding pattern
  6285. * @param {DestructuringErrorsShim | null=} refDestructuringErrors destructuring errors to fill
  6286. * @returns {Node} property, spread element or rest element
  6287. * @this {ParserInternals}
  6288. */
  6289. parseProperty(isPattern, refDestructuringErrors) {
  6290. if (!this._subscriptFastPath) {
  6291. return base.parseProperty.call(this, isPattern, refDestructuringErrors);
  6292. }
  6293. const nodeStart = this.start;
  6294. if (this.eat(tokTypes.ellipsis)) {
  6295. if (isPattern) {
  6296. const argument = /** @type {Node} */ (
  6297. /** @type {unknown} */ (this.parseIdent(false))
  6298. );
  6299. if (this.type === tokTypes.comma) {
  6300. this.raiseRecoverable(
  6301. this.start,
  6302. "Comma is not permitted after the rest element"
  6303. );
  6304. }
  6305. return /** @type {Node} */ (
  6306. /** @type {unknown} */ (
  6307. new RestSpreadNode(
  6308. nodeStart,
  6309. this.lastTokEnd,
  6310. "RestElement",
  6311. argument
  6312. )
  6313. )
  6314. );
  6315. }
  6316. const argument = /** @type {Node} */ (
  6317. /** @type {unknown} */ (
  6318. this.parseMaybeAssign(false, refDestructuringErrors)
  6319. )
  6320. );
  6321. // disallow trailing comma via `this.toAssignable()`
  6322. if (
  6323. this.type === tokTypes.comma &&
  6324. refDestructuringErrors &&
  6325. refDestructuringErrors.trailingComma < 0
  6326. ) {
  6327. refDestructuringErrors.trailingComma = this.start;
  6328. }
  6329. return /** @type {Node} */ (
  6330. /** @type {unknown} */ (
  6331. new RestSpreadNode(
  6332. nodeStart,
  6333. this.lastTokEnd,
  6334. "SpreadElement",
  6335. argument
  6336. )
  6337. )
  6338. );
  6339. }
  6340. const prop = /** @type {Node} */ (
  6341. /** @type {unknown} */ (new PropertyNode(nodeStart))
  6342. );
  6343. let isGenerator = false;
  6344. /** @type {number | undefined} */
  6345. let startPos;
  6346. /** @type {Position | undefined} */
  6347. let startLoc;
  6348. if (isPattern || refDestructuringErrors) {
  6349. startPos = this.start;
  6350. startLoc = this.startLoc;
  6351. }
  6352. if (!isPattern) isGenerator = this.eat(tokTypes.star);
  6353. const containsEsc = this.containsEsc;
  6354. this.parsePropertyName(prop);
  6355. let isAsync = false;
  6356. if (!isPattern && !containsEsc && !isGenerator && this.isAsyncProp(prop)) {
  6357. isAsync = true;
  6358. isGenerator = this.eat(tokTypes.star);
  6359. this.parsePropertyName(prop);
  6360. }
  6361. this.parsePropertyValue(
  6362. prop,
  6363. isPattern,
  6364. isGenerator,
  6365. isAsync,
  6366. startPos,
  6367. startLoc,
  6368. refDestructuringErrors,
  6369. containsEsc
  6370. );
  6371. return this.finishNode(prop, "Property");
  6372. }
  6373. /**
  6374. * Owned `parseLiteral`: builds the finished `LiteralNode` directly; the
  6375. * `bigint` branch matches acorn's. Non-lazy mode delegates to acorn.
  6376. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  6377. * @param {unknown} value literal value
  6378. * @returns {Node} literal node
  6379. * @this {ParserInternals}
  6380. */
  6381. parseLiteral(value) {
  6382. if (!this._lazy) return base.parseLiteral.call(this, value);
  6383. const start = this.start;
  6384. const end = this.end;
  6385. const raw = this.input.slice(start, end);
  6386. const node = new LiteralNode(start, end, value, raw);
  6387. if (raw.charCodeAt(raw.length - 1) === 110) {
  6388. // acorn falls back to normalizing `raw` when `BigInt` is missing;
  6389. // every Node version webpack supports has it, so `value` is set
  6390. /** @type {LiteralNode & { bigint?: string }} */ (node).bigint =
  6391. /** @type {bigint} */ (value).toString();
  6392. }
  6393. this.next();
  6394. return /** @type {Node} */ (/** @type {unknown} */ (node));
  6395. }
  6396. /**
  6397. * Single-construction regexp literals: acorn validates the pattern and
  6398. * then builds the value with a second `new RegExp`. This override scans
  6399. * like acorn, keeps acorn's flag validation (for its exact messages) and
  6400. * lets one `new RegExp` be both the V8-backed validation and the value.
  6401. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/tokenize.js
  6402. * @this {ParserInternals & { regexpState: unknown }}
  6403. * @returns {void}
  6404. */
  6405. readRegexp() {
  6406. const input = this.input;
  6407. const start = this.pos;
  6408. const len = input.length;
  6409. let escaped = false;
  6410. let inClass = false;
  6411. let pos = start;
  6412. for (;;) {
  6413. if (pos >= len) this.raise(start, "Unterminated regular expression");
  6414. const ch = input.charCodeAt(pos);
  6415. // LF, CR, LS, PS
  6416. if (ch === 10 || ch === 13 || ch === 0x2028 || ch === 0x2029) {
  6417. this.raise(start, "Unterminated regular expression");
  6418. }
  6419. if (escaped) {
  6420. escaped = false;
  6421. } else {
  6422. if (ch === 91) inClass = true;
  6423. else if (ch === 93 && inClass) inClass = false;
  6424. else if (ch === 47 && !inClass) break;
  6425. escaped = ch === 92;
  6426. }
  6427. pos++;
  6428. }
  6429. const pattern = input.slice(start, pos);
  6430. this.pos = pos + 1;
  6431. const flagsStart = this.pos;
  6432. const flags = this.readWord1();
  6433. if (this.containsEsc) this.unexpected(flagsStart);
  6434. // acorn's per-ecmaVersion flag validation, kept for its exact errors;
  6435. // the whitelist is precomputed in the constructor
  6436. const ecmaVersion = this._ecmaVersion;
  6437. const validFlags = this._validRegexpFlags;
  6438. let hasU = false;
  6439. let hasV = false;
  6440. for (let i = 0; i < flags.length; i++) {
  6441. const flag = flags.charAt(i);
  6442. if (!validFlags.includes(flag)) {
  6443. this.raise(start, "Invalid regular expression flag");
  6444. }
  6445. if (flags.includes(flag, i + 1)) {
  6446. this.raise(start, "Duplicate regular expression flag");
  6447. }
  6448. if (flag === "u") hasU = true;
  6449. if (flag === "v") hasV = true;
  6450. }
  6451. if (ecmaVersion >= 15 && hasU && hasV) {
  6452. this.raise(start, "Invalid regular expression flag");
  6453. }
  6454. let value = null;
  6455. try {
  6456. value = new RegExp(pattern, flags);
  6457. } catch (err) {
  6458. // V8's verdict on the pattern, like validateRegExpPattern below
  6459. this.raiseRecoverable(start, /** @type {Error} */ (err).message);
  6460. }
  6461. return this.finishToken(tokTypes.regexp, { pattern, flags, value });
  6462. }
  6463. // ----- regexp validation (V8-backed, replaces acorn's JS revalidation) -----
  6464. /**
  6465. * Acorn constructs the literal's `RegExp` value right after this hook, so
  6466. * V8 validates every pattern anyway; acorn's own JS copy of
  6467. * that validation costs several percent of parse time. Raise from V8's
  6468. * verdict instead — invalid patterns still fail the module build, only
  6469. * exotic engine-specific message texts may differ.
  6470. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/regexp.js
  6471. * @param {{ start: number, source: string, flags: string }} state acorn regexp validation state
  6472. * @this {ParserInternals}
  6473. */
  6474. validateRegExpPattern(state) {
  6475. try {
  6476. // eslint-disable-next-line no-new
  6477. new RegExp(state.source, state.flags);
  6478. } catch (err) {
  6479. this.raiseRecoverable(state.start, /** @type {Error} */ (err).message);
  6480. }
  6481. }
  6482. // ----- scope tracking (Set-based, replaces acorn's array + indexOf) -----
  6483. /**
  6484. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/scope.js
  6485. * @param {number} flags scope flags
  6486. * @this {ParserInternals}
  6487. */
  6488. enterScope(flags) {
  6489. this.scopeStack.push(new Scope(flags));
  6490. }
  6491. /**
  6492. * Set-backed replacement for acorn's `declareName` on Set-backed scopes.
  6493. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/scope.js
  6494. * @param {string} name declared name
  6495. * @param {number} bindingType acorn BIND_* binding type
  6496. * @param {number} pos source offset for redeclaration errors
  6497. * @this {ParserInternals}
  6498. */
  6499. declareName(name, bindingType, pos) {
  6500. let redeclared = false;
  6501. if (bindingType === BIND_LEXICAL) {
  6502. const scope = this.currentScope();
  6503. redeclared =
  6504. (scope.lexical !== undefined && scope.lexical.has(name)) ||
  6505. (scope.functions !== undefined && scope.functions.has(name)) ||
  6506. (scope.var !== undefined && scope.var.has(name));
  6507. if (scope.lexical === undefined) {
  6508. scope.firstLexical = name;
  6509. scope.lexical = new Set();
  6510. }
  6511. scope.lexical.add(name);
  6512. if (this.inModule && scope.flags & SCOPE_TOP) {
  6513. delete this.undefinedExports[name];
  6514. }
  6515. } else if (bindingType === /* BIND_SIMPLE_CATCH */ 4) {
  6516. const scope = this.currentScope();
  6517. if (scope.lexical === undefined) {
  6518. scope.firstLexical = name;
  6519. scope.lexical = new Set();
  6520. }
  6521. scope.lexical.add(name);
  6522. } else if (bindingType === /* BIND_FUNCTION */ 3) {
  6523. const scope = this.currentScope();
  6524. redeclared = this.treatFunctionsAsVar
  6525. ? scope.lexical !== undefined && scope.lexical.has(name)
  6526. : (scope.lexical !== undefined && scope.lexical.has(name)) ||
  6527. (scope.var !== undefined && scope.var.has(name));
  6528. (scope.functions || (scope.functions = new Set())).add(name);
  6529. } else {
  6530. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  6531. const scope = this.scopeStack[i];
  6532. if (
  6533. (scope.lexical !== undefined &&
  6534. scope.lexical.has(name) &&
  6535. !(
  6536. scope.flags & SCOPE_SIMPLE_CATCH && scope.firstLexical === name
  6537. )) ||
  6538. // lazy-Set check first: `functions` is undefined for almost all
  6539. // scopes, and the method call walks no state worth paying for then
  6540. (scope.functions !== undefined &&
  6541. !this.treatFunctionsAsVarInScope(scope) &&
  6542. scope.functions.has(name))
  6543. ) {
  6544. redeclared = true;
  6545. break;
  6546. }
  6547. (scope.var || (scope.var = new Set())).add(name);
  6548. if (this.inModule && scope.flags & SCOPE_TOP) {
  6549. delete this.undefinedExports[name];
  6550. }
  6551. if (scope.flags & SCOPE_VAR) break;
  6552. }
  6553. }
  6554. if (redeclared) {
  6555. this.raiseRecoverable(
  6556. pos,
  6557. `Identifier '${name}' has already been declared`
  6558. );
  6559. }
  6560. }
  6561. /**
  6562. * Set-backed replacement for acorn's `checkLocalExport` on Set-backed scopes.
  6563. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/scope.js
  6564. * @param {Identifier} id exported identifier
  6565. * @this {ParserInternals}
  6566. */
  6567. checkLocalExport(id) {
  6568. const topScope = this.scopeStack[0];
  6569. if (
  6570. !(topScope.lexical !== undefined && topScope.lexical.has(id.name)) &&
  6571. !(topScope.var !== undefined && topScope.var.has(id.name))
  6572. ) {
  6573. this.undefinedExports[id.name] = id;
  6574. }
  6575. }
  6576. // ----- import attributes (`with { ... }` / legacy `assert { ... }`) -----
  6577. /**
  6578. * @returns {ImportAttribute[]} import attributes
  6579. * @this {ParserInternals}
  6580. */
  6581. parseWithClause() {
  6582. /** @type {ImportAttribute[] & { [LEGACY_ASSERT_ATTRIBUTES]?: boolean }} */
  6583. const nodes = [];
  6584. const isAssertLegacy = this.value === "assert";
  6585. if (isAssertLegacy) {
  6586. if (!this.eat(tokTypes.name)) {
  6587. return nodes;
  6588. }
  6589. } else if (!this.eat(tokTypes._with)) {
  6590. return nodes;
  6591. }
  6592. this.expect(tokTypes.braceL);
  6593. /** @type {Record<string, boolean>} */
  6594. const attributeKeys = {};
  6595. let first = true;
  6596. while (!this.eat(tokTypes.braceR)) {
  6597. if (!first) {
  6598. this.expect(tokTypes.comma);
  6599. if (this.afterTrailingComma(tokTypes.braceR)) {
  6600. break;
  6601. }
  6602. } else {
  6603. first = false;
  6604. }
  6605. const attr = this.parseImportAttribute();
  6606. const keyName =
  6607. /** @type {string} */
  6608. (attr.key.type === "Identifier" ? attr.key.name : attr.key.value);
  6609. if (Object.prototype.hasOwnProperty.call(attributeKeys, keyName)) {
  6610. this.raiseRecoverable(
  6611. attr.key.start,
  6612. `Duplicate attribute key '${keyName}'`
  6613. );
  6614. }
  6615. attributeKeys[keyName] = true;
  6616. nodes.push(attr);
  6617. }
  6618. if (isAssertLegacy) {
  6619. nodes[LEGACY_ASSERT_ATTRIBUTES] = true;
  6620. }
  6621. return nodes;
  6622. }
  6623. // ----- import phases (`import defer/source`, `import.defer/source()`) -----
  6624. /**
  6625. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  6626. * @param {Node & { phase?: ImportPhase }} node import declaration node
  6627. * @returns {Node} finished node
  6628. * @this {ParserInternals}
  6629. */
  6630. parseImport(node) {
  6631. this._moduleSyntaxSeen = true;
  6632. this._importPhase = null;
  6633. const result = base.parseImport.call(this, node);
  6634. if (this._importPhase) node.phase = this._importPhase;
  6635. return result;
  6636. }
  6637. /**
  6638. * Owned `parseExport` only to flag module syntax for the auto-fallback guard;
  6639. * parsing itself delegates to acorn.
  6640. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  6641. * @param {Node} node started export node
  6642. * @param {unknown} exports export-name tracking object
  6643. * @returns {Node} export declaration
  6644. * @this {ParserInternals}
  6645. */
  6646. parseExport(node, exports) {
  6647. this._moduleSyntaxSeen = true;
  6648. return base.parseExport.call(this, node, exports);
  6649. }
  6650. /**
  6651. * Owned `parseAwait` only to flag top-level await (module-only) for the
  6652. * auto-fallback guard; await inside a function is not module syntax.
  6653. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  6654. * @param {boolean | string=} forInit for-loop init context flag
  6655. * @returns {Expression} await expression
  6656. * @this {ParserInternals}
  6657. */
  6658. parseAwait(forInit) {
  6659. if (this.inModule && this.currentVarScope().flags & SCOPE_TOP) {
  6660. this._moduleSyntaxSeen = true;
  6661. }
  6662. return base.parseAwait.call(this, forInit);
  6663. }
  6664. /**
  6665. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/statement.js
  6666. * @returns {AnyImportSpecifier[]} import specifiers
  6667. * @this {ParserInternals}
  6668. */
  6669. parseImportSpecifiers() {
  6670. if (!this._importPhasesEnabled) {
  6671. return base.parseImportSpecifiers.call(this);
  6672. }
  6673. /** @type {ImportPhase | null} */
  6674. const phase = this.isContextual("defer")
  6675. ? "defer"
  6676. : this.isContextual("source")
  6677. ? "source"
  6678. : null;
  6679. if (!phase) return base.parseImportSpecifiers.call(this);
  6680. const phaseId = this.parseIdent();
  6681. if (this.isContextual("from") || this.type === tokTypes.comma) {
  6682. // `defer`/`source` was the default import name, not a phase modifier
  6683. const defaultSpecifier =
  6684. /** @type {ImportDefaultSpecifier} */
  6685. (
  6686. this.startNodeAt(
  6687. phaseId.start,
  6688. phaseId.loc ? phaseId.loc.start : undefined
  6689. )
  6690. );
  6691. defaultSpecifier.local = phaseId;
  6692. this.checkLValSimple(phaseId, BIND_LEXICAL);
  6693. /** @type {AnyImportSpecifier[]} */
  6694. const nodes = [
  6695. /** @type {ImportDefaultSpecifier} */
  6696. (this.finishNode(defaultSpecifier, "ImportDefaultSpecifier"))
  6697. ];
  6698. if (this.eat(tokTypes.comma)) {
  6699. if (this.type !== tokTypes.star && this.type !== tokTypes.braceL) {
  6700. this.unexpected();
  6701. }
  6702. nodes.push(...base.parseImportSpecifiers.call(this));
  6703. }
  6704. return nodes;
  6705. }
  6706. this._importPhase = phase;
  6707. if (phase === "defer") {
  6708. if (this.type !== tokTypes.star) {
  6709. this.raiseRecoverable(
  6710. phaseId.start,
  6711. "'import defer' can only be used with namespace imports ('import defer * as identifierName from ...')."
  6712. );
  6713. }
  6714. } else if (this.type !== tokTypes.name) {
  6715. this.raiseRecoverable(
  6716. phaseId.start,
  6717. "'import source' can only be used with direct identifier specifier imports."
  6718. );
  6719. }
  6720. const specifiers = base.parseImportSpecifiers.call(this);
  6721. if (
  6722. phase === "source" &&
  6723. specifiers.some((s) => s.type !== "ImportDefaultSpecifier")
  6724. ) {
  6725. this.raiseRecoverable(
  6726. phaseId.start,
  6727. "'import source' can only be used with direct identifier specifier imports ('import source identifierName from ...')."
  6728. );
  6729. }
  6730. return specifiers;
  6731. }
  6732. /**
  6733. * acorn source: https://github.com/acornjs/acorn/blob/8.17.0/acorn/src/expression.js
  6734. * @param {boolean} forNew whether parsed as the operand of `new`
  6735. * @returns {Expression} expression node
  6736. * @this {ParserInternals}
  6737. */
  6738. parseExprImport(forNew) {
  6739. const node = base.parseExprImport.call(this, forNew);
  6740. if (
  6741. this._importPhasesEnabled &&
  6742. node.type === "MetaProperty" &&
  6743. (node.property.name === "defer" || node.property.name === "source")
  6744. ) {
  6745. if (this.type === tokTypes.parenL) {
  6746. if (forNew) {
  6747. // same guard acorn applies to `new import(...)`
  6748. this.raise(node.start, "import call cannot be the target of `new`");
  6749. }
  6750. const dynImport =
  6751. /** @type {ImportExpression & { phase?: ImportPhase }} */
  6752. (
  6753. this.parseDynamicImport(
  6754. this.startNodeAt(
  6755. node.start,
  6756. node.loc ? node.loc.start : undefined
  6757. )
  6758. )
  6759. );
  6760. dynImport.phase = node.property.name;
  6761. return dynImport;
  6762. }
  6763. this.raiseRecoverable(
  6764. node.start,
  6765. `'import.${node.property.name}' can only be used in a dynamic import.`
  6766. );
  6767. }
  6768. return node;
  6769. }
  6770. /**
  6771. * @param {Node & { property?: Identifier }} node started node with `meta` set to `import`
  6772. * @returns {Expression} MetaProperty node
  6773. * @this {ParserInternals}
  6774. */
  6775. parseImportMeta(node) {
  6776. if (!this._importPhasesEnabled) {
  6777. // base only accepts `import.meta` here, which is module-only
  6778. this._moduleSyntaxSeen = true;
  6779. return base.parseImportMeta.call(this, node);
  6780. }
  6781. this.next();
  6782. const containsEsc = this.containsEsc;
  6783. const property = this.parseIdent(true);
  6784. node.property = property;
  6785. const { name } = property;
  6786. // only `import.meta` is module-only; `import.defer`/`.source` are dynamic
  6787. if (name === "meta") this._moduleSyntaxSeen = true;
  6788. if (name !== "meta" && name !== "defer" && name !== "source") {
  6789. this.raiseRecoverable(
  6790. property.start,
  6791. "The only valid meta property for import is 'import.meta'"
  6792. );
  6793. }
  6794. if (containsEsc) {
  6795. this.raiseRecoverable(
  6796. node.start,
  6797. `'import.${name}' must not contain escaped characters`
  6798. );
  6799. }
  6800. if (
  6801. name === "meta" &&
  6802. this.options.sourceType !== "module" &&
  6803. !this.options.allowImportExportEverywhere
  6804. ) {
  6805. this.raiseRecoverable(
  6806. node.start,
  6807. "Cannot use 'import.meta' outside a module"
  6808. );
  6809. }
  6810. return /** @type {Expression} */ (this.finishNode(node, "MetaProperty"));
  6811. }
  6812. }
  6813. /** @import { SourcePosition } from "../Dependency" */
  6814. /**
  6815. * Whether a raw string literal contains a legacy octal (`\47`, `\0` followed by
  6816. * a digit) or non-octal decimal (`\8`, `\9`) escape — all SyntaxErrors in
  6817. * strict mode. Escaped backslashes (`\\`) and `\x` / `\u` escapes are skipped.
  6818. * @param {string} raw raw string literal text, including quotes
  6819. * @returns {boolean} true when a strict-forbidden escape is present
  6820. */
  6821. const hasOctalEscape = (raw) => {
  6822. for (let i = 0; i < raw.length; i++) {
  6823. if (raw.charCodeAt(i) !== 92) continue;
  6824. const next = raw.charCodeAt(i + 1);
  6825. if (next === 92) {
  6826. i++;
  6827. continue;
  6828. }
  6829. // `\0` is a valid NUL escape unless a digit follows it.
  6830. if (next === 48) {
  6831. const after = raw.charCodeAt(i + 2);
  6832. if (after >= 48 && after <= 57) return true;
  6833. i++;
  6834. continue;
  6835. }
  6836. if (next >= 49 && next <= 57) return true;
  6837. }
  6838. return false;
  6839. };
  6840. // Location decoding for lazy-mode output: nodes carry only offsets (the parser
  6841. // skips acorn's location tracking), so line/column are derived on demand from
  6842. // these two helpers.
  6843. /**
  6844. * Exact char-code scan matching acorn's `lineBreak` semantics (CRLF is one
  6845. * break). Kept as the fallback for the terminators `buildLineStarts` cannot
  6846. * find with a native search.
  6847. * @param {string} source source code
  6848. * @returns {number[]} line start offsets
  6849. */
  6850. const scanLineStarts = (source) => {
  6851. const len = source.length;
  6852. const lineStarts = [0];
  6853. for (let i = 0; i < len; i++) {
  6854. const ch = source.charCodeAt(i);
  6855. if (ch === 10) {
  6856. lineStarts.push(i + 1);
  6857. } else if (ch === 13) {
  6858. if (source.charCodeAt(i + 1) === 10) i++;
  6859. lineStarts.push(i + 1);
  6860. } else if (ch === 0x2028 || ch === 0x2029) {
  6861. lineStarts.push(i + 1);
  6862. }
  6863. }
  6864. return lineStarts;
  6865. };
  6866. /**
  6867. * Offset of each line's first character. `indexOf` searches the source natively,
  6868. * which beats a char-code loop by ~3x; CRLF needs no special case because it
  6869. * starts the next line after its `\n` either way. A lone `\r` or a unicode
  6870. * separator does break that equivalence, so those fall back to the char scan.
  6871. * @param {string} source source code
  6872. * @returns {number[]} line start offsets
  6873. */
  6874. const buildLineStarts = (source) => {
  6875. if (!source.includes("\u2028") && !source.includes("\u2029")) {
  6876. let cr = source.indexOf("\r");
  6877. while (cr !== -1 && source.charCodeAt(cr + 1) === 10) {
  6878. cr = source.indexOf("\r", cr + 2);
  6879. }
  6880. if (cr === -1) {
  6881. const lineStarts = [0];
  6882. let i = source.indexOf("\n");
  6883. while (i !== -1) {
  6884. lineStarts.push(i + 1);
  6885. i = source.indexOf("\n", i + 1);
  6886. }
  6887. return lineStarts;
  6888. }
  6889. }
  6890. return scanLineStarts(source);
  6891. };
  6892. /**
  6893. * Binary search for the line containing the offset.
  6894. * @param {number[]} lineStarts line start offsets
  6895. * @param {number} offset source offset
  6896. * @returns {SourcePosition} position (1-based line, 0-based column)
  6897. */
  6898. const positionAt = (lineStarts, offset) => {
  6899. let lo = 0;
  6900. let hi = lineStarts.length - 1;
  6901. while (lo < hi) {
  6902. const mid = (lo + hi + 1) >>> 1;
  6903. if (lineStarts[mid] <= offset) lo = mid;
  6904. else hi = mid - 1;
  6905. }
  6906. return { line: lo + 1, column: offset - lineStarts[lo] };
  6907. };
  6908. const KEYWORDS_BEFORE_REGEXP = new Set([
  6909. "await",
  6910. "case",
  6911. "delete",
  6912. "do",
  6913. "else",
  6914. "in",
  6915. "instanceof",
  6916. "new",
  6917. "of",
  6918. "return",
  6919. "throw",
  6920. "typeof",
  6921. "void",
  6922. "yield"
  6923. ]);
  6924. /**
  6925. * Whether a `/` at this point starts a regexp rather than division, decided by
  6926. * what precedes it: after a value (name, number, `)`, `]`) it divides, after an
  6927. * operator or a keyword it opens a regexp. `)` and `]` are always read as
  6928. * division — telling `if (a) /re/` from `(a) / b` needs paren-context tracking
  6929. * this single pass does not carry.
  6930. * @param {string} source source code
  6931. * @param {number} slash offset of the `/`
  6932. * @returns {boolean} true when a regexp literal starts here
  6933. */
  6934. const startsRegExp = (source, slash) => {
  6935. let i = slash - 1;
  6936. while (i >= 0) {
  6937. const code = source.charCodeAt(i);
  6938. if (code === 32 || code === 9 || code === 10 || code === 13) i--;
  6939. else break;
  6940. }
  6941. if (i < 0) return true;
  6942. const code = source.charCodeAt(i);
  6943. if (code === 41 || code === 93) return false;
  6944. if (!isIdentifierChar(code)) return true;
  6945. // a keyword before `/` is an operator position (`return /re/`), a name is not
  6946. let start = i;
  6947. while (start >= 0 && isIdentifierChar(source.charCodeAt(start))) start--;
  6948. return KEYWORDS_BEFORE_REGEXP.has(source.slice(start + 1, i + 1));
  6949. };
  6950. /**
  6951. * Skips whitespace and comments, returning the next code offset.
  6952. * @param {string} source source code
  6953. * @param {number} i offset to start at
  6954. * @returns {number} offset of the next significant character
  6955. */
  6956. const skipTrivia = (source, i) => {
  6957. while (i < source.length) {
  6958. const code = source.charCodeAt(i);
  6959. if (code === 32 || code === 9 || code === 10 || code === 13) {
  6960. i++;
  6961. } else if (code === 47 && source.charCodeAt(i + 1) === 47) {
  6962. const end = source.indexOf("\n", i + 2);
  6963. i = end === -1 ? source.length : end + 1;
  6964. } else if (code === 47 && source.charCodeAt(i + 1) === 42) {
  6965. const end = source.indexOf("*/", i + 2);
  6966. i = end === -1 ? source.length : end + 2;
  6967. } else {
  6968. break;
  6969. }
  6970. }
  6971. return i;
  6972. };
  6973. /** @type {Map<number, string>} */
  6974. const SINGLE_CHARACTER_ESCAPES = new Map([
  6975. [110, "\n"],
  6976. [114, "\r"],
  6977. [116, "\t"],
  6978. [98, "\b"],
  6979. [118, "\u000B"],
  6980. [102, "\f"]
  6981. ]);
  6982. /**
  6983. * Reads the hex digits of a `\x`/`\u` escape.
  6984. * @param {string} source source code
  6985. * @param {number} i offset of the first digit
  6986. * @param {number} length how many digits to read
  6987. * @returns {number} the code point, or `-1` when a digit is missing
  6988. */
  6989. const readHexEscapeValue = (source, i, length) => {
  6990. let value = 0;
  6991. for (let j = i; j < i + length; j++) {
  6992. const digit = Number.parseInt(source[j], 16);
  6993. if (Number.isNaN(digit)) return -1;
  6994. value = value * 16 + digit;
  6995. }
  6996. return value;
  6997. };
  6998. /**
  6999. * Cooks one escape sequence, sloppy-mode script semantics (legacy octal included).
  7000. * @param {string} source source code
  7001. * @param {number} i offset just past the backslash
  7002. * @returns {{ value: string, end: number } | undefined} the cooked text, or `undefined` when malformed
  7003. */
  7004. const readEscape = (source, i) => {
  7005. if (i >= source.length) return;
  7006. const code = source.charCodeAt(i);
  7007. const single = SINGLE_CHARACTER_ESCAPES.get(code);
  7008. if (single !== undefined) return { value: single, end: i + 1 };
  7009. // a line continuation cooks to nothing; `\r\n` counts as one terminator
  7010. if (code === 13) {
  7011. return { value: "", end: source.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 };
  7012. }
  7013. if (code === 10 || code === 0x2028 || code === 0x2029) {
  7014. return { value: "", end: i + 1 };
  7015. }
  7016. if (code === 120) {
  7017. const value = readHexEscapeValue(source, i + 1, 2);
  7018. if (value === -1) return;
  7019. return { value: String.fromCodePoint(value), end: i + 3 };
  7020. }
  7021. if (code === 117) {
  7022. if (source.charCodeAt(i + 1) === 123) {
  7023. const end = source.indexOf("}", i + 2);
  7024. if (end === -1 || end === i + 2) return;
  7025. const value = readHexEscapeValue(source, i + 2, end - i - 2);
  7026. if (value === -1 || value > 0x10ffff) return;
  7027. return { value: String.fromCodePoint(value), end: end + 1 };
  7028. }
  7029. const value = readHexEscapeValue(source, i + 1, 4);
  7030. if (value === -1) return;
  7031. return { value: String.fromCodePoint(value), end: i + 5 };
  7032. }
  7033. if (code >= 48 && code <= 55) {
  7034. let digits = /** @type {RegExpMatchArray} */ (
  7035. source.slice(i, i + 3).match(/^[0-7]+/)
  7036. )[0];
  7037. if (Number.parseInt(digits, 8) > 255) digits = digits.slice(0, -1);
  7038. return {
  7039. value: String.fromCharCode(Number.parseInt(digits, 8)),
  7040. end: i + digits.length
  7041. };
  7042. }
  7043. return { value: source[i], end: i + 1 };
  7044. };
  7045. /**
  7046. * Reads a `'`/`"` string starting at `i`, cooking its escapes the way the ast
  7047. * this replaces did — a `Literal` node carries the cooked value, so a specifier
  7048. * written `"\x2e/a"` is the same dependency as `"./a"`. Templates are not
  7049. * specifiers here: the ast only matched `Literal` nodes.
  7050. * @param {string} source source code
  7051. * @param {number} i offset of the opening quote
  7052. * @returns {{ value: string, end: number } | undefined} the literal
  7053. */
  7054. const readStringLiteral = (source, i) => {
  7055. const quote = source.charCodeAt(i);
  7056. if (quote !== 34 && quote !== 39) return;
  7057. for (let j = i + 1; j < source.length; j++) {
  7058. const code = source.charCodeAt(j);
  7059. if (code === 10 || code === 13) return;
  7060. if (code === 92) return readEscapedStringLiteral(source, i, j);
  7061. if (code === quote) return { value: source.slice(i + 1, j), end: j + 1 };
  7062. }
  7063. };
  7064. /**
  7065. * Continues `readStringLiteral` from its first escape, so the unescaped case
  7066. * stays a single slice.
  7067. * @param {string} source source code
  7068. * @param {number} i offset of the opening quote
  7069. * @param {number} firstEscape offset of the first backslash
  7070. * @returns {{ value: string, end: number } | undefined} the literal
  7071. */
  7072. const readEscapedStringLiteral = (source, i, firstEscape) => {
  7073. const quote = source.charCodeAt(i);
  7074. let value = "";
  7075. let segment = i + 1;
  7076. for (let j = firstEscape; j < source.length; j++) {
  7077. const code = source.charCodeAt(j);
  7078. if (code === 10 || code === 13) return;
  7079. if (code === quote) {
  7080. return { value: value + source.slice(segment, j), end: j + 1 };
  7081. }
  7082. if (code !== 92) continue;
  7083. const escape = readEscape(source, j + 1);
  7084. if (escape === undefined) return;
  7085. value += source.slice(segment, j) + escape.value;
  7086. segment = escape.end;
  7087. j = escape.end - 1;
  7088. }
  7089. };
  7090. /**
  7091. * Scans a template body from `i` (just past a backtick or a `}` resuming one).
  7092. * @param {string} source source code
  7093. * @param {number} i offset inside the template
  7094. * @returns {{ end: number, substitution: boolean }} where the body stops
  7095. */
  7096. const skipTemplateBody = (source, i) => {
  7097. for (; i < source.length; i++) {
  7098. const code = source.charCodeAt(i);
  7099. if (code === 92) {
  7100. i++;
  7101. } else if (code === 96) {
  7102. return { end: i, substitution: false };
  7103. } else if (code === 36 && source.charCodeAt(i + 1) === 123) {
  7104. return { end: i + 1, substitution: true };
  7105. }
  7106. }
  7107. return { end: source.length, substitution: false };
  7108. };
  7109. /**
  7110. * Collects the specifiers of static `require("…")` calls. A scan rather than a
  7111. * parse: it only has to skip what could hide or fake a call — comments, strings,
  7112. * templates and regexps — so it costs one pass and builds no ast. Template
  7113. * substitutions are scanned as the code they are, which is why the brace depth
  7114. * of each open `${` is tracked.
  7115. * @param {string} source source code
  7116. * @returns {Set<string>} required specifiers
  7117. */
  7118. const collectCjsRequireSpecifiers = (source) => {
  7119. /** @type {Set<string>} */
  7120. const specifiers = new Set();
  7121. /** @type {number[]} */
  7122. const templateBraceDepths = [];
  7123. let braceDepth = 0;
  7124. for (let i = 0; i < source.length; i++) {
  7125. const code = source.charCodeAt(i);
  7126. if (code === 96) {
  7127. const body = skipTemplateBody(source, i + 1);
  7128. i = body.end;
  7129. if (body.substitution) {
  7130. templateBraceDepths.push(braceDepth);
  7131. braceDepth++;
  7132. }
  7133. continue;
  7134. }
  7135. if (code === 123) {
  7136. braceDepth++;
  7137. continue;
  7138. }
  7139. if (code === 125) {
  7140. braceDepth--;
  7141. if (
  7142. templateBraceDepths.length > 0 &&
  7143. templateBraceDepths[templateBraceDepths.length - 1] === braceDepth
  7144. ) {
  7145. templateBraceDepths.pop();
  7146. const body = skipTemplateBody(source, i + 1);
  7147. i = body.end;
  7148. if (body.substitution) {
  7149. templateBraceDepths.push(braceDepth);
  7150. braceDepth++;
  7151. }
  7152. }
  7153. continue;
  7154. }
  7155. if (code === 34 || code === 39) {
  7156. for (i++; i < source.length; i++) {
  7157. const inner = source.charCodeAt(i);
  7158. if (inner === 92) i++;
  7159. else if (inner === code) break;
  7160. }
  7161. continue;
  7162. }
  7163. if (code === 47) {
  7164. const next = source.charCodeAt(i + 1);
  7165. if (next === 47) {
  7166. const end = source.indexOf("\n", i + 2);
  7167. i = end === -1 ? source.length : end;
  7168. continue;
  7169. }
  7170. if (next === 42) {
  7171. const end = source.indexOf("*/", i + 2);
  7172. i = end === -1 ? source.length : end + 1;
  7173. continue;
  7174. }
  7175. if (!startsRegExp(source, i)) continue;
  7176. let inClass = false;
  7177. for (i++; i < source.length; i++) {
  7178. const inner = source.charCodeAt(i);
  7179. if (inner === 92) i++;
  7180. else if (inner === 91) inClass = true;
  7181. else if (inner === 93) inClass = false;
  7182. else if (inner === 10) break;
  7183. else if (inner === 47 && !inClass) break;
  7184. }
  7185. continue;
  7186. }
  7187. // `r` of `require`, as a whole word that is not a member access
  7188. if (code !== 114 || !source.startsWith("require", i)) continue;
  7189. if (isIdentifierChar(source.charCodeAt(i + 7))) continue;
  7190. if (i > 0) {
  7191. const before = source.charCodeAt(i - 1);
  7192. if (isIdentifierChar(before) || before === 46) continue;
  7193. }
  7194. let j = skipTrivia(source, i + 7);
  7195. if (source.charCodeAt(j) !== 40) continue;
  7196. j = skipTrivia(source, j + 1);
  7197. // a cast wraps the specifier in its own parens: `require(/** … */ ("x"))`
  7198. let parens = 0;
  7199. while (source.charCodeAt(j) === 40) {
  7200. parens++;
  7201. j = skipTrivia(source, j + 1);
  7202. }
  7203. const literal = readStringLiteral(source, j);
  7204. if (literal === undefined) {
  7205. i += 6;
  7206. continue;
  7207. }
  7208. j = skipTrivia(source, literal.end);
  7209. while (parens > 0 && source.charCodeAt(j) === 41) {
  7210. parens--;
  7211. j = skipTrivia(source, j + 1);
  7212. }
  7213. if (parens !== 0 || source.charCodeAt(j) !== 41) {
  7214. i += 6;
  7215. continue;
  7216. }
  7217. specifiers.add(literal.value);
  7218. i = j;
  7219. }
  7220. return specifiers;
  7221. };
  7222. module.exports.LEGACY_ASSERT_ATTRIBUTES = LEGACY_ASSERT_ATTRIBUTES;
  7223. module.exports.WebpackParser = WebpackParser;
  7224. module.exports.buildLineStarts = buildLineStarts;
  7225. module.exports.collectCjsRequireSpecifiers = collectCjsRequireSpecifiers;
  7226. module.exports.hasOctalEscape = hasOctalEscape;
  7227. module.exports.isIdentifierChar = isIdentifierChar;
  7228. module.exports.positionAt = positionAt;