12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261 |
- /*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
- */
- "use strict";
- const vm = require("vm");
- const { Parser: AcornParser, tokTypes } = require("acorn");
- const { HookMap, SyncBailHook } = require("tapable");
- const Parser = require("../Parser");
- const StackedMap = require("../util/StackedMap");
- const binarySearchBounds = require("../util/binarySearchBounds");
- const {
- createMagicCommentContext,
- webpackCommentRegExp
- } = require("../util/magicComment");
- const memoize = require("../util/memoize");
- const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
- /** @typedef {import("acorn").Options} AcornOptions */
- /** @typedef {import("estree").AssignmentExpression} AssignmentExpression */
- /** @typedef {import("estree").BinaryExpression} BinaryExpression */
- /** @typedef {import("estree").BlockStatement} BlockStatement */
- /** @typedef {import("estree").SequenceExpression} SequenceExpression */
- /** @typedef {import("estree").CallExpression} CallExpression */
- /** @typedef {import("estree").BaseCallExpression} BaseCallExpression */
- /** @typedef {import("estree").StaticBlock} StaticBlock */
- /** @typedef {import("estree").ClassDeclaration} ClassDeclaration */
- /** @typedef {import("estree").ForStatement} ForStatement */
- /** @typedef {import("estree").SwitchStatement} SwitchStatement */
- /** @typedef {import("estree").ClassExpression} ClassExpression */
- /** @typedef {import("estree").Comment} Comment */
- /** @typedef {import("estree").ConditionalExpression} ConditionalExpression */
- /** @typedef {import("estree").Declaration} Declaration */
- /** @typedef {import("estree").PrivateIdentifier} PrivateIdentifier */
- /** @typedef {import("estree").PropertyDefinition} PropertyDefinition */
- /** @typedef {import("estree").Expression} Expression */
- /** @typedef {import("estree").Identifier} Identifier */
- /** @typedef {import("estree").VariableDeclaration} VariableDeclaration */
- /** @typedef {import("estree").IfStatement} IfStatement */
- /** @typedef {import("estree").LabeledStatement} LabeledStatement */
- /** @typedef {import("estree").Literal} Literal */
- /** @typedef {import("estree").LogicalExpression} LogicalExpression */
- /** @typedef {import("estree").ChainExpression} ChainExpression */
- /** @typedef {import("estree").MemberExpression} MemberExpression */
- /** @typedef {import("estree").YieldExpression} YieldExpression */
- /** @typedef {import("estree").MetaProperty} MetaProperty */
- /** @typedef {import("estree").Property} Property */
- /** @typedef {import("estree").AssignmentPattern} AssignmentPattern */
- /** @typedef {import("estree").ChainElement} ChainElement */
- /** @typedef {import("estree").Pattern} Pattern */
- /** @typedef {import("estree").UpdateExpression} UpdateExpression */
- /** @typedef {import("estree").ObjectExpression} ObjectExpression */
- /** @typedef {import("estree").UnaryExpression} UnaryExpression */
- /** @typedef {import("estree").ArrayExpression} ArrayExpression */
- /** @typedef {import("estree").ArrayPattern} ArrayPattern */
- /** @typedef {import("estree").AwaitExpression} AwaitExpression */
- /** @typedef {import("estree").ThisExpression} ThisExpression */
- /** @typedef {import("estree").RestElement} RestElement */
- /** @typedef {import("estree").ObjectPattern} ObjectPattern */
- /** @typedef {import("estree").SwitchCase} SwitchCase */
- /** @typedef {import("estree").CatchClause} CatchClause */
- /** @typedef {import("estree").VariableDeclarator} VariableDeclarator */
- /** @typedef {import("estree").ForInStatement} ForInStatement */
- /** @typedef {import("estree").ForOfStatement} ForOfStatement */
- /** @typedef {import("estree").ReturnStatement} ReturnStatement */
- /** @typedef {import("estree").WithStatement} WithStatement */
- /** @typedef {import("estree").ThrowStatement} ThrowStatement */
- /** @typedef {import("estree").MethodDefinition} MethodDefinition */
- /** @typedef {import("estree").NewExpression} NewExpression */
- /** @typedef {import("estree").SpreadElement} SpreadElement */
- /** @typedef {import("estree").FunctionExpression} FunctionExpression */
- /** @typedef {import("estree").WhileStatement} WhileStatement */
- /** @typedef {import("estree").ArrowFunctionExpression} ArrowFunctionExpression */
- /** @typedef {import("estree").ExpressionStatement} ExpressionStatement */
- /** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */
- /** @typedef {import("estree").DoWhileStatement} DoWhileStatement */
- /** @typedef {import("estree").TryStatement} TryStatement */
- /** @typedef {import("estree").Node} Node */
- /** @typedef {import("estree").Program} Program */
- /** @typedef {import("estree").Directive} Directive */
- /** @typedef {import("estree").Statement} Statement */
- /** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclaration */
- /** @typedef {import("estree").Super} Super */
- /** @typedef {import("estree").ImportSpecifier} ImportSpecifier */
- /** @typedef {import("estree").TaggedTemplateExpression} TaggedTemplateExpression */
- /** @typedef {import("estree").TemplateLiteral} TemplateLiteral */
- /** @typedef {import("estree").AssignmentProperty} AssignmentProperty */
- /** @typedef {import("estree").MaybeNamedFunctionDeclaration} MaybeNamedFunctionDeclaration */
- /** @typedef {import("estree").MaybeNamedClassDeclaration} MaybeNamedClassDeclaration */
- /**
- * @template T
- * @typedef {import("tapable").AsArray<T>} AsArray<T>
- */
- /** @typedef {import("../Parser").ParserState} ParserState */
- /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
- /** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[] }} GetInfoResult */
- /** @typedef {Statement | ModuleDeclaration | Expression | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} StatementPathItem */
- /** @typedef {(ident: string) => void} OnIdentString */
- /** @typedef {(ident: string, identifier: Identifier) => void} OnIdent */
- /** @typedef {StatementPathItem[]} StatementPath */
- // TODO remove cast when @types/estree has been updated to import assertions
- /** @typedef {import("estree").BaseNode & { type: "ImportAttribute", key: Identifier | Literal, value: Literal }} ImportAttribute */
- /** @typedef {import("estree").ImportDeclaration & { attributes?: Array<ImportAttribute>, phase?: "defer" }} ImportDeclaration */
- /** @typedef {import("estree").ExportNamedDeclaration & { attributes?: Array<ImportAttribute> }} ExportNamedDeclaration */
- /** @typedef {import("estree").ExportAllDeclaration & { attributes?: Array<ImportAttribute> }} ExportAllDeclaration */
- /** @typedef {import("estree").ImportExpression & { options?: Expression | null, phase?: "defer" }} ImportExpression */
- /** @typedef {ImportDeclaration | ExportNamedDeclaration | ExportDefaultDeclaration | ExportAllDeclaration} ModuleDeclaration */
- /** @type {string[]} */
- const EMPTY_ARRAY = [];
- const ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = 0b01;
- const ALLOWED_MEMBER_TYPES_EXPRESSION = 0b10;
- const ALLOWED_MEMBER_TYPES_ALL = 0b11;
- const LEGACY_ASSERT_ATTRIBUTES = Symbol("assert");
- /** @type {(BaseParser: typeof AcornParser) => typeof AcornParser} */
- const importAssertions = (Parser) =>
- class extends Parser {
- /**
- * @this {InstanceType<AcornParser>}
- * @returns {ImportAttribute[]} import attributes
- */
- parseWithClause() {
- /** @type {ImportAttribute[]} */
- const nodes = [];
- const isAssertLegacy = this.value === "assert";
- if (isAssertLegacy) {
- if (!this.eat(tokTypes.name)) {
- return nodes;
- }
- } else if (!this.eat(tokTypes._with)) {
- return nodes;
- }
- this.expect(tokTypes.braceL);
- /** @type {Record<string, boolean>} */
- const attributeKeys = {};
- let first = true;
- while (!this.eat(tokTypes.braceR)) {
- if (!first) {
- this.expect(tokTypes.comma);
- if (this.afterTrailingComma(tokTypes.braceR)) {
- break;
- }
- } else {
- first = false;
- }
- const attr =
- /** @type {ImportAttribute} */
- this.parseImportAttribute();
- const keyName =
- attr.key.type === "Identifier" ? attr.key.name : attr.key.value;
- if (Object.prototype.hasOwnProperty.call(attributeKeys, keyName)) {
- this.raiseRecoverable(
- attr.key.start,
- `Duplicate attribute key '${keyName}'`
- );
- }
- attributeKeys[keyName] = true;
- nodes.push(attr);
- }
- if (isAssertLegacy) {
- /** @type {EXPECTED_ANY} */
- (nodes)[LEGACY_ASSERT_ATTRIBUTES] = true;
- }
- return nodes;
- }
- };
- // Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API
- let parser = AcornParser.extend(importAssertions);
- /** @typedef {Record<string, string> & { _isLegacyAssert?: boolean }} ImportAttributes */
- /**
- * @param {ImportDeclaration | ExportNamedDeclaration | ExportAllDeclaration | ImportExpression} node node with assertions
- * @returns {ImportAttributes | undefined} import attributes
- */
- const getImportAttributes = (node) => {
- if (node.type === "ImportExpression") {
- if (
- node.options &&
- node.options.type === "ObjectExpression" &&
- node.options.properties[0] &&
- node.options.properties[0].type === "Property" &&
- node.options.properties[0].key.type === "Identifier" &&
- (node.options.properties[0].key.name === "with" ||
- node.options.properties[0].key.name === "assert") &&
- node.options.properties[0].value.type === "ObjectExpression" &&
- node.options.properties[0].value.properties.length > 0
- ) {
- const properties =
- /** @type {Property[]} */
- (node.options.properties[0].value.properties);
- const result = /** @type {ImportAttributes} */ ({});
- for (const property of properties) {
- const key =
- /** @type {string} */
- (
- property.key.type === "Identifier"
- ? property.key.name
- : /** @type {Literal} */ (property.key).value
- );
- result[key] =
- /** @type {string} */
- (/** @type {Literal} */ (property.value).value);
- }
- const key =
- node.options.properties[0].key.type === "Identifier"
- ? node.options.properties[0].key.name
- : /** @type {Literal} */ (node.options.properties[0].key).value;
- if (key === "assert") {
- result._isLegacyAssert = true;
- }
- return result;
- }
- return;
- }
- if (node.attributes === undefined || node.attributes.length === 0) {
- return;
- }
- const result = /** @type {ImportAttributes} */ ({});
- for (const attribute of node.attributes) {
- const key =
- /** @type {string} */
- (
- attribute.key.type === "Identifier"
- ? attribute.key.name
- : attribute.key.value
- );
- result[key] = /** @type {string} */ (attribute.value.value);
- }
- if (/** @type {EXPECTED_ANY} */ (node.attributes)[LEGACY_ASSERT_ATTRIBUTES]) {
- result._isLegacyAssert = true;
- }
- return result;
- };
- /** @typedef {typeof VariableInfoFlags.Evaluated | typeof VariableInfoFlags.Free | typeof VariableInfoFlags.Normal | typeof VariableInfoFlags.Tagged} VariableInfoFlagsType */
- const VariableInfoFlags = Object.freeze({
- Evaluated: 0b000,
- Free: 0b001,
- Normal: 0b010,
- Tagged: 0b100
- });
- class VariableInfo {
- /**
- * @param {ScopeInfo} declaredScope scope in which the variable is declared
- * @param {string | undefined} name which name the variable use, defined name or free name or tagged name
- * @param {VariableInfoFlagsType} flags how the variable is created
- * @param {TagInfo | undefined} tagInfo info about tags
- */
- constructor(declaredScope, name, flags, tagInfo) {
- this.declaredScope = declaredScope;
- this.name = name;
- this.flags = flags;
- this.tagInfo = tagInfo;
- }
- /**
- * @returns {boolean} the variable is free or not
- */
- isFree() {
- return (this.flags & VariableInfoFlags.Free) > 0;
- }
- /**
- * @returns {boolean} the variable is tagged by tagVariable or not
- */
- isTagged() {
- return (this.flags & VariableInfoFlags.Tagged) > 0;
- }
- }
- /** @typedef {string | ScopeInfo | VariableInfo} ExportedVariableInfo */
- /** @typedef {Literal | string | null | undefined} ImportSource */
- /** @typedef {Omit<AcornOptions, "sourceType" | "ecmaVersion"> & { sourceType: "module" | "script" | "auto", ecmaVersion?: AcornOptions["ecmaVersion"] }} ParseOptions */
- /** @typedef {symbol} Tag */
- /** @typedef {Record<string, TODO>} TagData */
- /**
- * @typedef {object} TagInfo
- * @property {Tag} tag
- * @property {TagData=} data
- * @property {TagInfo | undefined} next
- */
- const SCOPE_INFO_TERMINATED_RETURN = 1;
- const SCOPE_INFO_TERMINATED_THROW = 2;
- /**
- * @typedef {object} ScopeInfo
- * @property {StackedMap<string, VariableInfo | ScopeInfo>} definitions
- * @property {boolean | "arrow"} topLevelScope
- * @property {boolean | string} inShorthand
- * @property {boolean} inTaggedTemplateTag
- * @property {boolean} inTry
- * @property {boolean} isStrict
- * @property {boolean} isAsmJs
- * @property {undefined | 1 | 2} terminated
- */
- /** @typedef {[number, number]} Range */
- /**
- * @typedef {object} DestructuringAssignmentProperty
- * @property {string} id
- * @property {Range | undefined=} range
- * @property {boolean | string} shorthand
- */
- /**
- * Helper function for joining two ranges into a single range. This is useful
- * when working with AST nodes, as it allows you to combine the ranges of child nodes
- * to create the range of the _parent node_.
- * @param {Range} startRange start range to join
- * @param {Range} endRange end range to join
- * @returns {Range} joined range
- * @example
- * ```js
- * const startRange = [0, 5];
- * const endRange = [10, 15];
- * const joinedRange = joinRanges(startRange, endRange);
- * console.log(joinedRange); // [0, 15]
- * ```
- */
- const joinRanges = (startRange, endRange) => {
- if (!endRange) return startRange;
- if (!startRange) return endRange;
- return [startRange[0], endRange[1]];
- };
- /**
- * Helper function used to generate a string representation of a
- * [member expression](https://github.com/estree/estree/blob/master/es5.md#memberexpression).
- * @param {string} object object to name
- * @param {string[]} membersReversed reversed list of members
- * @returns {string} member expression as a string
- * @example
- * ```js
- * const membersReversed = ["property1", "property2", "property3"]; // Members parsed from the AST
- * const name = objectAndMembersToName("myObject", membersReversed);
- *
- * console.log(name); // "myObject.property1.property2.property3"
- * ```
- */
- const objectAndMembersToName = (object, membersReversed) => {
- let name = object;
- for (let i = membersReversed.length - 1; i >= 0; i--) {
- name = `${name}.${membersReversed[i]}`;
- }
- return name;
- };
- /**
- * Grabs the name of a given expression and returns it as a string or undefined. Has particular
- * handling for [Identifiers](https://github.com/estree/estree/blob/master/es5.md#identifier),
- * [ThisExpressions](https://github.com/estree/estree/blob/master/es5.md#identifier), and
- * [MetaProperties](https://github.com/estree/estree/blob/master/es2015.md#metaproperty) which is
- * specifically for handling the `new.target` meta property.
- * @param {Expression | SpreadElement | Super} expression expression
- * @returns {string | "this" | undefined} name or variable info
- */
- const getRootName = (expression) => {
- switch (expression.type) {
- case "Identifier":
- return expression.name;
- case "ThisExpression":
- return "this";
- case "MetaProperty":
- return `${expression.meta.name}.${expression.property.name}`;
- default:
- return undefined;
- }
- };
- /** @type {AcornOptions} */
- const defaultParserOptions = {
- ranges: true,
- locations: true,
- ecmaVersion: "latest",
- sourceType: "module",
- // https://github.com/tc39/proposal-hashbang
- allowHashBang: true,
- onComment: undefined
- };
- const EMPTY_COMMENT_OPTIONS = {
- options: null,
- errors: null
- };
- const CLASS_NAME = "JavascriptParser";
- class JavascriptParser extends Parser {
- /**
- * @param {"module" | "script" | "auto"} sourceType default source type
- */
- constructor(sourceType = "auto") {
- super();
- this.hooks = Object.freeze({
- /** @type {HookMap<SyncBailHook<[UnaryExpression], BasicEvaluatedExpression | null | undefined>>} */
- evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])),
- /** @type {HookMap<SyncBailHook<[Expression | SpreadElement | PrivateIdentifier | Super], BasicEvaluatedExpression | null | undefined>>} */
- evaluate: new HookMap(() => new SyncBailHook(["expression"])),
- /** @type {HookMap<SyncBailHook<[Identifier | ThisExpression | MemberExpression | MetaProperty], BasicEvaluatedExpression | null | undefined>>} */
- evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])),
- /** @type {HookMap<SyncBailHook<[Identifier | ThisExpression | MemberExpression], BasicEvaluatedExpression | null | undefined>>} */
- evaluateDefinedIdentifier: new HookMap(
- () => new SyncBailHook(["expression"])
- ),
- /** @type {HookMap<SyncBailHook<[NewExpression], BasicEvaluatedExpression | null | undefined>>} */
- evaluateNewExpression: new HookMap(
- () => new SyncBailHook(["expression"])
- ),
- /** @type {HookMap<SyncBailHook<[CallExpression], BasicEvaluatedExpression | null | undefined>>} */
- evaluateCallExpression: new HookMap(
- () => new SyncBailHook(["expression"])
- ),
- /** @type {HookMap<SyncBailHook<[CallExpression, BasicEvaluatedExpression], BasicEvaluatedExpression | null | undefined>>} */
- evaluateCallExpressionMember: new HookMap(
- () => new SyncBailHook(["expression", "param"])
- ),
- /** @type {HookMap<SyncBailHook<[Expression | Declaration | PrivateIdentifier | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration, number], boolean | void>>} */
- isPure: new HookMap(
- () => new SyncBailHook(["expression", "commentsStartPosition"])
- ),
- /** @type {SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration], boolean | void>} */
- preStatement: new SyncBailHook(["statement"]),
- /** @type {SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration], boolean | void>} */
- blockPreStatement: new SyncBailHook(["declaration"]),
- /** @type {SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration], boolean | void>} */
- statement: new SyncBailHook(["statement"]),
- /** @type {SyncBailHook<[IfStatement], boolean | void>} */
- statementIf: new SyncBailHook(["statement"]),
- /** @type {SyncBailHook<[Expression, ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration], boolean | void>} */
- classExtendsExpression: new SyncBailHook([
- "expression",
- "classDefinition"
- ]),
- /** @type {SyncBailHook<[MethodDefinition | PropertyDefinition | StaticBlock, ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration], boolean | void>} */
- classBodyElement: new SyncBailHook(["element", "classDefinition"]),
- /** @type {SyncBailHook<[Expression, MethodDefinition | PropertyDefinition, ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration], boolean | void>} */
- classBodyValue: new SyncBailHook([
- "expression",
- "element",
- "classDefinition"
- ]),
- /** @type {HookMap<SyncBailHook<[LabeledStatement], boolean | void>>} */
- label: new HookMap(() => new SyncBailHook(["statement"])),
- /** @type {SyncBailHook<[ImportDeclaration, ImportSource], boolean | void>} */
- import: new SyncBailHook(["statement", "source"]),
- /** @type {SyncBailHook<[ImportDeclaration, ImportSource, string | null, string], boolean | void>} */
- importSpecifier: new SyncBailHook([
- "statement",
- "source",
- "exportName",
- "identifierName"
- ]),
- /** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration], boolean | void>} */
- export: new SyncBailHook(["statement"]),
- /** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, ImportSource], boolean | void>} */
- exportImport: new SyncBailHook(["statement", "source"]),
- /** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration | ExportAllDeclaration, Declaration], boolean | void>} */
- exportDeclaration: new SyncBailHook(["statement", "declaration"]),
- /** @type {SyncBailHook<[ExportDefaultDeclaration, MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression], boolean | void>} */
- exportExpression: new SyncBailHook(["statement", "node"]),
- /** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration | ExportAllDeclaration, string, string, number | undefined], boolean | void>} */
- exportSpecifier: new SyncBailHook([
- "statement",
- "identifierName",
- "exportName",
- "index"
- ]),
- /** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, ImportSource, string | null, string | null, number | undefined], boolean | void>} */
- exportImportSpecifier: new SyncBailHook([
- "statement",
- "source",
- "identifierName",
- "exportName",
- "index"
- ]),
- /** @type {SyncBailHook<[VariableDeclarator, Statement], boolean | void>} */
- preDeclarator: new SyncBailHook(["declarator", "statement"]),
- /** @type {SyncBailHook<[VariableDeclarator, Statement], boolean | void>} */
- declarator: new SyncBailHook(["declarator", "statement"]),
- /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
- varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])),
- /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
- varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])),
- /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
- varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])),
- /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
- varDeclarationUsing: new HookMap(() => new SyncBailHook(["declaration"])),
- /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
- varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])),
- /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
- pattern: new HookMap(() => new SyncBailHook(["pattern"])),
- /** @type {SyncBailHook<[Expression], boolean | void>} */
- collectDestructuringAssignmentProperties: new SyncBailHook([
- "expression"
- ]),
- /** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
- canRename: new HookMap(() => new SyncBailHook(["initExpression"])),
- /** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
- rename: new HookMap(() => new SyncBailHook(["initExpression"])),
- /** @type {HookMap<SyncBailHook<[AssignmentExpression], boolean | void>>} */
- assign: new HookMap(() => new SyncBailHook(["expression"])),
- /** @type {HookMap<SyncBailHook<[AssignmentExpression, string[]], boolean | void>>} */
- assignMemberChain: new HookMap(
- () => new SyncBailHook(["expression", "members"])
- ),
- /** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
- typeof: new HookMap(() => new SyncBailHook(["expression"])),
- /** @type {SyncBailHook<[ImportExpression], boolean | void>} */
- importCall: new SyncBailHook(["expression"]),
- /** @type {SyncBailHook<[Expression | ForOfStatement], boolean | void>} */
- topLevelAwait: new SyncBailHook(["expression"]),
- /** @type {HookMap<SyncBailHook<[CallExpression], boolean | void>>} */
- call: new HookMap(() => new SyncBailHook(["expression"])),
- /** Something like "a.b()" */
- /** @type {HookMap<SyncBailHook<[CallExpression, string[], boolean[], Range[]], boolean | void>>} */
- callMemberChain: new HookMap(
- () =>
- new SyncBailHook([
- "expression",
- "members",
- "membersOptionals",
- "memberRanges"
- ])
- ),
- /** Something like "a.b().c.d" */
- /** @type {HookMap<SyncBailHook<[Expression, string[], CallExpression, string[], Range[]], boolean | void>>} */
- memberChainOfCallMemberChain: new HookMap(
- () =>
- new SyncBailHook([
- "expression",
- "calleeMembers",
- "callExpression",
- "members",
- "memberRanges"
- ])
- ),
- /** Something like "a.b().c.d()"" */
- /** @type {HookMap<SyncBailHook<[CallExpression, string[], CallExpression, string[], Range[]], boolean | void>>} */
- callMemberChainOfCallMemberChain: new HookMap(
- () =>
- new SyncBailHook([
- "expression",
- "calleeMembers",
- "innerCallExpression",
- "members",
- "memberRanges"
- ])
- ),
- /** @type {SyncBailHook<[ChainExpression], boolean | void>} */
- optionalChaining: new SyncBailHook(["optionalChaining"]),
- /** @type {HookMap<SyncBailHook<[NewExpression], boolean | void>>} */
- new: new HookMap(() => new SyncBailHook(["expression"])),
- /** @type {SyncBailHook<[BinaryExpression], boolean | void>} */
- binaryExpression: new SyncBailHook(["binaryExpression"]),
- /** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
- expression: new HookMap(() => new SyncBailHook(["expression"])),
- /** @type {HookMap<SyncBailHook<[MemberExpression, string[], boolean[], Range[]], boolean | void>>} */
- expressionMemberChain: new HookMap(
- () =>
- new SyncBailHook([
- "expression",
- "members",
- "membersOptionals",
- "memberRanges"
- ])
- ),
- /** @type {HookMap<SyncBailHook<[MemberExpression, string[]], boolean | void>>} */
- unhandledExpressionMemberChain: new HookMap(
- () => new SyncBailHook(["expression", "members"])
- ),
- /** @type {SyncBailHook<[ConditionalExpression], boolean | void>} */
- expressionConditionalOperator: new SyncBailHook(["expression"]),
- /** @type {SyncBailHook<[LogicalExpression], boolean | void>} */
- expressionLogicalOperator: new SyncBailHook(["expression"]),
- /** @type {SyncBailHook<[Program, Comment[]], boolean | void>} */
- program: new SyncBailHook(["ast", "comments"]),
- /** @type {SyncBailHook<[ThrowStatement | ReturnStatement], boolean | void>} */
- terminate: new SyncBailHook(["statement"]),
- /** @type {SyncBailHook<[Program, Comment[]], boolean | void>} */
- finish: new SyncBailHook(["ast", "comments"]),
- /** @type {SyncBailHook<[Statement], boolean | void>} */
- unusedStatement: new SyncBailHook(["statement"])
- });
- this.sourceType = sourceType;
- /** @type {ScopeInfo} */
- this.scope = /** @type {TODO} */ (undefined);
- /** @type {ParserState} */
- this.state = /** @type {TODO} */ (undefined);
- /** @type {Comment[] | undefined} */
- this.comments = undefined;
- /** @type {Set<number> | undefined} */
- this.semicolons = undefined;
- /** @type {StatementPath | undefined} */
- this.statementPath = undefined;
- /** @type {Statement | ModuleDeclaration | Expression | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | undefined} */
- this.prevStatement = undefined;
- /** @type {WeakMap<Expression, Set<DestructuringAssignmentProperty>> | undefined} */
- this.destructuringAssignmentProperties = undefined;
- /** @type {TagData | undefined} */
- this.currentTagData = undefined;
- this.magicCommentContext = createMagicCommentContext();
- this._initializeEvaluating();
- }
- _initializeEvaluating() {
- this.hooks.evaluate.for("Literal").tap(CLASS_NAME, (_expr) => {
- const expr = /** @type {Literal} */ (_expr);
- switch (typeof expr.value) {
- case "number":
- return new BasicEvaluatedExpression()
- .setNumber(expr.value)
- .setRange(/** @type {Range} */ (expr.range));
- case "bigint":
- return new BasicEvaluatedExpression()
- .setBigInt(expr.value)
- .setRange(/** @type {Range} */ (expr.range));
- case "string":
- return new BasicEvaluatedExpression()
- .setString(expr.value)
- .setRange(/** @type {Range} */ (expr.range));
- case "boolean":
- return new BasicEvaluatedExpression()
- .setBoolean(expr.value)
- .setRange(/** @type {Range} */ (expr.range));
- }
- if (expr.value === null) {
- return new BasicEvaluatedExpression()
- .setNull()
- .setRange(/** @type {Range} */ (expr.range));
- }
- if (expr.value instanceof RegExp) {
- return new BasicEvaluatedExpression()
- .setRegExp(expr.value)
- .setRange(/** @type {Range} */ (expr.range));
- }
- });
- this.hooks.evaluate.for("NewExpression").tap(CLASS_NAME, (_expr) => {
- const expr = /** @type {NewExpression} */ (_expr);
- const callee = expr.callee;
- if (callee.type !== "Identifier") return;
- if (callee.name !== "RegExp") {
- return this.callHooksForName(
- this.hooks.evaluateNewExpression,
- callee.name,
- expr
- );
- } else if (
- expr.arguments.length > 2 ||
- this.getVariableInfo("RegExp") !== "RegExp"
- ) {
- return;
- }
- let regExp;
- const arg1 = expr.arguments[0];
- if (arg1) {
- if (arg1.type === "SpreadElement") return;
- const evaluatedRegExp = this.evaluateExpression(arg1);
- if (!evaluatedRegExp) return;
- regExp = evaluatedRegExp.asString();
- if (!regExp) return;
- } else {
- return (
- new BasicEvaluatedExpression()
- // eslint-disable-next-line prefer-regex-literals
- .setRegExp(new RegExp(""))
- .setRange(/** @type {Range} */ (expr.range))
- );
- }
- let flags;
- const arg2 = expr.arguments[1];
- if (arg2) {
- if (arg2.type === "SpreadElement") return;
- const evaluatedFlags = this.evaluateExpression(arg2);
- if (!evaluatedFlags) return;
- if (!evaluatedFlags.isUndefined()) {
- flags = evaluatedFlags.asString();
- if (
- flags === undefined ||
- !BasicEvaluatedExpression.isValidRegExpFlags(flags)
- ) {
- return;
- }
- }
- }
- return new BasicEvaluatedExpression()
- .setRegExp(flags ? new RegExp(regExp, flags) : new RegExp(regExp))
- .setRange(/** @type {Range} */ (expr.range));
- });
- this.hooks.evaluate.for("LogicalExpression").tap(CLASS_NAME, (_expr) => {
- const expr = /** @type {LogicalExpression} */ (_expr);
- const left = this.evaluateExpression(expr.left);
- let returnRight = false;
- /** @type {boolean | undefined} */
- let allowedRight;
- if (expr.operator === "&&") {
- const leftAsBool = left.asBool();
- if (leftAsBool === false) {
- return left.setRange(/** @type {Range} */ (expr.range));
- }
- returnRight = leftAsBool === true;
- allowedRight = false;
- } else if (expr.operator === "||") {
- const leftAsBool = left.asBool();
- if (leftAsBool === true) {
- return left.setRange(/** @type {Range} */ (expr.range));
- }
- returnRight = leftAsBool === false;
- allowedRight = true;
- } else if (expr.operator === "??") {
- const leftAsNullish = left.asNullish();
- if (leftAsNullish === false) {
- return left.setRange(/** @type {Range} */ (expr.range));
- }
- if (leftAsNullish !== true) return;
- returnRight = true;
- } else {
- return;
- }
- const right = this.evaluateExpression(expr.right);
- if (returnRight) {
- if (left.couldHaveSideEffects()) right.setSideEffects();
- return right.setRange(/** @type {Range} */ (expr.range));
- }
- const asBool = right.asBool();
- if (allowedRight === true && asBool === true) {
- return new BasicEvaluatedExpression()
- .setRange(/** @type {Range} */ (expr.range))
- .setTruthy();
- } else if (allowedRight === false && asBool === false) {
- return new BasicEvaluatedExpression()
- .setRange(/** @type {Range} */ (expr.range))
- .setFalsy();
- }
- });
- /**
- * In simple logical cases, we can use valueAsExpression to assist us in evaluating the expression on
- * either side of a [BinaryExpression](https://github.com/estree/estree/blob/master/es5.md#binaryexpression).
- * This supports scenarios in webpack like conditionally `import()`'ing modules based on some simple evaluation:
- *
- * ```js
- * if (1 === 3) {
- * import("./moduleA"); // webpack will auto evaluate this and not import the modules
- * }
- * ```
- *
- * Additional scenarios include evaluation of strings inside of dynamic import statements:
- *
- * ```js
- * const foo = "foo";
- * const bar = "bar";
- *
- * import("./" + foo + bar); // webpack will auto evaluate this into import("./foobar")
- * ```
- * @param {boolean | number | bigint | string} value the value to convert to an expression
- * @param {BinaryExpression | UnaryExpression} expr the expression being evaluated
- * @param {boolean} sideEffects whether the expression has side effects
- * @returns {BasicEvaluatedExpression | undefined} the evaluated expression
- * @example
- *
- * ```js
- * const binaryExpr = new BinaryExpression("+",
- * { type: "Literal", value: 2 },
- * { type: "Literal", value: 3 }
- * );
- *
- * const leftValue = 2;
- * const rightValue = 3;
- *
- * const leftExpr = valueAsExpression(leftValue, binaryExpr.left, false);
- * const rightExpr = valueAsExpression(rightValue, binaryExpr.right, false);
- * const result = new BasicEvaluatedExpression()
- * .setNumber(leftExpr.number + rightExpr.number)
- * .setRange(binaryExpr.range);
- *
- * console.log(result.number); // Output: 5
- * ```
- */
- const valueAsExpression = (value, expr, sideEffects) => {
- switch (typeof value) {
- case "boolean":
- return new BasicEvaluatedExpression()
- .setBoolean(value)
- .setSideEffects(sideEffects)
- .setRange(/** @type {Range} */ (expr.range));
- case "number":
- return new BasicEvaluatedExpression()
- .setNumber(value)
- .setSideEffects(sideEffects)
- .setRange(/** @type {Range} */ (expr.range));
- case "bigint":
- return new BasicEvaluatedExpression()
- .setBigInt(value)
- .setSideEffects(sideEffects)
- .setRange(/** @type {Range} */ (expr.range));
- case "string":
- return new BasicEvaluatedExpression()
- .setString(value)
- .setSideEffects(sideEffects)
- .setRange(/** @type {Range} */ (expr.range));
- }
- };
- this.hooks.evaluate.for("BinaryExpression").tap(CLASS_NAME, (_expr) => {
- const expr = /** @type {BinaryExpression} */ (_expr);
- /**
- * Evaluates a binary expression if and only if it is a const operation (e.g. 1 + 2, "a" + "b", etc.).
- * @template T
- * @param {(leftOperand: T, rightOperand: T) => boolean | number | bigint | string} operandHandler the handler for the operation (e.g. (a, b) => a + b)
- * @returns {BasicEvaluatedExpression | undefined} the evaluated expression
- */
- const handleConstOperation = (operandHandler) => {
- const left = this.evaluateExpression(expr.left);
- if (!left.isCompileTimeValue()) return;
- const right = this.evaluateExpression(expr.right);
- if (!right.isCompileTimeValue()) return;
- const result = operandHandler(
- /** @type {T} */ (left.asCompileTimeValue()),
- /** @type {T} */ (right.asCompileTimeValue())
- );
- return valueAsExpression(
- result,
- expr,
- left.couldHaveSideEffects() || right.couldHaveSideEffects()
- );
- };
- /**
- * Helper function to determine if two booleans are always different. This is used in `handleStrictEqualityComparison`
- * to determine if an expressions boolean or nullish conversion is equal or not.
- * @param {boolean} a first boolean to compare
- * @param {boolean} b second boolean to compare
- * @returns {boolean} true if the two booleans are always different, false otherwise
- */
- const isAlwaysDifferent = (a, b) =>
- (a === true && b === false) || (a === false && b === true);
- /**
- * @param {BasicEvaluatedExpression} left left
- * @param {BasicEvaluatedExpression} right right
- * @param {BasicEvaluatedExpression} res res
- * @param {boolean} eql true for "===" and false for "!=="
- * @returns {BasicEvaluatedExpression | undefined} result
- */
- const handleTemplateStringCompare = (left, right, res, eql) => {
- /**
- * @param {BasicEvaluatedExpression[]} parts parts
- * @returns {string} value
- */
- const getPrefix = (parts) => {
- let value = "";
- for (const p of parts) {
- const v = p.asString();
- if (v !== undefined) value += v;
- else break;
- }
- return value;
- };
- /**
- * @param {BasicEvaluatedExpression[]} parts parts
- * @returns {string} value
- */
- const getSuffix = (parts) => {
- let value = "";
- for (let i = parts.length - 1; i >= 0; i--) {
- const v = parts[i].asString();
- if (v !== undefined) value = v + value;
- else break;
- }
- return value;
- };
- const leftPrefix = getPrefix(
- /** @type {BasicEvaluatedExpression[]} */ (left.parts)
- );
- const rightPrefix = getPrefix(
- /** @type {BasicEvaluatedExpression[]} */ (right.parts)
- );
- const leftSuffix = getSuffix(
- /** @type {BasicEvaluatedExpression[]} */ (left.parts)
- );
- const rightSuffix = getSuffix(
- /** @type {BasicEvaluatedExpression[]} */ (right.parts)
- );
- const lenPrefix = Math.min(leftPrefix.length, rightPrefix.length);
- const lenSuffix = Math.min(leftSuffix.length, rightSuffix.length);
- const prefixMismatch =
- lenPrefix > 0 &&
- leftPrefix.slice(0, lenPrefix) !== rightPrefix.slice(0, lenPrefix);
- const suffixMismatch =
- lenSuffix > 0 &&
- leftSuffix.slice(-lenSuffix) !== rightSuffix.slice(-lenSuffix);
- if (prefixMismatch || suffixMismatch) {
- return res
- .setBoolean(!eql)
- .setSideEffects(
- left.couldHaveSideEffects() || right.couldHaveSideEffects()
- );
- }
- };
- /**
- * Helper function to handle BinaryExpressions using strict equality comparisons (e.g. "===" and "!==").
- * @param {boolean} eql true for "===" and false for "!=="
- * @returns {BasicEvaluatedExpression | undefined} the evaluated expression
- */
- const handleStrictEqualityComparison = (eql) => {
- const left = this.evaluateExpression(expr.left);
- const right = this.evaluateExpression(expr.right);
- const res = new BasicEvaluatedExpression();
- res.setRange(/** @type {Range} */ (expr.range));
- const leftConst = left.isCompileTimeValue();
- const rightConst = right.isCompileTimeValue();
- if (leftConst && rightConst) {
- return res
- .setBoolean(
- eql === (left.asCompileTimeValue() === right.asCompileTimeValue())
- )
- .setSideEffects(
- left.couldHaveSideEffects() || right.couldHaveSideEffects()
- );
- }
- if (left.isArray() && right.isArray()) {
- return res
- .setBoolean(!eql)
- .setSideEffects(
- left.couldHaveSideEffects() || right.couldHaveSideEffects()
- );
- }
- if (left.isTemplateString() && right.isTemplateString()) {
- return handleTemplateStringCompare(left, right, res, eql);
- }
- const leftPrimitive = left.isPrimitiveType();
- const rightPrimitive = right.isPrimitiveType();
- if (
- // Primitive !== Object or
- // compile-time object types are never equal to something at runtime
- (leftPrimitive === false && (leftConst || rightPrimitive === true)) ||
- (rightPrimitive === false &&
- (rightConst || leftPrimitive === true)) ||
- // Different nullish or boolish status also means not equal
- isAlwaysDifferent(
- /** @type {boolean} */ (left.asBool()),
- /** @type {boolean} */ (right.asBool())
- ) ||
- isAlwaysDifferent(
- /** @type {boolean} */ (left.asNullish()),
- /** @type {boolean} */ (right.asNullish())
- )
- ) {
- return res
- .setBoolean(!eql)
- .setSideEffects(
- left.couldHaveSideEffects() || right.couldHaveSideEffects()
- );
- }
- };
- /**
- * Helper function to handle BinaryExpressions using abstract equality comparisons (e.g. "==" and "!=").
- * @param {boolean} eql true for "==" and false for "!="
- * @returns {BasicEvaluatedExpression | undefined} the evaluated expression
- */
- const handleAbstractEqualityComparison = (eql) => {
- const left = this.evaluateExpression(expr.left);
- const right = this.evaluateExpression(expr.right);
- const res = new BasicEvaluatedExpression();
- res.setRange(/** @type {Range} */ (expr.range));
- const leftConst = left.isCompileTimeValue();
- const rightConst = right.isCompileTimeValue();
- if (leftConst && rightConst) {
- return res
- .setBoolean(
- eql ===
- // eslint-disable-next-line eqeqeq
- (left.asCompileTimeValue() == right.asCompileTimeValue())
- )
- .setSideEffects(
- left.couldHaveSideEffects() || right.couldHaveSideEffects()
- );
- }
- if (left.isArray() && right.isArray()) {
- return res
- .setBoolean(!eql)
- .setSideEffects(
- left.couldHaveSideEffects() || right.couldHaveSideEffects()
- );
- }
- if (left.isTemplateString() && right.isTemplateString()) {
- return handleTemplateStringCompare(left, right, res, eql);
- }
- };
- if (expr.operator === "+") {
- const left = this.evaluateExpression(expr.left);
- const right = this.evaluateExpression(expr.right);
- const res = new BasicEvaluatedExpression();
- if (left.isString()) {
- if (right.isString()) {
- res.setString(
- /** @type {string} */ (left.string) +
- /** @type {string} */ (right.string)
- );
- } else if (right.isNumber()) {
- res.setString(/** @type {string} */ (left.string) + right.number);
- } else if (
- right.isWrapped() &&
- right.prefix &&
- right.prefix.isString()
- ) {
- // "left" + ("prefix" + inner + "postfix")
- // => ("leftPrefix" + inner + "postfix")
- res.setWrapped(
- new BasicEvaluatedExpression()
- .setString(
- /** @type {string} */ (left.string) +
- /** @type {string} */ (right.prefix.string)
- )
- .setRange(
- joinRanges(
- /** @type {Range} */ (left.range),
- /** @type {Range} */ (right.prefix.range)
- )
- ),
- right.postfix,
- right.wrappedInnerExpressions
- );
- } else if (right.isWrapped()) {
- // "left" + ([null] + inner + "postfix")
- // => ("left" + inner + "postfix")
- res.setWrapped(left, right.postfix, right.wrappedInnerExpressions);
- } else {
- // "left" + expr
- // => ("left" + expr + "")
- res.setWrapped(left, null, [right]);
- }
- } else if (left.isNumber()) {
- if (right.isString()) {
- res.setString(left.number + /** @type {string} */ (right.string));
- } else if (right.isNumber()) {
- res.setNumber(
- /** @type {number} */ (left.number) +
- /** @type {number} */ (right.number)
- );
- } else {
- return;
- }
- } else if (left.isBigInt()) {
- if (right.isBigInt()) {
- res.setBigInt(
- /** @type {bigint} */ (left.bigint) +
- /** @type {bigint} */ (right.bigint)
- );
- }
- } else if (left.isWrapped()) {
- if (left.postfix && left.postfix.isString() && right.isString()) {
- // ("prefix" + inner + "postfix") + "right"
- // => ("prefix" + inner + "postfixRight")
- res.setWrapped(
- left.prefix,
- new BasicEvaluatedExpression()
- .setString(
- /** @type {string} */ (left.postfix.string) +
- /** @type {string} */ (right.string)
- )
- .setRange(
- joinRanges(
- /** @type {Range} */ (left.postfix.range),
- /** @type {Range} */ (right.range)
- )
- ),
- left.wrappedInnerExpressions
- );
- } else if (
- left.postfix &&
- left.postfix.isString() &&
- right.isNumber()
- ) {
- // ("prefix" + inner + "postfix") + 123
- // => ("prefix" + inner + "postfix123")
- res.setWrapped(
- left.prefix,
- new BasicEvaluatedExpression()
- .setString(
- /** @type {string} */ (left.postfix.string) +
- /** @type {number} */ (right.number)
- )
- .setRange(
- joinRanges(
- /** @type {Range} */ (left.postfix.range),
- /** @type {Range} */ (right.range)
- )
- ),
- left.wrappedInnerExpressions
- );
- } else if (right.isString()) {
- // ("prefix" + inner + [null]) + "right"
- // => ("prefix" + inner + "right")
- res.setWrapped(left.prefix, right, left.wrappedInnerExpressions);
- } else if (right.isNumber()) {
- // ("prefix" + inner + [null]) + 123
- // => ("prefix" + inner + "123")
- res.setWrapped(
- left.prefix,
- new BasicEvaluatedExpression()
- .setString(String(right.number))
- .setRange(/** @type {Range} */ (right.range)),
- left.wrappedInnerExpressions
- );
- } else if (right.isWrapped()) {
- // ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2")
- // ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2")
- res.setWrapped(
- left.prefix,
- right.postfix,
- left.wrappedInnerExpressions &&
- right.wrappedInnerExpressions && [
- ...left.wrappedInnerExpressions,
- ...(left.postfix ? [left.postfix] : []),
- ...(right.prefix ? [right.prefix] : []),
- ...right.wrappedInnerExpressions
- ]
- );
- } else {
- // ("prefix" + inner + postfix) + expr
- // => ("prefix" + inner + postfix + expr + [null])
- res.setWrapped(
- left.prefix,
- null,
- left.wrappedInnerExpressions && [
- ...left.wrappedInnerExpressions,
- ...(left.postfix ? [left.postfix, right] : [right])
- ]
- );
- }
- } else if (right.isString()) {
- // left + "right"
- // => ([null] + left + "right")
- res.setWrapped(null, right, [left]);
- } else if (right.isWrapped()) {
- // left + (prefix + inner + "postfix")
- // => ([null] + left + prefix + inner + "postfix")
- res.setWrapped(
- null,
- right.postfix,
- right.wrappedInnerExpressions && [
- ...(right.prefix ? [left, right.prefix] : [left]),
- ...right.wrappedInnerExpressions
- ]
- );
- } else {
- return;
- }
- if (left.couldHaveSideEffects() || right.couldHaveSideEffects()) {
- res.setSideEffects();
- }
- res.setRange(/** @type {Range} */ (expr.range));
- return res;
- } else if (expr.operator === "-") {
- return handleConstOperation((l, r) => l - r);
- } else if (expr.operator === "*") {
- return handleConstOperation((l, r) => l * r);
- } else if (expr.operator === "/") {
- return handleConstOperation((l, r) => l / r);
- } else if (expr.operator === "**") {
- return handleConstOperation((l, r) => l ** r);
- } else if (expr.operator === "===") {
- return handleStrictEqualityComparison(true);
- } else if (expr.operator === "==") {
- return handleAbstractEqualityComparison(true);
- } else if (expr.operator === "!==") {
- return handleStrictEqualityComparison(false);
- } else if (expr.operator === "!=") {
- return handleAbstractEqualityComparison(false);
- } else if (expr.operator === "&") {
- return handleConstOperation((l, r) => l & r);
- } else if (expr.operator === "|") {
- return handleConstOperation((l, r) => l | r);
- } else if (expr.operator === "^") {
- return handleConstOperation((l, r) => l ^ r);
- } else if (expr.operator === ">>>") {
- return handleConstOperation((l, r) => l >>> r);
- } else if (expr.operator === ">>") {
- return handleConstOperation((l, r) => l >> r);
- } else if (expr.operator === "<<") {
- return handleConstOperation((l, r) => l << r);
- } else if (expr.operator === "<") {
- return handleConstOperation((l, r) => l < r);
- } else if (expr.operator === ">") {
- return handleConstOperation((l, r) => l > r);
- } else if (expr.operator === "<=") {
- return handleConstOperation((l, r) => l <= r);
- } else if (expr.operator === ">=") {
- return handleConstOperation((l, r) => l >= r);
- }
- });
- this.hooks.evaluate.for("UnaryExpression").tap(CLASS_NAME, (_expr) => {
- const expr = /** @type {UnaryExpression} */ (_expr);
- /**
- * Evaluates a UnaryExpression if and only if it is a basic const operator (e.g. +a, -a, ~a).
- * @template T
- * @param {(operand: T) => boolean | number | bigint | string} operandHandler handler for the operand
- * @returns {BasicEvaluatedExpression | undefined} evaluated expression
- */
- const handleConstOperation = (operandHandler) => {
- const argument = this.evaluateExpression(expr.argument);
- if (!argument.isCompileTimeValue()) return;
- const result = operandHandler(
- /** @type {T} */ (argument.asCompileTimeValue())
- );
- return valueAsExpression(result, expr, argument.couldHaveSideEffects());
- };
- if (expr.operator === "typeof") {
- switch (expr.argument.type) {
- case "Identifier": {
- const res = this.callHooksForName(
- this.hooks.evaluateTypeof,
- expr.argument.name,
- expr
- );
- if (res !== undefined) return res;
- break;
- }
- case "MetaProperty": {
- const res = this.callHooksForName(
- this.hooks.evaluateTypeof,
- /** @type {string} */
- (getRootName(expr.argument)),
- expr
- );
- if (res !== undefined) return res;
- break;
- }
- case "MemberExpression": {
- const res = this.callHooksForExpression(
- this.hooks.evaluateTypeof,
- expr.argument,
- expr
- );
- if (res !== undefined) return res;
- break;
- }
- case "ChainExpression": {
- const res = this.callHooksForExpression(
- this.hooks.evaluateTypeof,
- expr.argument.expression,
- expr
- );
- if (res !== undefined) return res;
- break;
- }
- case "FunctionExpression": {
- return new BasicEvaluatedExpression()
- .setString("function")
- .setRange(/** @type {Range} */ (expr.range));
- }
- }
- const arg = this.evaluateExpression(expr.argument);
- if (arg.isUnknown()) return;
- if (arg.isString()) {
- return new BasicEvaluatedExpression()
- .setString("string")
- .setRange(/** @type {Range} */ (expr.range));
- }
- if (arg.isWrapped()) {
- return new BasicEvaluatedExpression()
- .setString("string")
- .setSideEffects()
- .setRange(/** @type {Range} */ (expr.range));
- }
- if (arg.isUndefined()) {
- return new BasicEvaluatedExpression()
- .setString("undefined")
- .setRange(/** @type {Range} */ (expr.range));
- }
- if (arg.isNumber()) {
- return new BasicEvaluatedExpression()
- .setString("number")
- .setRange(/** @type {Range} */ (expr.range));
- }
- if (arg.isBigInt()) {
- return new BasicEvaluatedExpression()
- .setString("bigint")
- .setRange(/** @type {Range} */ (expr.range));
- }
- if (arg.isBoolean()) {
- return new BasicEvaluatedExpression()
- .setString("boolean")
- .setRange(/** @type {Range} */ (expr.range));
- }
- if (arg.isConstArray() || arg.isRegExp() || arg.isNull()) {
- return new BasicEvaluatedExpression()
- .setString("object")
- .setRange(/** @type {Range} */ (expr.range));
- }
- if (arg.isArray()) {
- return new BasicEvaluatedExpression()
- .setString("object")
- .setSideEffects(arg.couldHaveSideEffects())
- .setRange(/** @type {Range} */ (expr.range));
- }
- } else if (expr.operator === "!") {
- const argument = this.evaluateExpression(expr.argument);
- const bool = argument.asBool();
- if (typeof bool !== "boolean") return;
- return new BasicEvaluatedExpression()
- .setBoolean(!bool)
- .setSideEffects(argument.couldHaveSideEffects())
- .setRange(/** @type {Range} */ (expr.range));
- } else if (expr.operator === "~") {
- return handleConstOperation((v) => ~v);
- } else if (expr.operator === "+") {
- // eslint-disable-next-line no-implicit-coercion
- return handleConstOperation((v) => +v);
- } else if (expr.operator === "-") {
- return handleConstOperation((v) => -v);
- }
- });
- this.hooks.evaluateTypeof
- .for("undefined")
- .tap(CLASS_NAME, (expr) =>
- new BasicEvaluatedExpression()
- .setString("undefined")
- .setRange(/** @type {Range} */ (expr.range))
- );
- this.hooks.evaluate.for("Identifier").tap(CLASS_NAME, (expr) => {
- if (/** @type {Identifier} */ (expr).name === "undefined") {
- return new BasicEvaluatedExpression()
- .setUndefined()
- .setRange(/** @type {Range} */ (expr.range));
- }
- });
- /**
- * @param {"Identifier" | "ThisExpression" | "MemberExpression"} exprType expression type name
- * @param {(node: Expression | SpreadElement) => GetInfoResult | undefined} getInfo get info
- * @returns {void}
- */
- const tapEvaluateWithVariableInfo = (exprType, getInfo) => {
- /** @type {Expression | undefined} */
- let cachedExpression;
- /** @type {GetInfoResult | undefined} */
- let cachedInfo;
- this.hooks.evaluate.for(exprType).tap(CLASS_NAME, (expr) => {
- const expression =
- /** @type {Identifier | ThisExpression | MemberExpression} */ (expr);
- const info = getInfo(expression);
- if (info !== undefined) {
- return this.callHooksForInfoWithFallback(
- this.hooks.evaluateIdentifier,
- info.name,
- (_name) => {
- cachedExpression = expression;
- cachedInfo = info;
- return undefined;
- },
- (name) => {
- const hook = this.hooks.evaluateDefinedIdentifier.get(name);
- if (hook !== undefined) {
- return hook.call(expression);
- }
- },
- expression
- );
- }
- });
- this.hooks.evaluate
- .for(exprType)
- .tap({ name: CLASS_NAME, stage: 100 }, (expr) => {
- const expression =
- /** @type {Identifier | ThisExpression | MemberExpression} */
- (expr);
- const info =
- cachedExpression === expression ? cachedInfo : getInfo(expression);
- if (info !== undefined) {
- return new BasicEvaluatedExpression()
- .setIdentifier(
- info.name,
- info.rootInfo,
- info.getMembers,
- info.getMembersOptionals,
- info.getMemberRanges
- )
- .setRange(/** @type {Range} */ (expression.range));
- }
- });
- this.hooks.finish.tap(CLASS_NAME, () => {
- // Cleanup for GC
- cachedExpression = cachedInfo = undefined;
- });
- };
- tapEvaluateWithVariableInfo("Identifier", (expr) => {
- const info = this.getVariableInfo(/** @type {Identifier} */ (expr).name);
- if (
- typeof info === "string" ||
- (info instanceof VariableInfo && (info.isFree() || info.isTagged()))
- ) {
- return {
- name: info,
- rootInfo: info,
- getMembers: () => [],
- getMembersOptionals: () => [],
- getMemberRanges: () => []
- };
- }
- });
- tapEvaluateWithVariableInfo("ThisExpression", (_expr) => {
- const info = this.getVariableInfo("this");
- if (
- typeof info === "string" ||
- (info instanceof VariableInfo && (info.isFree() || info.isTagged()))
- ) {
- return {
- name: info,
- rootInfo: info,
- getMembers: () => [],
- getMembersOptionals: () => [],
- getMemberRanges: () => []
- };
- }
- });
- this.hooks.evaluate.for("MetaProperty").tap(CLASS_NAME, (expr) => {
- const metaProperty = /** @type {MetaProperty} */ (expr);
- return this.callHooksForName(
- this.hooks.evaluateIdentifier,
- /** @type {string} */
- (getRootName(metaProperty)),
- metaProperty
- );
- });
- tapEvaluateWithVariableInfo("MemberExpression", (expr) =>
- this.getMemberExpressionInfo(
- /** @type {MemberExpression} */ (expr),
- ALLOWED_MEMBER_TYPES_EXPRESSION
- )
- );
- this.hooks.evaluate.for("CallExpression").tap(CLASS_NAME, (_expr) => {
- const expr = /** @type {CallExpression} */ (_expr);
- if (
- expr.callee.type === "MemberExpression" &&
- expr.callee.property.type ===
- (expr.callee.computed ? "Literal" : "Identifier")
- ) {
- // type Super also possible here
- const param = this.evaluateExpression(
- /** @type {Expression} */ (expr.callee.object)
- );
- const property =
- expr.callee.property.type === "Literal"
- ? `${expr.callee.property.value}`
- : expr.callee.property.name;
- const hook = this.hooks.evaluateCallExpressionMember.get(property);
- if (hook !== undefined) {
- return hook.call(expr, param);
- }
- } else if (expr.callee.type === "Identifier") {
- return this.callHooksForName(
- this.hooks.evaluateCallExpression,
- expr.callee.name,
- expr
- );
- }
- });
- this.hooks.evaluateCallExpressionMember
- .for("indexOf")
- .tap(CLASS_NAME, (expr, param) => {
- if (!param.isString()) return;
- if (expr.arguments.length === 0) return;
- const [arg1, arg2] = expr.arguments;
- if (arg1.type === "SpreadElement") return;
- const arg1Eval = this.evaluateExpression(arg1);
- if (!arg1Eval.isString()) return;
- const arg1Value = /** @type {string} */ (arg1Eval.string);
- let result;
- if (arg2) {
- if (arg2.type === "SpreadElement") return;
- const arg2Eval = this.evaluateExpression(arg2);
- if (!arg2Eval.isNumber()) return;
- result = /** @type {string} */ (param.string).indexOf(
- arg1Value,
- arg2Eval.number
- );
- } else {
- result = /** @type {string} */ (param.string).indexOf(arg1Value);
- }
- return new BasicEvaluatedExpression()
- .setNumber(result)
- .setSideEffects(param.couldHaveSideEffects())
- .setRange(/** @type {Range} */ (expr.range));
- });
- this.hooks.evaluateCallExpressionMember
- .for("replace")
- .tap(CLASS_NAME, (expr, param) => {
- if (!param.isString()) return;
- if (expr.arguments.length !== 2) return;
- if (expr.arguments[0].type === "SpreadElement") return;
- if (expr.arguments[1].type === "SpreadElement") return;
- const arg1 = this.evaluateExpression(expr.arguments[0]);
- const arg2 = this.evaluateExpression(expr.arguments[1]);
- if (!arg1.isString() && !arg1.isRegExp()) return;
- const arg1Value = /** @type {string | RegExp} */ (
- arg1.regExp || arg1.string
- );
- if (!arg2.isString()) return;
- const arg2Value = /** @type {string} */ (arg2.string);
- return new BasicEvaluatedExpression()
- .setString(
- /** @type {string} */ (param.string).replace(arg1Value, arg2Value)
- )
- .setSideEffects(param.couldHaveSideEffects())
- .setRange(/** @type {Range} */ (expr.range));
- });
- for (const fn of ["substr", "substring", "slice"]) {
- this.hooks.evaluateCallExpressionMember
- .for(fn)
- .tap(CLASS_NAME, (expr, param) => {
- if (!param.isString()) return;
- let arg1;
- let result;
- const str = /** @type {string} */ (param.string);
- switch (expr.arguments.length) {
- case 1:
- if (expr.arguments[0].type === "SpreadElement") return;
- arg1 = this.evaluateExpression(expr.arguments[0]);
- if (!arg1.isNumber()) return;
- result = str[
- /** @type {"substr" | "substring" | "slice"} */ (fn)
- ](/** @type {number} */ (arg1.number));
- break;
- case 2: {
- if (expr.arguments[0].type === "SpreadElement") return;
- if (expr.arguments[1].type === "SpreadElement") return;
- arg1 = this.evaluateExpression(expr.arguments[0]);
- const arg2 = this.evaluateExpression(expr.arguments[1]);
- if (!arg1.isNumber()) return;
- if (!arg2.isNumber()) return;
- result = str[
- /** @type {"substr" | "substring" | "slice"} */ (fn)
- ](
- /** @type {number} */ (arg1.number),
- /** @type {number} */ (arg2.number)
- );
- break;
- }
- default:
- return;
- }
- return new BasicEvaluatedExpression()
- .setString(result)
- .setSideEffects(param.couldHaveSideEffects())
- .setRange(/** @type {Range} */ (expr.range));
- });
- }
- /**
- * @param {"cooked" | "raw"} kind kind of values to get
- * @param {TemplateLiteral} templateLiteralExpr TemplateLiteral expr
- * @returns {{quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[]}} Simplified template
- */
- const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => {
- /** @type {BasicEvaluatedExpression[]} */
- const quasis = [];
- /** @type {BasicEvaluatedExpression[]} */
- const parts = [];
- for (let i = 0; i < templateLiteralExpr.quasis.length; i++) {
- const quasiExpr = templateLiteralExpr.quasis[i];
- const quasi = quasiExpr.value[kind];
- if (i > 0) {
- const prevExpr = parts[parts.length - 1];
- const expr = this.evaluateExpression(
- templateLiteralExpr.expressions[i - 1]
- );
- const exprAsString = expr.asString();
- if (
- typeof exprAsString === "string" &&
- !expr.couldHaveSideEffects()
- ) {
- // We can merge quasi + expr + quasi when expr
- // is a const string
- prevExpr.setString(prevExpr.string + exprAsString + quasi);
- prevExpr.setRange([
- /** @type {Range} */ (prevExpr.range)[0],
- /** @type {Range} */ (quasiExpr.range)[1]
- ]);
- // We unset the expression as it doesn't match to a single expression
- prevExpr.setExpression(undefined);
- continue;
- }
- parts.push(expr);
- }
- const part = new BasicEvaluatedExpression()
- .setString(/** @type {string} */ (quasi))
- .setRange(/** @type {Range} */ (quasiExpr.range))
- .setExpression(quasiExpr);
- quasis.push(part);
- parts.push(part);
- }
- return {
- quasis,
- parts
- };
- };
- this.hooks.evaluate.for("TemplateLiteral").tap(CLASS_NAME, (_node) => {
- const node = /** @type {TemplateLiteral} */ (_node);
- const { quasis, parts } = getSimplifiedTemplateResult("cooked", node);
- if (parts.length === 1) {
- return parts[0].setRange(/** @type {Range} */ (node.range));
- }
- return new BasicEvaluatedExpression()
- .setTemplateString(quasis, parts, "cooked")
- .setRange(/** @type {Range} */ (node.range));
- });
- this.hooks.evaluate
- .for("TaggedTemplateExpression")
- .tap(CLASS_NAME, (_node) => {
- const node = /** @type {TaggedTemplateExpression} */ (_node);
- const tag = this.evaluateExpression(node.tag);
- if (tag.isIdentifier() && tag.identifier === "String.raw") {
- const { quasis, parts } = getSimplifiedTemplateResult(
- "raw",
- node.quasi
- );
- return new BasicEvaluatedExpression()
- .setTemplateString(quasis, parts, "raw")
- .setRange(/** @type {Range} */ (node.range));
- }
- });
- this.hooks.evaluateCallExpressionMember
- .for("concat")
- .tap(CLASS_NAME, (expr, param) => {
- if (!param.isString() && !param.isWrapped()) return;
- let stringSuffix = null;
- let hasUnknownParams = false;
- /** @type {BasicEvaluatedExpression[]} */
- const innerExpressions = [];
- for (let i = expr.arguments.length - 1; i >= 0; i--) {
- const arg = expr.arguments[i];
- if (arg.type === "SpreadElement") return;
- const argExpr = this.evaluateExpression(arg);
- if (
- hasUnknownParams ||
- (!argExpr.isString() && !argExpr.isNumber())
- ) {
- hasUnknownParams = true;
- innerExpressions.push(argExpr);
- continue;
- }
- const value = argExpr.isString()
- ? /** @type {string} */ (argExpr.string)
- : String(argExpr.number);
- /** @type {string} */
- const newString =
- value +
- (stringSuffix ? /** @type {string} */ (stringSuffix.string) : "");
- const newRange = /** @type {Range} */ ([
- /** @type {Range} */ (argExpr.range)[0],
- /** @type {Range} */ ((stringSuffix || argExpr).range)[1]
- ]);
- stringSuffix = new BasicEvaluatedExpression()
- .setString(newString)
- .setSideEffects(
- (stringSuffix && stringSuffix.couldHaveSideEffects()) ||
- argExpr.couldHaveSideEffects()
- )
- .setRange(newRange);
- }
- if (hasUnknownParams) {
- const prefix = param.isString() ? param : param.prefix;
- const inner =
- param.isWrapped() && param.wrappedInnerExpressions
- ? [
- ...param.wrappedInnerExpressions,
- ...innerExpressions.reverse()
- ]
- : innerExpressions.reverse();
- return new BasicEvaluatedExpression()
- .setWrapped(prefix, stringSuffix, inner)
- .setRange(/** @type {Range} */ (expr.range));
- } else if (param.isWrapped()) {
- const postfix = stringSuffix || param.postfix;
- const inner = param.wrappedInnerExpressions
- ? [...param.wrappedInnerExpressions, ...innerExpressions.reverse()]
- : innerExpressions.reverse();
- return new BasicEvaluatedExpression()
- .setWrapped(param.prefix, postfix, inner)
- .setRange(/** @type {Range} */ (expr.range));
- }
- const newString =
- /** @type {string} */ (param.string) +
- (stringSuffix ? stringSuffix.string : "");
- return new BasicEvaluatedExpression()
- .setString(newString)
- .setSideEffects(
- (stringSuffix && stringSuffix.couldHaveSideEffects()) ||
- param.couldHaveSideEffects()
- )
- .setRange(/** @type {Range} */ (expr.range));
- });
- this.hooks.evaluateCallExpressionMember
- .for("split")
- .tap(CLASS_NAME, (expr, param) => {
- if (!param.isString()) return;
- if (expr.arguments.length !== 1) return;
- if (expr.arguments[0].type === "SpreadElement") return;
- let result;
- const arg = this.evaluateExpression(expr.arguments[0]);
- if (arg.isString()) {
- result =
- /** @type {string} */
- (param.string).split(/** @type {string} */ (arg.string));
- } else if (arg.isRegExp()) {
- result = /** @type {string} */ (param.string).split(
- /** @type {RegExp} */ (arg.regExp)
- );
- } else {
- return;
- }
- return new BasicEvaluatedExpression()
- .setArray(result)
- .setSideEffects(param.couldHaveSideEffects())
- .setRange(/** @type {Range} */ (expr.range));
- });
- this.hooks.evaluate
- .for("ConditionalExpression")
- .tap(CLASS_NAME, (_expr) => {
- const expr = /** @type {ConditionalExpression} */ (_expr);
- const condition = this.evaluateExpression(expr.test);
- const conditionValue = condition.asBool();
- let res;
- if (conditionValue === undefined) {
- const consequent = this.evaluateExpression(expr.consequent);
- const alternate = this.evaluateExpression(expr.alternate);
- res = new BasicEvaluatedExpression();
- if (consequent.isConditional()) {
- res.setOptions(
- /** @type {BasicEvaluatedExpression[]} */ (consequent.options)
- );
- } else {
- res.setOptions([consequent]);
- }
- if (alternate.isConditional()) {
- res.addOptions(
- /** @type {BasicEvaluatedExpression[]} */ (alternate.options)
- );
- } else {
- res.addOptions([alternate]);
- }
- } else {
- res = this.evaluateExpression(
- conditionValue ? expr.consequent : expr.alternate
- );
- if (condition.couldHaveSideEffects()) res.setSideEffects();
- }
- res.setRange(/** @type {Range} */ (expr.range));
- return res;
- });
- this.hooks.evaluate.for("ArrayExpression").tap(CLASS_NAME, (_expr) => {
- const expr = /** @type {ArrayExpression} */ (_expr);
- const items = expr.elements.map(
- (element) =>
- element !== null &&
- element.type !== "SpreadElement" &&
- this.evaluateExpression(element)
- );
- if (!items.every(Boolean)) return;
- return new BasicEvaluatedExpression()
- .setItems(/** @type {BasicEvaluatedExpression[]} */ (items))
- .setRange(/** @type {Range} */ (expr.range));
- });
- this.hooks.evaluate.for("ChainExpression").tap(CLASS_NAME, (_expr) => {
- const expr = /** @type {ChainExpression} */ (_expr);
- /** @type {Expression[]} */
- const optionalExpressionsStack = [];
- /** @type {Expression|Super} */
- let next = expr.expression;
- while (
- next.type === "MemberExpression" ||
- next.type === "CallExpression"
- ) {
- if (next.type === "MemberExpression") {
- if (next.optional) {
- // SuperNode can not be optional
- optionalExpressionsStack.push(
- /** @type {Expression} */ (next.object)
- );
- }
- next = next.object;
- } else {
- if (next.optional) {
- // SuperNode can not be optional
- optionalExpressionsStack.push(
- /** @type {Expression} */ (next.callee)
- );
- }
- next = next.callee;
- }
- }
- while (optionalExpressionsStack.length > 0) {
- const expression =
- /** @type {Expression} */
- (optionalExpressionsStack.pop());
- const evaluated = this.evaluateExpression(expression);
- if (evaluated.asNullish()) {
- return evaluated.setRange(/** @type {Range} */ (_expr.range));
- }
- }
- return this.evaluateExpression(expr.expression);
- });
- }
- /**
- * @param {Expression} node node
- * @returns {Set<DestructuringAssignmentProperty> | undefined} destructured identifiers
- */
- destructuringAssignmentPropertiesFor(node) {
- if (!this.destructuringAssignmentProperties) return;
- return this.destructuringAssignmentProperties.get(node);
- }
- /**
- * @param {Expression | SpreadElement} expr expression
- * @returns {string | VariableInfo | undefined} identifier
- */
- getRenameIdentifier(expr) {
- const result = this.evaluateExpression(expr);
- if (result.isIdentifier()) {
- return result.identifier;
- }
- }
- /**
- * @param {ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration} classy a class node
- * @returns {void}
- */
- walkClass(classy) {
- if (
- classy.superClass &&
- !this.hooks.classExtendsExpression.call(classy.superClass, classy)
- ) {
- this.walkExpression(classy.superClass);
- }
- if (classy.body && classy.body.type === "ClassBody") {
- const scopeParams = [];
- // Add class name in scope for recursive calls
- if (classy.id) {
- scopeParams.push(classy.id);
- }
- this.inClassScope(true, scopeParams, () => {
- for (const classElement of classy.body.body) {
- if (!this.hooks.classBodyElement.call(classElement, classy)) {
- if (classElement.type === "StaticBlock") {
- const wasTopLevel = this.scope.topLevelScope;
- this.scope.topLevelScope = false;
- this.walkBlockStatement(classElement);
- this.scope.topLevelScope = wasTopLevel;
- } else {
- if (classElement.computed && classElement.key) {
- this.walkExpression(classElement.key);
- }
- if (
- classElement.value &&
- !this.hooks.classBodyValue.call(
- classElement.value,
- classElement,
- classy
- )
- ) {
- const wasTopLevel = this.scope.topLevelScope;
- this.scope.topLevelScope = false;
- this.walkExpression(classElement.value);
- this.scope.topLevelScope = wasTopLevel;
- }
- }
- }
- }
- });
- }
- }
- /**
- * Module pre walking iterates the scope for import entries
- * @param {(Statement | ModuleDeclaration)[]} statements statements
- */
- modulePreWalkStatements(statements) {
- for (let index = 0, len = statements.length; index < len; index++) {
- const statement = statements[index];
- /** @type {StatementPath} */
- (this.statementPath).push(statement);
- switch (statement.type) {
- case "ImportDeclaration":
- this.modulePreWalkImportDeclaration(statement);
- break;
- case "ExportAllDeclaration":
- this.modulePreWalkExportAllDeclaration(statement);
- break;
- case "ExportNamedDeclaration":
- this.modulePreWalkExportNamedDeclaration(statement);
- break;
- }
- this.prevStatement =
- /** @type {StatementPath} */
- (this.statementPath).pop();
- }
- }
- /**
- * Pre walking iterates the scope for variable declarations
- * @param {(Statement | ModuleDeclaration)[]} statements statements
- */
- preWalkStatements(statements) {
- for (let index = 0, len = statements.length; index < len; index++) {
- const statement = statements[index];
- this.preWalkStatement(statement);
- }
- }
- /**
- * Block pre walking iterates the scope for block variable declarations
- * @param {(Statement | ModuleDeclaration)[]} statements statements
- */
- blockPreWalkStatements(statements) {
- for (let index = 0, len = statements.length; index < len; index++) {
- const statement = statements[index];
- this.blockPreWalkStatement(statement);
- }
- }
- /**
- * Walking iterates the statements and expressions and processes them
- * @param {(Statement | ModuleDeclaration)[]} statements statements
- */
- walkStatements(statements) {
- let onlyFunctionDeclaration = false;
- for (let index = 0, len = statements.length; index < len; index++) {
- const statement = statements[index];
- if (
- onlyFunctionDeclaration &&
- statement.type !== "FunctionDeclaration" &&
- this.hooks.unusedStatement.call(/** @type {Statement} */ (statement))
- ) {
- continue;
- }
- this.walkStatement(statement);
- if (this.scope.terminated) {
- onlyFunctionDeclaration = true;
- }
- }
- }
- /**
- * Walking iterates the statements and expressions and processes them
- * @param {Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration} statement statement
- */
- preWalkStatement(statement) {
- /** @type {StatementPath} */
- (this.statementPath).push(statement);
- if (this.hooks.preStatement.call(statement)) {
- this.prevStatement =
- /** @type {StatementPath} */
- (this.statementPath).pop();
- return;
- }
- switch (statement.type) {
- case "BlockStatement":
- this.preWalkBlockStatement(statement);
- break;
- case "DoWhileStatement":
- this.preWalkDoWhileStatement(statement);
- break;
- case "ForInStatement":
- this.preWalkForInStatement(statement);
- break;
- case "ForOfStatement":
- this.preWalkForOfStatement(statement);
- break;
- case "ForStatement":
- this.preWalkForStatement(statement);
- break;
- case "FunctionDeclaration":
- this.preWalkFunctionDeclaration(statement);
- break;
- case "IfStatement":
- this.preWalkIfStatement(statement);
- break;
- case "LabeledStatement":
- this.preWalkLabeledStatement(statement);
- break;
- case "SwitchStatement":
- this.preWalkSwitchStatement(statement);
- break;
- case "TryStatement":
- this.preWalkTryStatement(statement);
- break;
- case "VariableDeclaration":
- this.preWalkVariableDeclaration(statement);
- break;
- case "WhileStatement":
- this.preWalkWhileStatement(statement);
- break;
- case "WithStatement":
- this.preWalkWithStatement(statement);
- break;
- }
- this.prevStatement =
- /** @type {StatementPath} */
- (this.statementPath).pop();
- }
- /**
- * @param {Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration} statement statement
- */
- blockPreWalkStatement(statement) {
- /** @type {StatementPath} */
- (this.statementPath).push(statement);
- if (this.hooks.blockPreStatement.call(statement)) {
- this.prevStatement =
- /** @type {StatementPath} */
- (this.statementPath).pop();
- return;
- }
- switch (statement.type) {
- case "ExportDefaultDeclaration":
- this.blockPreWalkExportDefaultDeclaration(statement);
- break;
- case "ExportNamedDeclaration":
- this.blockPreWalkExportNamedDeclaration(statement);
- break;
- case "VariableDeclaration":
- this.blockPreWalkVariableDeclaration(statement);
- break;
- case "ClassDeclaration":
- this.blockPreWalkClassDeclaration(statement);
- break;
- case "ExpressionStatement":
- this.blockPreWalkExpressionStatement(statement);
- }
- this.prevStatement =
- /** @type {StatementPath} */
- (this.statementPath).pop();
- }
- /**
- * @param {Statement | ModuleDeclaration | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} statement statement
- */
- walkStatement(statement) {
- /** @type {StatementPath} */
- (this.statementPath).push(statement);
- if (this.hooks.statement.call(statement) !== undefined) {
- this.prevStatement =
- /** @type {StatementPath} */
- (this.statementPath).pop();
- return;
- }
- switch (statement.type) {
- case "BlockStatement":
- this.walkBlockStatement(statement);
- break;
- case "ClassDeclaration":
- this.walkClassDeclaration(statement);
- break;
- case "DoWhileStatement":
- this.walkDoWhileStatement(statement);
- break;
- case "ExportDefaultDeclaration":
- this.walkExportDefaultDeclaration(statement);
- break;
- case "ExportNamedDeclaration":
- this.walkExportNamedDeclaration(statement);
- break;
- case "ExpressionStatement":
- this.walkExpressionStatement(statement);
- break;
- case "ForInStatement":
- this.walkForInStatement(statement);
- break;
- case "ForOfStatement":
- this.walkForOfStatement(statement);
- break;
- case "ForStatement":
- this.walkForStatement(statement);
- break;
- case "FunctionDeclaration":
- this.walkFunctionDeclaration(statement);
- break;
- case "IfStatement":
- this.walkIfStatement(statement);
- break;
- case "LabeledStatement":
- this.walkLabeledStatement(statement);
- break;
- case "ReturnStatement":
- this.walkReturnStatement(statement);
- break;
- case "SwitchStatement":
- this.walkSwitchStatement(statement);
- break;
- case "ThrowStatement":
- this.walkThrowStatement(statement);
- break;
- case "TryStatement":
- this.walkTryStatement(statement);
- break;
- case "VariableDeclaration":
- this.walkVariableDeclaration(statement);
- break;
- case "WhileStatement":
- this.walkWhileStatement(statement);
- break;
- case "WithStatement":
- this.walkWithStatement(statement);
- break;
- }
- this.prevStatement =
- /** @type {StatementPath} */
- (this.statementPath).pop();
- }
- /**
- * Walks a statements that is nested within a parent statement
- * and can potentially be a non-block statement.
- * This enforces the nested statement to never be in ASI position.
- * @param {Statement} statement the nested statement
- */
- walkNestedStatement(statement) {
- this.prevStatement = undefined;
- this.walkStatement(statement);
- }
- // Real Statements
- /**
- * @param {BlockStatement} statement block statement
- */
- preWalkBlockStatement(statement) {
- this.preWalkStatements(statement.body);
- }
- /**
- * @param {BlockStatement | StaticBlock} statement block statement
- */
- walkBlockStatement(statement) {
- this.inBlockScope(() => {
- const body = statement.body;
- const prev = this.prevStatement;
- this.blockPreWalkStatements(body);
- this.prevStatement = prev;
- this.walkStatements(body);
- }, true);
- }
- /**
- * @param {ExpressionStatement} statement expression statement
- */
- walkExpressionStatement(statement) {
- this.walkExpression(statement.expression);
- }
- /**
- * @param {IfStatement} statement if statement
- */
- preWalkIfStatement(statement) {
- this.preWalkStatement(statement.consequent);
- if (statement.alternate) {
- this.preWalkStatement(statement.alternate);
- }
- }
- /**
- * @param {IfStatement} statement if statement
- */
- walkIfStatement(statement) {
- const result = this.hooks.statementIf.call(statement);
- if (result === undefined) {
- this.walkExpression(statement.test);
- this.walkNestedStatement(statement.consequent);
- const consequentTerminated = this.scope.terminated;
- this.scope.terminated = undefined;
- if (statement.alternate) {
- this.walkNestedStatement(statement.alternate);
- }
- const alternateTerminated = this.scope.terminated;
- this.scope.terminated =
- consequentTerminated && alternateTerminated
- ? alternateTerminated
- : undefined;
- } else if (result) {
- this.walkNestedStatement(statement.consequent);
- } else if (statement.alternate) {
- this.walkNestedStatement(statement.alternate);
- }
- }
- /**
- * @param {LabeledStatement} statement with statement
- */
- preWalkLabeledStatement(statement) {
- this.preWalkStatement(statement.body);
- }
- /**
- * @param {LabeledStatement} statement with statement
- */
- walkLabeledStatement(statement) {
- const hook = this.hooks.label.get(statement.label.name);
- if (hook !== undefined) {
- const result = hook.call(statement);
- if (result === true) return;
- }
- this.inBlockScope(() => {
- this.walkNestedStatement(statement.body);
- });
- }
- /**
- * @param {WithStatement} statement with statement
- */
- preWalkWithStatement(statement) {
- this.preWalkStatement(statement.body);
- }
- /**
- * @param {WithStatement} statement with statement
- */
- walkWithStatement(statement) {
- this.inBlockScope(() => {
- this.walkExpression(statement.object);
- this.walkNestedStatement(statement.body);
- });
- }
- /**
- * @param {SwitchStatement} statement switch statement
- */
- preWalkSwitchStatement(statement) {
- this.preWalkSwitchCases(statement.cases);
- }
- /**
- * @param {SwitchStatement} statement switch statement
- */
- walkSwitchStatement(statement) {
- this.walkExpression(statement.discriminant);
- this.walkSwitchCases(statement.cases);
- }
- /**
- * @param {ReturnStatement | ThrowStatement} statement return or throw statement
- */
- walkTerminatingStatement(statement) {
- if (statement.argument) this.walkExpression(statement.argument);
- // Skip top level scope because to handle `export` and `module.exports` after terminate
- if (this.scope.topLevelScope === true) return;
- if (this.hooks.terminate.call(statement)) {
- this.scope.terminated =
- statement.type === "ReturnStatement"
- ? SCOPE_INFO_TERMINATED_RETURN
- : SCOPE_INFO_TERMINATED_THROW;
- }
- }
- /**
- * @param {ReturnStatement} statement return statement
- */
- walkReturnStatement(statement) {
- this.walkTerminatingStatement(statement);
- }
- /**
- * @param {ThrowStatement} statement return statement
- */
- walkThrowStatement(statement) {
- this.walkTerminatingStatement(statement);
- }
- /**
- * @param {TryStatement} statement try statement
- */
- preWalkTryStatement(statement) {
- this.preWalkStatement(statement.block);
- if (statement.handler) this.preWalkCatchClause(statement.handler);
- if (statement.finalizer) this.preWalkStatement(statement.finalizer);
- }
- /**
- * @param {TryStatement} statement try statement
- */
- walkTryStatement(statement) {
- if (this.scope.inTry) {
- this.walkStatement(statement.block);
- } else {
- this.scope.inTry = true;
- this.walkStatement(statement.block);
- this.scope.inTry = false;
- }
- const tryTerminated = this.scope.terminated;
- this.scope.terminated = undefined;
- if (statement.handler) this.walkCatchClause(statement.handler);
- const handlerTerminated = this.scope.terminated;
- this.scope.terminated = undefined;
- if (statement.finalizer) {
- this.walkStatement(statement.finalizer);
- }
- const finalizerTerminated = this.scope.terminated;
- this.scope.terminated = undefined;
- if (finalizerTerminated) {
- this.scope.terminated = finalizerTerminated;
- } else if (
- tryTerminated &&
- (statement.handler ? handlerTerminated : true)
- ) {
- this.scope.terminated = handlerTerminated || tryTerminated;
- }
- }
- /**
- * @param {WhileStatement} statement while statement
- */
- preWalkWhileStatement(statement) {
- this.preWalkStatement(statement.body);
- }
- /**
- * @param {WhileStatement} statement while statement
- */
- walkWhileStatement(statement) {
- this.inBlockScope(() => {
- this.walkExpression(statement.test);
- this.walkNestedStatement(statement.body);
- });
- }
- /**
- * @param {DoWhileStatement} statement do while statement
- */
- preWalkDoWhileStatement(statement) {
- this.preWalkStatement(statement.body);
- }
- /**
- * @param {DoWhileStatement} statement do while statement
- */
- walkDoWhileStatement(statement) {
- this.inBlockScope(() => {
- this.walkNestedStatement(statement.body);
- this.walkExpression(statement.test);
- });
- }
- /**
- * @param {ForStatement} statement for statement
- */
- preWalkForStatement(statement) {
- if (statement.init && statement.init.type === "VariableDeclaration") {
- this.preWalkStatement(statement.init);
- }
- this.preWalkStatement(statement.body);
- }
- /**
- * @param {ForStatement} statement for statement
- */
- walkForStatement(statement) {
- this.inBlockScope(() => {
- if (statement.init) {
- if (statement.init.type === "VariableDeclaration") {
- this.blockPreWalkVariableDeclaration(statement.init);
- this.prevStatement = undefined;
- this.walkStatement(statement.init);
- } else {
- this.walkExpression(statement.init);
- }
- }
- if (statement.test) {
- this.walkExpression(statement.test);
- }
- if (statement.update) {
- this.walkExpression(statement.update);
- }
- const body = statement.body;
- if (body.type === "BlockStatement") {
- // no need to add additional scope
- const prev = this.prevStatement;
- this.blockPreWalkStatements(body.body);
- this.prevStatement = prev;
- this.walkStatements(body.body);
- } else {
- this.walkNestedStatement(body);
- }
- });
- }
- /**
- * @param {ForInStatement} statement for statement
- */
- preWalkForInStatement(statement) {
- if (statement.left.type === "VariableDeclaration") {
- this.preWalkVariableDeclaration(statement.left);
- }
- this.preWalkStatement(statement.body);
- }
- /**
- * @param {ForInStatement} statement for statement
- */
- walkForInStatement(statement) {
- this.inBlockScope(() => {
- if (statement.left.type === "VariableDeclaration") {
- this.blockPreWalkVariableDeclaration(statement.left);
- this.walkVariableDeclaration(statement.left);
- } else {
- this.walkPattern(statement.left);
- }
- this.walkExpression(statement.right);
- const body = statement.body;
- if (body.type === "BlockStatement") {
- // no need to add additional scope
- const prev = this.prevStatement;
- this.blockPreWalkStatements(body.body);
- this.prevStatement = prev;
- this.walkStatements(body.body);
- } else {
- this.walkNestedStatement(body);
- }
- });
- }
- /**
- * @param {ForOfStatement} statement statement
- */
- preWalkForOfStatement(statement) {
- if (statement.await && this.scope.topLevelScope === true) {
- this.hooks.topLevelAwait.call(statement);
- }
- if (statement.left.type === "VariableDeclaration") {
- this.preWalkVariableDeclaration(statement.left);
- }
- this.preWalkStatement(statement.body);
- }
- /**
- * @param {ForOfStatement} statement for statement
- */
- walkForOfStatement(statement) {
- this.inBlockScope(() => {
- if (statement.left.type === "VariableDeclaration") {
- this.blockPreWalkVariableDeclaration(statement.left);
- this.walkVariableDeclaration(statement.left);
- } else {
- this.walkPattern(statement.left);
- }
- this.walkExpression(statement.right);
- const body = statement.body;
- if (body.type === "BlockStatement") {
- // no need to add additional scope
- const prev = this.prevStatement;
- this.blockPreWalkStatements(body.body);
- this.prevStatement = prev;
- this.walkStatements(body.body);
- } else {
- this.walkNestedStatement(body);
- }
- });
- }
- /**
- * @param {FunctionDeclaration | MaybeNamedFunctionDeclaration} statement function declaration
- */
- preWalkFunctionDeclaration(statement) {
- if (statement.id) {
- this.defineVariable(statement.id.name);
- }
- }
- /**
- * @param {FunctionDeclaration | MaybeNamedFunctionDeclaration} statement function declaration
- */
- walkFunctionDeclaration(statement) {
- const wasTopLevel = this.scope.topLevelScope;
- this.scope.topLevelScope = false;
- this.inFunctionScope(true, statement.params, () => {
- for (const param of statement.params) {
- this.walkPattern(param);
- }
- this.detectMode(statement.body.body);
- const prev = this.prevStatement;
- this.preWalkStatement(statement.body);
- this.prevStatement = prev;
- this.walkStatement(statement.body);
- });
- this.scope.topLevelScope = wasTopLevel;
- }
- /**
- * @param {ExpressionStatement} statement expression statement
- */
- blockPreWalkExpressionStatement(statement) {
- const expression = statement.expression;
- switch (expression.type) {
- case "AssignmentExpression":
- this.preWalkAssignmentExpression(expression);
- }
- }
- /**
- * @param {AssignmentExpression} expression assignment expression
- */
- preWalkAssignmentExpression(expression) {
- this.enterDestructuringAssignment(expression.left, expression.right);
- }
- /**
- * @param {Pattern} pattern pattern
- * @param {Expression} expression assignment expression
- * @returns {Expression | undefined} destructuring expression
- */
- enterDestructuringAssignment(pattern, expression) {
- if (
- pattern.type !== "ObjectPattern" ||
- !this.destructuringAssignmentProperties
- ) {
- return;
- }
- const expr =
- expression.type === "AwaitExpression" ? expression.argument : expression;
- const destructuring =
- expr.type === "AssignmentExpression"
- ? this.enterDestructuringAssignment(expr.left, expr.right)
- : this.hooks.collectDestructuringAssignmentProperties.call(expr)
- ? expr
- : undefined;
- if (destructuring) {
- const keys = this._preWalkObjectPattern(pattern);
- if (!keys) return;
- // check multiple assignments
- if (this.destructuringAssignmentProperties.has(destructuring)) {
- const set =
- /** @type {Set<DestructuringAssignmentProperty>} */
- (this.destructuringAssignmentProperties.get(destructuring));
- for (const id of keys) set.add(id);
- } else {
- this.destructuringAssignmentProperties.set(destructuring, keys);
- }
- }
- return destructuring;
- }
- /**
- * @param {ImportDeclaration} statement statement
- */
- modulePreWalkImportDeclaration(statement) {
- const source = /** @type {ImportSource} */ (statement.source.value);
- this.hooks.import.call(statement, source);
- for (const specifier of statement.specifiers) {
- const name = specifier.local.name;
- switch (specifier.type) {
- case "ImportDefaultSpecifier":
- if (
- !this.hooks.importSpecifier.call(statement, source, "default", name)
- ) {
- this.defineVariable(name);
- }
- break;
- case "ImportSpecifier":
- if (
- !this.hooks.importSpecifier.call(
- statement,
- source,
- /** @type {Identifier} */
- (specifier.imported).name ||
- /** @type {string} */
- (
- /** @type {Literal} */
- (specifier.imported).value
- ),
- name
- )
- ) {
- this.defineVariable(name);
- }
- break;
- case "ImportNamespaceSpecifier":
- if (!this.hooks.importSpecifier.call(statement, source, null, name)) {
- this.defineVariable(name);
- }
- break;
- default:
- this.defineVariable(name);
- }
- }
- }
- /**
- * @param {Declaration} declaration declaration
- * @param {OnIdent} onIdent on ident callback
- */
- enterDeclaration(declaration, onIdent) {
- switch (declaration.type) {
- case "VariableDeclaration":
- for (const declarator of declaration.declarations) {
- switch (declarator.type) {
- case "VariableDeclarator": {
- this.enterPattern(declarator.id, onIdent);
- break;
- }
- }
- }
- break;
- case "FunctionDeclaration":
- this.enterPattern(declaration.id, onIdent);
- break;
- case "ClassDeclaration":
- this.enterPattern(declaration.id, onIdent);
- break;
- }
- }
- /**
- * @param {ExportNamedDeclaration} statement statement
- */
- modulePreWalkExportNamedDeclaration(statement) {
- if (!statement.source) return;
- const source = /** @type {ImportSource} */ (statement.source.value);
- this.hooks.exportImport.call(statement, source);
- if (statement.specifiers) {
- for (
- let specifierIndex = 0;
- specifierIndex < statement.specifiers.length;
- specifierIndex++
- ) {
- const specifier = statement.specifiers[specifierIndex];
- switch (specifier.type) {
- case "ExportSpecifier": {
- const localName =
- /** @type {Identifier} */ (specifier.local).name ||
- /** @type {string} */ (
- /** @type {Literal} */ (specifier.local).value
- );
- const name =
- /** @type {Identifier} */
- (specifier.exported).name ||
- /** @type {string} */
- (/** @type {Literal} */ (specifier.exported).value);
- this.hooks.exportImportSpecifier.call(
- statement,
- source,
- localName,
- name,
- specifierIndex
- );
- break;
- }
- }
- }
- }
- }
- /**
- * @param {ExportNamedDeclaration} statement statement
- */
- blockPreWalkExportNamedDeclaration(statement) {
- if (statement.source) return;
- this.hooks.export.call(statement);
- if (
- statement.declaration &&
- !this.hooks.exportDeclaration.call(statement, statement.declaration)
- ) {
- const prev = this.prevStatement;
- this.preWalkStatement(statement.declaration);
- this.prevStatement = prev;
- this.blockPreWalkStatement(statement.declaration);
- let index = 0;
- this.enterDeclaration(statement.declaration, (def) => {
- this.hooks.exportSpecifier.call(statement, def, def, index++);
- });
- }
- if (statement.specifiers) {
- for (
- let specifierIndex = 0;
- specifierIndex < statement.specifiers.length;
- specifierIndex++
- ) {
- const specifier = statement.specifiers[specifierIndex];
- switch (specifier.type) {
- case "ExportSpecifier": {
- const localName =
- /** @type {Identifier} */ (specifier.local).name ||
- /** @type {string} */ (
- /** @type {Literal} */ (specifier.local).value
- );
- const name =
- /** @type {Identifier} */
- (specifier.exported).name ||
- /** @type {string} */
- (/** @type {Literal} */ (specifier.exported).value);
- this.hooks.exportSpecifier.call(
- statement,
- localName,
- name,
- specifierIndex
- );
- break;
- }
- }
- }
- }
- }
- /**
- * @param {ExportNamedDeclaration} statement the statement
- */
- walkExportNamedDeclaration(statement) {
- if (statement.declaration) {
- this.walkStatement(statement.declaration);
- }
- }
- /**
- * @param {ExportDefaultDeclaration} statement statement
- */
- blockPreWalkExportDefaultDeclaration(statement) {
- const prev = this.prevStatement;
- this.preWalkStatement(/** @type {TODO} */ (statement.declaration));
- this.prevStatement = prev;
- this.blockPreWalkStatement(/** @type {TODO} */ (statement.declaration));
- if (
- /** @type {MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} */
- (statement.declaration).id &&
- statement.declaration.type !== "FunctionExpression" &&
- statement.declaration.type !== "ClassExpression"
- ) {
- const declaration =
- /** @type {MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} */
- (statement.declaration);
- this.hooks.exportSpecifier.call(
- statement,
- /** @type {Identifier} */
- (declaration.id).name,
- "default",
- undefined
- );
- }
- }
- /**
- * @param {ExportDefaultDeclaration} statement statement
- */
- walkExportDefaultDeclaration(statement) {
- this.hooks.export.call(statement);
- if (
- /** @type {FunctionDeclaration | ClassDeclaration} */
- (statement.declaration).id &&
- statement.declaration.type !== "FunctionExpression" &&
- statement.declaration.type !== "ClassExpression"
- ) {
- const declaration =
- /** @type {FunctionDeclaration | ClassDeclaration} */
- (statement.declaration);
- if (!this.hooks.exportDeclaration.call(statement, declaration)) {
- this.walkStatement(declaration);
- }
- } else {
- // Acorn parses `export default function() {}` as `FunctionDeclaration` and
- // `export default class {}` as `ClassDeclaration`, both with `id = null`.
- // These nodes must be treated as expressions.
- if (
- statement.declaration.type === "FunctionDeclaration" ||
- statement.declaration.type === "ClassDeclaration"
- ) {
- this.walkStatement(statement.declaration);
- } else {
- this.walkExpression(statement.declaration);
- }
- if (!this.hooks.exportExpression.call(statement, statement.declaration)) {
- this.hooks.exportSpecifier.call(
- statement,
- /** @type {TODO} */
- (statement.declaration),
- "default",
- undefined
- );
- }
- }
- }
- /**
- * @param {ExportAllDeclaration} statement statement
- */
- modulePreWalkExportAllDeclaration(statement) {
- const source = /** @type {ImportSource} */ (statement.source.value);
- const name = statement.exported
- ? /** @type {Identifier} */
- (statement.exported).name ||
- /** @type {string} */
- (/** @type {Literal} */ (statement.exported).value)
- : null;
- this.hooks.exportImport.call(statement, source);
- this.hooks.exportImportSpecifier.call(statement, source, null, name, 0);
- }
- /**
- * @param {VariableDeclaration} statement variable declaration
- */
- preWalkVariableDeclaration(statement) {
- if (statement.kind !== "var") return;
- this._preWalkVariableDeclaration(statement, this.hooks.varDeclarationVar);
- }
- /**
- * @param {VariableDeclaration} statement variable declaration
- */
- blockPreWalkVariableDeclaration(statement) {
- if (statement.kind === "var") return;
- const hookMap =
- statement.kind === "const"
- ? this.hooks.varDeclarationConst
- : statement.kind === "using" || statement.kind === "await using"
- ? this.hooks.varDeclarationUsing
- : this.hooks.varDeclarationLet;
- this._preWalkVariableDeclaration(statement, hookMap);
- }
- /**
- * @param {VariableDeclaration} statement variable declaration
- * @param {HookMap<SyncBailHook<[Identifier], boolean | void>>} hookMap map of hooks
- */
- _preWalkVariableDeclaration(statement, hookMap) {
- for (const declarator of statement.declarations) {
- switch (declarator.type) {
- case "VariableDeclarator": {
- this.preWalkVariableDeclarator(declarator);
- if (!this.hooks.preDeclarator.call(declarator, statement)) {
- this.enterPattern(declarator.id, (name, ident) => {
- let hook = hookMap.get(name);
- if (hook === undefined || !hook.call(ident)) {
- hook = this.hooks.varDeclaration.get(name);
- if (hook === undefined || !hook.call(ident)) {
- this.defineVariable(name);
- }
- }
- });
- }
- break;
- }
- }
- }
- }
- /**
- * @param {ObjectPattern} objectPattern object pattern
- * @returns {Set<DestructuringAssignmentProperty> | undefined} set of names or undefined if not all keys are identifiers
- */
- _preWalkObjectPattern(objectPattern) {
- /** @type {Set<DestructuringAssignmentProperty>} */
- const props = new Set();
- const properties = objectPattern.properties;
- for (let i = 0; i < properties.length; i++) {
- const property = properties[i];
- if (property.type !== "Property") return;
- if (property.shorthand) {
- if (property.value.type === "Identifier") {
- this.scope.inShorthand = property.value.name;
- } else if (
- property.value.type === "AssignmentPattern" &&
- property.value.left.type === "Identifier"
- ) {
- this.scope.inShorthand = property.value.left.name;
- }
- }
- const key = property.key;
- if (key.type === "Identifier" && !property.computed) {
- props.add({
- id: key.name,
- range: key.range,
- shorthand: this.scope.inShorthand
- });
- } else {
- const id = this.evaluateExpression(key);
- const str = id.asString();
- if (str) {
- props.add({
- id: str,
- range: key.range,
- shorthand: this.scope.inShorthand
- });
- } else {
- // could not evaluate key
- return;
- }
- }
- this.scope.inShorthand = false;
- }
- return props;
- }
- /**
- * @param {VariableDeclarator} declarator variable declarator
- */
- preWalkVariableDeclarator(declarator) {
- if (declarator.init) {
- this.enterDestructuringAssignment(declarator.id, declarator.init);
- }
- }
- /**
- * @param {VariableDeclaration} statement variable declaration
- */
- walkVariableDeclaration(statement) {
- for (const declarator of statement.declarations) {
- switch (declarator.type) {
- case "VariableDeclarator": {
- const renameIdentifier =
- declarator.init && this.getRenameIdentifier(declarator.init);
- if (renameIdentifier && declarator.id.type === "Identifier") {
- const hook = this.hooks.canRename.get(renameIdentifier);
- if (
- hook !== undefined &&
- hook.call(/** @type {Expression} */ (declarator.init))
- ) {
- // renaming with "var a = b;"
- const hook = this.hooks.rename.get(renameIdentifier);
- if (
- hook === undefined ||
- !hook.call(/** @type {Expression} */ (declarator.init))
- ) {
- this.setVariable(declarator.id.name, renameIdentifier);
- }
- break;
- }
- }
- if (!this.hooks.declarator.call(declarator, statement)) {
- this.walkPattern(declarator.id);
- if (declarator.init) this.walkExpression(declarator.init);
- }
- break;
- }
- }
- }
- }
- /**
- * @param {ClassDeclaration | MaybeNamedClassDeclaration} statement class declaration
- */
- blockPreWalkClassDeclaration(statement) {
- if (statement.id) {
- this.defineVariable(statement.id.name);
- }
- }
- /**
- * @param {ClassDeclaration | MaybeNamedClassDeclaration} statement class declaration
- */
- walkClassDeclaration(statement) {
- this.walkClass(statement);
- }
- /**
- * @param {SwitchCase[]} switchCases switch statement
- */
- preWalkSwitchCases(switchCases) {
- for (let index = 0, len = switchCases.length; index < len; index++) {
- const switchCase = switchCases[index];
- this.preWalkStatements(switchCase.consequent);
- }
- }
- /**
- * @param {SwitchCase[]} switchCases switch statement
- */
- walkSwitchCases(switchCases) {
- this.inBlockScope(() => {
- const len = switchCases.length;
- // we need to pre walk all statements first since we can have invalid code
- // import A from "module";
- // switch(1) {
- // case 1:
- // console.log(A); // should fail at runtime
- // case 2:
- // const A = 1;
- // }
- for (let index = 0; index < len; index++) {
- const switchCase = switchCases[index];
- if (switchCase.consequent.length > 0) {
- const prev = this.prevStatement;
- this.blockPreWalkStatements(switchCase.consequent);
- this.prevStatement = prev;
- }
- }
- for (let index = 0; index < len; index++) {
- const switchCase = switchCases[index];
- if (switchCase.test) {
- this.walkExpression(switchCase.test);
- }
- if (switchCase.consequent.length > 0) {
- this.walkStatements(switchCase.consequent);
- this.scope.terminated = undefined;
- }
- }
- });
- }
- /**
- * @param {CatchClause} catchClause catch clause
- */
- preWalkCatchClause(catchClause) {
- this.preWalkStatement(catchClause.body);
- }
- /**
- * @param {CatchClause} catchClause catch clause
- */
- walkCatchClause(catchClause) {
- this.inBlockScope(() => {
- // Error binding is optional in catch clause since ECMAScript 2019
- if (catchClause.param !== null) {
- this.enterPattern(catchClause.param, (ident) => {
- this.defineVariable(ident);
- });
- this.walkPattern(catchClause.param);
- }
- const prev = this.prevStatement;
- this.blockPreWalkStatement(catchClause.body);
- this.prevStatement = prev;
- this.walkStatement(catchClause.body);
- }, true);
- }
- /**
- * @param {Pattern} pattern pattern
- */
- walkPattern(pattern) {
- switch (pattern.type) {
- case "ArrayPattern":
- this.walkArrayPattern(pattern);
- break;
- case "AssignmentPattern":
- this.walkAssignmentPattern(pattern);
- break;
- case "MemberExpression":
- this.walkMemberExpression(pattern);
- break;
- case "ObjectPattern":
- this.walkObjectPattern(pattern);
- break;
- case "RestElement":
- this.walkRestElement(pattern);
- break;
- }
- }
- /**
- * @param {AssignmentPattern} pattern assignment pattern
- */
- walkAssignmentPattern(pattern) {
- this.walkExpression(pattern.right);
- this.walkPattern(pattern.left);
- }
- /**
- * @param {ObjectPattern} pattern pattern
- */
- walkObjectPattern(pattern) {
- for (let i = 0, len = pattern.properties.length; i < len; i++) {
- const prop = pattern.properties[i];
- if (prop) {
- if (prop.type === "RestElement") {
- continue;
- }
- if (prop.computed) this.walkExpression(prop.key);
- if (prop.value) this.walkPattern(prop.value);
- }
- }
- }
- /**
- * @param {ArrayPattern} pattern array pattern
- */
- walkArrayPattern(pattern) {
- for (let i = 0, len = pattern.elements.length; i < len; i++) {
- const element = pattern.elements[i];
- if (element) this.walkPattern(element);
- }
- }
- /**
- * @param {RestElement} pattern rest element
- */
- walkRestElement(pattern) {
- this.walkPattern(pattern.argument);
- }
- /**
- * @param {(Expression | SpreadElement | null)[]} expressions expressions
- */
- walkExpressions(expressions) {
- for (const expression of expressions) {
- if (expression) {
- this.walkExpression(expression);
- }
- }
- }
- /**
- * @param {Expression | SpreadElement | PrivateIdentifier | Super} expression expression
- */
- walkExpression(expression) {
- switch (expression.type) {
- case "ArrayExpression":
- this.walkArrayExpression(expression);
- break;
- case "ArrowFunctionExpression":
- this.walkArrowFunctionExpression(expression);
- break;
- case "AssignmentExpression":
- this.walkAssignmentExpression(expression);
- break;
- case "AwaitExpression":
- this.walkAwaitExpression(expression);
- break;
- case "BinaryExpression":
- this.walkBinaryExpression(expression);
- break;
- case "CallExpression":
- this.walkCallExpression(expression);
- break;
- case "ChainExpression":
- this.walkChainExpression(expression);
- break;
- case "ClassExpression":
- this.walkClassExpression(expression);
- break;
- case "ConditionalExpression":
- this.walkConditionalExpression(expression);
- break;
- case "FunctionExpression":
- this.walkFunctionExpression(expression);
- break;
- case "Identifier":
- this.walkIdentifier(expression);
- break;
- case "ImportExpression":
- this.walkImportExpression(expression);
- break;
- case "LogicalExpression":
- this.walkLogicalExpression(expression);
- break;
- case "MetaProperty":
- this.walkMetaProperty(expression);
- break;
- case "MemberExpression":
- this.walkMemberExpression(expression);
- break;
- case "NewExpression":
- this.walkNewExpression(expression);
- break;
- case "ObjectExpression":
- this.walkObjectExpression(expression);
- break;
- case "SequenceExpression":
- this.walkSequenceExpression(expression);
- break;
- case "SpreadElement":
- this.walkSpreadElement(expression);
- break;
- case "TaggedTemplateExpression":
- this.walkTaggedTemplateExpression(expression);
- break;
- case "TemplateLiteral":
- this.walkTemplateLiteral(expression);
- break;
- case "ThisExpression":
- this.walkThisExpression(expression);
- break;
- case "UnaryExpression":
- this.walkUnaryExpression(expression);
- break;
- case "UpdateExpression":
- this.walkUpdateExpression(expression);
- break;
- case "YieldExpression":
- this.walkYieldExpression(expression);
- break;
- }
- }
- /**
- * @param {AwaitExpression} expression await expression
- */
- walkAwaitExpression(expression) {
- if (this.scope.topLevelScope === true) {
- this.hooks.topLevelAwait.call(expression);
- }
- this.walkExpression(expression.argument);
- }
- /**
- * @param {ArrayExpression} expression array expression
- */
- walkArrayExpression(expression) {
- if (expression.elements) {
- this.walkExpressions(expression.elements);
- }
- }
- /**
- * @param {SpreadElement} expression spread element
- */
- walkSpreadElement(expression) {
- if (expression.argument) {
- this.walkExpression(expression.argument);
- }
- }
- /**
- * @param {ObjectExpression} expression object expression
- */
- walkObjectExpression(expression) {
- for (
- let propIndex = 0, len = expression.properties.length;
- propIndex < len;
- propIndex++
- ) {
- const prop = expression.properties[propIndex];
- this.walkProperty(prop);
- }
- }
- /**
- * @param {Property | SpreadElement} prop property or spread element
- */
- walkProperty(prop) {
- if (prop.type === "SpreadElement") {
- this.walkExpression(prop.argument);
- return;
- }
- if (prop.computed) {
- this.walkExpression(prop.key);
- }
- if (prop.shorthand && prop.value && prop.value.type === "Identifier") {
- this.scope.inShorthand = prop.value.name;
- this.walkIdentifier(prop.value);
- this.scope.inShorthand = false;
- } else {
- this.walkExpression(
- /** @type {Exclude<Property["value"], AssignmentPattern | ObjectPattern | ArrayPattern | RestElement>} */
- (prop.value)
- );
- }
- }
- /**
- * @param {FunctionExpression} expression arrow function expression
- */
- walkFunctionExpression(expression) {
- const wasTopLevel = this.scope.topLevelScope;
- this.scope.topLevelScope = false;
- const scopeParams = [...expression.params];
- // Add function name in scope for recursive calls
- if (expression.id) {
- scopeParams.push(expression.id);
- }
- this.inFunctionScope(true, scopeParams, () => {
- for (const param of expression.params) {
- this.walkPattern(param);
- }
- this.detectMode(expression.body.body);
- const prev = this.prevStatement;
- this.preWalkStatement(expression.body);
- this.prevStatement = prev;
- this.walkStatement(expression.body);
- });
- this.scope.topLevelScope = wasTopLevel;
- }
- /**
- * @param {ArrowFunctionExpression} expression arrow function expression
- */
- walkArrowFunctionExpression(expression) {
- const wasTopLevel = this.scope.topLevelScope;
- this.scope.topLevelScope = wasTopLevel ? "arrow" : false;
- this.inFunctionScope(false, expression.params, () => {
- for (const param of expression.params) {
- this.walkPattern(param);
- }
- if (expression.body.type === "BlockStatement") {
- this.detectMode(expression.body.body);
- const prev = this.prevStatement;
- this.preWalkStatement(expression.body);
- this.prevStatement = prev;
- this.walkStatement(expression.body);
- } else {
- this.walkExpression(expression.body);
- }
- });
- this.scope.topLevelScope = wasTopLevel;
- }
- /**
- * @param {SequenceExpression} expression the sequence
- */
- walkSequenceExpression(expression) {
- if (!expression.expressions) return;
- // We treat sequence expressions like statements when they are one statement level
- // This has some benefits for optimizations that only work on statement level
- const currentStatement =
- /** @type {StatementPath} */
- (this.statementPath)[
- /** @type {StatementPath} */
- (this.statementPath).length - 1
- ];
- if (
- currentStatement === expression ||
- (currentStatement.type === "ExpressionStatement" &&
- currentStatement.expression === expression)
- ) {
- const old =
- /** @type {StatementPathItem} */
- (/** @type {StatementPath} */ (this.statementPath).pop());
- const prev = this.prevStatement;
- for (const expr of expression.expressions) {
- /** @type {StatementPath} */
- (this.statementPath).push(expr);
- this.walkExpression(expr);
- this.prevStatement =
- /** @type {StatementPath} */
- (this.statementPath).pop();
- }
- this.prevStatement = prev;
- /** @type {StatementPath} */
- (this.statementPath).push(old);
- } else {
- this.walkExpressions(expression.expressions);
- }
- }
- /**
- * @param {UpdateExpression} expression the update expression
- */
- walkUpdateExpression(expression) {
- this.walkExpression(expression.argument);
- }
- /**
- * @param {UnaryExpression} expression the unary expression
- */
- walkUnaryExpression(expression) {
- if (expression.operator === "typeof") {
- const result = this.callHooksForExpression(
- this.hooks.typeof,
- expression.argument,
- expression
- );
- if (result === true) return;
- if (expression.argument.type === "ChainExpression") {
- const result = this.callHooksForExpression(
- this.hooks.typeof,
- expression.argument.expression,
- expression
- );
- if (result === true) return;
- }
- }
- this.walkExpression(expression.argument);
- }
- /**
- * @param {LogicalExpression | BinaryExpression} expression the expression
- */
- walkLeftRightExpression(expression) {
- this.walkExpression(expression.left);
- this.walkExpression(expression.right);
- }
- /**
- * @param {BinaryExpression} expression the binary expression
- */
- walkBinaryExpression(expression) {
- if (this.hooks.binaryExpression.call(expression) === undefined) {
- this.walkLeftRightExpression(expression);
- }
- }
- /**
- * @param {LogicalExpression} expression the logical expression
- */
- walkLogicalExpression(expression) {
- const result = this.hooks.expressionLogicalOperator.call(expression);
- if (result === undefined) {
- this.walkLeftRightExpression(expression);
- } else if (result) {
- this.walkExpression(expression.right);
- }
- }
- /**
- * @param {AssignmentExpression} expression assignment expression
- */
- walkAssignmentExpression(expression) {
- if (expression.left.type === "Identifier") {
- const renameIdentifier = this.getRenameIdentifier(expression.right);
- if (
- renameIdentifier &&
- this.callHooksForInfo(
- this.hooks.canRename,
- renameIdentifier,
- expression.right
- )
- ) {
- // renaming "a = b;"
- if (
- !this.callHooksForInfo(
- this.hooks.rename,
- renameIdentifier,
- expression.right
- )
- ) {
- this.setVariable(
- expression.left.name,
- typeof renameIdentifier === "string"
- ? this.getVariableInfo(renameIdentifier)
- : renameIdentifier
- );
- }
- return;
- }
- this.walkExpression(expression.right);
- this.enterPattern(expression.left, (name, _decl) => {
- if (!this.callHooksForName(this.hooks.assign, name, expression)) {
- this.walkExpression(
- /** @type {MemberExpression} */
- (expression.left)
- );
- }
- });
- } else if (expression.left.type.endsWith("Pattern")) {
- this.walkExpression(expression.right);
- this.enterPattern(expression.left, (name, _decl) => {
- if (!this.callHooksForName(this.hooks.assign, name, expression)) {
- this.defineVariable(name);
- }
- });
- this.walkPattern(expression.left);
- } else if (expression.left.type === "MemberExpression") {
- const exprName = this.getMemberExpressionInfo(
- expression.left,
- ALLOWED_MEMBER_TYPES_EXPRESSION
- );
- if (
- exprName &&
- this.callHooksForInfo(
- this.hooks.assignMemberChain,
- exprName.rootInfo,
- expression,
- exprName.getMembers()
- )
- ) {
- return;
- }
- this.walkExpression(expression.right);
- this.walkExpression(expression.left);
- } else {
- this.walkExpression(expression.right);
- this.walkExpression(
- /** @type {Exclude<AssignmentExpression["left"], Identifier | RestElement | MemberExpression | ObjectPattern | ArrayPattern | AssignmentPattern>} */
- (expression.left)
- );
- }
- }
- /**
- * @param {ConditionalExpression} expression conditional expression
- */
- walkConditionalExpression(expression) {
- const result = this.hooks.expressionConditionalOperator.call(expression);
- if (result === undefined) {
- this.walkExpression(expression.test);
- this.walkExpression(expression.consequent);
- if (expression.alternate) {
- this.walkExpression(expression.alternate);
- }
- } else if (result) {
- this.walkExpression(expression.consequent);
- } else if (expression.alternate) {
- this.walkExpression(expression.alternate);
- }
- }
- /**
- * @param {NewExpression} expression new expression
- */
- walkNewExpression(expression) {
- const result = this.callHooksForExpression(
- this.hooks.new,
- expression.callee,
- expression
- );
- if (result === true) return;
- this.walkExpression(expression.callee);
- if (expression.arguments) {
- this.walkExpressions(expression.arguments);
- }
- }
- /**
- * @param {YieldExpression} expression yield expression
- */
- walkYieldExpression(expression) {
- if (expression.argument) {
- this.walkExpression(expression.argument);
- }
- }
- /**
- * @param {TemplateLiteral} expression template literal
- */
- walkTemplateLiteral(expression) {
- if (expression.expressions) {
- this.walkExpressions(expression.expressions);
- }
- }
- /**
- * @param {TaggedTemplateExpression} expression tagged template expression
- */
- walkTaggedTemplateExpression(expression) {
- if (expression.tag) {
- this.scope.inTaggedTemplateTag = true;
- this.walkExpression(expression.tag);
- this.scope.inTaggedTemplateTag = false;
- }
- if (expression.quasi && expression.quasi.expressions) {
- this.walkExpressions(expression.quasi.expressions);
- }
- }
- /**
- * @param {ClassExpression} expression the class expression
- */
- walkClassExpression(expression) {
- this.walkClass(expression);
- }
- /**
- * @param {ChainExpression} expression expression
- */
- walkChainExpression(expression) {
- const result = this.hooks.optionalChaining.call(expression);
- if (result === undefined) {
- if (expression.expression.type === "CallExpression") {
- this.walkCallExpression(expression.expression);
- } else {
- this.walkMemberExpression(expression.expression);
- }
- }
- }
- /**
- * @private
- * @param {FunctionExpression | ArrowFunctionExpression} functionExpression function expression
- * @param {(Expression | SpreadElement)[]} options options
- * @param {Expression | SpreadElement | null} currentThis current this
- */
- _walkIIFE(functionExpression, options, currentThis) {
- /**
- * @param {Expression | SpreadElement} argOrThis arg or this
- * @returns {string | VariableInfo | undefined} var info
- */
- const getVarInfo = (argOrThis) => {
- const renameIdentifier = this.getRenameIdentifier(argOrThis);
- if (
- renameIdentifier &&
- this.callHooksForInfo(
- this.hooks.canRename,
- renameIdentifier,
- /** @type {Expression} */
- (argOrThis)
- ) &&
- !this.callHooksForInfo(
- this.hooks.rename,
- renameIdentifier,
- /** @type {Expression} */
- (argOrThis)
- )
- ) {
- return typeof renameIdentifier === "string"
- ? /** @type {string} */ (this.getVariableInfo(renameIdentifier))
- : renameIdentifier;
- }
- this.walkExpression(argOrThis);
- };
- const { params, type } = functionExpression;
- const arrow = type === "ArrowFunctionExpression";
- const renameThis = currentThis ? getVarInfo(currentThis) : null;
- const varInfoForArgs = options.map(getVarInfo);
- const wasTopLevel = this.scope.topLevelScope;
- this.scope.topLevelScope = wasTopLevel && arrow ? "arrow" : false;
- const scopeParams =
- /** @type {(Identifier | string)[]} */
- (params.filter((identifier, idx) => !varInfoForArgs[idx]));
- // Add function name in scope for recursive calls
- if (
- functionExpression.type === "FunctionExpression" &&
- functionExpression.id
- ) {
- scopeParams.push(functionExpression.id.name);
- }
- this.inFunctionScope(true, scopeParams, () => {
- if (renameThis && !arrow) {
- this.setVariable("this", renameThis);
- }
- for (let i = 0; i < varInfoForArgs.length; i++) {
- const varInfo = varInfoForArgs[i];
- if (!varInfo) continue;
- if (!params[i] || params[i].type !== "Identifier") continue;
- this.setVariable(/** @type {Identifier} */ (params[i]).name, varInfo);
- }
- if (functionExpression.body.type === "BlockStatement") {
- this.detectMode(functionExpression.body.body);
- const prev = this.prevStatement;
- this.preWalkStatement(functionExpression.body);
- this.prevStatement = prev;
- this.walkStatement(functionExpression.body);
- } else {
- this.walkExpression(functionExpression.body);
- }
- });
- this.scope.topLevelScope = wasTopLevel;
- }
- /**
- * @param {ImportExpression} expression import expression
- */
- walkImportExpression(expression) {
- const result = this.hooks.importCall.call(expression);
- if (result === true) return;
- this.walkExpression(expression.source);
- }
- /**
- * @param {CallExpression} expression expression
- */
- walkCallExpression(expression) {
- /**
- * @param {FunctionExpression | ArrowFunctionExpression} fn function
- * @returns {boolean} true when simple function
- */
- const isSimpleFunction = (fn) =>
- fn.params.every((p) => p.type === "Identifier");
- if (
- expression.callee.type === "MemberExpression" &&
- expression.callee.object.type.endsWith("FunctionExpression") &&
- !expression.callee.computed &&
- /** @type {boolean} */
- (
- /** @type {Identifier} */
- (expression.callee.property).name === "call" ||
- /** @type {Identifier} */
- (expression.callee.property).name === "bind"
- ) &&
- expression.arguments.length > 0 &&
- isSimpleFunction(
- /** @type {FunctionExpression | ArrowFunctionExpression} */
- (expression.callee.object)
- )
- ) {
- // (function(…) { }.call/bind(?, …))
- this._walkIIFE(
- /** @type {FunctionExpression | ArrowFunctionExpression} */
- (expression.callee.object),
- expression.arguments.slice(1),
- expression.arguments[0]
- );
- } else if (
- expression.callee.type.endsWith("FunctionExpression") &&
- isSimpleFunction(
- /** @type {FunctionExpression | ArrowFunctionExpression} */
- (expression.callee)
- )
- ) {
- // (function(…) { }(…))
- this._walkIIFE(
- /** @type {FunctionExpression | ArrowFunctionExpression} */
- (expression.callee),
- expression.arguments,
- null
- );
- } else {
- if (expression.callee.type === "MemberExpression") {
- const exprInfo = this.getMemberExpressionInfo(
- expression.callee,
- ALLOWED_MEMBER_TYPES_CALL_EXPRESSION
- );
- if (exprInfo && exprInfo.type === "call") {
- const result = this.callHooksForInfo(
- this.hooks.callMemberChainOfCallMemberChain,
- exprInfo.rootInfo,
- expression,
- exprInfo.getCalleeMembers(),
- exprInfo.call,
- exprInfo.getMembers(),
- exprInfo.getMemberRanges()
- );
- if (result === true) return;
- }
- }
- const callee = this.evaluateExpression(expression.callee);
- if (callee.isIdentifier()) {
- const result1 = this.callHooksForInfo(
- this.hooks.callMemberChain,
- /** @type {NonNullable<BasicEvaluatedExpression["rootInfo"]>} */
- (callee.rootInfo),
- expression,
- /** @type {NonNullable<BasicEvaluatedExpression["getMembers"]>} */
- (callee.getMembers)(),
- callee.getMembersOptionals
- ? callee.getMembersOptionals()
- : /** @type {NonNullable<BasicEvaluatedExpression["getMembers"]>} */
- (callee.getMembers)().map(() => false),
- callee.getMemberRanges ? callee.getMemberRanges() : []
- );
- if (result1 === true) return;
- const result2 = this.callHooksForInfo(
- this.hooks.call,
- /** @type {NonNullable<BasicEvaluatedExpression["identifier"]>} */
- (callee.identifier),
- expression
- );
- if (result2 === true) return;
- }
- if (expression.callee) {
- if (expression.callee.type === "MemberExpression") {
- // because of call context we need to walk the call context as expression
- this.walkExpression(expression.callee.object);
- if (expression.callee.computed === true) {
- this.walkExpression(expression.callee.property);
- }
- } else {
- this.walkExpression(expression.callee);
- }
- }
- if (expression.arguments) this.walkExpressions(expression.arguments);
- }
- }
- /**
- * @param {MemberExpression} expression member expression
- */
- walkMemberExpression(expression) {
- const exprInfo = this.getMemberExpressionInfo(
- expression,
- ALLOWED_MEMBER_TYPES_ALL
- );
- if (exprInfo) {
- switch (exprInfo.type) {
- case "expression": {
- const result1 = this.callHooksForInfo(
- this.hooks.expression,
- exprInfo.name,
- expression
- );
- if (result1 === true) return;
- const members = exprInfo.getMembers();
- const membersOptionals = exprInfo.getMembersOptionals();
- const memberRanges = exprInfo.getMemberRanges();
- const result2 = this.callHooksForInfo(
- this.hooks.expressionMemberChain,
- exprInfo.rootInfo,
- expression,
- members,
- membersOptionals,
- memberRanges
- );
- if (result2 === true) return;
- this.walkMemberExpressionWithExpressionName(
- expression,
- exprInfo.name,
- exprInfo.rootInfo,
- [...members],
- () =>
- this.callHooksForInfo(
- this.hooks.unhandledExpressionMemberChain,
- exprInfo.rootInfo,
- expression,
- members
- )
- );
- return;
- }
- case "call": {
- const result = this.callHooksForInfo(
- this.hooks.memberChainOfCallMemberChain,
- exprInfo.rootInfo,
- expression,
- exprInfo.getCalleeMembers(),
- exprInfo.call,
- exprInfo.getMembers(),
- exprInfo.getMemberRanges()
- );
- if (result === true) return;
- // Fast skip over the member chain as we already called memberChainOfCallMemberChain
- // and call computed property are literals anyway
- this.walkExpression(exprInfo.call);
- return;
- }
- }
- }
- this.walkExpression(expression.object);
- if (expression.computed === true) this.walkExpression(expression.property);
- }
- /**
- * @template R
- * @param {MemberExpression} expression member expression
- * @param {string} name name
- * @param {string | VariableInfo} rootInfo root info
- * @param {string[]} members members
- * @param {() => R | undefined} onUnhandled on unhandled callback
- */
- walkMemberExpressionWithExpressionName(
- expression,
- name,
- rootInfo,
- members,
- onUnhandled
- ) {
- if (expression.object.type === "MemberExpression") {
- // optimize the case where expression.object is a MemberExpression too.
- // we can keep info here when calling walkMemberExpression directly
- const property =
- /** @type {Identifier} */
- (expression.property).name ||
- `${/** @type {Literal} */ (expression.property).value}`;
- name = name.slice(0, -property.length - 1);
- members.pop();
- const result = this.callHooksForInfo(
- this.hooks.expression,
- name,
- expression.object
- );
- if (result === true) return;
- this.walkMemberExpressionWithExpressionName(
- expression.object,
- name,
- rootInfo,
- members,
- onUnhandled
- );
- } else if (!onUnhandled || !onUnhandled()) {
- this.walkExpression(expression.object);
- }
- if (expression.computed === true) this.walkExpression(expression.property);
- }
- /**
- * @param {ThisExpression} expression this expression
- */
- walkThisExpression(expression) {
- this.callHooksForName(this.hooks.expression, "this", expression);
- }
- /**
- * @param {Identifier} expression identifier
- */
- walkIdentifier(expression) {
- this.callHooksForName(this.hooks.expression, expression.name, expression);
- }
- /**
- * @param {MetaProperty} metaProperty meta property
- */
- walkMetaProperty(metaProperty) {
- this.hooks.expression.for(getRootName(metaProperty)).call(metaProperty);
- }
- /**
- * @template T
- * @template R
- * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
- * @param {Expression | Super} expr expression
- * @param {AsArray<T>} args args for the hook
- * @returns {R | undefined} result of hook
- */
- callHooksForExpression(hookMap, expr, ...args) {
- return this.callHooksForExpressionWithFallback(
- hookMap,
- expr,
- undefined,
- undefined,
- ...args
- );
- }
- /**
- * @template T
- * @template R
- * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
- * @param {Expression | Super} expr expression info
- * @param {((name: string, rootInfo: string | ScopeInfo | VariableInfo, getMembers: () => string[]) => R) | undefined} fallback callback when variable in not handled by hooks
- * @param {((result?: string) => R | undefined) | undefined} defined callback when variable is defined
- * @param {AsArray<T>} args args for the hook
- * @returns {R | undefined} result of hook
- */
- callHooksForExpressionWithFallback(
- hookMap,
- expr,
- fallback,
- defined,
- ...args
- ) {
- const exprName = this.getMemberExpressionInfo(
- expr,
- ALLOWED_MEMBER_TYPES_EXPRESSION
- );
- if (exprName !== undefined) {
- const members = exprName.getMembers();
- return this.callHooksForInfoWithFallback(
- hookMap,
- members.length === 0 ? exprName.rootInfo : exprName.name,
- fallback &&
- ((name) => fallback(name, exprName.rootInfo, exprName.getMembers)),
- defined && (() => defined(exprName.name)),
- ...args
- );
- }
- }
- /**
- * @template T
- * @template R
- * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
- * @param {string} name key in map
- * @param {AsArray<T>} args args for the hook
- * @returns {R | undefined} result of hook
- */
- callHooksForName(hookMap, name, ...args) {
- return this.callHooksForNameWithFallback(
- hookMap,
- name,
- undefined,
- undefined,
- ...args
- );
- }
- /**
- * @template T
- * @template R
- * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks that should be called
- * @param {ExportedVariableInfo} info variable info
- * @param {AsArray<T>} args args for the hook
- * @returns {R | undefined} result of hook
- */
- callHooksForInfo(hookMap, info, ...args) {
- return this.callHooksForInfoWithFallback(
- hookMap,
- info,
- undefined,
- undefined,
- ...args
- );
- }
- /**
- * @template T
- * @template R
- * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
- * @param {ExportedVariableInfo} info variable info
- * @param {((name: string) => R | undefined) | undefined} fallback callback when variable in not handled by hooks
- * @param {((result?: string) => TODO) | undefined} defined callback when variable is defined
- * @param {AsArray<T>} args args for the hook
- * @returns {R | undefined} result of hook
- */
- callHooksForInfoWithFallback(hookMap, info, fallback, defined, ...args) {
- let name;
- if (typeof info === "string") {
- name = info;
- } else {
- if (!(info instanceof VariableInfo)) {
- if (defined !== undefined) {
- return defined();
- }
- return;
- }
- let tagInfo = info.tagInfo;
- while (tagInfo !== undefined) {
- const hook = hookMap.get(tagInfo.tag);
- if (hook !== undefined) {
- this.currentTagData = tagInfo.data;
- const result = hook.call(...args);
- this.currentTagData = undefined;
- if (result !== undefined) return result;
- }
- tagInfo = tagInfo.next;
- }
- if (!info.isFree() && !info.isTagged()) {
- if (defined !== undefined) {
- return defined();
- }
- return;
- }
- name = info.name;
- }
- const hook = hookMap.get(name);
- if (hook !== undefined) {
- const result = hook.call(...args);
- if (result !== undefined) return result;
- }
- if (fallback !== undefined) {
- return fallback(/** @type {string} */ (name));
- }
- }
- /**
- * @template T
- * @template R
- * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
- * @param {string} name key in map
- * @param {((value: string) => R | undefined) | undefined} fallback callback when variable in not handled by hooks
- * @param {(() => R) | undefined} defined callback when variable is defined
- * @param {AsArray<T>} args args for the hook
- * @returns {R | undefined} result of hook
- */
- callHooksForNameWithFallback(hookMap, name, fallback, defined, ...args) {
- return this.callHooksForInfoWithFallback(
- hookMap,
- this.getVariableInfo(name),
- fallback,
- defined,
- ...args
- );
- }
- /**
- * @deprecated
- * @param {(string | Pattern | Property)[]} params scope params
- * @param {() => void} fn inner function
- * @returns {void}
- */
- inScope(params, fn) {
- const oldScope = this.scope;
- this.scope = {
- topLevelScope: oldScope.topLevelScope,
- inTry: false,
- inShorthand: false,
- inTaggedTemplateTag: false,
- isStrict: oldScope.isStrict,
- isAsmJs: oldScope.isAsmJs,
- terminated: undefined,
- definitions: oldScope.definitions.createChild()
- };
- this.undefineVariable("this");
- this.enterPatterns(params, (ident) => {
- this.defineVariable(ident);
- });
- fn();
- this.scope = oldScope;
- }
- /**
- * @param {boolean} hasThis true, when this is defined
- * @param {Identifier[]} params scope params
- * @param {() => void} fn inner function
- * @returns {void}
- */
- inClassScope(hasThis, params, fn) {
- const oldScope = this.scope;
- this.scope = {
- topLevelScope: oldScope.topLevelScope,
- inTry: false,
- inShorthand: false,
- inTaggedTemplateTag: false,
- isStrict: oldScope.isStrict,
- isAsmJs: oldScope.isAsmJs,
- terminated: undefined,
- definitions: oldScope.definitions.createChild()
- };
- if (hasThis) {
- this.undefineVariable("this");
- }
- this.enterPatterns(params, (ident) => {
- this.defineVariable(ident);
- });
- fn();
- this.scope = oldScope;
- }
- /**
- * @param {boolean} hasThis true, when this is defined
- * @param {(Pattern | string)[]} params scope params
- * @param {() => void} fn inner function
- * @returns {void}
- */
- inFunctionScope(hasThis, params, fn) {
- const oldScope = this.scope;
- this.scope = {
- topLevelScope: oldScope.topLevelScope,
- inTry: false,
- inShorthand: false,
- inTaggedTemplateTag: false,
- isStrict: oldScope.isStrict,
- isAsmJs: oldScope.isAsmJs,
- terminated: undefined,
- definitions: oldScope.definitions.createChild()
- };
- if (hasThis) {
- this.undefineVariable("this");
- }
- this.enterPatterns(params, (ident) => {
- this.defineVariable(ident);
- });
- fn();
- this.scope = oldScope;
- }
- /**
- * @param {() => void} fn inner function
- * @param {boolean} inExecutedPath executed state
- * @returns {void}
- */
- inBlockScope(fn, inExecutedPath = false) {
- const oldScope = this.scope;
- this.scope = {
- topLevelScope: oldScope.topLevelScope,
- inTry: oldScope.inTry,
- inShorthand: false,
- inTaggedTemplateTag: false,
- isStrict: oldScope.isStrict,
- isAsmJs: oldScope.isAsmJs,
- terminated: oldScope.terminated,
- definitions: oldScope.definitions.createChild()
- };
- fn();
- const terminated = this.scope.terminated;
- if (inExecutedPath && terminated) {
- oldScope.terminated = terminated;
- }
- this.scope = oldScope;
- }
- /**
- * @param {Array<Directive | Statement | ModuleDeclaration>} statements statements
- */
- detectMode(statements) {
- const isLiteral =
- statements.length >= 1 &&
- statements[0].type === "ExpressionStatement" &&
- statements[0].expression.type === "Literal";
- if (
- isLiteral &&
- /** @type {Literal} */
- (/** @type {ExpressionStatement} */ (statements[0]).expression).value ===
- "use strict"
- ) {
- this.scope.isStrict = true;
- }
- if (
- isLiteral &&
- /** @type {Literal} */
- (/** @type {ExpressionStatement} */ (statements[0]).expression).value ===
- "use asm"
- ) {
- this.scope.isAsmJs = true;
- }
- }
- /**
- * @param {(string | Pattern | Property)[]} patterns patterns
- * @param {OnIdentString} onIdent on ident callback
- */
- enterPatterns(patterns, onIdent) {
- for (const pattern of patterns) {
- if (typeof pattern !== "string") {
- this.enterPattern(pattern, onIdent);
- } else if (pattern) {
- onIdent(pattern);
- }
- }
- }
- /**
- * @param {Pattern | Property} pattern pattern
- * @param {OnIdent} onIdent on ident callback
- */
- enterPattern(pattern, onIdent) {
- if (!pattern) return;
- switch (pattern.type) {
- case "ArrayPattern":
- this.enterArrayPattern(pattern, onIdent);
- break;
- case "AssignmentPattern":
- this.enterAssignmentPattern(pattern, onIdent);
- break;
- case "Identifier":
- this.enterIdentifier(pattern, onIdent);
- break;
- case "ObjectPattern":
- this.enterObjectPattern(pattern, onIdent);
- break;
- case "RestElement":
- this.enterRestElement(pattern, onIdent);
- break;
- case "Property":
- if (pattern.shorthand && pattern.value.type === "Identifier") {
- this.scope.inShorthand = pattern.value.name;
- this.enterIdentifier(pattern.value, onIdent);
- this.scope.inShorthand = false;
- } else {
- this.enterPattern(/** @type {Pattern} */ (pattern.value), onIdent);
- }
- break;
- }
- }
- /**
- * @param {Identifier} pattern identifier pattern
- * @param {OnIdent} onIdent callback
- */
- enterIdentifier(pattern, onIdent) {
- if (!this.callHooksForName(this.hooks.pattern, pattern.name, pattern)) {
- onIdent(pattern.name, pattern);
- }
- }
- /**
- * @param {ObjectPattern} pattern object pattern
- * @param {OnIdent} onIdent callback
- */
- enterObjectPattern(pattern, onIdent) {
- for (
- let propIndex = 0, len = pattern.properties.length;
- propIndex < len;
- propIndex++
- ) {
- const prop = pattern.properties[propIndex];
- this.enterPattern(prop, onIdent);
- }
- }
- /**
- * @param {ArrayPattern} pattern object pattern
- * @param {OnIdent} onIdent callback
- */
- enterArrayPattern(pattern, onIdent) {
- for (
- let elementIndex = 0, len = pattern.elements.length;
- elementIndex < len;
- elementIndex++
- ) {
- const element = pattern.elements[elementIndex];
- if (element) {
- this.enterPattern(element, onIdent);
- }
- }
- }
- /**
- * @param {RestElement} pattern object pattern
- * @param {OnIdent} onIdent callback
- */
- enterRestElement(pattern, onIdent) {
- this.enterPattern(pattern.argument, onIdent);
- }
- /**
- * @param {AssignmentPattern} pattern object pattern
- * @param {OnIdent} onIdent callback
- */
- enterAssignmentPattern(pattern, onIdent) {
- this.enterPattern(pattern.left, onIdent);
- }
- /**
- * @param {Expression | SpreadElement | PrivateIdentifier | Super} expression expression node
- * @returns {BasicEvaluatedExpression} evaluation result
- */
- evaluateExpression(expression) {
- try {
- const hook = this.hooks.evaluate.get(expression.type);
- if (hook !== undefined) {
- const result = hook.call(expression);
- if (result !== undefined && result !== null) {
- result.setExpression(expression);
- return result;
- }
- }
- } catch (err) {
- // eslint-disable-next-line no-console
- console.warn(err);
- // ignore error
- }
- return new BasicEvaluatedExpression()
- .setRange(/** @type {Range} */ (expression.range))
- .setExpression(expression);
- }
- /**
- * @param {Expression} expression expression
- * @returns {string} parsed string
- */
- parseString(expression) {
- switch (expression.type) {
- case "BinaryExpression":
- if (expression.operator === "+") {
- return (
- this.parseString(/** @type {Expression} */ (expression.left)) +
- this.parseString(expression.right)
- );
- }
- break;
- case "Literal":
- return String(expression.value);
- }
- throw new Error(
- `${expression.type} is not supported as parameter for require`
- );
- }
- /** @typedef {{ range?: Range, value: string, code: boolean, conditional: false | CalculatedStringResult[] }} CalculatedStringResult */
- /**
- * @param {Expression} expression expression
- * @returns {CalculatedStringResult} result
- */
- parseCalculatedString(expression) {
- switch (expression.type) {
- case "BinaryExpression":
- if (expression.operator === "+") {
- const left = this.parseCalculatedString(
- /** @type {Expression} */
- (expression.left)
- );
- const right = this.parseCalculatedString(expression.right);
- if (left.code) {
- return {
- range: left.range,
- value: left.value,
- code: true,
- conditional: false
- };
- } else if (right.code) {
- return {
- range: [
- /** @type {Range} */
- (left.range)[0],
- right.range
- ? right.range[1]
- : /** @type {Range} */ (left.range)[1]
- ],
- value: left.value + right.value,
- code: true,
- conditional: false
- };
- }
- return {
- range: [
- /** @type {Range} */
- (left.range)[0],
- /** @type {Range} */
- (right.range)[1]
- ],
- value: left.value + right.value,
- code: false,
- conditional: false
- };
- }
- break;
- case "ConditionalExpression": {
- const consequent = this.parseCalculatedString(expression.consequent);
- const alternate = this.parseCalculatedString(expression.alternate);
- /** @type {CalculatedStringResult[]} */
- const items = [];
- if (consequent.conditional) {
- items.push(...consequent.conditional);
- } else if (!consequent.code) {
- items.push(consequent);
- } else {
- break;
- }
- if (alternate.conditional) {
- items.push(...alternate.conditional);
- } else if (!alternate.code) {
- items.push(alternate);
- } else {
- break;
- }
- return {
- range: undefined,
- value: "",
- code: true,
- conditional: items
- };
- }
- case "Literal":
- return {
- range: expression.range,
- value: String(expression.value),
- code: false,
- conditional: false
- };
- }
- return {
- range: undefined,
- value: "",
- code: true,
- conditional: false
- };
- }
- /**
- * @param {string | Buffer | PreparsedAst} source the source to parse
- * @param {ParserState} state the parser state
- * @returns {ParserState} the parser state
- */
- parse(source, state) {
- let ast;
- /** @type {import("acorn").Comment[]} */
- let comments;
- const semicolons = new Set();
- if (source === null) {
- throw new Error("source must not be null");
- }
- if (Buffer.isBuffer(source)) {
- source = source.toString("utf8");
- }
- if (typeof source === "object") {
- ast = /** @type {Program} */ (source);
- comments = source.comments;
- if (source.semicolons) {
- // Forward semicolon information from the preparsed AST if present
- // This ensures the output is consistent with that of a fresh AST
- for (const pos of source.semicolons) {
- semicolons.add(pos);
- }
- }
- } else {
- comments = [];
- ast = JavascriptParser._parse(source, {
- sourceType: this.sourceType,
- onComment: comments,
- onInsertedSemicolon: (pos) => semicolons.add(pos)
- });
- }
- const oldScope = this.scope;
- const oldState = this.state;
- const oldComments = this.comments;
- const oldSemicolons = this.semicolons;
- const oldStatementPath = this.statementPath;
- const oldPrevStatement = this.prevStatement;
- this.scope = {
- topLevelScope: true,
- inTry: false,
- inShorthand: false,
- inTaggedTemplateTag: false,
- isStrict: false,
- isAsmJs: false,
- terminated: undefined,
- definitions: new StackedMap()
- };
- this.state = /** @type {ParserState} */ (state);
- this.comments = comments;
- this.semicolons = semicolons;
- this.statementPath = [];
- this.prevStatement = undefined;
- if (this.hooks.program.call(ast, comments) === undefined) {
- this.destructuringAssignmentProperties = new WeakMap();
- this.detectMode(ast.body);
- this.modulePreWalkStatements(ast.body);
- this.preWalkStatements(ast.body);
- this.prevStatement = undefined;
- this.blockPreWalkStatements(ast.body);
- this.prevStatement = undefined;
- this.walkStatements(ast.body);
- this.destructuringAssignmentProperties = undefined;
- }
- this.hooks.finish.call(ast, comments);
- this.scope = oldScope;
- this.state = oldState;
- this.comments = oldComments;
- this.semicolons = oldSemicolons;
- this.statementPath = oldStatementPath;
- this.prevStatement = oldPrevStatement;
- return state;
- }
- /**
- * @param {string} source source code
- * @returns {BasicEvaluatedExpression} evaluation result
- */
- evaluate(source) {
- const ast = JavascriptParser._parse(`(${source})`, {
- sourceType: this.sourceType,
- locations: false
- });
- if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") {
- throw new Error("evaluate: Source is not a expression");
- }
- return this.evaluateExpression(ast.body[0].expression);
- }
- /**
- * @param {Expression | Declaration | PrivateIdentifier | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | null | undefined} expr an expression
- * @param {number} commentsStartPos source position from which annotation comments are checked
- * @returns {boolean} true, when the expression is pure
- */
- isPure(expr, commentsStartPos) {
- if (!expr) return true;
- const result = this.hooks.isPure
- .for(expr.type)
- .call(expr, commentsStartPos);
- if (typeof result === "boolean") return result;
- switch (expr.type) {
- // TODO handle more cases
- case "ClassDeclaration":
- case "ClassExpression": {
- if (expr.body.type !== "ClassBody") return false;
- if (
- expr.superClass &&
- !this.isPure(expr.superClass, /** @type {Range} */ (expr.range)[0])
- ) {
- return false;
- }
- const items = expr.body.body;
- return items.every((item) => {
- if (item.type === "StaticBlock") {
- return false;
- }
- if (
- item.computed &&
- item.key &&
- !this.isPure(
- item.key,
- /** @type {Range} */
- (item.range)[0]
- )
- ) {
- return false;
- }
- if (
- item.static &&
- item.value &&
- !this.isPure(
- item.value,
- item.key
- ? /** @type {Range} */ (item.key.range)[1]
- : /** @type {Range} */ (item.range)[0]
- )
- ) {
- return false;
- }
- if (
- expr.superClass &&
- item.type === "MethodDefinition" &&
- item.kind === "constructor"
- ) {
- return false;
- }
- return true;
- });
- }
- case "FunctionDeclaration":
- case "FunctionExpression":
- case "ArrowFunctionExpression":
- case "ThisExpression":
- case "Literal":
- case "TemplateLiteral":
- case "Identifier":
- case "PrivateIdentifier":
- return true;
- case "VariableDeclaration":
- return expr.declarations.every((decl) =>
- this.isPure(decl.init, /** @type {Range} */ (decl.range)[0])
- );
- case "ConditionalExpression":
- return (
- this.isPure(expr.test, commentsStartPos) &&
- this.isPure(
- expr.consequent,
- /** @type {Range} */ (expr.test.range)[1]
- ) &&
- this.isPure(
- expr.alternate,
- /** @type {Range} */ (expr.consequent.range)[1]
- )
- );
- case "LogicalExpression":
- return (
- this.isPure(expr.left, commentsStartPos) &&
- this.isPure(expr.right, /** @type {Range} */ (expr.left.range)[1])
- );
- case "SequenceExpression":
- return expr.expressions.every((expr) => {
- const pureFlag = this.isPure(expr, commentsStartPos);
- commentsStartPos = /** @type {Range} */ (expr.range)[1];
- return pureFlag;
- });
- case "CallExpression": {
- const pureFlag =
- /** @type {Range} */ (expr.range)[0] - commentsStartPos > 12 &&
- this.getComments([
- commentsStartPos,
- /** @type {Range} */ (expr.range)[0]
- ]).some(
- (comment) =>
- comment.type === "Block" &&
- /^\s*(#|@)__PURE__\s*$/.test(comment.value)
- );
- if (!pureFlag) return false;
- commentsStartPos = /** @type {Range} */ (expr.callee.range)[1];
- return expr.arguments.every((arg) => {
- if (arg.type === "SpreadElement") return false;
- const pureFlag = this.isPure(arg, commentsStartPos);
- commentsStartPos = /** @type {Range} */ (arg.range)[1];
- return pureFlag;
- });
- }
- }
- const evaluated = this.evaluateExpression(expr);
- return !evaluated.couldHaveSideEffects();
- }
- /**
- * @param {Range} range range
- * @returns {Comment[]} comments in the range
- */
- getComments(range) {
- const [rangeStart, rangeEnd] = range;
- /**
- * @param {Comment} comment comment
- * @param {number} needle needle
- * @returns {number} compared
- */
- const compare = (comment, needle) =>
- /** @type {Range} */ (comment.range)[0] - needle;
- const comments = /** @type {Comment[]} */ (this.comments);
- let idx = binarySearchBounds.ge(comments, rangeStart, compare);
- /** @type {Comment[]} */
- const commentsInRange = [];
- while (
- comments[idx] &&
- /** @type {Range} */ (comments[idx].range)[1] <= rangeEnd
- ) {
- commentsInRange.push(comments[idx]);
- idx++;
- }
- return commentsInRange;
- }
- /**
- * @param {number} pos source code position
- * @returns {boolean} true when a semicolon has been inserted before this position, false if not
- */
- isAsiPosition(pos) {
- const currentStatement =
- /** @type {StatementPath} */
- (this.statementPath)[
- /** @type {StatementPath} */
- (this.statementPath).length - 1
- ];
- if (currentStatement === undefined) throw new Error("Not in statement");
- const range = /** @type {Range} */ (currentStatement.range);
- return (
- // Either asking directly for the end position of the current statement
- (range[1] === pos &&
- /** @type {Set<number>} */ (this.semicolons).has(pos)) ||
- // Or asking for the start position of the current statement,
- // here we have to check multiple things
- (range[0] === pos &&
- // is there a previous statement which might be relevant?
- this.prevStatement !== undefined &&
- // is the end position of the previous statement an ASI position?
- /** @type {Set<number>} */ (this.semicolons).has(
- /** @type {Range} */ (this.prevStatement.range)[1]
- ))
- );
- }
- /**
- * @param {number} pos source code position
- * @returns {void}
- */
- setAsiPosition(pos) {
- /** @type {Set<number>} */ (this.semicolons).add(pos);
- }
- /**
- * @param {number} pos source code position
- * @returns {void}
- */
- unsetAsiPosition(pos) {
- /** @type {Set<number>} */ (this.semicolons).delete(pos);
- }
- /**
- * @param {Expression} expr expression
- * @returns {boolean} true, when the expression is a statement level expression
- */
- isStatementLevelExpression(expr) {
- const currentStatement =
- /** @type {StatementPath} */
- (this.statementPath)[
- /** @type {StatementPath} */
- (this.statementPath).length - 1
- ];
- return (
- expr === currentStatement ||
- (currentStatement.type === "ExpressionStatement" &&
- currentStatement.expression === expr)
- );
- }
- /**
- * @param {string} name name
- * @param {Tag} tag tag info
- * @returns {TagData | undefined} tag data
- */
- getTagData(name, tag) {
- const info = this.scope.definitions.get(name);
- if (info instanceof VariableInfo) {
- let tagInfo = info.tagInfo;
- while (tagInfo !== undefined) {
- if (tagInfo.tag === tag) return tagInfo.data;
- tagInfo = tagInfo.next;
- }
- }
- }
- /**
- * @param {string} name name
- * @param {Tag} tag tag info
- * @param {TagData=} data data
- * @param {VariableInfoFlagsType=} flags flags
- */
- tagVariable(name, tag, data, flags = VariableInfoFlags.Tagged) {
- const oldInfo = this.scope.definitions.get(name);
- /** @type {VariableInfo} */
- let newInfo;
- if (oldInfo === undefined) {
- newInfo = new VariableInfo(this.scope, name, flags, {
- tag,
- data,
- next: undefined
- });
- } else if (oldInfo instanceof VariableInfo) {
- newInfo = new VariableInfo(
- oldInfo.declaredScope,
- oldInfo.name,
- /** @type {VariableInfoFlagsType} */ (oldInfo.flags | flags),
- {
- tag,
- data,
- next: oldInfo.tagInfo
- }
- );
- } else {
- newInfo = new VariableInfo(oldInfo, name, flags, {
- tag,
- data,
- next: undefined
- });
- }
- this.scope.definitions.set(name, newInfo);
- }
- /**
- * @param {string} name variable name
- */
- defineVariable(name) {
- const oldInfo = this.scope.definitions.get(name);
- // Don't redefine variable in same scope to keep existing tags
- if (
- oldInfo instanceof VariableInfo &&
- oldInfo.declaredScope === this.scope
- ) {
- return;
- }
- this.scope.definitions.set(name, this.scope);
- }
- /**
- * @param {string} name variable name
- */
- undefineVariable(name) {
- this.scope.definitions.delete(name);
- }
- /**
- * @param {string} name variable name
- * @returns {boolean} true, when variable is defined
- */
- isVariableDefined(name) {
- const info = this.scope.definitions.get(name);
- if (info === undefined) return false;
- if (info instanceof VariableInfo) {
- return !info.isFree();
- }
- return true;
- }
- /**
- * @param {string} name variable name
- * @returns {string | ExportedVariableInfo} info for this variable
- */
- getVariableInfo(name) {
- const value = this.scope.definitions.get(name);
- if (value === undefined) {
- return name;
- }
- return value;
- }
- /**
- * @param {string} name variable name
- * @param {string | ExportedVariableInfo} variableInfo new info for this variable
- * @returns {void}
- */
- setVariable(name, variableInfo) {
- if (typeof variableInfo === "string") {
- if (variableInfo === name) {
- this.scope.definitions.delete(name);
- } else {
- this.scope.definitions.set(
- name,
- new VariableInfo(
- this.scope,
- variableInfo,
- VariableInfoFlags.Free,
- undefined
- )
- );
- }
- } else {
- this.scope.definitions.set(name, variableInfo);
- }
- }
- /**
- * @param {TagInfo} tagInfo tag info
- * @returns {VariableInfo} variable info
- */
- evaluatedVariable(tagInfo) {
- return new VariableInfo(
- this.scope,
- undefined,
- VariableInfoFlags.Evaluated,
- tagInfo
- );
- }
- /**
- * @param {Range} range range of the comment
- * @returns {{ options: Record<string, EXPECTED_ANY> | null, errors: (Error & { comment: Comment })[] | null }} result
- */
- parseCommentOptions(range) {
- const comments = this.getComments(range);
- if (comments.length === 0) {
- return EMPTY_COMMENT_OPTIONS;
- }
- /** @type {Record<string, EXPECTED_ANY> } */
- const options = {};
- /** @type {(Error & { comment: Comment })[]} */
- const errors = [];
- for (const comment of comments) {
- const { value } = comment;
- if (value && webpackCommentRegExp.test(value)) {
- // try compile only if webpack options comment is present
- try {
- for (let [key, val] of Object.entries(
- vm.runInContext(
- `(function(){return {${value}};})()`,
- this.magicCommentContext
- )
- )) {
- if (typeof val === "object" && val !== null) {
- val =
- val.constructor.name === "RegExp"
- ? new RegExp(val)
- : JSON.parse(JSON.stringify(val));
- }
- options[key] = val;
- }
- } catch (err) {
- const newErr = new Error(String(/** @type {Error} */ (err).message));
- newErr.stack = String(/** @type {Error} */ (err).stack);
- Object.assign(newErr, { comment });
- errors.push(/** @type {(Error & { comment: Comment })} */ (newErr));
- }
- }
- }
- return { options, errors };
- }
- /**
- * @param {Expression | Super} expression a member expression
- * @returns {{ members: string[], object: Expression | Super, membersOptionals: boolean[], memberRanges: Range[] }} member names (reverse order) and remaining object
- */
- extractMemberExpressionChain(expression) {
- /** @type {Node} */
- let expr = expression;
- const members = [];
- const membersOptionals = [];
- const memberRanges = [];
- while (expr.type === "MemberExpression") {
- if (expr.computed) {
- if (expr.property.type !== "Literal") break;
- members.push(`${expr.property.value}`); // the literal
- memberRanges.push(/** @type {Range} */ (expr.object.range)); // the range of the expression fragment before the literal
- } else {
- if (expr.property.type !== "Identifier") break;
- members.push(expr.property.name); // the identifier
- memberRanges.push(/** @type {Range} */ (expr.object.range)); // the range of the expression fragment before the identifier
- }
- membersOptionals.push(expr.optional);
- expr = expr.object;
- }
- return {
- members,
- membersOptionals,
- memberRanges,
- object: expr
- };
- }
- /**
- * @param {string} varName variable name
- * @returns {{name: string, info: VariableInfo | string} | undefined} name of the free variable and variable info for that
- */
- getFreeInfoFromVariable(varName) {
- const info = this.getVariableInfo(varName);
- let name;
- if (info instanceof VariableInfo && info.name) {
- if (!info.isFree()) return;
- name = info.name;
- } else if (typeof info !== "string") {
- return;
- } else {
- name = info;
- }
- return { info, name };
- }
- /**
- * @param {string} varName variable name
- * @returns {{name: string, info: VariableInfo | string} | undefined} name of the free variable and variable info for that
- */
- getNameInfoFromVariable(varName) {
- const info = this.getVariableInfo(varName);
- let name;
- if (info instanceof VariableInfo && info.name) {
- if (!info.isFree() && !info.isTagged()) return;
- name = info.name;
- } else if (typeof info !== "string") {
- return;
- } else {
- name = info;
- }
- return { info, name };
- }
- /** @typedef {{ type: "call", call: CallExpression, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => string[], name: string, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[]}} CallExpressionInfo */
- /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[]}} ExpressionExpressionInfo */
- /**
- * @param {Expression | Super} expression a member expression
- * @param {number} allowedTypes which types should be returned, presented in bit mask
- * @returns {CallExpressionInfo | ExpressionExpressionInfo | undefined} expression info
- */
- getMemberExpressionInfo(expression, allowedTypes) {
- const { object, members, membersOptionals, memberRanges } =
- this.extractMemberExpressionChain(expression);
- switch (object.type) {
- case "CallExpression": {
- if ((allowedTypes & ALLOWED_MEMBER_TYPES_CALL_EXPRESSION) === 0) return;
- let callee = object.callee;
- let rootMembers = EMPTY_ARRAY;
- if (callee.type === "MemberExpression") {
- ({ object: callee, members: rootMembers } =
- this.extractMemberExpressionChain(callee));
- }
- const rootName = getRootName(callee);
- if (!rootName) return;
- const result = this.getNameInfoFromVariable(rootName);
- if (!result) return;
- const { info: rootInfo, name: resolvedRoot } = result;
- const calleeName = objectAndMembersToName(resolvedRoot, rootMembers);
- return {
- type: "call",
- call: object,
- calleeName,
- rootInfo,
- getCalleeMembers: memoize(() => rootMembers.reverse()),
- name: objectAndMembersToName(`${calleeName}()`, members),
- getMembers: memoize(() => members.reverse()),
- getMembersOptionals: memoize(() => membersOptionals.reverse()),
- getMemberRanges: memoize(() => memberRanges.reverse())
- };
- }
- case "Identifier":
- case "MetaProperty":
- case "ThisExpression": {
- if ((allowedTypes & ALLOWED_MEMBER_TYPES_EXPRESSION) === 0) return;
- const rootName = getRootName(object);
- if (!rootName) return;
- const result = this.getNameInfoFromVariable(rootName);
- if (!result) return;
- const { info: rootInfo, name: resolvedRoot } = result;
- return {
- type: "expression",
- name: objectAndMembersToName(resolvedRoot, members),
- rootInfo,
- getMembers: memoize(() => members.reverse()),
- getMembersOptionals: memoize(() => membersOptionals.reverse()),
- getMemberRanges: memoize(() => memberRanges.reverse())
- };
- }
- }
- }
- /**
- * @param {Expression} expression an expression
- * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => string[]} | undefined} name info
- */
- getNameForExpression(expression) {
- return this.getMemberExpressionInfo(
- expression,
- ALLOWED_MEMBER_TYPES_EXPRESSION
- );
- }
- /**
- * @param {string} code source code
- * @param {ParseOptions} options parsing options
- * @returns {Program} parsed ast
- */
- static _parse(code, options) {
- const type = options ? options.sourceType : "module";
- /** @type {AcornOptions} */
- const parserOptions = {
- ...defaultParserOptions,
- allowReturnOutsideFunction: type === "script",
- ...options,
- sourceType: type === "auto" ? "module" : type
- };
- /** @type {import("acorn").Program | undefined} */
- let ast;
- let error;
- let threw = false;
- try {
- ast = parser.parse(code, parserOptions);
- } catch (err) {
- error = err;
- threw = true;
- }
- if (threw && type === "auto") {
- parserOptions.sourceType = "script";
- if (!("allowReturnOutsideFunction" in options)) {
- parserOptions.allowReturnOutsideFunction = true;
- }
- if (Array.isArray(parserOptions.onComment)) {
- parserOptions.onComment.length = 0;
- }
- try {
- ast = parser.parse(code, parserOptions);
- threw = false;
- } catch (_err) {
- // we use the error from first parse try
- // so nothing to do here
- }
- }
- if (threw) {
- throw error;
- }
- return /** @type {Program} */ (ast);
- }
- /**
- * @param {((BaseParser: typeof AcornParser) => typeof AcornParser)[]} plugins parser plugin
- * @returns {typeof JavascriptParser} parser
- */
- static extend(...plugins) {
- parser = parser.extend(...plugins);
- return JavascriptParser;
- }
- }
- module.exports = JavascriptParser;
- module.exports.ALLOWED_MEMBER_TYPES_ALL = ALLOWED_MEMBER_TYPES_ALL;
- module.exports.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION =
- ALLOWED_MEMBER_TYPES_CALL_EXPRESSION;
- module.exports.ALLOWED_MEMBER_TYPES_EXPRESSION =
- ALLOWED_MEMBER_TYPES_EXPRESSION;
- module.exports.VariableInfo = VariableInfo;
- module.exports.VariableInfoFlags = VariableInfoFlags;
- module.exports.getImportAttributes = getImportAttributes;
|