JavascriptParser.js 162 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const vm = require("vm");
  7. const { Parser: AcornParser, tokTypes } = require("acorn");
  8. const { HookMap, SyncBailHook } = require("tapable");
  9. const NormalModule = require("../NormalModule");
  10. const Parser = require("../Parser");
  11. const StackedMap = require("../util/StackedMap");
  12. const binarySearchBounds = require("../util/binarySearchBounds");
  13. const {
  14. createMagicCommentContext,
  15. webpackCommentRegExp
  16. } = require("../util/magicComment");
  17. const memoize = require("../util/memoize");
  18. const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
  19. /** @typedef {import("acorn").Options} AcornOptions */
  20. /** @typedef {import("acorn").ecmaVersion} EcmaVersion */
  21. /** @typedef {import("estree").AssignmentExpression} AssignmentExpression */
  22. /** @typedef {import("estree").BinaryExpression} BinaryExpression */
  23. /** @typedef {import("estree").BlockStatement} BlockStatement */
  24. /** @typedef {import("estree").SequenceExpression} SequenceExpression */
  25. /** @typedef {import("estree").CallExpression} CallExpression */
  26. /** @typedef {import("estree").StaticBlock} StaticBlock */
  27. /** @typedef {import("estree").ClassDeclaration} ClassDeclaration */
  28. /** @typedef {import("estree").ForStatement} ForStatement */
  29. /** @typedef {import("estree").SwitchStatement} SwitchStatement */
  30. /** @typedef {import("estree").ClassExpression} ClassExpression */
  31. /** @typedef {import("estree").SourceLocation} SourceLocation */
  32. /** @typedef {import("estree").Comment & { start: number, end: number, loc: SourceLocation }} Comment */
  33. /** @typedef {import("estree").ConditionalExpression} ConditionalExpression */
  34. /** @typedef {import("estree").Declaration} Declaration */
  35. /** @typedef {import("estree").PrivateIdentifier} PrivateIdentifier */
  36. /** @typedef {import("estree").PropertyDefinition} PropertyDefinition */
  37. /** @typedef {import("estree").Expression} Expression */
  38. /** @typedef {import("estree").ImportAttribute} ImportAttribute */
  39. /** @typedef {import("estree").ImportDeclaration} ImportDeclaration */
  40. /** @typedef {import("estree").Identifier} Identifier */
  41. /** @typedef {import("estree").VariableDeclaration} VariableDeclaration */
  42. /** @typedef {import("estree").IfStatement} IfStatement */
  43. /** @typedef {import("estree").LabeledStatement} LabeledStatement */
  44. /** @typedef {import("estree").Literal} Literal */
  45. /** @typedef {import("estree").LogicalExpression} LogicalExpression */
  46. /** @typedef {import("estree").ChainExpression} ChainExpression */
  47. /** @typedef {import("estree").MemberExpression} MemberExpression */
  48. /** @typedef {import("estree").YieldExpression} YieldExpression */
  49. /** @typedef {import("estree").MetaProperty} MetaProperty */
  50. /** @typedef {import("estree").Property} Property */
  51. /** @typedef {import("estree").AssignmentPattern} AssignmentPattern */
  52. /** @typedef {import("estree").Pattern} Pattern */
  53. /** @typedef {import("estree").UpdateExpression} UpdateExpression */
  54. /** @typedef {import("estree").ObjectExpression} ObjectExpression */
  55. /** @typedef {import("estree").UnaryExpression} UnaryExpression */
  56. /** @typedef {import("estree").ArrayExpression} ArrayExpression */
  57. /** @typedef {import("estree").ArrayPattern} ArrayPattern */
  58. /** @typedef {import("estree").AwaitExpression} AwaitExpression */
  59. /** @typedef {import("estree").ThisExpression} ThisExpression */
  60. /** @typedef {import("estree").RestElement} RestElement */
  61. /** @typedef {import("estree").ObjectPattern} ObjectPattern */
  62. /** @typedef {import("estree").SwitchCase} SwitchCase */
  63. /** @typedef {import("estree").CatchClause} CatchClause */
  64. /** @typedef {import("estree").VariableDeclarator} VariableDeclarator */
  65. /** @typedef {import("estree").ForInStatement} ForInStatement */
  66. /** @typedef {import("estree").ForOfStatement} ForOfStatement */
  67. /** @typedef {import("estree").ReturnStatement} ReturnStatement */
  68. /** @typedef {import("estree").WithStatement} WithStatement */
  69. /** @typedef {import("estree").ThrowStatement} ThrowStatement */
  70. /** @typedef {import("estree").MethodDefinition} MethodDefinition */
  71. /** @typedef {import("estree").NewExpression} NewExpression */
  72. /** @typedef {import("estree").SpreadElement} SpreadElement */
  73. /** @typedef {import("estree").FunctionExpression} FunctionExpression */
  74. /** @typedef {import("estree").WhileStatement} WhileStatement */
  75. /** @typedef {import("estree").ArrowFunctionExpression} ArrowFunctionExpression */
  76. /** @typedef {import("estree").ExpressionStatement} ExpressionStatement */
  77. /** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */
  78. /** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */
  79. /** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */
  80. /** @typedef {import("estree").DoWhileStatement} DoWhileStatement */
  81. /** @typedef {import("estree").TryStatement} TryStatement */
  82. /** @typedef {import("estree").Node} Node */
  83. /** @typedef {import("estree").Program} Program */
  84. /** @typedef {import("estree").Directive} Directive */
  85. /** @typedef {import("estree").Statement} Statement */
  86. /** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclaration */
  87. /** @typedef {import("estree").Super} Super */
  88. /** @typedef {import("estree").TaggedTemplateExpression} TaggedTemplateExpression */
  89. /** @typedef {import("estree").TemplateLiteral} TemplateLiteral */
  90. /** @typedef {import("estree").ModuleDeclaration} ModuleDeclaration */
  91. /** @typedef {import("estree").MaybeNamedFunctionDeclaration} MaybeNamedFunctionDeclaration */
  92. /** @typedef {import("estree").MaybeNamedClassDeclaration} MaybeNamedClassDeclaration */
  93. /**
  94. * @template T
  95. * @typedef {import("tapable").AsArray<T>} AsArray<T>
  96. */
  97. /** @typedef {import("../Parser").ParserState} ParserState */
  98. /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
  99. /** @typedef {import("../dependencies/LocalModule")} LocalModule */
  100. /** @typedef {import("../dependencies/HarmonyExportImportedSpecifierDependency").HarmonyStarExportsList} HarmonyStarExportsList */
  101. /**
  102. * @typedef {object} KnownJavascriptParserState
  103. * @property {Set<string>=} harmonyNamedExports
  104. * @property {HarmonyStarExportsList=} harmonyStarExports
  105. * @property {number=} lastHarmonyImportOrder
  106. * @property {LocalModule[]=} localModules
  107. */
  108. /** @typedef {ParserState & KnownJavascriptParserState} JavascriptParserState */
  109. /** @typedef {import("../Compilation")} Compilation */
  110. /** @typedef {import("../Module")} Module */
  111. /** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => Members, getMembersOptionals: () => MembersOptionals, getMemberRanges: () => MemberRanges }} GetInfoResult */
  112. /** @typedef {Statement | ModuleDeclaration | Expression | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} StatementPathItem */
  113. /** @typedef {(ident: string) => void} OnIdentString */
  114. /** @typedef {(ident: string, identifier: Identifier) => void} OnIdent */
  115. /** @typedef {StatementPathItem[]} StatementPath */
  116. /** @typedef {Set<DestructuringAssignmentProperty>} DestructuringAssignmentProperties */
  117. // TODO remove cast when @types/estree has been updated to import assertions
  118. /** @typedef {import("estree").ImportExpression & { phase?: "defer" }} ImportExpression */
  119. /** @type {string[]} */
  120. const EMPTY_ARRAY = [];
  121. const ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = 0b01;
  122. const ALLOWED_MEMBER_TYPES_EXPRESSION = 0b10;
  123. const ALLOWED_MEMBER_TYPES_ALL = 0b11;
  124. const LEGACY_ASSERT_ATTRIBUTES = Symbol("assert");
  125. /** @type {(BaseParser: typeof AcornParser) => typeof AcornParser} */
  126. const importAssertions = (Parser) =>
  127. class extends Parser {
  128. /**
  129. * @this {InstanceType<AcornParser>}
  130. * @returns {ImportAttribute[]} import attributes
  131. */
  132. parseWithClause() {
  133. /** @type {ImportAttribute[]} */
  134. const nodes = [];
  135. const isAssertLegacy = this.value === "assert";
  136. if (isAssertLegacy) {
  137. if (!this.eat(tokTypes.name)) {
  138. return nodes;
  139. }
  140. } else if (!this.eat(tokTypes._with)) {
  141. return nodes;
  142. }
  143. this.expect(tokTypes.braceL);
  144. /** @type {Record<string, boolean>} */
  145. const attributeKeys = {};
  146. let first = true;
  147. while (!this.eat(tokTypes.braceR)) {
  148. if (!first) {
  149. this.expect(tokTypes.comma);
  150. if (this.afterTrailingComma(tokTypes.braceR)) {
  151. break;
  152. }
  153. } else {
  154. first = false;
  155. }
  156. const attr =
  157. /** @type {ImportAttribute} */
  158. this.parseImportAttribute();
  159. const keyName =
  160. attr.key.type === "Identifier" ? attr.key.name : attr.key.value;
  161. if (Object.prototype.hasOwnProperty.call(attributeKeys, keyName)) {
  162. this.raiseRecoverable(
  163. attr.key.start,
  164. `Duplicate attribute key '${keyName}'`
  165. );
  166. }
  167. attributeKeys[keyName] = true;
  168. nodes.push(attr);
  169. }
  170. if (isAssertLegacy) {
  171. /** @type {EXPECTED_ANY} */
  172. (nodes)[LEGACY_ASSERT_ATTRIBUTES] = true;
  173. }
  174. return nodes;
  175. }
  176. };
  177. // Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API
  178. let parser = AcornParser.extend(importAssertions);
  179. /** @typedef {Record<string, string> & { _isLegacyAssert?: boolean }} ImportAttributes */
  180. /**
  181. * @param {ImportDeclaration | ExportNamedDeclaration | ExportAllDeclaration | ImportExpression} node node with assertions
  182. * @returns {ImportAttributes | undefined} import attributes
  183. */
  184. const getImportAttributes = (node) => {
  185. if (node.type === "ImportExpression") {
  186. if (
  187. node.options &&
  188. node.options.type === "ObjectExpression" &&
  189. node.options.properties[0] &&
  190. node.options.properties[0].type === "Property" &&
  191. node.options.properties[0].key.type === "Identifier" &&
  192. (node.options.properties[0].key.name === "with" ||
  193. node.options.properties[0].key.name === "assert") &&
  194. node.options.properties[0].value.type === "ObjectExpression" &&
  195. node.options.properties[0].value.properties.length > 0
  196. ) {
  197. const properties =
  198. /** @type {Property[]} */
  199. (node.options.properties[0].value.properties);
  200. const result = /** @type {ImportAttributes} */ ({});
  201. for (const property of properties) {
  202. const key =
  203. /** @type {string} */
  204. (
  205. property.key.type === "Identifier"
  206. ? property.key.name
  207. : /** @type {Literal} */ (property.key).value
  208. );
  209. result[key] =
  210. /** @type {string} */
  211. (/** @type {Literal} */ (property.value).value);
  212. }
  213. const key =
  214. node.options.properties[0].key.type === "Identifier"
  215. ? node.options.properties[0].key.name
  216. : /** @type {Literal} */ (node.options.properties[0].key).value;
  217. if (key === "assert") {
  218. result._isLegacyAssert = true;
  219. }
  220. return result;
  221. }
  222. return;
  223. }
  224. if (node.attributes === undefined || node.attributes.length === 0) {
  225. return;
  226. }
  227. const result = /** @type {ImportAttributes} */ ({});
  228. for (const attribute of node.attributes) {
  229. const key =
  230. /** @type {string} */
  231. (
  232. attribute.key.type === "Identifier"
  233. ? attribute.key.name
  234. : attribute.key.value
  235. );
  236. result[key] = /** @type {string} */ (attribute.value.value);
  237. }
  238. if (/** @type {EXPECTED_ANY} */ (node.attributes)[LEGACY_ASSERT_ATTRIBUTES]) {
  239. result._isLegacyAssert = true;
  240. }
  241. return result;
  242. };
  243. /** @typedef {typeof VariableInfoFlags.Evaluated | typeof VariableInfoFlags.Free | typeof VariableInfoFlags.Normal | typeof VariableInfoFlags.Tagged} VariableInfoFlagsType */
  244. const VariableInfoFlags = Object.freeze({
  245. Evaluated: 0b000,
  246. Free: 0b001,
  247. Normal: 0b010,
  248. Tagged: 0b100
  249. });
  250. class VariableInfo {
  251. /**
  252. * @param {ScopeInfo} declaredScope scope in which the variable is declared
  253. * @param {string | undefined} name which name the variable use, defined name or free name or tagged name
  254. * @param {VariableInfoFlagsType} flags how the variable is created
  255. * @param {TagInfo | undefined} tagInfo info about tags
  256. */
  257. constructor(declaredScope, name, flags, tagInfo) {
  258. this.declaredScope = declaredScope;
  259. this.name = name;
  260. this.flags = flags;
  261. this.tagInfo = tagInfo;
  262. }
  263. /**
  264. * @returns {boolean} the variable is free or not
  265. */
  266. isFree() {
  267. return (this.flags & VariableInfoFlags.Free) > 0;
  268. }
  269. /**
  270. * @returns {boolean} the variable is tagged by tagVariable or not
  271. */
  272. isTagged() {
  273. return (this.flags & VariableInfoFlags.Tagged) > 0;
  274. }
  275. }
  276. /** @typedef {string | ScopeInfo | VariableInfo} ExportedVariableInfo */
  277. /** @typedef {Literal | string | null | undefined} ImportSource */
  278. /**
  279. * @typedef {Omit<ParseOptions, "sourceType" | "ecmaVersion"> & { sourceType: "module" | "script" | "auto" }} InternalParseOptions
  280. */
  281. /**
  282. * @typedef {object} ParseOptions
  283. * @property {"module" | "script"} sourceType
  284. * @property {EcmaVersion} ecmaVersion
  285. * @property {boolean=} locations
  286. * @property {boolean=} comments
  287. * @property {boolean=} ranges
  288. * @property {boolean=} semicolons
  289. * @property {boolean=} allowHashBang
  290. * @property {boolean=} allowReturnOutsideFunction
  291. */
  292. /**
  293. * @typedef {object} ParseResult
  294. * @property {Program} ast
  295. * @property {Comment[]} comments
  296. * @property {Set<number>} semicolons
  297. */
  298. /**
  299. * @typedef {(code: string, options: ParseOptions) => ParseResult} ParseFunction
  300. */
  301. /** @typedef {symbol} Tag */
  302. /** @typedef {import("../dependencies/HarmonyImportDependencyParserPlugin").HarmonySettings} HarmonySettings */
  303. /** @typedef {import("../dependencies/HarmonyImportDependencyParserPlugin").HarmonySpecifierGuards} HarmonySpecifierGuards */
  304. /** @typedef {import("../dependencies/ImportParserPlugin").ImportSettings} ImportSettings */
  305. /** @typedef {import("../dependencies/CommonJsImportsParserPlugin").CommonJsImportSettings} CommonJsImportSettings */
  306. /** @typedef {import("../CompatibilityPlugin").CompatibilitySettings} CompatibilitySettings */
  307. /** @typedef {import("../optimize/InnerGraph").TopLevelSymbol} TopLevelSymbol */
  308. /** @typedef {HarmonySettings | ImportSettings | CommonJsImportSettings | TopLevelSymbol | CompatibilitySettings | HarmonySpecifierGuards} KnownTagData */
  309. /** @typedef {KnownTagData | Record<string, EXPECTED_ANY>} TagData */
  310. /**
  311. * @typedef {object} TagInfo
  312. * @property {Tag} tag
  313. * @property {TagData=} data
  314. * @property {TagInfo | undefined} next
  315. */
  316. /** @typedef {string[]} CalleeMembers */
  317. /** @typedef {string[]} Members */
  318. /** @typedef {boolean[]} MembersOptionals */
  319. /** @typedef {Range[]} MemberRanges */
  320. const SCOPE_INFO_TERMINATED_RETURN = 1;
  321. const SCOPE_INFO_TERMINATED_THROW = 2;
  322. /**
  323. * @typedef {object} ScopeInfo
  324. * @property {StackedMap<string, VariableInfo | ScopeInfo>} definitions
  325. * @property {boolean | "arrow"} topLevelScope
  326. * @property {boolean | string} inShorthand
  327. * @property {boolean} inTaggedTemplateTag
  328. * @property {boolean} inTry
  329. * @property {boolean} isStrict
  330. * @property {boolean} isAsmJs
  331. * @property {undefined | 1 | 2} terminated
  332. */
  333. /** @typedef {[number, number]} Range */
  334. /**
  335. * @typedef {object} DestructuringAssignmentProperty
  336. * @property {string} id
  337. * @property {Range} range
  338. * @property {SourceLocation} loc
  339. * @property {Set<DestructuringAssignmentProperty> | undefined=} pattern
  340. * @property {boolean | string} shorthand
  341. */
  342. /**
  343. * Helper function for joining two ranges into a single range. This is useful
  344. * when working with AST nodes, as it allows you to combine the ranges of child nodes
  345. * to create the range of the _parent node_.
  346. * @param {Range} startRange start range to join
  347. * @param {Range} endRange end range to join
  348. * @returns {Range} joined range
  349. * @example
  350. * ```js
  351. * const startRange = [0, 5];
  352. * const endRange = [10, 15];
  353. * const joinedRange = joinRanges(startRange, endRange);
  354. * console.log(joinedRange); // [0, 15]
  355. * ```
  356. */
  357. const joinRanges = (startRange, endRange) => {
  358. if (!endRange) return startRange;
  359. if (!startRange) return endRange;
  360. return [startRange[0], endRange[1]];
  361. };
  362. /**
  363. * Helper function used to generate a string representation of a
  364. * [member expression](https://github.com/estree/estree/blob/master/es5.md#memberexpression).
  365. * @param {string} object object to name
  366. * @param {Members} membersReversed reversed list of members
  367. * @returns {string} member expression as a string
  368. * @example
  369. * ```js
  370. * const membersReversed = ["property1", "property2", "property3"]; // Members parsed from the AST
  371. * const name = objectAndMembersToName("myObject", membersReversed);
  372. *
  373. * console.log(name); // "myObject.property1.property2.property3"
  374. * ```
  375. */
  376. const objectAndMembersToName = (object, membersReversed) => {
  377. let name = object;
  378. for (let i = membersReversed.length - 1; i >= 0; i--) {
  379. name = `${name}.${membersReversed[i]}`;
  380. }
  381. return name;
  382. };
  383. /**
  384. * Grabs the name of a given expression and returns it as a string or undefined. Has particular
  385. * handling for [Identifiers](https://github.com/estree/estree/blob/master/es5.md#identifier),
  386. * [ThisExpressions](https://github.com/estree/estree/blob/master/es5.md#identifier), and
  387. * [MetaProperties](https://github.com/estree/estree/blob/master/es2015.md#metaproperty) which is
  388. * specifically for handling the `new.target` meta property.
  389. * @param {Expression | SpreadElement | Super} expression expression
  390. * @returns {string | "this" | undefined} name or variable info
  391. */
  392. const getRootName = (expression) => {
  393. switch (expression.type) {
  394. case "Identifier":
  395. return expression.name;
  396. case "ThisExpression":
  397. return "this";
  398. case "MetaProperty":
  399. return `${expression.meta.name}.${expression.property.name}`;
  400. default:
  401. return undefined;
  402. }
  403. };
  404. /** @type {ParseOptions} */
  405. const defaultParserOptions = {
  406. sourceType: "module",
  407. ecmaVersion: "latest",
  408. ranges: false,
  409. locations: false,
  410. comments: false,
  411. // https://github.com/tc39/proposal-hashbang
  412. allowHashBang: true
  413. };
  414. const EMPTY_COMMENT_OPTIONS = {
  415. options: null,
  416. errors: null
  417. };
  418. const CLASS_NAME = "JavascriptParser";
  419. class JavascriptParser extends Parser {
  420. /**
  421. * @param {"module" | "script" | "auto"=} sourceType default source type
  422. * @param {{ parse?: ParseFunction }=} options parser options
  423. */
  424. constructor(sourceType = "auto", options = {}) {
  425. super();
  426. this.hooks = Object.freeze({
  427. /** @type {HookMap<SyncBailHook<[UnaryExpression], BasicEvaluatedExpression | null | undefined>>} */
  428. evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])),
  429. /** @type {HookMap<SyncBailHook<[Expression | SpreadElement | PrivateIdentifier | Super], BasicEvaluatedExpression | null | undefined>>} */
  430. evaluate: new HookMap(() => new SyncBailHook(["expression"])),
  431. /** @type {HookMap<SyncBailHook<[Identifier | ThisExpression | MemberExpression | MetaProperty], BasicEvaluatedExpression | null | undefined>>} */
  432. evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])),
  433. /** @type {HookMap<SyncBailHook<[Identifier | ThisExpression | MemberExpression], BasicEvaluatedExpression | null | undefined>>} */
  434. evaluateDefinedIdentifier: new HookMap(
  435. () => new SyncBailHook(["expression"])
  436. ),
  437. /** @type {HookMap<SyncBailHook<[NewExpression], BasicEvaluatedExpression | null | undefined>>} */
  438. evaluateNewExpression: new HookMap(
  439. () => new SyncBailHook(["expression"])
  440. ),
  441. /** @type {HookMap<SyncBailHook<[CallExpression], BasicEvaluatedExpression | null | undefined>>} */
  442. evaluateCallExpression: new HookMap(
  443. () => new SyncBailHook(["expression"])
  444. ),
  445. /** @type {HookMap<SyncBailHook<[CallExpression, BasicEvaluatedExpression], BasicEvaluatedExpression | null | undefined>>} */
  446. evaluateCallExpressionMember: new HookMap(
  447. () => new SyncBailHook(["expression", "param"])
  448. ),
  449. /** @type {HookMap<SyncBailHook<[Expression | Declaration | PrivateIdentifier | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration, number], boolean | void>>} */
  450. isPure: new HookMap(
  451. () => new SyncBailHook(["expression", "commentsStartPosition"])
  452. ),
  453. /** @type {SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration], boolean | void>} */
  454. preStatement: new SyncBailHook(["statement"]),
  455. /** @type {SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration], boolean | void>} */
  456. blockPreStatement: new SyncBailHook(["declaration"]),
  457. /** @type {SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration], boolean | void>} */
  458. statement: new SyncBailHook(["statement"]),
  459. /** @type {SyncBailHook<[IfStatement], boolean | void>} */
  460. statementIf: new SyncBailHook(["statement"]),
  461. /** @type {SyncBailHook<[Expression], ((walk: () => void) => void) | void>} */
  462. collectGuards: new SyncBailHook(["expression"]),
  463. /** @type {SyncBailHook<[Expression, ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration], boolean | void>} */
  464. classExtendsExpression: new SyncBailHook([
  465. "expression",
  466. "classDefinition"
  467. ]),
  468. /** @type {SyncBailHook<[MethodDefinition | PropertyDefinition | StaticBlock, ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration], boolean | void>} */
  469. classBodyElement: new SyncBailHook(["element", "classDefinition"]),
  470. /** @type {SyncBailHook<[Expression, MethodDefinition | PropertyDefinition, ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration], boolean | void>} */
  471. classBodyValue: new SyncBailHook([
  472. "expression",
  473. "element",
  474. "classDefinition"
  475. ]),
  476. /** @type {HookMap<SyncBailHook<[LabeledStatement], boolean | void>>} */
  477. label: new HookMap(() => new SyncBailHook(["statement"])),
  478. /** @type {SyncBailHook<[ImportDeclaration, ImportSource], boolean | void>} */
  479. import: new SyncBailHook(["statement", "source"]),
  480. /** @type {SyncBailHook<[ImportDeclaration, ImportSource, string | null, string], boolean | void>} */
  481. importSpecifier: new SyncBailHook([
  482. "statement",
  483. "source",
  484. "exportName",
  485. "identifierName"
  486. ]),
  487. /** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration], boolean | void>} */
  488. export: new SyncBailHook(["statement"]),
  489. /** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, ImportSource], boolean | void>} */
  490. exportImport: new SyncBailHook(["statement", "source"]),
  491. /** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration | ExportAllDeclaration, Declaration], boolean | void>} */
  492. exportDeclaration: new SyncBailHook(["statement", "declaration"]),
  493. /** @type {SyncBailHook<[ExportDefaultDeclaration, MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression], boolean | void>} */
  494. exportExpression: new SyncBailHook(["statement", "node"]),
  495. /** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration | ExportAllDeclaration, string, string, number | undefined], boolean | void>} */
  496. exportSpecifier: new SyncBailHook([
  497. "statement",
  498. "identifierName",
  499. "exportName",
  500. "index"
  501. ]),
  502. /** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, ImportSource, string | null, string | null, number | undefined], boolean | void>} */
  503. exportImportSpecifier: new SyncBailHook([
  504. "statement",
  505. "source",
  506. "identifierName",
  507. "exportName",
  508. "index"
  509. ]),
  510. /** @type {SyncBailHook<[VariableDeclarator, Statement], boolean | void>} */
  511. preDeclarator: new SyncBailHook(["declarator", "statement"]),
  512. /** @type {SyncBailHook<[VariableDeclarator, Statement], boolean | void>} */
  513. declarator: new SyncBailHook(["declarator", "statement"]),
  514. /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
  515. varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])),
  516. /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
  517. varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])),
  518. /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
  519. varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])),
  520. /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
  521. varDeclarationUsing: new HookMap(() => new SyncBailHook(["declaration"])),
  522. /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
  523. varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])),
  524. /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
  525. pattern: new HookMap(() => new SyncBailHook(["pattern"])),
  526. /** @type {SyncBailHook<[Expression], boolean | void>} */
  527. collectDestructuringAssignmentProperties: new SyncBailHook([
  528. "expression"
  529. ]),
  530. /** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
  531. canRename: new HookMap(() => new SyncBailHook(["initExpression"])),
  532. /** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
  533. rename: new HookMap(() => new SyncBailHook(["initExpression"])),
  534. /** @type {HookMap<SyncBailHook<[AssignmentExpression], boolean | void>>} */
  535. assign: new HookMap(() => new SyncBailHook(["expression"])),
  536. /** @type {HookMap<SyncBailHook<[AssignmentExpression, Members], boolean | void>>} */
  537. assignMemberChain: new HookMap(
  538. () => new SyncBailHook(["expression", "members"])
  539. ),
  540. /** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
  541. typeof: new HookMap(() => new SyncBailHook(["expression"])),
  542. /** @type {SyncBailHook<[ImportExpression, CallExpression?], boolean | void>} */
  543. importCall: new SyncBailHook(["expression", "importThen"]),
  544. /** @type {SyncBailHook<[Expression | ForOfStatement], boolean | void>} */
  545. topLevelAwait: new SyncBailHook(["expression"]),
  546. /** @type {HookMap<SyncBailHook<[CallExpression], boolean | void>>} */
  547. call: new HookMap(() => new SyncBailHook(["expression"])),
  548. /** Something like "a.b()" */
  549. /** @type {HookMap<SyncBailHook<[CallExpression, Members, MembersOptionals, MemberRanges], boolean | void>>} */
  550. callMemberChain: new HookMap(
  551. () =>
  552. new SyncBailHook([
  553. "expression",
  554. "members",
  555. "membersOptionals",
  556. "memberRanges"
  557. ])
  558. ),
  559. /** Something like "a.b().c.d" */
  560. /** @type {HookMap<SyncBailHook<[Expression, CalleeMembers, CallExpression, Members, MemberRanges], boolean | void>>} */
  561. memberChainOfCallMemberChain: new HookMap(
  562. () =>
  563. new SyncBailHook([
  564. "expression",
  565. "calleeMembers",
  566. "callExpression",
  567. "members",
  568. "memberRanges"
  569. ])
  570. ),
  571. /** Something like "a.b().c.d()"" */
  572. /** @type {HookMap<SyncBailHook<[CallExpression, CalleeMembers, CallExpression, Members, MemberRanges], boolean | void>>} */
  573. callMemberChainOfCallMemberChain: new HookMap(
  574. () =>
  575. new SyncBailHook([
  576. "expression",
  577. "calleeMembers",
  578. "innerCallExpression",
  579. "members",
  580. "memberRanges"
  581. ])
  582. ),
  583. /** @type {SyncBailHook<[ChainExpression], boolean | void>} */
  584. optionalChaining: new SyncBailHook(["optionalChaining"]),
  585. /** @type {HookMap<SyncBailHook<[NewExpression], boolean | void>>} */
  586. new: new HookMap(() => new SyncBailHook(["expression"])),
  587. /** @type {SyncBailHook<[BinaryExpression], boolean | void>} */
  588. binaryExpression: new SyncBailHook(["binaryExpression"]),
  589. /** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
  590. expression: new HookMap(() => new SyncBailHook(["expression"])),
  591. /** @type {HookMap<SyncBailHook<[MemberExpression, Members, MembersOptionals, MemberRanges], boolean | void>>} */
  592. expressionMemberChain: new HookMap(
  593. () =>
  594. new SyncBailHook([
  595. "expression",
  596. "members",
  597. "membersOptionals",
  598. "memberRanges"
  599. ])
  600. ),
  601. /** @type {HookMap<SyncBailHook<[MemberExpression, Members], boolean | void>>} */
  602. unhandledExpressionMemberChain: new HookMap(
  603. () => new SyncBailHook(["expression", "members"])
  604. ),
  605. /** @type {SyncBailHook<[ConditionalExpression], boolean | void>} */
  606. expressionConditionalOperator: new SyncBailHook(["expression"]),
  607. /** @type {SyncBailHook<[LogicalExpression], boolean | void>} */
  608. expressionLogicalOperator: new SyncBailHook(["expression"]),
  609. /** @type {SyncBailHook<[Program, Comment[]], boolean | void>} */
  610. program: new SyncBailHook(["ast", "comments"]),
  611. /** @type {SyncBailHook<[ThrowStatement | ReturnStatement], boolean | void>} */
  612. terminate: new SyncBailHook(["statement"]),
  613. /** @type {SyncBailHook<[Program, Comment[]], boolean | void>} */
  614. finish: new SyncBailHook(["ast", "comments"]),
  615. /** @type {SyncBailHook<[Statement], boolean | void>} */
  616. unusedStatement: new SyncBailHook(["statement"])
  617. });
  618. this.sourceType = sourceType;
  619. this.options = options;
  620. /** @type {ScopeInfo} */
  621. this.scope = /** @type {EXPECTED_ANY} */ (undefined);
  622. /** @type {JavascriptParserState} */
  623. this.state = /** @type {EXPECTED_ANY} */ (undefined);
  624. /** @type {Comment[] | undefined} */
  625. this.comments = undefined;
  626. /** @type {Set<number> | undefined} */
  627. this.semicolons = undefined;
  628. /** @type {StatementPath | undefined} */
  629. this.statementPath = undefined;
  630. /** @type {Statement | ModuleDeclaration | Expression | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | undefined} */
  631. this.prevStatement = undefined;
  632. /** @type {WeakMap<Expression, DestructuringAssignmentProperties> | undefined} */
  633. this.destructuringAssignmentProperties = undefined;
  634. /** @type {TagData | undefined} */
  635. this.currentTagData = undefined;
  636. this.magicCommentContext = createMagicCommentContext();
  637. this._initializeEvaluating();
  638. }
  639. _initializeEvaluating() {
  640. this.hooks.evaluate.for("Literal").tap(CLASS_NAME, (_expr) => {
  641. const expr = /** @type {Literal} */ (_expr);
  642. switch (typeof expr.value) {
  643. case "number":
  644. return new BasicEvaluatedExpression()
  645. .setNumber(expr.value)
  646. .setRange(/** @type {Range} */ (expr.range));
  647. case "bigint":
  648. return new BasicEvaluatedExpression()
  649. .setBigInt(expr.value)
  650. .setRange(/** @type {Range} */ (expr.range));
  651. case "string":
  652. return new BasicEvaluatedExpression()
  653. .setString(expr.value)
  654. .setRange(/** @type {Range} */ (expr.range));
  655. case "boolean":
  656. return new BasicEvaluatedExpression()
  657. .setBoolean(expr.value)
  658. .setRange(/** @type {Range} */ (expr.range));
  659. }
  660. if (expr.value === null) {
  661. return new BasicEvaluatedExpression()
  662. .setNull()
  663. .setRange(/** @type {Range} */ (expr.range));
  664. }
  665. if (expr.value instanceof RegExp) {
  666. return new BasicEvaluatedExpression()
  667. .setRegExp(expr.value)
  668. .setRange(/** @type {Range} */ (expr.range));
  669. }
  670. });
  671. this.hooks.evaluate.for("NewExpression").tap(CLASS_NAME, (_expr) => {
  672. const expr = /** @type {NewExpression} */ (_expr);
  673. const callee = expr.callee;
  674. if (callee.type !== "Identifier") return;
  675. if (callee.name !== "RegExp") {
  676. return this.callHooksForName(
  677. this.hooks.evaluateNewExpression,
  678. callee.name,
  679. expr
  680. );
  681. } else if (
  682. expr.arguments.length > 2 ||
  683. this.getVariableInfo("RegExp") !== "RegExp"
  684. ) {
  685. return;
  686. }
  687. /** @type {undefined | string} */
  688. let regExp;
  689. const arg1 = expr.arguments[0];
  690. if (arg1) {
  691. if (arg1.type === "SpreadElement") return;
  692. const evaluatedRegExp = this.evaluateExpression(arg1);
  693. if (!evaluatedRegExp) return;
  694. regExp = evaluatedRegExp.asString();
  695. if (!regExp) return;
  696. } else {
  697. return (
  698. new BasicEvaluatedExpression()
  699. // eslint-disable-next-line prefer-regex-literals
  700. .setRegExp(new RegExp(""))
  701. .setRange(/** @type {Range} */ (expr.range))
  702. );
  703. }
  704. /** @type {undefined | string} */
  705. let flags;
  706. const arg2 = expr.arguments[1];
  707. if (arg2) {
  708. if (arg2.type === "SpreadElement") return;
  709. const evaluatedFlags = this.evaluateExpression(arg2);
  710. if (!evaluatedFlags) return;
  711. if (!evaluatedFlags.isUndefined()) {
  712. flags = evaluatedFlags.asString();
  713. if (
  714. flags === undefined ||
  715. !BasicEvaluatedExpression.isValidRegExpFlags(flags)
  716. ) {
  717. return;
  718. }
  719. }
  720. }
  721. return new BasicEvaluatedExpression()
  722. .setRegExp(flags ? new RegExp(regExp, flags) : new RegExp(regExp))
  723. .setRange(/** @type {Range} */ (expr.range));
  724. });
  725. this.hooks.evaluate.for("LogicalExpression").tap(CLASS_NAME, (_expr) => {
  726. const expr = /** @type {LogicalExpression} */ (_expr);
  727. const left = this.evaluateExpression(expr.left);
  728. let returnRight = false;
  729. /** @type {boolean | undefined} */
  730. let allowedRight;
  731. if (expr.operator === "&&") {
  732. const leftAsBool = left.asBool();
  733. if (leftAsBool === false) {
  734. return left.setRange(/** @type {Range} */ (expr.range));
  735. }
  736. returnRight = leftAsBool === true;
  737. allowedRight = false;
  738. } else if (expr.operator === "||") {
  739. const leftAsBool = left.asBool();
  740. if (leftAsBool === true) {
  741. return left.setRange(/** @type {Range} */ (expr.range));
  742. }
  743. returnRight = leftAsBool === false;
  744. allowedRight = true;
  745. } else if (expr.operator === "??") {
  746. const leftAsNullish = left.asNullish();
  747. if (leftAsNullish === false) {
  748. return left.setRange(/** @type {Range} */ (expr.range));
  749. }
  750. if (leftAsNullish !== true) return;
  751. returnRight = true;
  752. } else {
  753. return;
  754. }
  755. const right = this.evaluateExpression(expr.right);
  756. if (returnRight) {
  757. if (left.couldHaveSideEffects()) right.setSideEffects();
  758. return right.setRange(/** @type {Range} */ (expr.range));
  759. }
  760. const asBool = right.asBool();
  761. if (allowedRight === true && asBool === true) {
  762. return new BasicEvaluatedExpression()
  763. .setRange(/** @type {Range} */ (expr.range))
  764. .setTruthy();
  765. } else if (allowedRight === false && asBool === false) {
  766. return new BasicEvaluatedExpression()
  767. .setRange(/** @type {Range} */ (expr.range))
  768. .setFalsy();
  769. }
  770. });
  771. /**
  772. * In simple logical cases, we can use valueAsExpression to assist us in evaluating the expression on
  773. * either side of a [BinaryExpression](https://github.com/estree/estree/blob/master/es5.md#binaryexpression).
  774. * This supports scenarios in webpack like conditionally `import()`'ing modules based on some simple evaluation:
  775. *
  776. * ```js
  777. * if (1 === 3) {
  778. * import("./moduleA"); // webpack will auto evaluate this and not import the modules
  779. * }
  780. * ```
  781. *
  782. * Additional scenarios include evaluation of strings inside of dynamic import statements:
  783. *
  784. * ```js
  785. * const foo = "foo";
  786. * const bar = "bar";
  787. *
  788. * import("./" + foo + bar); // webpack will auto evaluate this into import("./foobar")
  789. * ```
  790. * @param {boolean | number | bigint | string} value the value to convert to an expression
  791. * @param {BinaryExpression | UnaryExpression} expr the expression being evaluated
  792. * @param {boolean} sideEffects whether the expression has side effects
  793. * @returns {BasicEvaluatedExpression | undefined} the evaluated expression
  794. * @example
  795. *
  796. * ```js
  797. * const binaryExpr = new BinaryExpression("+",
  798. * { type: "Literal", value: 2 },
  799. * { type: "Literal", value: 3 }
  800. * );
  801. *
  802. * const leftValue = 2;
  803. * const rightValue = 3;
  804. *
  805. * const leftExpr = valueAsExpression(leftValue, binaryExpr.left, false);
  806. * const rightExpr = valueAsExpression(rightValue, binaryExpr.right, false);
  807. * const result = new BasicEvaluatedExpression()
  808. * .setNumber(leftExpr.number + rightExpr.number)
  809. * .setRange(binaryExpr.range);
  810. *
  811. * console.log(result.number); // Output: 5
  812. * ```
  813. */
  814. const valueAsExpression = (value, expr, sideEffects) => {
  815. switch (typeof value) {
  816. case "boolean":
  817. return new BasicEvaluatedExpression()
  818. .setBoolean(value)
  819. .setSideEffects(sideEffects)
  820. .setRange(/** @type {Range} */ (expr.range));
  821. case "number":
  822. return new BasicEvaluatedExpression()
  823. .setNumber(value)
  824. .setSideEffects(sideEffects)
  825. .setRange(/** @type {Range} */ (expr.range));
  826. case "bigint":
  827. return new BasicEvaluatedExpression()
  828. .setBigInt(value)
  829. .setSideEffects(sideEffects)
  830. .setRange(/** @type {Range} */ (expr.range));
  831. case "string":
  832. return new BasicEvaluatedExpression()
  833. .setString(value)
  834. .setSideEffects(sideEffects)
  835. .setRange(/** @type {Range} */ (expr.range));
  836. }
  837. };
  838. this.hooks.evaluate.for("BinaryExpression").tap(CLASS_NAME, (_expr) => {
  839. const expr = /** @type {BinaryExpression} */ (_expr);
  840. /**
  841. * Evaluates a binary expression if and only if it is a const operation (e.g. 1 + 2, "a" + "b", etc.).
  842. * @template T
  843. * @param {(leftOperand: T, rightOperand: T) => boolean | number | bigint | string} operandHandler the handler for the operation (e.g. (a, b) => a + b)
  844. * @returns {BasicEvaluatedExpression | undefined} the evaluated expression
  845. */
  846. const handleConstOperation = (operandHandler) => {
  847. const left = this.evaluateExpression(expr.left);
  848. if (!left.isCompileTimeValue()) return;
  849. const right = this.evaluateExpression(expr.right);
  850. if (!right.isCompileTimeValue()) return;
  851. const result = operandHandler(
  852. /** @type {T} */ (left.asCompileTimeValue()),
  853. /** @type {T} */ (right.asCompileTimeValue())
  854. );
  855. return valueAsExpression(
  856. result,
  857. expr,
  858. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  859. );
  860. };
  861. /**
  862. * Helper function to determine if two booleans are always different. This is used in `handleStrictEqualityComparison`
  863. * to determine if an expressions boolean or nullish conversion is equal or not.
  864. * @param {boolean} a first boolean to compare
  865. * @param {boolean} b second boolean to compare
  866. * @returns {boolean} true if the two booleans are always different, false otherwise
  867. */
  868. const isAlwaysDifferent = (a, b) =>
  869. (a === true && b === false) || (a === false && b === true);
  870. /**
  871. * @param {BasicEvaluatedExpression} left left
  872. * @param {BasicEvaluatedExpression} right right
  873. * @param {BasicEvaluatedExpression} res res
  874. * @param {boolean} eql true for "===" and false for "!=="
  875. * @returns {BasicEvaluatedExpression | undefined} result
  876. */
  877. const handleTemplateStringCompare = (left, right, res, eql) => {
  878. /**
  879. * @param {BasicEvaluatedExpression[]} parts parts
  880. * @returns {string} value
  881. */
  882. const getPrefix = (parts) => {
  883. let value = "";
  884. for (const p of parts) {
  885. const v = p.asString();
  886. if (v !== undefined) value += v;
  887. else break;
  888. }
  889. return value;
  890. };
  891. /**
  892. * @param {BasicEvaluatedExpression[]} parts parts
  893. * @returns {string} value
  894. */
  895. const getSuffix = (parts) => {
  896. let value = "";
  897. for (let i = parts.length - 1; i >= 0; i--) {
  898. const v = parts[i].asString();
  899. if (v !== undefined) value = v + value;
  900. else break;
  901. }
  902. return value;
  903. };
  904. const leftPrefix = getPrefix(
  905. /** @type {BasicEvaluatedExpression[]} */ (left.parts)
  906. );
  907. const rightPrefix = getPrefix(
  908. /** @type {BasicEvaluatedExpression[]} */ (right.parts)
  909. );
  910. const leftSuffix = getSuffix(
  911. /** @type {BasicEvaluatedExpression[]} */ (left.parts)
  912. );
  913. const rightSuffix = getSuffix(
  914. /** @type {BasicEvaluatedExpression[]} */ (right.parts)
  915. );
  916. const lenPrefix = Math.min(leftPrefix.length, rightPrefix.length);
  917. const lenSuffix = Math.min(leftSuffix.length, rightSuffix.length);
  918. const prefixMismatch =
  919. lenPrefix > 0 &&
  920. leftPrefix.slice(0, lenPrefix) !== rightPrefix.slice(0, lenPrefix);
  921. const suffixMismatch =
  922. lenSuffix > 0 &&
  923. leftSuffix.slice(-lenSuffix) !== rightSuffix.slice(-lenSuffix);
  924. if (prefixMismatch || suffixMismatch) {
  925. return res
  926. .setBoolean(!eql)
  927. .setSideEffects(
  928. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  929. );
  930. }
  931. };
  932. /**
  933. * Helper function to handle BinaryExpressions using strict equality comparisons (e.g. "===" and "!==").
  934. * @param {boolean} eql true for "===" and false for "!=="
  935. * @returns {BasicEvaluatedExpression | undefined} the evaluated expression
  936. */
  937. const handleStrictEqualityComparison = (eql) => {
  938. const left = this.evaluateExpression(expr.left);
  939. const right = this.evaluateExpression(expr.right);
  940. const res = new BasicEvaluatedExpression();
  941. res.setRange(/** @type {Range} */ (expr.range));
  942. const leftConst = left.isCompileTimeValue();
  943. const rightConst = right.isCompileTimeValue();
  944. if (leftConst && rightConst) {
  945. return res
  946. .setBoolean(
  947. eql === (left.asCompileTimeValue() === right.asCompileTimeValue())
  948. )
  949. .setSideEffects(
  950. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  951. );
  952. }
  953. if (left.isArray() && right.isArray()) {
  954. return res
  955. .setBoolean(!eql)
  956. .setSideEffects(
  957. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  958. );
  959. }
  960. if (left.isTemplateString() && right.isTemplateString()) {
  961. return handleTemplateStringCompare(left, right, res, eql);
  962. }
  963. const leftPrimitive = left.isPrimitiveType();
  964. const rightPrimitive = right.isPrimitiveType();
  965. if (
  966. // Primitive !== Object or
  967. // compile-time object types are never equal to something at runtime
  968. (leftPrimitive === false && (leftConst || rightPrimitive === true)) ||
  969. (rightPrimitive === false &&
  970. (rightConst || leftPrimitive === true)) ||
  971. // Different nullish or boolish status also means not equal
  972. isAlwaysDifferent(
  973. /** @type {boolean} */ (left.asBool()),
  974. /** @type {boolean} */ (right.asBool())
  975. ) ||
  976. isAlwaysDifferent(
  977. /** @type {boolean} */ (left.asNullish()),
  978. /** @type {boolean} */ (right.asNullish())
  979. )
  980. ) {
  981. return res
  982. .setBoolean(!eql)
  983. .setSideEffects(
  984. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  985. );
  986. }
  987. };
  988. /**
  989. * Helper function to handle BinaryExpressions using abstract equality comparisons (e.g. "==" and "!=").
  990. * @param {boolean} eql true for "==" and false for "!="
  991. * @returns {BasicEvaluatedExpression | undefined} the evaluated expression
  992. */
  993. const handleAbstractEqualityComparison = (eql) => {
  994. const left = this.evaluateExpression(expr.left);
  995. const right = this.evaluateExpression(expr.right);
  996. const res = new BasicEvaluatedExpression();
  997. res.setRange(/** @type {Range} */ (expr.range));
  998. const leftConst = left.isCompileTimeValue();
  999. const rightConst = right.isCompileTimeValue();
  1000. if (leftConst && rightConst) {
  1001. return res
  1002. .setBoolean(
  1003. eql ===
  1004. // eslint-disable-next-line eqeqeq
  1005. (left.asCompileTimeValue() == right.asCompileTimeValue())
  1006. )
  1007. .setSideEffects(
  1008. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  1009. );
  1010. }
  1011. if (left.isArray() && right.isArray()) {
  1012. return res
  1013. .setBoolean(!eql)
  1014. .setSideEffects(
  1015. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  1016. );
  1017. }
  1018. if (left.isTemplateString() && right.isTemplateString()) {
  1019. return handleTemplateStringCompare(left, right, res, eql);
  1020. }
  1021. };
  1022. if (expr.operator === "+") {
  1023. const left = this.evaluateExpression(expr.left);
  1024. const right = this.evaluateExpression(expr.right);
  1025. const res = new BasicEvaluatedExpression();
  1026. if (left.isString()) {
  1027. if (right.isString()) {
  1028. res.setString(
  1029. /** @type {string} */ (left.string) +
  1030. /** @type {string} */ (right.string)
  1031. );
  1032. } else if (right.isNumber()) {
  1033. res.setString(/** @type {string} */ (left.string) + right.number);
  1034. } else if (
  1035. right.isWrapped() &&
  1036. right.prefix &&
  1037. right.prefix.isString()
  1038. ) {
  1039. // "left" + ("prefix" + inner + "postfix")
  1040. // => ("leftPrefix" + inner + "postfix")
  1041. res.setWrapped(
  1042. new BasicEvaluatedExpression()
  1043. .setString(
  1044. /** @type {string} */ (left.string) +
  1045. /** @type {string} */ (right.prefix.string)
  1046. )
  1047. .setRange(
  1048. joinRanges(
  1049. /** @type {Range} */ (left.range),
  1050. /** @type {Range} */ (right.prefix.range)
  1051. )
  1052. ),
  1053. right.postfix,
  1054. right.wrappedInnerExpressions
  1055. );
  1056. } else if (right.isWrapped()) {
  1057. // "left" + ([null] + inner + "postfix")
  1058. // => ("left" + inner + "postfix")
  1059. res.setWrapped(left, right.postfix, right.wrappedInnerExpressions);
  1060. } else {
  1061. // "left" + expr
  1062. // => ("left" + expr + "")
  1063. res.setWrapped(left, null, [right]);
  1064. }
  1065. } else if (left.isNumber()) {
  1066. if (right.isString()) {
  1067. res.setString(left.number + /** @type {string} */ (right.string));
  1068. } else if (right.isNumber()) {
  1069. res.setNumber(
  1070. /** @type {number} */ (left.number) +
  1071. /** @type {number} */ (right.number)
  1072. );
  1073. } else {
  1074. return;
  1075. }
  1076. } else if (left.isBigInt()) {
  1077. if (right.isBigInt()) {
  1078. res.setBigInt(
  1079. /** @type {bigint} */ (left.bigint) +
  1080. /** @type {bigint} */ (right.bigint)
  1081. );
  1082. }
  1083. } else if (left.isWrapped()) {
  1084. if (left.postfix && left.postfix.isString() && right.isString()) {
  1085. // ("prefix" + inner + "postfix") + "right"
  1086. // => ("prefix" + inner + "postfixRight")
  1087. res.setWrapped(
  1088. left.prefix,
  1089. new BasicEvaluatedExpression()
  1090. .setString(
  1091. /** @type {string} */ (left.postfix.string) +
  1092. /** @type {string} */ (right.string)
  1093. )
  1094. .setRange(
  1095. joinRanges(
  1096. /** @type {Range} */ (left.postfix.range),
  1097. /** @type {Range} */ (right.range)
  1098. )
  1099. ),
  1100. left.wrappedInnerExpressions
  1101. );
  1102. } else if (
  1103. left.postfix &&
  1104. left.postfix.isString() &&
  1105. right.isNumber()
  1106. ) {
  1107. // ("prefix" + inner + "postfix") + 123
  1108. // => ("prefix" + inner + "postfix123")
  1109. res.setWrapped(
  1110. left.prefix,
  1111. new BasicEvaluatedExpression()
  1112. .setString(
  1113. /** @type {string} */ (left.postfix.string) +
  1114. /** @type {number} */ (right.number)
  1115. )
  1116. .setRange(
  1117. joinRanges(
  1118. /** @type {Range} */ (left.postfix.range),
  1119. /** @type {Range} */ (right.range)
  1120. )
  1121. ),
  1122. left.wrappedInnerExpressions
  1123. );
  1124. } else if (right.isString()) {
  1125. // ("prefix" + inner + [null]) + "right"
  1126. // => ("prefix" + inner + "right")
  1127. res.setWrapped(left.prefix, right, left.wrappedInnerExpressions);
  1128. } else if (right.isNumber()) {
  1129. // ("prefix" + inner + [null]) + 123
  1130. // => ("prefix" + inner + "123")
  1131. res.setWrapped(
  1132. left.prefix,
  1133. new BasicEvaluatedExpression()
  1134. .setString(String(right.number))
  1135. .setRange(/** @type {Range} */ (right.range)),
  1136. left.wrappedInnerExpressions
  1137. );
  1138. } else if (right.isWrapped()) {
  1139. // ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2")
  1140. // ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2")
  1141. res.setWrapped(
  1142. left.prefix,
  1143. right.postfix,
  1144. left.wrappedInnerExpressions &&
  1145. right.wrappedInnerExpressions && [
  1146. ...left.wrappedInnerExpressions,
  1147. ...(left.postfix ? [left.postfix] : []),
  1148. ...(right.prefix ? [right.prefix] : []),
  1149. ...right.wrappedInnerExpressions
  1150. ]
  1151. );
  1152. } else {
  1153. // ("prefix" + inner + postfix) + expr
  1154. // => ("prefix" + inner + postfix + expr + [null])
  1155. res.setWrapped(
  1156. left.prefix,
  1157. null,
  1158. left.wrappedInnerExpressions && [
  1159. ...left.wrappedInnerExpressions,
  1160. ...(left.postfix ? [left.postfix, right] : [right])
  1161. ]
  1162. );
  1163. }
  1164. } else if (right.isString()) {
  1165. // left + "right"
  1166. // => ([null] + left + "right")
  1167. res.setWrapped(null, right, [left]);
  1168. } else if (right.isWrapped()) {
  1169. // left + (prefix + inner + "postfix")
  1170. // => ([null] + left + prefix + inner + "postfix")
  1171. res.setWrapped(
  1172. null,
  1173. right.postfix,
  1174. right.wrappedInnerExpressions && [
  1175. ...(right.prefix ? [left, right.prefix] : [left]),
  1176. ...right.wrappedInnerExpressions
  1177. ]
  1178. );
  1179. } else {
  1180. return;
  1181. }
  1182. if (left.couldHaveSideEffects() || right.couldHaveSideEffects()) {
  1183. res.setSideEffects();
  1184. }
  1185. res.setRange(/** @type {Range} */ (expr.range));
  1186. return res;
  1187. } else if (expr.operator === "-") {
  1188. return handleConstOperation((l, r) => l - r);
  1189. } else if (expr.operator === "*") {
  1190. return handleConstOperation((l, r) => l * r);
  1191. } else if (expr.operator === "/") {
  1192. return handleConstOperation((l, r) => l / r);
  1193. } else if (expr.operator === "**") {
  1194. return handleConstOperation((l, r) => l ** r);
  1195. } else if (expr.operator === "===") {
  1196. return handleStrictEqualityComparison(true);
  1197. } else if (expr.operator === "==") {
  1198. return handleAbstractEqualityComparison(true);
  1199. } else if (expr.operator === "!==") {
  1200. return handleStrictEqualityComparison(false);
  1201. } else if (expr.operator === "!=") {
  1202. return handleAbstractEqualityComparison(false);
  1203. } else if (expr.operator === "&") {
  1204. return handleConstOperation((l, r) => l & r);
  1205. } else if (expr.operator === "|") {
  1206. return handleConstOperation((l, r) => l | r);
  1207. } else if (expr.operator === "^") {
  1208. return handleConstOperation((l, r) => l ^ r);
  1209. } else if (expr.operator === ">>>") {
  1210. return handleConstOperation((l, r) => l >>> r);
  1211. } else if (expr.operator === ">>") {
  1212. return handleConstOperation((l, r) => l >> r);
  1213. } else if (expr.operator === "<<") {
  1214. return handleConstOperation((l, r) => l << r);
  1215. } else if (expr.operator === "<") {
  1216. return handleConstOperation((l, r) => l < r);
  1217. } else if (expr.operator === ">") {
  1218. return handleConstOperation((l, r) => l > r);
  1219. } else if (expr.operator === "<=") {
  1220. return handleConstOperation((l, r) => l <= r);
  1221. } else if (expr.operator === ">=") {
  1222. return handleConstOperation((l, r) => l >= r);
  1223. }
  1224. });
  1225. this.hooks.evaluate.for("UnaryExpression").tap(CLASS_NAME, (_expr) => {
  1226. const expr = /** @type {UnaryExpression} */ (_expr);
  1227. /**
  1228. * Evaluates a UnaryExpression if and only if it is a basic const operator (e.g. +a, -a, ~a).
  1229. * @template T
  1230. * @param {(operand: T) => boolean | number | bigint | string} operandHandler handler for the operand
  1231. * @returns {BasicEvaluatedExpression | undefined} evaluated expression
  1232. */
  1233. const handleConstOperation = (operandHandler) => {
  1234. const argument = this.evaluateExpression(expr.argument);
  1235. if (!argument.isCompileTimeValue()) return;
  1236. const result = operandHandler(
  1237. /** @type {T} */ (argument.asCompileTimeValue())
  1238. );
  1239. return valueAsExpression(result, expr, argument.couldHaveSideEffects());
  1240. };
  1241. if (expr.operator === "typeof") {
  1242. switch (expr.argument.type) {
  1243. case "Identifier": {
  1244. const res = this.callHooksForName(
  1245. this.hooks.evaluateTypeof,
  1246. expr.argument.name,
  1247. expr
  1248. );
  1249. if (res !== undefined) return res;
  1250. break;
  1251. }
  1252. case "MetaProperty": {
  1253. const res = this.callHooksForName(
  1254. this.hooks.evaluateTypeof,
  1255. /** @type {string} */
  1256. (getRootName(expr.argument)),
  1257. expr
  1258. );
  1259. if (res !== undefined) return res;
  1260. break;
  1261. }
  1262. case "MemberExpression": {
  1263. const res = this.callHooksForExpression(
  1264. this.hooks.evaluateTypeof,
  1265. expr.argument,
  1266. expr
  1267. );
  1268. if (res !== undefined) return res;
  1269. break;
  1270. }
  1271. case "ChainExpression": {
  1272. const res = this.callHooksForExpression(
  1273. this.hooks.evaluateTypeof,
  1274. expr.argument.expression,
  1275. expr
  1276. );
  1277. if (res !== undefined) return res;
  1278. break;
  1279. }
  1280. case "FunctionExpression": {
  1281. return new BasicEvaluatedExpression()
  1282. .setString("function")
  1283. .setRange(/** @type {Range} */ (expr.range));
  1284. }
  1285. }
  1286. const arg = this.evaluateExpression(expr.argument);
  1287. if (arg.isUnknown()) return;
  1288. if (arg.isString()) {
  1289. return new BasicEvaluatedExpression()
  1290. .setString("string")
  1291. .setRange(/** @type {Range} */ (expr.range));
  1292. }
  1293. if (arg.isWrapped()) {
  1294. return new BasicEvaluatedExpression()
  1295. .setString("string")
  1296. .setSideEffects()
  1297. .setRange(/** @type {Range} */ (expr.range));
  1298. }
  1299. if (arg.isUndefined()) {
  1300. return new BasicEvaluatedExpression()
  1301. .setString("undefined")
  1302. .setRange(/** @type {Range} */ (expr.range));
  1303. }
  1304. if (arg.isNumber()) {
  1305. return new BasicEvaluatedExpression()
  1306. .setString("number")
  1307. .setRange(/** @type {Range} */ (expr.range));
  1308. }
  1309. if (arg.isBigInt()) {
  1310. return new BasicEvaluatedExpression()
  1311. .setString("bigint")
  1312. .setRange(/** @type {Range} */ (expr.range));
  1313. }
  1314. if (arg.isBoolean()) {
  1315. return new BasicEvaluatedExpression()
  1316. .setString("boolean")
  1317. .setRange(/** @type {Range} */ (expr.range));
  1318. }
  1319. if (arg.isConstArray() || arg.isRegExp() || arg.isNull()) {
  1320. return new BasicEvaluatedExpression()
  1321. .setString("object")
  1322. .setRange(/** @type {Range} */ (expr.range));
  1323. }
  1324. if (arg.isArray()) {
  1325. return new BasicEvaluatedExpression()
  1326. .setString("object")
  1327. .setSideEffects(arg.couldHaveSideEffects())
  1328. .setRange(/** @type {Range} */ (expr.range));
  1329. }
  1330. } else if (expr.operator === "!") {
  1331. const argument = this.evaluateExpression(expr.argument);
  1332. const bool = argument.asBool();
  1333. if (typeof bool !== "boolean") return;
  1334. return new BasicEvaluatedExpression()
  1335. .setBoolean(!bool)
  1336. .setSideEffects(argument.couldHaveSideEffects())
  1337. .setRange(/** @type {Range} */ (expr.range));
  1338. } else if (expr.operator === "~") {
  1339. return handleConstOperation((v) => ~v);
  1340. } else if (expr.operator === "+") {
  1341. // eslint-disable-next-line no-implicit-coercion
  1342. return handleConstOperation((v) => +v);
  1343. } else if (expr.operator === "-") {
  1344. return handleConstOperation((v) => -v);
  1345. }
  1346. });
  1347. this.hooks.evaluateTypeof
  1348. .for("undefined")
  1349. .tap(CLASS_NAME, (expr) =>
  1350. new BasicEvaluatedExpression()
  1351. .setString("undefined")
  1352. .setRange(/** @type {Range} */ (expr.range))
  1353. );
  1354. this.hooks.evaluate.for("Identifier").tap(CLASS_NAME, (expr) => {
  1355. if (/** @type {Identifier} */ (expr).name === "undefined") {
  1356. return new BasicEvaluatedExpression()
  1357. .setUndefined()
  1358. .setRange(/** @type {Range} */ (expr.range));
  1359. }
  1360. });
  1361. /**
  1362. * @param {"Identifier" | "ThisExpression" | "MemberExpression"} exprType expression type name
  1363. * @param {(node: Expression | SpreadElement) => GetInfoResult | undefined} getInfo get info
  1364. * @returns {void}
  1365. */
  1366. const tapEvaluateWithVariableInfo = (exprType, getInfo) => {
  1367. /** @type {Expression | undefined} */
  1368. let cachedExpression;
  1369. /** @type {GetInfoResult | undefined} */
  1370. let cachedInfo;
  1371. this.hooks.evaluate.for(exprType).tap(CLASS_NAME, (expr) => {
  1372. const expression =
  1373. /** @type {Identifier | ThisExpression | MemberExpression} */ (expr);
  1374. const info = getInfo(expression);
  1375. if (info !== undefined) {
  1376. return this.callHooksForInfoWithFallback(
  1377. this.hooks.evaluateIdentifier,
  1378. info.name,
  1379. (_name) => {
  1380. cachedExpression = expression;
  1381. cachedInfo = info;
  1382. return undefined;
  1383. },
  1384. (name) => {
  1385. const hook = this.hooks.evaluateDefinedIdentifier.get(name);
  1386. if (hook !== undefined) {
  1387. return hook.call(expression);
  1388. }
  1389. },
  1390. expression
  1391. );
  1392. }
  1393. });
  1394. this.hooks.evaluate
  1395. .for(exprType)
  1396. .tap({ name: CLASS_NAME, stage: 100 }, (expr) => {
  1397. const expression =
  1398. /** @type {Identifier | ThisExpression | MemberExpression} */
  1399. (expr);
  1400. const info =
  1401. cachedExpression === expression ? cachedInfo : getInfo(expression);
  1402. if (info !== undefined) {
  1403. return new BasicEvaluatedExpression()
  1404. .setIdentifier(
  1405. info.name,
  1406. info.rootInfo,
  1407. info.getMembers,
  1408. info.getMembersOptionals,
  1409. info.getMemberRanges
  1410. )
  1411. .setRange(/** @type {Range} */ (expression.range));
  1412. }
  1413. });
  1414. this.hooks.finish.tap(CLASS_NAME, () => {
  1415. // Cleanup for GC
  1416. cachedExpression = cachedInfo = undefined;
  1417. });
  1418. };
  1419. tapEvaluateWithVariableInfo("Identifier", (expr) => {
  1420. const info = this.getVariableInfo(/** @type {Identifier} */ (expr).name);
  1421. if (
  1422. typeof info === "string" ||
  1423. (info instanceof VariableInfo && (info.isFree() || info.isTagged()))
  1424. ) {
  1425. return {
  1426. name: info,
  1427. rootInfo: info,
  1428. getMembers: () => [],
  1429. getMembersOptionals: () => [],
  1430. getMemberRanges: () => []
  1431. };
  1432. }
  1433. });
  1434. tapEvaluateWithVariableInfo("ThisExpression", (_expr) => {
  1435. const info = this.getVariableInfo("this");
  1436. if (
  1437. typeof info === "string" ||
  1438. (info instanceof VariableInfo && (info.isFree() || info.isTagged()))
  1439. ) {
  1440. return {
  1441. name: info,
  1442. rootInfo: info,
  1443. getMembers: () => [],
  1444. getMembersOptionals: () => [],
  1445. getMemberRanges: () => []
  1446. };
  1447. }
  1448. });
  1449. this.hooks.evaluate.for("MetaProperty").tap(CLASS_NAME, (expr) => {
  1450. const metaProperty = /** @type {MetaProperty} */ (expr);
  1451. return this.callHooksForName(
  1452. this.hooks.evaluateIdentifier,
  1453. /** @type {string} */
  1454. (getRootName(metaProperty)),
  1455. metaProperty
  1456. );
  1457. });
  1458. tapEvaluateWithVariableInfo("MemberExpression", (expr) =>
  1459. this.getMemberExpressionInfo(
  1460. /** @type {MemberExpression} */ (expr),
  1461. ALLOWED_MEMBER_TYPES_EXPRESSION
  1462. )
  1463. );
  1464. this.hooks.evaluate.for("CallExpression").tap(CLASS_NAME, (_expr) => {
  1465. const expr = /** @type {CallExpression} */ (_expr);
  1466. if (
  1467. expr.callee.type === "MemberExpression" &&
  1468. expr.callee.property.type ===
  1469. (expr.callee.computed ? "Literal" : "Identifier")
  1470. ) {
  1471. // type Super also possible here
  1472. const param = this.evaluateExpression(
  1473. /** @type {Expression} */ (expr.callee.object)
  1474. );
  1475. const property =
  1476. expr.callee.property.type === "Literal"
  1477. ? `${expr.callee.property.value}`
  1478. : expr.callee.property.name;
  1479. const hook = this.hooks.evaluateCallExpressionMember.get(property);
  1480. if (hook !== undefined) {
  1481. return hook.call(expr, param);
  1482. }
  1483. } else if (expr.callee.type === "Identifier") {
  1484. return this.callHooksForName(
  1485. this.hooks.evaluateCallExpression,
  1486. expr.callee.name,
  1487. expr
  1488. );
  1489. }
  1490. });
  1491. this.hooks.evaluateCallExpressionMember
  1492. .for("indexOf")
  1493. .tap(CLASS_NAME, (expr, param) => {
  1494. if (!param.isString()) return;
  1495. if (expr.arguments.length === 0) return;
  1496. const [arg1, arg2] = expr.arguments;
  1497. if (arg1.type === "SpreadElement") return;
  1498. const arg1Eval = this.evaluateExpression(arg1);
  1499. if (!arg1Eval.isString()) return;
  1500. const arg1Value = /** @type {string} */ (arg1Eval.string);
  1501. /** @type {number} */
  1502. let result;
  1503. if (arg2) {
  1504. if (arg2.type === "SpreadElement") return;
  1505. const arg2Eval = this.evaluateExpression(arg2);
  1506. if (!arg2Eval.isNumber()) return;
  1507. result = /** @type {string} */ (param.string).indexOf(
  1508. arg1Value,
  1509. arg2Eval.number
  1510. );
  1511. } else {
  1512. result = /** @type {string} */ (param.string).indexOf(arg1Value);
  1513. }
  1514. return new BasicEvaluatedExpression()
  1515. .setNumber(result)
  1516. .setSideEffects(param.couldHaveSideEffects())
  1517. .setRange(/** @type {Range} */ (expr.range));
  1518. });
  1519. this.hooks.evaluateCallExpressionMember
  1520. .for("replace")
  1521. .tap(CLASS_NAME, (expr, param) => {
  1522. if (!param.isString()) return;
  1523. if (expr.arguments.length !== 2) return;
  1524. if (expr.arguments[0].type === "SpreadElement") return;
  1525. if (expr.arguments[1].type === "SpreadElement") return;
  1526. const arg1 = this.evaluateExpression(expr.arguments[0]);
  1527. const arg2 = this.evaluateExpression(expr.arguments[1]);
  1528. if (!arg1.isString() && !arg1.isRegExp()) return;
  1529. const arg1Value = /** @type {string | RegExp} */ (
  1530. arg1.regExp || arg1.string
  1531. );
  1532. if (!arg2.isString()) return;
  1533. const arg2Value = /** @type {string} */ (arg2.string);
  1534. return new BasicEvaluatedExpression()
  1535. .setString(
  1536. /** @type {string} */ (param.string).replace(arg1Value, arg2Value)
  1537. )
  1538. .setSideEffects(param.couldHaveSideEffects())
  1539. .setRange(/** @type {Range} */ (expr.range));
  1540. });
  1541. for (const fn of ["substr", "substring", "slice"]) {
  1542. this.hooks.evaluateCallExpressionMember
  1543. .for(fn)
  1544. .tap(CLASS_NAME, (expr, param) => {
  1545. if (!param.isString()) return;
  1546. /** @type {BasicEvaluatedExpression} */
  1547. let arg1;
  1548. /** @type {string} */
  1549. let result;
  1550. const str = /** @type {string} */ (param.string);
  1551. switch (expr.arguments.length) {
  1552. case 1:
  1553. if (expr.arguments[0].type === "SpreadElement") return;
  1554. arg1 = this.evaluateExpression(expr.arguments[0]);
  1555. if (!arg1.isNumber()) return;
  1556. result = str[
  1557. /** @type {"substr" | "substring" | "slice"} */ (fn)
  1558. ](/** @type {number} */ (arg1.number));
  1559. break;
  1560. case 2: {
  1561. if (expr.arguments[0].type === "SpreadElement") return;
  1562. if (expr.arguments[1].type === "SpreadElement") return;
  1563. arg1 = this.evaluateExpression(expr.arguments[0]);
  1564. const arg2 = this.evaluateExpression(expr.arguments[1]);
  1565. if (!arg1.isNumber()) return;
  1566. if (!arg2.isNumber()) return;
  1567. result = str[
  1568. /** @type {"substr" | "substring" | "slice"} */ (fn)
  1569. ](
  1570. /** @type {number} */ (arg1.number),
  1571. /** @type {number} */ (arg2.number)
  1572. );
  1573. break;
  1574. }
  1575. default:
  1576. return;
  1577. }
  1578. return new BasicEvaluatedExpression()
  1579. .setString(result)
  1580. .setSideEffects(param.couldHaveSideEffects())
  1581. .setRange(/** @type {Range} */ (expr.range));
  1582. });
  1583. }
  1584. /**
  1585. * @param {"cooked" | "raw"} kind kind of values to get
  1586. * @param {TemplateLiteral} templateLiteralExpr TemplateLiteral expr
  1587. * @returns {{ quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[] }} Simplified template
  1588. */
  1589. const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => {
  1590. /** @type {BasicEvaluatedExpression[]} */
  1591. const quasis = [];
  1592. /** @type {BasicEvaluatedExpression[]} */
  1593. const parts = [];
  1594. for (let i = 0; i < templateLiteralExpr.quasis.length; i++) {
  1595. const quasiExpr = templateLiteralExpr.quasis[i];
  1596. const quasi = quasiExpr.value[kind];
  1597. if (i > 0) {
  1598. const prevExpr = parts[parts.length - 1];
  1599. const expr = this.evaluateExpression(
  1600. templateLiteralExpr.expressions[i - 1]
  1601. );
  1602. const exprAsString = expr.asString();
  1603. if (
  1604. typeof exprAsString === "string" &&
  1605. !expr.couldHaveSideEffects()
  1606. ) {
  1607. // We can merge quasi + expr + quasi when expr
  1608. // is a const string
  1609. prevExpr.setString(prevExpr.string + exprAsString + quasi);
  1610. prevExpr.setRange([
  1611. /** @type {Range} */ (prevExpr.range)[0],
  1612. /** @type {Range} */ (quasiExpr.range)[1]
  1613. ]);
  1614. // We unset the expression as it doesn't match to a single expression
  1615. prevExpr.setExpression(undefined);
  1616. continue;
  1617. }
  1618. parts.push(expr);
  1619. }
  1620. const part = new BasicEvaluatedExpression()
  1621. .setString(/** @type {string} */ (quasi))
  1622. .setRange(/** @type {Range} */ (quasiExpr.range))
  1623. .setExpression(quasiExpr);
  1624. quasis.push(part);
  1625. parts.push(part);
  1626. }
  1627. return {
  1628. quasis,
  1629. parts
  1630. };
  1631. };
  1632. this.hooks.evaluate.for("TemplateLiteral").tap(CLASS_NAME, (_node) => {
  1633. const node = /** @type {TemplateLiteral} */ (_node);
  1634. const { quasis, parts } = getSimplifiedTemplateResult("cooked", node);
  1635. if (parts.length === 1) {
  1636. return parts[0].setRange(/** @type {Range} */ (node.range));
  1637. }
  1638. return new BasicEvaluatedExpression()
  1639. .setTemplateString(quasis, parts, "cooked")
  1640. .setRange(/** @type {Range} */ (node.range));
  1641. });
  1642. this.hooks.evaluate
  1643. .for("TaggedTemplateExpression")
  1644. .tap(CLASS_NAME, (_node) => {
  1645. const node = /** @type {TaggedTemplateExpression} */ (_node);
  1646. const tag = this.evaluateExpression(node.tag);
  1647. if (tag.isIdentifier() && tag.identifier === "String.raw") {
  1648. const { quasis, parts } = getSimplifiedTemplateResult(
  1649. "raw",
  1650. node.quasi
  1651. );
  1652. return new BasicEvaluatedExpression()
  1653. .setTemplateString(quasis, parts, "raw")
  1654. .setRange(/** @type {Range} */ (node.range));
  1655. }
  1656. });
  1657. this.hooks.evaluateCallExpressionMember
  1658. .for("concat")
  1659. .tap(CLASS_NAME, (expr, param) => {
  1660. if (!param.isString() && !param.isWrapped()) return;
  1661. /** @type {undefined | BasicEvaluatedExpression} */
  1662. let stringSuffix;
  1663. let hasUnknownParams = false;
  1664. /** @type {BasicEvaluatedExpression[]} */
  1665. const innerExpressions = [];
  1666. for (let i = expr.arguments.length - 1; i >= 0; i--) {
  1667. const arg = expr.arguments[i];
  1668. if (arg.type === "SpreadElement") return;
  1669. const argExpr = this.evaluateExpression(arg);
  1670. if (
  1671. hasUnknownParams ||
  1672. (!argExpr.isString() && !argExpr.isNumber())
  1673. ) {
  1674. hasUnknownParams = true;
  1675. innerExpressions.push(argExpr);
  1676. continue;
  1677. }
  1678. const value = argExpr.isString()
  1679. ? /** @type {string} */ (argExpr.string)
  1680. : String(argExpr.number);
  1681. /** @type {string} */
  1682. const newString =
  1683. value +
  1684. (stringSuffix ? /** @type {string} */ (stringSuffix.string) : "");
  1685. const newRange = /** @type {Range} */ ([
  1686. /** @type {Range} */ (argExpr.range)[0],
  1687. /** @type {Range} */ ((stringSuffix || argExpr).range)[1]
  1688. ]);
  1689. stringSuffix = new BasicEvaluatedExpression()
  1690. .setString(newString)
  1691. .setSideEffects(
  1692. (stringSuffix && stringSuffix.couldHaveSideEffects()) ||
  1693. argExpr.couldHaveSideEffects()
  1694. )
  1695. .setRange(newRange);
  1696. }
  1697. if (hasUnknownParams) {
  1698. const prefix = param.isString() ? param : param.prefix;
  1699. const inner =
  1700. param.isWrapped() && param.wrappedInnerExpressions
  1701. ? [
  1702. ...param.wrappedInnerExpressions,
  1703. ...innerExpressions.reverse()
  1704. ]
  1705. : innerExpressions.reverse();
  1706. return new BasicEvaluatedExpression()
  1707. .setWrapped(prefix, stringSuffix, inner)
  1708. .setRange(/** @type {Range} */ (expr.range));
  1709. } else if (param.isWrapped()) {
  1710. const postfix = stringSuffix || param.postfix;
  1711. const inner = param.wrappedInnerExpressions
  1712. ? [...param.wrappedInnerExpressions, ...innerExpressions.reverse()]
  1713. : innerExpressions.reverse();
  1714. return new BasicEvaluatedExpression()
  1715. .setWrapped(param.prefix, postfix, inner)
  1716. .setRange(/** @type {Range} */ (expr.range));
  1717. }
  1718. const newString =
  1719. /** @type {string} */ (param.string) +
  1720. (stringSuffix ? stringSuffix.string : "");
  1721. return new BasicEvaluatedExpression()
  1722. .setString(newString)
  1723. .setSideEffects(
  1724. (stringSuffix && stringSuffix.couldHaveSideEffects()) ||
  1725. param.couldHaveSideEffects()
  1726. )
  1727. .setRange(/** @type {Range} */ (expr.range));
  1728. });
  1729. this.hooks.evaluateCallExpressionMember
  1730. .for("split")
  1731. .tap(CLASS_NAME, (expr, param) => {
  1732. if (!param.isString()) return;
  1733. if (expr.arguments.length !== 1) return;
  1734. if (expr.arguments[0].type === "SpreadElement") return;
  1735. /** @type {string[]} */
  1736. let result;
  1737. const arg = this.evaluateExpression(expr.arguments[0]);
  1738. if (arg.isString()) {
  1739. result =
  1740. /** @type {string} */
  1741. (param.string).split(/** @type {string} */ (arg.string));
  1742. } else if (arg.isRegExp()) {
  1743. result = /** @type {string} */ (param.string).split(
  1744. /** @type {RegExp} */ (arg.regExp)
  1745. );
  1746. } else {
  1747. return;
  1748. }
  1749. return new BasicEvaluatedExpression()
  1750. .setArray(result)
  1751. .setSideEffects(param.couldHaveSideEffects())
  1752. .setRange(/** @type {Range} */ (expr.range));
  1753. });
  1754. this.hooks.evaluate
  1755. .for("ConditionalExpression")
  1756. .tap(CLASS_NAME, (_expr) => {
  1757. const expr = /** @type {ConditionalExpression} */ (_expr);
  1758. const condition = this.evaluateExpression(expr.test);
  1759. const conditionValue = condition.asBool();
  1760. /** @type {BasicEvaluatedExpression} */
  1761. let res;
  1762. if (conditionValue === undefined) {
  1763. const consequent = this.evaluateExpression(expr.consequent);
  1764. const alternate = this.evaluateExpression(expr.alternate);
  1765. res = new BasicEvaluatedExpression();
  1766. if (consequent.isConditional()) {
  1767. res.setOptions(
  1768. /** @type {BasicEvaluatedExpression[]} */ (consequent.options)
  1769. );
  1770. } else {
  1771. res.setOptions([consequent]);
  1772. }
  1773. if (alternate.isConditional()) {
  1774. res.addOptions(
  1775. /** @type {BasicEvaluatedExpression[]} */ (alternate.options)
  1776. );
  1777. } else {
  1778. res.addOptions([alternate]);
  1779. }
  1780. } else {
  1781. res = this.evaluateExpression(
  1782. conditionValue ? expr.consequent : expr.alternate
  1783. );
  1784. if (condition.couldHaveSideEffects()) res.setSideEffects();
  1785. }
  1786. res.setRange(/** @type {Range} */ (expr.range));
  1787. return res;
  1788. });
  1789. this.hooks.evaluate.for("ArrayExpression").tap(CLASS_NAME, (_expr) => {
  1790. const expr = /** @type {ArrayExpression} */ (_expr);
  1791. const items = expr.elements.map(
  1792. (element) =>
  1793. element !== null &&
  1794. element.type !== "SpreadElement" &&
  1795. this.evaluateExpression(element)
  1796. );
  1797. if (!items.every(Boolean)) return;
  1798. return new BasicEvaluatedExpression()
  1799. .setItems(/** @type {BasicEvaluatedExpression[]} */ (items))
  1800. .setRange(/** @type {Range} */ (expr.range));
  1801. });
  1802. this.hooks.evaluate.for("ChainExpression").tap(CLASS_NAME, (_expr) => {
  1803. const expr = /** @type {ChainExpression} */ (_expr);
  1804. /** @type {Expression[]} */
  1805. const optionalExpressionsStack = [];
  1806. /** @type {Expression | Super} */
  1807. let next = expr.expression;
  1808. while (
  1809. next.type === "MemberExpression" ||
  1810. next.type === "CallExpression"
  1811. ) {
  1812. if (next.type === "MemberExpression") {
  1813. if (next.optional) {
  1814. // SuperNode can not be optional
  1815. optionalExpressionsStack.push(
  1816. /** @type {Expression} */ (next.object)
  1817. );
  1818. }
  1819. next = next.object;
  1820. } else {
  1821. if (next.optional) {
  1822. // SuperNode can not be optional
  1823. optionalExpressionsStack.push(
  1824. /** @type {Expression} */ (next.callee)
  1825. );
  1826. }
  1827. next = next.callee;
  1828. }
  1829. }
  1830. while (optionalExpressionsStack.length > 0) {
  1831. const expression =
  1832. /** @type {Expression} */
  1833. (optionalExpressionsStack.pop());
  1834. const evaluated = this.evaluateExpression(expression);
  1835. if (evaluated.asNullish()) {
  1836. return evaluated.setRange(/** @type {Range} */ (_expr.range));
  1837. }
  1838. }
  1839. return this.evaluateExpression(expr.expression);
  1840. });
  1841. }
  1842. /**
  1843. * @param {Expression} node node
  1844. * @returns {DestructuringAssignmentProperties | undefined} destructured identifiers
  1845. */
  1846. destructuringAssignmentPropertiesFor(node) {
  1847. if (!this.destructuringAssignmentProperties) return;
  1848. return this.destructuringAssignmentProperties.get(node);
  1849. }
  1850. /**
  1851. * @param {Expression | SpreadElement} expr expression
  1852. * @returns {string | VariableInfo | undefined} identifier
  1853. */
  1854. getRenameIdentifier(expr) {
  1855. const result = this.evaluateExpression(expr);
  1856. if (result.isIdentifier()) {
  1857. return result.identifier;
  1858. }
  1859. }
  1860. /**
  1861. * @param {ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration} classy a class node
  1862. * @returns {void}
  1863. */
  1864. walkClass(classy) {
  1865. if (
  1866. classy.superClass &&
  1867. !this.hooks.classExtendsExpression.call(classy.superClass, classy)
  1868. ) {
  1869. this.walkExpression(classy.superClass);
  1870. }
  1871. if (classy.body && classy.body.type === "ClassBody") {
  1872. /** @type {Identifier[]} */
  1873. const scopeParams = [];
  1874. // Add class name in scope for recursive calls
  1875. if (classy.id) {
  1876. scopeParams.push(classy.id);
  1877. }
  1878. this.inClassScope(true, scopeParams, () => {
  1879. for (const classElement of classy.body.body) {
  1880. if (!this.hooks.classBodyElement.call(classElement, classy)) {
  1881. if (classElement.type === "StaticBlock") {
  1882. const wasTopLevel = this.scope.topLevelScope;
  1883. this.scope.topLevelScope = false;
  1884. this.walkBlockStatement(classElement);
  1885. this.scope.topLevelScope = wasTopLevel;
  1886. } else {
  1887. if (classElement.computed && classElement.key) {
  1888. this.walkExpression(classElement.key);
  1889. }
  1890. if (
  1891. classElement.value &&
  1892. !this.hooks.classBodyValue.call(
  1893. classElement.value,
  1894. classElement,
  1895. classy
  1896. )
  1897. ) {
  1898. const wasTopLevel = this.scope.topLevelScope;
  1899. this.scope.topLevelScope = false;
  1900. this.walkExpression(classElement.value);
  1901. this.scope.topLevelScope = wasTopLevel;
  1902. }
  1903. }
  1904. }
  1905. }
  1906. });
  1907. }
  1908. }
  1909. /**
  1910. * Module pre walking iterates the scope for import entries
  1911. * @param {(Statement | ModuleDeclaration)[]} statements statements
  1912. */
  1913. modulePreWalkStatements(statements) {
  1914. for (let index = 0, len = statements.length; index < len; index++) {
  1915. const statement = statements[index];
  1916. /** @type {StatementPath} */
  1917. (this.statementPath).push(statement);
  1918. switch (statement.type) {
  1919. case "ImportDeclaration":
  1920. this.modulePreWalkImportDeclaration(statement);
  1921. break;
  1922. case "ExportAllDeclaration":
  1923. this.modulePreWalkExportAllDeclaration(statement);
  1924. break;
  1925. case "ExportNamedDeclaration":
  1926. this.modulePreWalkExportNamedDeclaration(statement);
  1927. break;
  1928. }
  1929. this.prevStatement =
  1930. /** @type {StatementPath} */
  1931. (this.statementPath).pop();
  1932. }
  1933. }
  1934. /**
  1935. * Pre walking iterates the scope for variable declarations
  1936. * @param {(Statement | ModuleDeclaration)[]} statements statements
  1937. */
  1938. preWalkStatements(statements) {
  1939. for (let index = 0, len = statements.length; index < len; index++) {
  1940. const statement = statements[index];
  1941. this.preWalkStatement(statement);
  1942. }
  1943. }
  1944. /**
  1945. * Block pre walking iterates the scope for block variable declarations
  1946. * @param {(Statement | ModuleDeclaration)[]} statements statements
  1947. */
  1948. blockPreWalkStatements(statements) {
  1949. for (let index = 0, len = statements.length; index < len; index++) {
  1950. const statement = statements[index];
  1951. this.blockPreWalkStatement(statement);
  1952. }
  1953. }
  1954. /**
  1955. * Walking iterates the statements and expressions and processes them
  1956. * @param {(Statement | ModuleDeclaration)[]} statements statements
  1957. */
  1958. walkStatements(statements) {
  1959. let onlyFunctionDeclaration = false;
  1960. for (let index = 0, len = statements.length; index < len; index++) {
  1961. const statement = statements[index];
  1962. if (
  1963. onlyFunctionDeclaration &&
  1964. statement.type !== "FunctionDeclaration" &&
  1965. this.hooks.unusedStatement.call(/** @type {Statement} */ (statement))
  1966. ) {
  1967. continue;
  1968. }
  1969. this.walkStatement(statement);
  1970. if (this.scope.terminated) {
  1971. onlyFunctionDeclaration = true;
  1972. }
  1973. }
  1974. }
  1975. /**
  1976. * Walking iterates the statements and expressions and processes them
  1977. * @param {Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration} statement statement
  1978. */
  1979. preWalkStatement(statement) {
  1980. /** @type {StatementPath} */
  1981. (this.statementPath).push(statement);
  1982. if (this.hooks.preStatement.call(statement)) {
  1983. this.prevStatement =
  1984. /** @type {StatementPath} */
  1985. (this.statementPath).pop();
  1986. return;
  1987. }
  1988. switch (statement.type) {
  1989. case "BlockStatement":
  1990. this.preWalkBlockStatement(statement);
  1991. break;
  1992. case "DoWhileStatement":
  1993. this.preWalkDoWhileStatement(statement);
  1994. break;
  1995. case "ForInStatement":
  1996. this.preWalkForInStatement(statement);
  1997. break;
  1998. case "ForOfStatement":
  1999. this.preWalkForOfStatement(statement);
  2000. break;
  2001. case "ForStatement":
  2002. this.preWalkForStatement(statement);
  2003. break;
  2004. case "FunctionDeclaration":
  2005. this.preWalkFunctionDeclaration(statement);
  2006. break;
  2007. case "IfStatement":
  2008. this.preWalkIfStatement(statement);
  2009. break;
  2010. case "LabeledStatement":
  2011. this.preWalkLabeledStatement(statement);
  2012. break;
  2013. case "SwitchStatement":
  2014. this.preWalkSwitchStatement(statement);
  2015. break;
  2016. case "TryStatement":
  2017. this.preWalkTryStatement(statement);
  2018. break;
  2019. case "VariableDeclaration":
  2020. this.preWalkVariableDeclaration(statement);
  2021. break;
  2022. case "WhileStatement":
  2023. this.preWalkWhileStatement(statement);
  2024. break;
  2025. case "WithStatement":
  2026. this.preWalkWithStatement(statement);
  2027. break;
  2028. }
  2029. this.prevStatement =
  2030. /** @type {StatementPath} */
  2031. (this.statementPath).pop();
  2032. }
  2033. /**
  2034. * @param {Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration} statement statement
  2035. */
  2036. blockPreWalkStatement(statement) {
  2037. /** @type {StatementPath} */
  2038. (this.statementPath).push(statement);
  2039. if (this.hooks.blockPreStatement.call(statement)) {
  2040. this.prevStatement =
  2041. /** @type {StatementPath} */
  2042. (this.statementPath).pop();
  2043. return;
  2044. }
  2045. switch (statement.type) {
  2046. case "ExportDefaultDeclaration":
  2047. this.blockPreWalkExportDefaultDeclaration(statement);
  2048. break;
  2049. case "ExportNamedDeclaration":
  2050. this.blockPreWalkExportNamedDeclaration(statement);
  2051. break;
  2052. case "VariableDeclaration":
  2053. this.blockPreWalkVariableDeclaration(statement);
  2054. break;
  2055. case "ClassDeclaration":
  2056. this.blockPreWalkClassDeclaration(statement);
  2057. break;
  2058. case "ExpressionStatement":
  2059. this.blockPreWalkExpressionStatement(statement);
  2060. }
  2061. this.prevStatement =
  2062. /** @type {StatementPath} */
  2063. (this.statementPath).pop();
  2064. }
  2065. /**
  2066. * @param {Statement | ModuleDeclaration | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} statement statement
  2067. */
  2068. walkStatement(statement) {
  2069. /** @type {StatementPath} */
  2070. (this.statementPath).push(statement);
  2071. if (this.hooks.statement.call(statement) !== undefined) {
  2072. this.prevStatement =
  2073. /** @type {StatementPath} */
  2074. (this.statementPath).pop();
  2075. return;
  2076. }
  2077. switch (statement.type) {
  2078. case "BlockStatement":
  2079. this.walkBlockStatement(statement);
  2080. break;
  2081. case "ClassDeclaration":
  2082. this.walkClassDeclaration(statement);
  2083. break;
  2084. case "DoWhileStatement":
  2085. this.walkDoWhileStatement(statement);
  2086. break;
  2087. case "ExportDefaultDeclaration":
  2088. this.walkExportDefaultDeclaration(statement);
  2089. break;
  2090. case "ExportNamedDeclaration":
  2091. this.walkExportNamedDeclaration(statement);
  2092. break;
  2093. case "ExpressionStatement":
  2094. this.walkExpressionStatement(statement);
  2095. break;
  2096. case "ForInStatement":
  2097. this.walkForInStatement(statement);
  2098. break;
  2099. case "ForOfStatement":
  2100. this.walkForOfStatement(statement);
  2101. break;
  2102. case "ForStatement":
  2103. this.walkForStatement(statement);
  2104. break;
  2105. case "FunctionDeclaration":
  2106. this.walkFunctionDeclaration(statement);
  2107. break;
  2108. case "IfStatement":
  2109. this.walkIfStatement(statement);
  2110. break;
  2111. case "LabeledStatement":
  2112. this.walkLabeledStatement(statement);
  2113. break;
  2114. case "ReturnStatement":
  2115. this.walkReturnStatement(statement);
  2116. break;
  2117. case "SwitchStatement":
  2118. this.walkSwitchStatement(statement);
  2119. break;
  2120. case "ThrowStatement":
  2121. this.walkThrowStatement(statement);
  2122. break;
  2123. case "TryStatement":
  2124. this.walkTryStatement(statement);
  2125. break;
  2126. case "VariableDeclaration":
  2127. this.walkVariableDeclaration(statement);
  2128. break;
  2129. case "WhileStatement":
  2130. this.walkWhileStatement(statement);
  2131. break;
  2132. case "WithStatement":
  2133. this.walkWithStatement(statement);
  2134. break;
  2135. }
  2136. this.prevStatement =
  2137. /** @type {StatementPath} */
  2138. (this.statementPath).pop();
  2139. }
  2140. /**
  2141. * Walks a statements that is nested within a parent statement
  2142. * and can potentially be a non-block statement.
  2143. * This enforces the nested statement to never be in ASI position.
  2144. * @param {Statement} statement the nested statement
  2145. */
  2146. walkNestedStatement(statement) {
  2147. this.prevStatement = undefined;
  2148. this.walkStatement(statement);
  2149. }
  2150. // Real Statements
  2151. /**
  2152. * @param {BlockStatement} statement block statement
  2153. */
  2154. preWalkBlockStatement(statement) {
  2155. this.preWalkStatements(statement.body);
  2156. }
  2157. /**
  2158. * @param {BlockStatement | StaticBlock} statement block statement
  2159. */
  2160. walkBlockStatement(statement) {
  2161. this.inBlockScope(() => {
  2162. const body = statement.body;
  2163. const prev = this.prevStatement;
  2164. this.blockPreWalkStatements(body);
  2165. this.prevStatement = prev;
  2166. this.walkStatements(body);
  2167. }, true);
  2168. }
  2169. /**
  2170. * @param {ExpressionStatement} statement expression statement
  2171. */
  2172. walkExpressionStatement(statement) {
  2173. this.walkExpression(statement.expression);
  2174. }
  2175. /**
  2176. * @param {IfStatement} statement if statement
  2177. */
  2178. preWalkIfStatement(statement) {
  2179. this.preWalkStatement(statement.consequent);
  2180. if (statement.alternate) {
  2181. this.preWalkStatement(statement.alternate);
  2182. }
  2183. }
  2184. /**
  2185. * @param {IfStatement} statement if statement
  2186. */
  2187. walkIfStatement(statement) {
  2188. const result = this.hooks.statementIf.call(statement);
  2189. if (result === undefined) {
  2190. const inGuard = this.hooks.collectGuards.call(statement.test);
  2191. if (inGuard) {
  2192. inGuard(() => {
  2193. this.walkExpression(statement.test);
  2194. this.walkNestedStatement(statement.consequent);
  2195. });
  2196. } else {
  2197. this.walkExpression(statement.test);
  2198. this.walkNestedStatement(statement.consequent);
  2199. }
  2200. const consequentTerminated = this.scope.terminated;
  2201. this.scope.terminated = undefined;
  2202. if (statement.alternate) {
  2203. this.walkNestedStatement(statement.alternate);
  2204. }
  2205. const alternateTerminated = this.scope.terminated;
  2206. this.scope.terminated =
  2207. consequentTerminated && alternateTerminated
  2208. ? alternateTerminated
  2209. : undefined;
  2210. } else if (result) {
  2211. this.walkNestedStatement(statement.consequent);
  2212. } else if (statement.alternate) {
  2213. this.walkNestedStatement(statement.alternate);
  2214. }
  2215. }
  2216. /**
  2217. * @param {LabeledStatement} statement with statement
  2218. */
  2219. preWalkLabeledStatement(statement) {
  2220. this.preWalkStatement(statement.body);
  2221. }
  2222. /**
  2223. * @param {LabeledStatement} statement with statement
  2224. */
  2225. walkLabeledStatement(statement) {
  2226. const hook = this.hooks.label.get(statement.label.name);
  2227. if (hook !== undefined) {
  2228. const result = hook.call(statement);
  2229. if (result === true) return;
  2230. }
  2231. this.inBlockScope(() => {
  2232. this.walkNestedStatement(statement.body);
  2233. });
  2234. }
  2235. /**
  2236. * @param {WithStatement} statement with statement
  2237. */
  2238. preWalkWithStatement(statement) {
  2239. this.preWalkStatement(statement.body);
  2240. }
  2241. /**
  2242. * @param {WithStatement} statement with statement
  2243. */
  2244. walkWithStatement(statement) {
  2245. this.inBlockScope(() => {
  2246. this.walkExpression(statement.object);
  2247. this.walkNestedStatement(statement.body);
  2248. });
  2249. }
  2250. /**
  2251. * @param {SwitchStatement} statement switch statement
  2252. */
  2253. preWalkSwitchStatement(statement) {
  2254. this.preWalkSwitchCases(statement.cases);
  2255. }
  2256. /**
  2257. * @param {SwitchStatement} statement switch statement
  2258. */
  2259. walkSwitchStatement(statement) {
  2260. this.walkExpression(statement.discriminant);
  2261. this.walkSwitchCases(statement.cases);
  2262. }
  2263. /**
  2264. * @param {ReturnStatement | ThrowStatement} statement return or throw statement
  2265. */
  2266. walkTerminatingStatement(statement) {
  2267. if (statement.argument) this.walkExpression(statement.argument);
  2268. // Skip top level scope because to handle `export` and `module.exports` after terminate
  2269. if (this.scope.topLevelScope === true) return;
  2270. if (this.hooks.terminate.call(statement)) {
  2271. this.scope.terminated =
  2272. statement.type === "ReturnStatement"
  2273. ? SCOPE_INFO_TERMINATED_RETURN
  2274. : SCOPE_INFO_TERMINATED_THROW;
  2275. }
  2276. }
  2277. /**
  2278. * @param {ReturnStatement} statement return statement
  2279. */
  2280. walkReturnStatement(statement) {
  2281. this.walkTerminatingStatement(statement);
  2282. }
  2283. /**
  2284. * @param {ThrowStatement} statement return statement
  2285. */
  2286. walkThrowStatement(statement) {
  2287. this.walkTerminatingStatement(statement);
  2288. }
  2289. /**
  2290. * @param {TryStatement} statement try statement
  2291. */
  2292. preWalkTryStatement(statement) {
  2293. this.preWalkStatement(statement.block);
  2294. if (statement.handler) this.preWalkCatchClause(statement.handler);
  2295. if (statement.finalizer) this.preWalkStatement(statement.finalizer);
  2296. }
  2297. /**
  2298. * @param {TryStatement} statement try statement
  2299. */
  2300. walkTryStatement(statement) {
  2301. if (this.scope.inTry) {
  2302. this.walkStatement(statement.block);
  2303. } else {
  2304. this.scope.inTry = true;
  2305. this.walkStatement(statement.block);
  2306. this.scope.inTry = false;
  2307. }
  2308. const tryTerminated = this.scope.terminated;
  2309. this.scope.terminated = undefined;
  2310. if (statement.handler) this.walkCatchClause(statement.handler);
  2311. const handlerTerminated = this.scope.terminated;
  2312. this.scope.terminated = undefined;
  2313. if (statement.finalizer) {
  2314. this.walkStatement(statement.finalizer);
  2315. }
  2316. const finalizerTerminated = this.scope.terminated;
  2317. this.scope.terminated = undefined;
  2318. if (finalizerTerminated) {
  2319. this.scope.terminated = finalizerTerminated;
  2320. } else if (
  2321. tryTerminated &&
  2322. (statement.handler ? handlerTerminated : true)
  2323. ) {
  2324. this.scope.terminated = handlerTerminated || tryTerminated;
  2325. }
  2326. }
  2327. /**
  2328. * @param {WhileStatement} statement while statement
  2329. */
  2330. preWalkWhileStatement(statement) {
  2331. this.preWalkStatement(statement.body);
  2332. }
  2333. /**
  2334. * @param {WhileStatement} statement while statement
  2335. */
  2336. walkWhileStatement(statement) {
  2337. this.inBlockScope(() => {
  2338. this.walkExpression(statement.test);
  2339. this.walkNestedStatement(statement.body);
  2340. });
  2341. }
  2342. /**
  2343. * @param {DoWhileStatement} statement do while statement
  2344. */
  2345. preWalkDoWhileStatement(statement) {
  2346. this.preWalkStatement(statement.body);
  2347. }
  2348. /**
  2349. * @param {DoWhileStatement} statement do while statement
  2350. */
  2351. walkDoWhileStatement(statement) {
  2352. this.inBlockScope(() => {
  2353. this.walkNestedStatement(statement.body);
  2354. this.walkExpression(statement.test);
  2355. });
  2356. }
  2357. /**
  2358. * @param {ForStatement} statement for statement
  2359. */
  2360. preWalkForStatement(statement) {
  2361. if (statement.init && statement.init.type === "VariableDeclaration") {
  2362. this.preWalkStatement(statement.init);
  2363. }
  2364. this.preWalkStatement(statement.body);
  2365. }
  2366. /**
  2367. * @param {ForStatement} statement for statement
  2368. */
  2369. walkForStatement(statement) {
  2370. this.inBlockScope(() => {
  2371. if (statement.init) {
  2372. if (statement.init.type === "VariableDeclaration") {
  2373. this.blockPreWalkVariableDeclaration(statement.init);
  2374. this.prevStatement = undefined;
  2375. this.walkStatement(statement.init);
  2376. } else {
  2377. this.walkExpression(statement.init);
  2378. }
  2379. }
  2380. if (statement.test) {
  2381. this.walkExpression(statement.test);
  2382. }
  2383. if (statement.update) {
  2384. this.walkExpression(statement.update);
  2385. }
  2386. const body = statement.body;
  2387. if (body.type === "BlockStatement") {
  2388. // no need to add additional scope
  2389. const prev = this.prevStatement;
  2390. this.blockPreWalkStatements(body.body);
  2391. this.prevStatement = prev;
  2392. this.walkStatements(body.body);
  2393. } else {
  2394. this.walkNestedStatement(body);
  2395. }
  2396. });
  2397. }
  2398. /**
  2399. * @param {ForInStatement} statement for statement
  2400. */
  2401. preWalkForInStatement(statement) {
  2402. if (statement.left.type === "VariableDeclaration") {
  2403. this.preWalkVariableDeclaration(statement.left);
  2404. }
  2405. this.preWalkStatement(statement.body);
  2406. }
  2407. /**
  2408. * @param {ForInStatement} statement for statement
  2409. */
  2410. walkForInStatement(statement) {
  2411. this.inBlockScope(() => {
  2412. if (statement.left.type === "VariableDeclaration") {
  2413. this.blockPreWalkVariableDeclaration(statement.left);
  2414. this.walkVariableDeclaration(statement.left);
  2415. } else {
  2416. this.walkPattern(statement.left);
  2417. }
  2418. this.walkExpression(statement.right);
  2419. const body = statement.body;
  2420. if (body.type === "BlockStatement") {
  2421. // no need to add additional scope
  2422. const prev = this.prevStatement;
  2423. this.blockPreWalkStatements(body.body);
  2424. this.prevStatement = prev;
  2425. this.walkStatements(body.body);
  2426. } else {
  2427. this.walkNestedStatement(body);
  2428. }
  2429. });
  2430. }
  2431. /**
  2432. * @param {ForOfStatement} statement statement
  2433. */
  2434. preWalkForOfStatement(statement) {
  2435. if (statement.await && this.scope.topLevelScope === true) {
  2436. this.hooks.topLevelAwait.call(statement);
  2437. }
  2438. if (statement.left.type === "VariableDeclaration") {
  2439. this.preWalkVariableDeclaration(statement.left);
  2440. }
  2441. this.preWalkStatement(statement.body);
  2442. }
  2443. /**
  2444. * @param {ForOfStatement} statement for statement
  2445. */
  2446. walkForOfStatement(statement) {
  2447. this.inBlockScope(() => {
  2448. if (statement.left.type === "VariableDeclaration") {
  2449. this.blockPreWalkVariableDeclaration(statement.left);
  2450. this.walkVariableDeclaration(statement.left);
  2451. } else {
  2452. this.walkPattern(statement.left);
  2453. }
  2454. this.walkExpression(statement.right);
  2455. const body = statement.body;
  2456. if (body.type === "BlockStatement") {
  2457. // no need to add additional scope
  2458. const prev = this.prevStatement;
  2459. this.blockPreWalkStatements(body.body);
  2460. this.prevStatement = prev;
  2461. this.walkStatements(body.body);
  2462. } else {
  2463. this.walkNestedStatement(body);
  2464. }
  2465. });
  2466. }
  2467. /**
  2468. * @param {FunctionDeclaration | MaybeNamedFunctionDeclaration} statement function declaration
  2469. */
  2470. preWalkFunctionDeclaration(statement) {
  2471. if (statement.id) {
  2472. this.defineVariable(statement.id.name);
  2473. }
  2474. }
  2475. /**
  2476. * @param {FunctionDeclaration | MaybeNamedFunctionDeclaration} statement function declaration
  2477. */
  2478. walkFunctionDeclaration(statement) {
  2479. const wasTopLevel = this.scope.topLevelScope;
  2480. this.scope.topLevelScope = false;
  2481. this.inFunctionScope(true, statement.params, () => {
  2482. for (const param of statement.params) {
  2483. this.walkPattern(param);
  2484. }
  2485. this.detectMode(statement.body.body);
  2486. const prev = this.prevStatement;
  2487. this.preWalkStatement(statement.body);
  2488. this.prevStatement = prev;
  2489. this.walkStatement(statement.body);
  2490. });
  2491. this.scope.topLevelScope = wasTopLevel;
  2492. }
  2493. /**
  2494. * @param {ExpressionStatement} statement expression statement
  2495. */
  2496. blockPreWalkExpressionStatement(statement) {
  2497. const expression = statement.expression;
  2498. switch (expression.type) {
  2499. case "AssignmentExpression":
  2500. this.preWalkAssignmentExpression(expression);
  2501. }
  2502. }
  2503. /**
  2504. * @param {AssignmentExpression} expression assignment expression
  2505. */
  2506. preWalkAssignmentExpression(expression) {
  2507. this.enterDestructuringAssignment(expression.left, expression.right);
  2508. }
  2509. /**
  2510. * @param {Pattern} pattern pattern
  2511. * @param {Expression} expression assignment expression
  2512. * @returns {Expression | undefined} destructuring expression
  2513. */
  2514. enterDestructuringAssignment(pattern, expression) {
  2515. if (
  2516. pattern.type !== "ObjectPattern" ||
  2517. !this.destructuringAssignmentProperties
  2518. ) {
  2519. return;
  2520. }
  2521. const expr =
  2522. expression.type === "AwaitExpression" ? expression.argument : expression;
  2523. const destructuring =
  2524. expr.type === "AssignmentExpression"
  2525. ? this.enterDestructuringAssignment(expr.left, expr.right)
  2526. : this.hooks.collectDestructuringAssignmentProperties.call(expr)
  2527. ? expr
  2528. : undefined;
  2529. if (destructuring) {
  2530. const keys = this._preWalkObjectPattern(pattern);
  2531. if (!keys) return;
  2532. // check multiple assignments
  2533. if (this.destructuringAssignmentProperties.has(destructuring)) {
  2534. const set =
  2535. /** @type {DestructuringAssignmentProperties} */
  2536. (this.destructuringAssignmentProperties.get(destructuring));
  2537. for (const id of keys) set.add(id);
  2538. } else {
  2539. this.destructuringAssignmentProperties.set(destructuring, keys);
  2540. }
  2541. }
  2542. return destructuring;
  2543. }
  2544. /**
  2545. * @param {ImportDeclaration} statement statement
  2546. */
  2547. modulePreWalkImportDeclaration(statement) {
  2548. const source = /** @type {ImportSource} */ (statement.source.value);
  2549. this.hooks.import.call(statement, source);
  2550. for (const specifier of statement.specifiers) {
  2551. const name = specifier.local.name;
  2552. switch (specifier.type) {
  2553. case "ImportDefaultSpecifier":
  2554. if (
  2555. !this.hooks.importSpecifier.call(statement, source, "default", name)
  2556. ) {
  2557. this.defineVariable(name);
  2558. }
  2559. break;
  2560. case "ImportSpecifier":
  2561. if (
  2562. !this.hooks.importSpecifier.call(
  2563. statement,
  2564. source,
  2565. /** @type {Identifier} */
  2566. (specifier.imported).name ||
  2567. /** @type {string} */
  2568. (
  2569. /** @type {Literal} */
  2570. (specifier.imported).value
  2571. ),
  2572. name
  2573. )
  2574. ) {
  2575. this.defineVariable(name);
  2576. }
  2577. break;
  2578. case "ImportNamespaceSpecifier":
  2579. if (!this.hooks.importSpecifier.call(statement, source, null, name)) {
  2580. this.defineVariable(name);
  2581. }
  2582. break;
  2583. default:
  2584. this.defineVariable(name);
  2585. }
  2586. }
  2587. }
  2588. /**
  2589. * @param {Declaration} declaration declaration
  2590. * @param {OnIdent} onIdent on ident callback
  2591. */
  2592. enterDeclaration(declaration, onIdent) {
  2593. switch (declaration.type) {
  2594. case "VariableDeclaration":
  2595. for (const declarator of declaration.declarations) {
  2596. switch (declarator.type) {
  2597. case "VariableDeclarator": {
  2598. this.enterPattern(declarator.id, onIdent);
  2599. break;
  2600. }
  2601. }
  2602. }
  2603. break;
  2604. case "FunctionDeclaration":
  2605. this.enterPattern(declaration.id, onIdent);
  2606. break;
  2607. case "ClassDeclaration":
  2608. this.enterPattern(declaration.id, onIdent);
  2609. break;
  2610. }
  2611. }
  2612. /**
  2613. * @param {ExportNamedDeclaration} statement statement
  2614. */
  2615. modulePreWalkExportNamedDeclaration(statement) {
  2616. if (!statement.source) return;
  2617. const source = /** @type {ImportSource} */ (statement.source.value);
  2618. this.hooks.exportImport.call(statement, source);
  2619. if (statement.specifiers) {
  2620. for (
  2621. let specifierIndex = 0;
  2622. specifierIndex < statement.specifiers.length;
  2623. specifierIndex++
  2624. ) {
  2625. const specifier = statement.specifiers[specifierIndex];
  2626. switch (specifier.type) {
  2627. case "ExportSpecifier": {
  2628. const localName =
  2629. /** @type {Identifier} */ (specifier.local).name ||
  2630. /** @type {string} */ (
  2631. /** @type {Literal} */ (specifier.local).value
  2632. );
  2633. const name =
  2634. /** @type {Identifier} */
  2635. (specifier.exported).name ||
  2636. /** @type {string} */
  2637. (/** @type {Literal} */ (specifier.exported).value);
  2638. this.hooks.exportImportSpecifier.call(
  2639. statement,
  2640. source,
  2641. localName,
  2642. name,
  2643. specifierIndex
  2644. );
  2645. break;
  2646. }
  2647. }
  2648. }
  2649. }
  2650. }
  2651. /**
  2652. * @param {ExportNamedDeclaration} statement statement
  2653. */
  2654. blockPreWalkExportNamedDeclaration(statement) {
  2655. if (statement.source) return;
  2656. this.hooks.export.call(statement);
  2657. if (
  2658. statement.declaration &&
  2659. !this.hooks.exportDeclaration.call(statement, statement.declaration)
  2660. ) {
  2661. const prev = this.prevStatement;
  2662. this.preWalkStatement(statement.declaration);
  2663. this.prevStatement = prev;
  2664. this.blockPreWalkStatement(statement.declaration);
  2665. let index = 0;
  2666. this.enterDeclaration(statement.declaration, (def) => {
  2667. this.hooks.exportSpecifier.call(statement, def, def, index++);
  2668. });
  2669. }
  2670. if (statement.specifiers) {
  2671. for (
  2672. let specifierIndex = 0;
  2673. specifierIndex < statement.specifiers.length;
  2674. specifierIndex++
  2675. ) {
  2676. const specifier = statement.specifiers[specifierIndex];
  2677. switch (specifier.type) {
  2678. case "ExportSpecifier": {
  2679. const localName =
  2680. /** @type {Identifier} */ (specifier.local).name ||
  2681. /** @type {string} */ (
  2682. /** @type {Literal} */ (specifier.local).value
  2683. );
  2684. const name =
  2685. /** @type {Identifier} */
  2686. (specifier.exported).name ||
  2687. /** @type {string} */
  2688. (/** @type {Literal} */ (specifier.exported).value);
  2689. this.hooks.exportSpecifier.call(
  2690. statement,
  2691. localName,
  2692. name,
  2693. specifierIndex
  2694. );
  2695. break;
  2696. }
  2697. }
  2698. }
  2699. }
  2700. }
  2701. /**
  2702. * @param {ExportNamedDeclaration} statement the statement
  2703. */
  2704. walkExportNamedDeclaration(statement) {
  2705. if (statement.declaration) {
  2706. this.walkStatement(statement.declaration);
  2707. }
  2708. }
  2709. /**
  2710. * @param {ExportDefaultDeclaration} statement statement
  2711. */
  2712. blockPreWalkExportDefaultDeclaration(statement) {
  2713. if (
  2714. statement.declaration.type === "FunctionDeclaration" ||
  2715. statement.declaration.type === "ClassDeclaration"
  2716. ) {
  2717. const prev = this.prevStatement;
  2718. this.preWalkStatement(statement.declaration);
  2719. this.prevStatement = prev;
  2720. this.blockPreWalkStatement(statement.declaration);
  2721. }
  2722. if (
  2723. /** @type {MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} */
  2724. (statement.declaration).id &&
  2725. statement.declaration.type !== "FunctionExpression" &&
  2726. statement.declaration.type !== "ClassExpression"
  2727. ) {
  2728. const declaration =
  2729. /** @type {MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} */
  2730. (statement.declaration);
  2731. this.hooks.exportSpecifier.call(
  2732. statement,
  2733. /** @type {Identifier} */
  2734. (declaration.id).name,
  2735. "default",
  2736. undefined
  2737. );
  2738. }
  2739. }
  2740. /**
  2741. * @param {ExportDefaultDeclaration} statement statement
  2742. */
  2743. walkExportDefaultDeclaration(statement) {
  2744. this.hooks.export.call(statement);
  2745. if (
  2746. /** @type {FunctionDeclaration | ClassDeclaration} */
  2747. (statement.declaration).id &&
  2748. statement.declaration.type !== "FunctionExpression" &&
  2749. statement.declaration.type !== "ClassExpression"
  2750. ) {
  2751. const declaration =
  2752. /** @type {FunctionDeclaration | ClassDeclaration} */
  2753. (statement.declaration);
  2754. if (!this.hooks.exportDeclaration.call(statement, declaration)) {
  2755. this.walkStatement(declaration);
  2756. }
  2757. } else {
  2758. // Acorn parses `export default function() {}` as `FunctionDeclaration` and
  2759. // `export default class {}` as `ClassDeclaration`, both with `id = null`.
  2760. // These nodes must be treated as expressions.
  2761. if (
  2762. statement.declaration.type === "FunctionDeclaration" ||
  2763. statement.declaration.type === "ClassDeclaration"
  2764. ) {
  2765. this.walkStatement(statement.declaration);
  2766. } else {
  2767. this.walkExpression(statement.declaration);
  2768. }
  2769. this.hooks.exportExpression.call(statement, statement.declaration);
  2770. }
  2771. }
  2772. /**
  2773. * @param {ExportAllDeclaration} statement statement
  2774. */
  2775. modulePreWalkExportAllDeclaration(statement) {
  2776. const source = /** @type {ImportSource} */ (statement.source.value);
  2777. const name = statement.exported
  2778. ? /** @type {Identifier} */
  2779. (statement.exported).name ||
  2780. /** @type {string} */
  2781. (/** @type {Literal} */ (statement.exported).value)
  2782. : null;
  2783. this.hooks.exportImport.call(statement, source);
  2784. this.hooks.exportImportSpecifier.call(statement, source, null, name, 0);
  2785. }
  2786. /**
  2787. * @param {VariableDeclaration} statement variable declaration
  2788. */
  2789. preWalkVariableDeclaration(statement) {
  2790. if (statement.kind !== "var") return;
  2791. this._preWalkVariableDeclaration(statement, this.hooks.varDeclarationVar);
  2792. }
  2793. /**
  2794. * @param {VariableDeclaration} statement variable declaration
  2795. */
  2796. blockPreWalkVariableDeclaration(statement) {
  2797. if (statement.kind === "var") return;
  2798. const hookMap =
  2799. statement.kind === "const"
  2800. ? this.hooks.varDeclarationConst
  2801. : statement.kind === "using" || statement.kind === "await using"
  2802. ? this.hooks.varDeclarationUsing
  2803. : this.hooks.varDeclarationLet;
  2804. this._preWalkVariableDeclaration(statement, hookMap);
  2805. }
  2806. /**
  2807. * @param {VariableDeclaration} statement variable declaration
  2808. * @param {HookMap<SyncBailHook<[Identifier], boolean | void>>} hookMap map of hooks
  2809. */
  2810. _preWalkVariableDeclaration(statement, hookMap) {
  2811. for (const declarator of statement.declarations) {
  2812. switch (declarator.type) {
  2813. case "VariableDeclarator": {
  2814. this.preWalkVariableDeclarator(declarator);
  2815. if (!this.hooks.preDeclarator.call(declarator, statement)) {
  2816. this.enterPattern(declarator.id, (name, ident) => {
  2817. let hook = hookMap.get(name);
  2818. if (hook === undefined || !hook.call(ident)) {
  2819. hook = this.hooks.varDeclaration.get(name);
  2820. if (hook === undefined || !hook.call(ident)) {
  2821. this.defineVariable(name);
  2822. }
  2823. }
  2824. });
  2825. }
  2826. break;
  2827. }
  2828. }
  2829. }
  2830. }
  2831. /**
  2832. * @param {ObjectPattern} objectPattern object pattern
  2833. * @returns {DestructuringAssignmentProperties | undefined} set of names or undefined if not all keys are identifiers
  2834. */
  2835. _preWalkObjectPattern(objectPattern) {
  2836. /** @type {DestructuringAssignmentProperties} */
  2837. const props = new Set();
  2838. const properties = objectPattern.properties;
  2839. for (let i = 0; i < properties.length; i++) {
  2840. const property = properties[i];
  2841. if (property.type !== "Property") return;
  2842. if (property.shorthand) {
  2843. if (property.value.type === "Identifier") {
  2844. this.scope.inShorthand = property.value.name;
  2845. } else if (
  2846. property.value.type === "AssignmentPattern" &&
  2847. property.value.left.type === "Identifier"
  2848. ) {
  2849. this.scope.inShorthand = property.value.left.name;
  2850. }
  2851. }
  2852. const key = property.key;
  2853. if (key.type === "Identifier" && !property.computed) {
  2854. const pattern =
  2855. property.value.type === "ObjectPattern"
  2856. ? this._preWalkObjectPattern(property.value)
  2857. : property.value.type === "ArrayPattern"
  2858. ? this._preWalkArrayPattern(property.value)
  2859. : undefined;
  2860. props.add({
  2861. id: key.name,
  2862. range: /** @type {Range} */ (key.range),
  2863. loc: /** @type {SourceLocation} */ (key.loc),
  2864. pattern,
  2865. shorthand: this.scope.inShorthand
  2866. });
  2867. } else {
  2868. const id = this.evaluateExpression(key);
  2869. const str = id.asString();
  2870. if (str) {
  2871. const pattern =
  2872. property.value.type === "ObjectPattern"
  2873. ? this._preWalkObjectPattern(property.value)
  2874. : property.value.type === "ArrayPattern"
  2875. ? this._preWalkArrayPattern(property.value)
  2876. : undefined;
  2877. props.add({
  2878. id: str,
  2879. range: /** @type {Range} */ (key.range),
  2880. loc: /** @type {SourceLocation} */ (key.loc),
  2881. pattern,
  2882. shorthand: this.scope.inShorthand
  2883. });
  2884. } else {
  2885. // could not evaluate key
  2886. return;
  2887. }
  2888. }
  2889. this.scope.inShorthand = false;
  2890. }
  2891. return props;
  2892. }
  2893. /**
  2894. * @param {ArrayPattern} arrayPattern array pattern
  2895. * @returns {Set<DestructuringAssignmentProperty> | undefined} set of names or undefined if not all keys are identifiers
  2896. */
  2897. _preWalkArrayPattern(arrayPattern) {
  2898. /** @type {Set<DestructuringAssignmentProperty>} */
  2899. const props = new Set();
  2900. const elements = arrayPattern.elements;
  2901. for (let i = 0; i < elements.length; i++) {
  2902. const element = elements[i];
  2903. if (!element) continue;
  2904. if (element.type === "RestElement") return;
  2905. const pattern =
  2906. element.type === "ObjectPattern"
  2907. ? this._preWalkObjectPattern(element)
  2908. : element.type === "ArrayPattern"
  2909. ? this._preWalkArrayPattern(element)
  2910. : undefined;
  2911. props.add({
  2912. id: `${i}`,
  2913. range: /** @type {Range} */ (element.range),
  2914. loc: /** @type {SourceLocation} */ (element.loc),
  2915. pattern,
  2916. shorthand: false
  2917. });
  2918. }
  2919. return props;
  2920. }
  2921. /**
  2922. * @param {VariableDeclarator} declarator variable declarator
  2923. */
  2924. preWalkVariableDeclarator(declarator) {
  2925. if (declarator.init) {
  2926. this.enterDestructuringAssignment(declarator.id, declarator.init);
  2927. }
  2928. }
  2929. /**
  2930. * @param {VariableDeclaration} statement variable declaration
  2931. */
  2932. walkVariableDeclaration(statement) {
  2933. for (const declarator of statement.declarations) {
  2934. switch (declarator.type) {
  2935. case "VariableDeclarator": {
  2936. const renameIdentifier =
  2937. declarator.init && this.getRenameIdentifier(declarator.init);
  2938. if (renameIdentifier && declarator.id.type === "Identifier") {
  2939. const hook = this.hooks.canRename.get(renameIdentifier);
  2940. if (
  2941. hook !== undefined &&
  2942. hook.call(/** @type {Expression} */ (declarator.init))
  2943. ) {
  2944. // renaming with "var a = b;"
  2945. const hook = this.hooks.rename.get(renameIdentifier);
  2946. if (
  2947. hook === undefined ||
  2948. !hook.call(/** @type {Expression} */ (declarator.init))
  2949. ) {
  2950. this.setVariable(declarator.id.name, renameIdentifier);
  2951. }
  2952. break;
  2953. }
  2954. }
  2955. if (!this.hooks.declarator.call(declarator, statement)) {
  2956. this.walkPattern(declarator.id);
  2957. if (declarator.init) this.walkExpression(declarator.init);
  2958. }
  2959. break;
  2960. }
  2961. }
  2962. }
  2963. }
  2964. /**
  2965. * @param {ClassDeclaration | MaybeNamedClassDeclaration} statement class declaration
  2966. */
  2967. blockPreWalkClassDeclaration(statement) {
  2968. if (statement.id) {
  2969. this.defineVariable(statement.id.name);
  2970. }
  2971. }
  2972. /**
  2973. * @param {ClassDeclaration | MaybeNamedClassDeclaration} statement class declaration
  2974. */
  2975. walkClassDeclaration(statement) {
  2976. this.walkClass(statement);
  2977. }
  2978. /**
  2979. * @param {SwitchCase[]} switchCases switch statement
  2980. */
  2981. preWalkSwitchCases(switchCases) {
  2982. for (let index = 0, len = switchCases.length; index < len; index++) {
  2983. const switchCase = switchCases[index];
  2984. this.preWalkStatements(switchCase.consequent);
  2985. }
  2986. }
  2987. /**
  2988. * @param {SwitchCase[]} switchCases switch statement
  2989. */
  2990. walkSwitchCases(switchCases) {
  2991. this.inBlockScope(() => {
  2992. const len = switchCases.length;
  2993. // we need to pre walk all statements first since we can have invalid code
  2994. // import A from "module";
  2995. // switch(1) {
  2996. // case 1:
  2997. // console.log(A); // should fail at runtime
  2998. // case 2:
  2999. // const A = 1;
  3000. // }
  3001. for (let index = 0; index < len; index++) {
  3002. const switchCase = switchCases[index];
  3003. if (switchCase.consequent.length > 0) {
  3004. const prev = this.prevStatement;
  3005. this.blockPreWalkStatements(switchCase.consequent);
  3006. this.prevStatement = prev;
  3007. }
  3008. }
  3009. for (let index = 0; index < len; index++) {
  3010. const switchCase = switchCases[index];
  3011. if (switchCase.test) {
  3012. this.walkExpression(switchCase.test);
  3013. }
  3014. if (switchCase.consequent.length > 0) {
  3015. this.walkStatements(switchCase.consequent);
  3016. this.scope.terminated = undefined;
  3017. }
  3018. }
  3019. });
  3020. }
  3021. /**
  3022. * @param {CatchClause} catchClause catch clause
  3023. */
  3024. preWalkCatchClause(catchClause) {
  3025. this.preWalkStatement(catchClause.body);
  3026. }
  3027. /**
  3028. * @param {CatchClause} catchClause catch clause
  3029. */
  3030. walkCatchClause(catchClause) {
  3031. this.inBlockScope(() => {
  3032. // Error binding is optional in catch clause since ECMAScript 2019
  3033. if (catchClause.param !== null) {
  3034. this.enterPattern(catchClause.param, (ident) => {
  3035. this.defineVariable(ident);
  3036. });
  3037. this.walkPattern(catchClause.param);
  3038. }
  3039. const prev = this.prevStatement;
  3040. this.blockPreWalkStatement(catchClause.body);
  3041. this.prevStatement = prev;
  3042. this.walkStatement(catchClause.body);
  3043. }, true);
  3044. }
  3045. /**
  3046. * @param {Pattern} pattern pattern
  3047. */
  3048. walkPattern(pattern) {
  3049. switch (pattern.type) {
  3050. case "ArrayPattern":
  3051. this.walkArrayPattern(pattern);
  3052. break;
  3053. case "AssignmentPattern":
  3054. this.walkAssignmentPattern(pattern);
  3055. break;
  3056. case "MemberExpression":
  3057. this.walkMemberExpression(pattern);
  3058. break;
  3059. case "ObjectPattern":
  3060. this.walkObjectPattern(pattern);
  3061. break;
  3062. case "RestElement":
  3063. this.walkRestElement(pattern);
  3064. break;
  3065. }
  3066. }
  3067. /**
  3068. * @param {AssignmentPattern} pattern assignment pattern
  3069. */
  3070. walkAssignmentPattern(pattern) {
  3071. this.walkExpression(pattern.right);
  3072. this.walkPattern(pattern.left);
  3073. }
  3074. /**
  3075. * @param {ObjectPattern} pattern pattern
  3076. */
  3077. walkObjectPattern(pattern) {
  3078. for (let i = 0, len = pattern.properties.length; i < len; i++) {
  3079. const prop = pattern.properties[i];
  3080. if (prop) {
  3081. if (prop.type === "RestElement") {
  3082. continue;
  3083. }
  3084. if (prop.computed) this.walkExpression(prop.key);
  3085. if (prop.value) this.walkPattern(prop.value);
  3086. }
  3087. }
  3088. }
  3089. /**
  3090. * @param {ArrayPattern} pattern array pattern
  3091. */
  3092. walkArrayPattern(pattern) {
  3093. for (let i = 0, len = pattern.elements.length; i < len; i++) {
  3094. const element = pattern.elements[i];
  3095. if (element) this.walkPattern(element);
  3096. }
  3097. }
  3098. /**
  3099. * @param {RestElement} pattern rest element
  3100. */
  3101. walkRestElement(pattern) {
  3102. this.walkPattern(pattern.argument);
  3103. }
  3104. /**
  3105. * @param {(Expression | SpreadElement | null)[]} expressions expressions
  3106. */
  3107. walkExpressions(expressions) {
  3108. for (const expression of expressions) {
  3109. if (expression) {
  3110. this.walkExpression(expression);
  3111. }
  3112. }
  3113. }
  3114. /**
  3115. * @param {Expression | SpreadElement | PrivateIdentifier | Super} expression expression
  3116. */
  3117. walkExpression(expression) {
  3118. switch (expression.type) {
  3119. case "ArrayExpression":
  3120. this.walkArrayExpression(expression);
  3121. break;
  3122. case "ArrowFunctionExpression":
  3123. this.walkArrowFunctionExpression(expression);
  3124. break;
  3125. case "AssignmentExpression":
  3126. this.walkAssignmentExpression(expression);
  3127. break;
  3128. case "AwaitExpression":
  3129. this.walkAwaitExpression(expression);
  3130. break;
  3131. case "BinaryExpression":
  3132. this.walkBinaryExpression(expression);
  3133. break;
  3134. case "CallExpression":
  3135. this.walkCallExpression(expression);
  3136. break;
  3137. case "ChainExpression":
  3138. this.walkChainExpression(expression);
  3139. break;
  3140. case "ClassExpression":
  3141. this.walkClassExpression(expression);
  3142. break;
  3143. case "ConditionalExpression":
  3144. this.walkConditionalExpression(expression);
  3145. break;
  3146. case "FunctionExpression":
  3147. this.walkFunctionExpression(expression);
  3148. break;
  3149. case "Identifier":
  3150. this.walkIdentifier(expression);
  3151. break;
  3152. case "ImportExpression":
  3153. this.walkImportExpression(expression);
  3154. break;
  3155. case "LogicalExpression":
  3156. this.walkLogicalExpression(expression);
  3157. break;
  3158. case "MetaProperty":
  3159. this.walkMetaProperty(expression);
  3160. break;
  3161. case "MemberExpression":
  3162. this.walkMemberExpression(expression);
  3163. break;
  3164. case "NewExpression":
  3165. this.walkNewExpression(expression);
  3166. break;
  3167. case "ObjectExpression":
  3168. this.walkObjectExpression(expression);
  3169. break;
  3170. case "SequenceExpression":
  3171. this.walkSequenceExpression(expression);
  3172. break;
  3173. case "SpreadElement":
  3174. this.walkSpreadElement(expression);
  3175. break;
  3176. case "TaggedTemplateExpression":
  3177. this.walkTaggedTemplateExpression(expression);
  3178. break;
  3179. case "TemplateLiteral":
  3180. this.walkTemplateLiteral(expression);
  3181. break;
  3182. case "ThisExpression":
  3183. this.walkThisExpression(expression);
  3184. break;
  3185. case "UnaryExpression":
  3186. this.walkUnaryExpression(expression);
  3187. break;
  3188. case "UpdateExpression":
  3189. this.walkUpdateExpression(expression);
  3190. break;
  3191. case "YieldExpression":
  3192. this.walkYieldExpression(expression);
  3193. break;
  3194. }
  3195. }
  3196. /**
  3197. * @param {AwaitExpression} expression await expression
  3198. */
  3199. walkAwaitExpression(expression) {
  3200. if (this.scope.topLevelScope === true) {
  3201. this.hooks.topLevelAwait.call(expression);
  3202. }
  3203. this.walkExpression(expression.argument);
  3204. }
  3205. /**
  3206. * @param {ArrayExpression} expression array expression
  3207. */
  3208. walkArrayExpression(expression) {
  3209. if (expression.elements) {
  3210. this.walkExpressions(expression.elements);
  3211. }
  3212. }
  3213. /**
  3214. * @param {SpreadElement} expression spread element
  3215. */
  3216. walkSpreadElement(expression) {
  3217. if (expression.argument) {
  3218. this.walkExpression(expression.argument);
  3219. }
  3220. }
  3221. /**
  3222. * @param {ObjectExpression} expression object expression
  3223. */
  3224. walkObjectExpression(expression) {
  3225. for (
  3226. let propIndex = 0, len = expression.properties.length;
  3227. propIndex < len;
  3228. propIndex++
  3229. ) {
  3230. const prop = expression.properties[propIndex];
  3231. this.walkProperty(prop);
  3232. }
  3233. }
  3234. /**
  3235. * @param {Property | SpreadElement} prop property or spread element
  3236. */
  3237. walkProperty(prop) {
  3238. if (prop.type === "SpreadElement") {
  3239. this.walkExpression(prop.argument);
  3240. return;
  3241. }
  3242. if (prop.computed) {
  3243. this.walkExpression(prop.key);
  3244. }
  3245. if (prop.shorthand && prop.value && prop.value.type === "Identifier") {
  3246. this.scope.inShorthand = prop.value.name;
  3247. this.walkIdentifier(prop.value);
  3248. this.scope.inShorthand = false;
  3249. } else {
  3250. this.walkExpression(
  3251. /** @type {Exclude<Property["value"], AssignmentPattern | ObjectPattern | ArrayPattern | RestElement>} */
  3252. (prop.value)
  3253. );
  3254. }
  3255. }
  3256. /**
  3257. * @param {FunctionExpression} expression arrow function expression
  3258. */
  3259. walkFunctionExpression(expression) {
  3260. const wasTopLevel = this.scope.topLevelScope;
  3261. this.scope.topLevelScope = false;
  3262. const scopeParams = [...expression.params];
  3263. // Add function name in scope for recursive calls
  3264. if (expression.id) {
  3265. scopeParams.push(expression.id);
  3266. }
  3267. this.inFunctionScope(true, scopeParams, () => {
  3268. for (const param of expression.params) {
  3269. this.walkPattern(param);
  3270. }
  3271. this.detectMode(expression.body.body);
  3272. const prev = this.prevStatement;
  3273. this.preWalkStatement(expression.body);
  3274. this.prevStatement = prev;
  3275. this.walkStatement(expression.body);
  3276. });
  3277. this.scope.topLevelScope = wasTopLevel;
  3278. }
  3279. /**
  3280. * @param {ArrowFunctionExpression} expression arrow function expression
  3281. */
  3282. walkArrowFunctionExpression(expression) {
  3283. const wasTopLevel = this.scope.topLevelScope;
  3284. this.scope.topLevelScope = wasTopLevel ? "arrow" : false;
  3285. this.inFunctionScope(false, expression.params, () => {
  3286. for (const param of expression.params) {
  3287. this.walkPattern(param);
  3288. }
  3289. if (expression.body.type === "BlockStatement") {
  3290. this.detectMode(expression.body.body);
  3291. const prev = this.prevStatement;
  3292. this.preWalkStatement(expression.body);
  3293. this.prevStatement = prev;
  3294. this.walkStatement(expression.body);
  3295. } else {
  3296. this.walkExpression(expression.body);
  3297. }
  3298. });
  3299. this.scope.topLevelScope = wasTopLevel;
  3300. }
  3301. /**
  3302. * @param {SequenceExpression} expression the sequence
  3303. */
  3304. walkSequenceExpression(expression) {
  3305. if (!expression.expressions) return;
  3306. // We treat sequence expressions like statements when they are one statement level
  3307. // This has some benefits for optimizations that only work on statement level
  3308. const currentStatement =
  3309. /** @type {StatementPath} */
  3310. (this.statementPath)[
  3311. /** @type {StatementPath} */
  3312. (this.statementPath).length - 1
  3313. ];
  3314. if (
  3315. currentStatement === expression ||
  3316. (currentStatement.type === "ExpressionStatement" &&
  3317. currentStatement.expression === expression)
  3318. ) {
  3319. const old =
  3320. /** @type {StatementPathItem} */
  3321. (/** @type {StatementPath} */ (this.statementPath).pop());
  3322. const prev = this.prevStatement;
  3323. for (const expr of expression.expressions) {
  3324. /** @type {StatementPath} */
  3325. (this.statementPath).push(expr);
  3326. this.walkExpression(expr);
  3327. this.prevStatement =
  3328. /** @type {StatementPath} */
  3329. (this.statementPath).pop();
  3330. }
  3331. this.prevStatement = prev;
  3332. /** @type {StatementPath} */
  3333. (this.statementPath).push(old);
  3334. } else {
  3335. this.walkExpressions(expression.expressions);
  3336. }
  3337. }
  3338. /**
  3339. * @param {UpdateExpression} expression the update expression
  3340. */
  3341. walkUpdateExpression(expression) {
  3342. this.walkExpression(expression.argument);
  3343. }
  3344. /**
  3345. * @param {UnaryExpression} expression the unary expression
  3346. */
  3347. walkUnaryExpression(expression) {
  3348. if (expression.operator === "typeof") {
  3349. const result = this.callHooksForExpression(
  3350. this.hooks.typeof,
  3351. expression.argument,
  3352. expression
  3353. );
  3354. if (result === true) return;
  3355. if (expression.argument.type === "ChainExpression") {
  3356. const result = this.callHooksForExpression(
  3357. this.hooks.typeof,
  3358. expression.argument.expression,
  3359. expression
  3360. );
  3361. if (result === true) return;
  3362. }
  3363. }
  3364. this.walkExpression(expression.argument);
  3365. }
  3366. /**
  3367. * @param {LogicalExpression | BinaryExpression} expression the expression
  3368. */
  3369. walkLeftRightExpression(expression) {
  3370. this.walkExpression(expression.left);
  3371. this.walkExpression(expression.right);
  3372. }
  3373. /**
  3374. * @param {BinaryExpression} expression the binary expression
  3375. */
  3376. walkBinaryExpression(expression) {
  3377. if (this.hooks.binaryExpression.call(expression) === undefined) {
  3378. this.walkLeftRightExpression(expression);
  3379. }
  3380. }
  3381. /**
  3382. * @param {LogicalExpression} expression the logical expression
  3383. */
  3384. walkLogicalExpression(expression) {
  3385. const result = this.hooks.expressionLogicalOperator.call(expression);
  3386. if (result === undefined) {
  3387. this.walkLeftRightExpression(expression);
  3388. } else if (result) {
  3389. this.walkExpression(expression.right);
  3390. }
  3391. }
  3392. /**
  3393. * @param {AssignmentExpression} expression assignment expression
  3394. */
  3395. walkAssignmentExpression(expression) {
  3396. if (expression.left.type === "Identifier") {
  3397. const renameIdentifier = this.getRenameIdentifier(expression.right);
  3398. if (
  3399. renameIdentifier &&
  3400. this.callHooksForInfo(
  3401. this.hooks.canRename,
  3402. renameIdentifier,
  3403. expression.right
  3404. )
  3405. ) {
  3406. // renaming "a = b;"
  3407. if (
  3408. !this.callHooksForInfo(
  3409. this.hooks.rename,
  3410. renameIdentifier,
  3411. expression.right
  3412. )
  3413. ) {
  3414. this.setVariable(
  3415. expression.left.name,
  3416. typeof renameIdentifier === "string"
  3417. ? this.getVariableInfo(renameIdentifier)
  3418. : renameIdentifier
  3419. );
  3420. }
  3421. return;
  3422. }
  3423. this.walkExpression(expression.right);
  3424. this.enterPattern(expression.left, (name, _decl) => {
  3425. if (!this.callHooksForName(this.hooks.assign, name, expression)) {
  3426. this.walkExpression(
  3427. /** @type {MemberExpression} */
  3428. (expression.left)
  3429. );
  3430. }
  3431. });
  3432. } else if (expression.left.type.endsWith("Pattern")) {
  3433. this.walkExpression(expression.right);
  3434. this.enterPattern(expression.left, (name, _decl) => {
  3435. if (!this.callHooksForName(this.hooks.assign, name, expression)) {
  3436. this.defineVariable(name);
  3437. }
  3438. });
  3439. this.walkPattern(expression.left);
  3440. } else if (expression.left.type === "MemberExpression") {
  3441. const exprName = this.getMemberExpressionInfo(
  3442. expression.left,
  3443. ALLOWED_MEMBER_TYPES_EXPRESSION
  3444. );
  3445. if (
  3446. exprName &&
  3447. this.callHooksForInfo(
  3448. this.hooks.assignMemberChain,
  3449. exprName.rootInfo,
  3450. expression,
  3451. exprName.getMembers()
  3452. )
  3453. ) {
  3454. return;
  3455. }
  3456. this.walkExpression(expression.right);
  3457. this.walkExpression(expression.left);
  3458. } else {
  3459. this.walkExpression(expression.right);
  3460. this.walkExpression(
  3461. /** @type {Exclude<AssignmentExpression["left"], Identifier | RestElement | MemberExpression | ObjectPattern | ArrayPattern | AssignmentPattern>} */
  3462. (expression.left)
  3463. );
  3464. }
  3465. }
  3466. /**
  3467. * @param {ConditionalExpression} expression conditional expression
  3468. */
  3469. walkConditionalExpression(expression) {
  3470. const result = this.hooks.expressionConditionalOperator.call(expression);
  3471. if (result === undefined) {
  3472. const inGuard = this.hooks.collectGuards.call(expression.test);
  3473. if (inGuard) {
  3474. inGuard(() => {
  3475. this.walkExpression(expression.test);
  3476. this.walkExpression(expression.consequent);
  3477. });
  3478. } else {
  3479. this.walkExpression(expression.test);
  3480. this.walkExpression(expression.consequent);
  3481. }
  3482. if (expression.alternate) {
  3483. this.walkExpression(expression.alternate);
  3484. }
  3485. } else if (result) {
  3486. this.walkExpression(expression.consequent);
  3487. } else if (expression.alternate) {
  3488. this.walkExpression(expression.alternate);
  3489. }
  3490. }
  3491. /**
  3492. * @param {NewExpression} expression new expression
  3493. */
  3494. walkNewExpression(expression) {
  3495. const result = this.callHooksForExpression(
  3496. this.hooks.new,
  3497. expression.callee,
  3498. expression
  3499. );
  3500. if (result === true) return;
  3501. this.walkExpression(expression.callee);
  3502. if (expression.arguments) {
  3503. this.walkExpressions(expression.arguments);
  3504. }
  3505. }
  3506. /**
  3507. * @param {YieldExpression} expression yield expression
  3508. */
  3509. walkYieldExpression(expression) {
  3510. if (expression.argument) {
  3511. this.walkExpression(expression.argument);
  3512. }
  3513. }
  3514. /**
  3515. * @param {TemplateLiteral} expression template literal
  3516. */
  3517. walkTemplateLiteral(expression) {
  3518. if (expression.expressions) {
  3519. this.walkExpressions(expression.expressions);
  3520. }
  3521. }
  3522. /**
  3523. * @param {TaggedTemplateExpression} expression tagged template expression
  3524. */
  3525. walkTaggedTemplateExpression(expression) {
  3526. if (expression.tag) {
  3527. this.scope.inTaggedTemplateTag = true;
  3528. this.walkExpression(expression.tag);
  3529. this.scope.inTaggedTemplateTag = false;
  3530. }
  3531. if (expression.quasi && expression.quasi.expressions) {
  3532. this.walkExpressions(expression.quasi.expressions);
  3533. }
  3534. }
  3535. /**
  3536. * @param {ClassExpression} expression the class expression
  3537. */
  3538. walkClassExpression(expression) {
  3539. this.walkClass(expression);
  3540. }
  3541. /**
  3542. * @param {ChainExpression} expression expression
  3543. */
  3544. walkChainExpression(expression) {
  3545. const result = this.hooks.optionalChaining.call(expression);
  3546. if (result === undefined) {
  3547. if (expression.expression.type === "CallExpression") {
  3548. this.walkCallExpression(expression.expression);
  3549. } else {
  3550. this.walkMemberExpression(expression.expression);
  3551. }
  3552. }
  3553. }
  3554. /**
  3555. * @private
  3556. * @param {FunctionExpression | ArrowFunctionExpression} functionExpression function expression
  3557. * @param {(Expression | SpreadElement)[]} options options
  3558. * @param {Expression | SpreadElement | null} currentThis current this
  3559. */
  3560. _walkIIFE(functionExpression, options, currentThis) {
  3561. /**
  3562. * @param {Expression | SpreadElement} argOrThis arg or this
  3563. * @returns {string | VariableInfo | undefined} var info
  3564. */
  3565. const getVarInfo = (argOrThis) => {
  3566. const renameIdentifier = this.getRenameIdentifier(argOrThis);
  3567. if (
  3568. renameIdentifier &&
  3569. this.callHooksForInfo(
  3570. this.hooks.canRename,
  3571. renameIdentifier,
  3572. /** @type {Expression} */
  3573. (argOrThis)
  3574. ) &&
  3575. !this.callHooksForInfo(
  3576. this.hooks.rename,
  3577. renameIdentifier,
  3578. /** @type {Expression} */
  3579. (argOrThis)
  3580. )
  3581. ) {
  3582. return typeof renameIdentifier === "string"
  3583. ? /** @type {string} */ (this.getVariableInfo(renameIdentifier))
  3584. : renameIdentifier;
  3585. }
  3586. this.walkExpression(argOrThis);
  3587. };
  3588. const { params, type } = functionExpression;
  3589. const arrow = type === "ArrowFunctionExpression";
  3590. const renameThis = currentThis ? getVarInfo(currentThis) : null;
  3591. const varInfoForArgs = options.map(getVarInfo);
  3592. const wasTopLevel = this.scope.topLevelScope;
  3593. this.scope.topLevelScope = wasTopLevel && arrow ? "arrow" : false;
  3594. const scopeParams =
  3595. /** @type {(Identifier | string)[]} */
  3596. (params.filter((identifier, idx) => !varInfoForArgs[idx]));
  3597. // Add function name in scope for recursive calls
  3598. if (
  3599. functionExpression.type === "FunctionExpression" &&
  3600. functionExpression.id
  3601. ) {
  3602. scopeParams.push(functionExpression.id.name);
  3603. }
  3604. this.inFunctionScope(true, scopeParams, () => {
  3605. if (renameThis && !arrow) {
  3606. this.setVariable("this", renameThis);
  3607. }
  3608. for (let i = 0; i < varInfoForArgs.length; i++) {
  3609. const varInfo = varInfoForArgs[i];
  3610. if (!varInfo) continue;
  3611. if (!params[i] || params[i].type !== "Identifier") continue;
  3612. this.setVariable(/** @type {Identifier} */ (params[i]).name, varInfo);
  3613. }
  3614. if (functionExpression.body.type === "BlockStatement") {
  3615. this.detectMode(functionExpression.body.body);
  3616. const prev = this.prevStatement;
  3617. this.preWalkStatement(functionExpression.body);
  3618. this.prevStatement = prev;
  3619. this.walkStatement(functionExpression.body);
  3620. } else {
  3621. this.walkExpression(functionExpression.body);
  3622. }
  3623. });
  3624. this.scope.topLevelScope = wasTopLevel;
  3625. }
  3626. /**
  3627. * @param {ImportExpression} expression import expression
  3628. */
  3629. walkImportExpression(expression) {
  3630. const result = this.hooks.importCall.call(expression);
  3631. if (result === true) return;
  3632. this.walkExpression(expression.source);
  3633. }
  3634. /**
  3635. * @param {CallExpression} expression expression
  3636. */
  3637. walkCallExpression(expression) {
  3638. /**
  3639. * @param {FunctionExpression | ArrowFunctionExpression} fn function
  3640. * @returns {boolean} true when simple function
  3641. */
  3642. const isSimpleFunction = (fn) =>
  3643. fn.params.every((p) => p.type === "Identifier");
  3644. if (
  3645. expression.callee.type === "MemberExpression" &&
  3646. expression.callee.object.type.endsWith("FunctionExpression") &&
  3647. !expression.callee.computed &&
  3648. /** @type {boolean} */
  3649. (
  3650. /** @type {Identifier} */
  3651. (expression.callee.property).name === "call" ||
  3652. /** @type {Identifier} */
  3653. (expression.callee.property).name === "bind"
  3654. ) &&
  3655. expression.arguments.length > 0 &&
  3656. isSimpleFunction(
  3657. /** @type {FunctionExpression | ArrowFunctionExpression} */
  3658. (expression.callee.object)
  3659. )
  3660. ) {
  3661. // (function(…) { }.call/bind(?, …))
  3662. this._walkIIFE(
  3663. /** @type {FunctionExpression | ArrowFunctionExpression} */
  3664. (expression.callee.object),
  3665. expression.arguments.slice(1),
  3666. expression.arguments[0]
  3667. );
  3668. } else if (
  3669. expression.callee.type.endsWith("FunctionExpression") &&
  3670. isSimpleFunction(
  3671. /** @type {FunctionExpression | ArrowFunctionExpression} */
  3672. (expression.callee)
  3673. )
  3674. ) {
  3675. // (function(…) { }(…))
  3676. this._walkIIFE(
  3677. /** @type {FunctionExpression | ArrowFunctionExpression} */
  3678. (expression.callee),
  3679. expression.arguments,
  3680. null
  3681. );
  3682. } else {
  3683. if (expression.callee.type === "MemberExpression") {
  3684. const exprInfo = this.getMemberExpressionInfo(
  3685. expression.callee,
  3686. ALLOWED_MEMBER_TYPES_CALL_EXPRESSION
  3687. );
  3688. if (exprInfo && exprInfo.type === "call") {
  3689. const result = this.callHooksForInfo(
  3690. this.hooks.callMemberChainOfCallMemberChain,
  3691. exprInfo.rootInfo,
  3692. expression,
  3693. exprInfo.getCalleeMembers(),
  3694. exprInfo.call,
  3695. exprInfo.getMembers(),
  3696. exprInfo.getMemberRanges()
  3697. );
  3698. if (result === true) return;
  3699. }
  3700. // import("./m").then(m => { ... })
  3701. if (
  3702. expression.callee.object.type === "ImportExpression" &&
  3703. expression.callee.property.type === "Identifier" &&
  3704. expression.callee.property.name === "then"
  3705. ) {
  3706. const result = this.hooks.importCall.call(
  3707. expression.callee.object,
  3708. expression
  3709. );
  3710. if (result === true) return;
  3711. }
  3712. }
  3713. const callee = this.evaluateExpression(expression.callee);
  3714. if (callee.isIdentifier()) {
  3715. const result1 = this.callHooksForInfo(
  3716. this.hooks.callMemberChain,
  3717. /** @type {NonNullable<BasicEvaluatedExpression["rootInfo"]>} */
  3718. (callee.rootInfo),
  3719. expression,
  3720. /** @type {NonNullable<BasicEvaluatedExpression["getMembers"]>} */
  3721. (callee.getMembers)(),
  3722. callee.getMembersOptionals
  3723. ? callee.getMembersOptionals()
  3724. : /** @type {NonNullable<BasicEvaluatedExpression["getMembers"]>} */
  3725. (callee.getMembers)().map(() => false),
  3726. callee.getMemberRanges ? callee.getMemberRanges() : []
  3727. );
  3728. if (result1 === true) return;
  3729. const result2 = this.callHooksForInfo(
  3730. this.hooks.call,
  3731. /** @type {NonNullable<BasicEvaluatedExpression["identifier"]>} */
  3732. (callee.identifier),
  3733. expression
  3734. );
  3735. if (result2 === true) return;
  3736. }
  3737. if (expression.callee) {
  3738. if (expression.callee.type === "MemberExpression") {
  3739. // because of call context we need to walk the call context as expression
  3740. this.walkExpression(expression.callee.object);
  3741. if (expression.callee.computed === true) {
  3742. this.walkExpression(expression.callee.property);
  3743. }
  3744. } else {
  3745. this.walkExpression(expression.callee);
  3746. }
  3747. }
  3748. if (expression.arguments) this.walkExpressions(expression.arguments);
  3749. }
  3750. }
  3751. /**
  3752. * @param {MemberExpression} expression member expression
  3753. */
  3754. walkMemberExpression(expression) {
  3755. const exprInfo = this.getMemberExpressionInfo(
  3756. expression,
  3757. ALLOWED_MEMBER_TYPES_ALL
  3758. );
  3759. if (exprInfo) {
  3760. switch (exprInfo.type) {
  3761. case "expression": {
  3762. const result1 = this.callHooksForInfo(
  3763. this.hooks.expression,
  3764. exprInfo.name,
  3765. expression
  3766. );
  3767. if (result1 === true) return;
  3768. const members = exprInfo.getMembers();
  3769. const membersOptionals = exprInfo.getMembersOptionals();
  3770. const memberRanges = exprInfo.getMemberRanges();
  3771. const result2 = this.callHooksForInfo(
  3772. this.hooks.expressionMemberChain,
  3773. exprInfo.rootInfo,
  3774. expression,
  3775. members,
  3776. membersOptionals,
  3777. memberRanges
  3778. );
  3779. if (result2 === true) return;
  3780. this.walkMemberExpressionWithExpressionName(
  3781. expression,
  3782. exprInfo.name,
  3783. exprInfo.rootInfo,
  3784. [...members],
  3785. () =>
  3786. this.callHooksForInfo(
  3787. this.hooks.unhandledExpressionMemberChain,
  3788. exprInfo.rootInfo,
  3789. expression,
  3790. members
  3791. )
  3792. );
  3793. return;
  3794. }
  3795. case "call": {
  3796. const result = this.callHooksForInfo(
  3797. this.hooks.memberChainOfCallMemberChain,
  3798. exprInfo.rootInfo,
  3799. expression,
  3800. exprInfo.getCalleeMembers(),
  3801. exprInfo.call,
  3802. exprInfo.getMembers(),
  3803. exprInfo.getMemberRanges()
  3804. );
  3805. if (result === true) return;
  3806. // Fast skip over the member chain as we already called memberChainOfCallMemberChain
  3807. // and call computed property are literals anyway
  3808. this.walkExpression(exprInfo.call);
  3809. return;
  3810. }
  3811. }
  3812. }
  3813. this.walkExpression(expression.object);
  3814. if (expression.computed === true) this.walkExpression(expression.property);
  3815. }
  3816. /**
  3817. * @template R
  3818. * @param {MemberExpression} expression member expression
  3819. * @param {string} name name
  3820. * @param {string | VariableInfo} rootInfo root info
  3821. * @param {Members} members members
  3822. * @param {() => R | undefined} onUnhandled on unhandled callback
  3823. */
  3824. walkMemberExpressionWithExpressionName(
  3825. expression,
  3826. name,
  3827. rootInfo,
  3828. members,
  3829. onUnhandled
  3830. ) {
  3831. if (expression.object.type === "MemberExpression") {
  3832. // optimize the case where expression.object is a MemberExpression too.
  3833. // we can keep info here when calling walkMemberExpression directly
  3834. const property =
  3835. /** @type {Identifier} */
  3836. (expression.property).name ||
  3837. `${/** @type {Literal} */ (expression.property).value}`;
  3838. name = name.slice(0, -property.length - 1);
  3839. members.pop();
  3840. const result = this.callHooksForInfo(
  3841. this.hooks.expression,
  3842. name,
  3843. expression.object
  3844. );
  3845. if (result === true) return;
  3846. this.walkMemberExpressionWithExpressionName(
  3847. expression.object,
  3848. name,
  3849. rootInfo,
  3850. members,
  3851. onUnhandled
  3852. );
  3853. } else if (!onUnhandled || !onUnhandled()) {
  3854. this.walkExpression(expression.object);
  3855. }
  3856. if (expression.computed === true) this.walkExpression(expression.property);
  3857. }
  3858. /**
  3859. * @param {ThisExpression} expression this expression
  3860. */
  3861. walkThisExpression(expression) {
  3862. this.callHooksForName(this.hooks.expression, "this", expression);
  3863. }
  3864. /**
  3865. * @param {Identifier} expression identifier
  3866. */
  3867. walkIdentifier(expression) {
  3868. this.callHooksForName(this.hooks.expression, expression.name, expression);
  3869. }
  3870. /**
  3871. * @param {MetaProperty} metaProperty meta property
  3872. */
  3873. walkMetaProperty(metaProperty) {
  3874. this.hooks.expression.for(getRootName(metaProperty)).call(metaProperty);
  3875. }
  3876. /**
  3877. * @template T
  3878. * @template R
  3879. * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
  3880. * @param {Expression | Super} expr expression
  3881. * @param {AsArray<T>} args args for the hook
  3882. * @returns {R | undefined} result of hook
  3883. */
  3884. callHooksForExpression(hookMap, expr, ...args) {
  3885. return this.callHooksForExpressionWithFallback(
  3886. hookMap,
  3887. expr,
  3888. undefined,
  3889. undefined,
  3890. ...args
  3891. );
  3892. }
  3893. /**
  3894. * @template T
  3895. * @template R
  3896. * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
  3897. * @param {Expression | Super} expr expression info
  3898. * @param {((name: string, rootInfo: string | ScopeInfo | VariableInfo, getMembers: () => Members) => R) | undefined} fallback callback when variable in not handled by hooks
  3899. * @param {((result?: string) => R | undefined) | undefined} defined callback when variable is defined
  3900. * @param {AsArray<T>} args args for the hook
  3901. * @returns {R | undefined} result of hook
  3902. */
  3903. callHooksForExpressionWithFallback(
  3904. hookMap,
  3905. expr,
  3906. fallback,
  3907. defined,
  3908. ...args
  3909. ) {
  3910. const exprName = this.getMemberExpressionInfo(
  3911. expr,
  3912. ALLOWED_MEMBER_TYPES_EXPRESSION
  3913. );
  3914. if (exprName !== undefined) {
  3915. const members = exprName.getMembers();
  3916. return this.callHooksForInfoWithFallback(
  3917. hookMap,
  3918. members.length === 0 ? exprName.rootInfo : exprName.name,
  3919. fallback &&
  3920. ((name) => fallback(name, exprName.rootInfo, exprName.getMembers)),
  3921. defined && (() => defined(exprName.name)),
  3922. ...args
  3923. );
  3924. }
  3925. }
  3926. /**
  3927. * @template T
  3928. * @template R
  3929. * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
  3930. * @param {string} name key in map
  3931. * @param {AsArray<T>} args args for the hook
  3932. * @returns {R | undefined} result of hook
  3933. */
  3934. callHooksForName(hookMap, name, ...args) {
  3935. return this.callHooksForNameWithFallback(
  3936. hookMap,
  3937. name,
  3938. undefined,
  3939. undefined,
  3940. ...args
  3941. );
  3942. }
  3943. /**
  3944. * @template T
  3945. * @template R
  3946. * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks that should be called
  3947. * @param {ExportedVariableInfo} info variable info
  3948. * @param {AsArray<T>} args args for the hook
  3949. * @returns {R | undefined} result of hook
  3950. */
  3951. callHooksForInfo(hookMap, info, ...args) {
  3952. return this.callHooksForInfoWithFallback(
  3953. hookMap,
  3954. info,
  3955. undefined,
  3956. undefined,
  3957. ...args
  3958. );
  3959. }
  3960. /**
  3961. * @template T
  3962. * @template R
  3963. * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
  3964. * @param {ExportedVariableInfo} info variable info
  3965. * @param {((name: string) => R | undefined) | undefined} fallback callback when variable in not handled by hooks
  3966. * @param {((result?: string) => R | undefined) | undefined} defined callback when variable is defined
  3967. * @param {AsArray<T>} args args for the hook
  3968. * @returns {R | undefined} result of hook
  3969. */
  3970. callHooksForInfoWithFallback(hookMap, info, fallback, defined, ...args) {
  3971. /** @type {string} */
  3972. let name;
  3973. if (typeof info === "string") {
  3974. name = info;
  3975. } else {
  3976. if (!(info instanceof VariableInfo)) {
  3977. if (defined !== undefined) {
  3978. return defined();
  3979. }
  3980. return;
  3981. }
  3982. let tagInfo = info.tagInfo;
  3983. while (tagInfo !== undefined) {
  3984. const hook = hookMap.get(tagInfo.tag);
  3985. if (hook !== undefined) {
  3986. this.currentTagData = tagInfo.data;
  3987. const result = hook.call(...args);
  3988. this.currentTagData = undefined;
  3989. if (result !== undefined) return result;
  3990. }
  3991. tagInfo = tagInfo.next;
  3992. }
  3993. if (!info.isFree() && !info.isTagged()) {
  3994. if (defined !== undefined) {
  3995. return defined();
  3996. }
  3997. return;
  3998. }
  3999. name = /** @type {string} */ (info.name);
  4000. }
  4001. const hook = hookMap.get(name);
  4002. if (hook !== undefined) {
  4003. const result = hook.call(...args);
  4004. if (result !== undefined) return result;
  4005. }
  4006. if (fallback !== undefined) {
  4007. return fallback(name);
  4008. }
  4009. }
  4010. /**
  4011. * @template T
  4012. * @template R
  4013. * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
  4014. * @param {string} name key in map
  4015. * @param {((value: string) => R | undefined) | undefined} fallback callback when variable in not handled by hooks
  4016. * @param {(() => R) | undefined} defined callback when variable is defined
  4017. * @param {AsArray<T>} args args for the hook
  4018. * @returns {R | undefined} result of hook
  4019. */
  4020. callHooksForNameWithFallback(hookMap, name, fallback, defined, ...args) {
  4021. return this.callHooksForInfoWithFallback(
  4022. hookMap,
  4023. this.getVariableInfo(name),
  4024. fallback,
  4025. defined,
  4026. ...args
  4027. );
  4028. }
  4029. /**
  4030. * @deprecated
  4031. * @param {(string | Pattern | Property)[]} params scope params
  4032. * @param {() => void} fn inner function
  4033. * @returns {void}
  4034. */
  4035. inScope(params, fn) {
  4036. const oldScope = this.scope;
  4037. this.scope = {
  4038. topLevelScope: oldScope.topLevelScope,
  4039. inTry: false,
  4040. inShorthand: false,
  4041. inTaggedTemplateTag: false,
  4042. isStrict: oldScope.isStrict,
  4043. isAsmJs: oldScope.isAsmJs,
  4044. terminated: undefined,
  4045. definitions: oldScope.definitions.createChild()
  4046. };
  4047. this.undefineVariable("this");
  4048. this.enterPatterns(params, (ident) => {
  4049. this.defineVariable(ident);
  4050. });
  4051. fn();
  4052. this.scope = oldScope;
  4053. }
  4054. /**
  4055. * @param {boolean} hasThis true, when this is defined
  4056. * @param {Identifier[]} params scope params
  4057. * @param {() => void} fn inner function
  4058. * @returns {void}
  4059. */
  4060. inClassScope(hasThis, params, fn) {
  4061. const oldScope = this.scope;
  4062. this.scope = {
  4063. topLevelScope: oldScope.topLevelScope,
  4064. inTry: false,
  4065. inShorthand: false,
  4066. inTaggedTemplateTag: false,
  4067. isStrict: oldScope.isStrict,
  4068. isAsmJs: oldScope.isAsmJs,
  4069. terminated: undefined,
  4070. definitions: oldScope.definitions.createChild()
  4071. };
  4072. if (hasThis) {
  4073. this.undefineVariable("this");
  4074. }
  4075. this.enterPatterns(params, (ident) => {
  4076. this.defineVariable(ident);
  4077. });
  4078. fn();
  4079. this.scope = oldScope;
  4080. }
  4081. /**
  4082. * @param {boolean} hasThis true, when this is defined
  4083. * @param {(Pattern | string)[]} params scope params
  4084. * @param {() => void} fn inner function
  4085. * @returns {void}
  4086. */
  4087. inFunctionScope(hasThis, params, fn) {
  4088. const oldScope = this.scope;
  4089. this.scope = {
  4090. topLevelScope: oldScope.topLevelScope,
  4091. inTry: false,
  4092. inShorthand: false,
  4093. inTaggedTemplateTag: false,
  4094. isStrict: oldScope.isStrict,
  4095. isAsmJs: oldScope.isAsmJs,
  4096. terminated: undefined,
  4097. definitions: oldScope.definitions.createChild()
  4098. };
  4099. if (hasThis) {
  4100. this.undefineVariable("this");
  4101. }
  4102. this.enterPatterns(params, (ident) => {
  4103. this.defineVariable(ident);
  4104. });
  4105. fn();
  4106. this.scope = oldScope;
  4107. }
  4108. /**
  4109. * @param {() => void} fn inner function
  4110. * @param {boolean} inExecutedPath executed state
  4111. * @returns {void}
  4112. */
  4113. inBlockScope(fn, inExecutedPath = false) {
  4114. const oldScope = this.scope;
  4115. this.scope = {
  4116. topLevelScope: oldScope.topLevelScope,
  4117. inTry: oldScope.inTry,
  4118. inShorthand: false,
  4119. inTaggedTemplateTag: false,
  4120. isStrict: oldScope.isStrict,
  4121. isAsmJs: oldScope.isAsmJs,
  4122. terminated: oldScope.terminated,
  4123. definitions: oldScope.definitions.createChild()
  4124. };
  4125. fn();
  4126. const terminated = this.scope.terminated;
  4127. if (inExecutedPath && terminated) {
  4128. oldScope.terminated = terminated;
  4129. }
  4130. this.scope = oldScope;
  4131. }
  4132. /**
  4133. * @param {(Directive | Statement | ModuleDeclaration)[]} statements statements
  4134. */
  4135. detectMode(statements) {
  4136. const isLiteral =
  4137. statements.length >= 1 &&
  4138. statements[0].type === "ExpressionStatement" &&
  4139. statements[0].expression.type === "Literal";
  4140. if (
  4141. isLiteral &&
  4142. /** @type {Literal} */
  4143. (/** @type {ExpressionStatement} */ (statements[0]).expression).value ===
  4144. "use strict"
  4145. ) {
  4146. this.scope.isStrict = true;
  4147. }
  4148. if (
  4149. isLiteral &&
  4150. /** @type {Literal} */
  4151. (/** @type {ExpressionStatement} */ (statements[0]).expression).value ===
  4152. "use asm"
  4153. ) {
  4154. this.scope.isAsmJs = true;
  4155. }
  4156. }
  4157. /**
  4158. * @param {(string | Pattern | Property)[]} patterns patterns
  4159. * @param {OnIdentString} onIdent on ident callback
  4160. */
  4161. enterPatterns(patterns, onIdent) {
  4162. for (const pattern of patterns) {
  4163. if (typeof pattern !== "string") {
  4164. this.enterPattern(pattern, onIdent);
  4165. } else if (pattern) {
  4166. onIdent(pattern);
  4167. }
  4168. }
  4169. }
  4170. /**
  4171. * @param {Pattern | Property} pattern pattern
  4172. * @param {OnIdent} onIdent on ident callback
  4173. */
  4174. enterPattern(pattern, onIdent) {
  4175. if (!pattern) return;
  4176. switch (pattern.type) {
  4177. case "ArrayPattern":
  4178. this.enterArrayPattern(pattern, onIdent);
  4179. break;
  4180. case "AssignmentPattern":
  4181. this.enterAssignmentPattern(pattern, onIdent);
  4182. break;
  4183. case "Identifier":
  4184. this.enterIdentifier(pattern, onIdent);
  4185. break;
  4186. case "ObjectPattern":
  4187. this.enterObjectPattern(pattern, onIdent);
  4188. break;
  4189. case "RestElement":
  4190. this.enterRestElement(pattern, onIdent);
  4191. break;
  4192. case "Property":
  4193. if (pattern.shorthand && pattern.value.type === "Identifier") {
  4194. this.scope.inShorthand = pattern.value.name;
  4195. this.enterIdentifier(pattern.value, onIdent);
  4196. this.scope.inShorthand = false;
  4197. } else {
  4198. this.enterPattern(/** @type {Pattern} */ (pattern.value), onIdent);
  4199. }
  4200. break;
  4201. }
  4202. }
  4203. /**
  4204. * @param {Identifier} pattern identifier pattern
  4205. * @param {OnIdent} onIdent callback
  4206. */
  4207. enterIdentifier(pattern, onIdent) {
  4208. if (!this.callHooksForName(this.hooks.pattern, pattern.name, pattern)) {
  4209. onIdent(pattern.name, pattern);
  4210. }
  4211. }
  4212. /**
  4213. * @param {ObjectPattern} pattern object pattern
  4214. * @param {OnIdent} onIdent callback
  4215. */
  4216. enterObjectPattern(pattern, onIdent) {
  4217. for (
  4218. let propIndex = 0, len = pattern.properties.length;
  4219. propIndex < len;
  4220. propIndex++
  4221. ) {
  4222. const prop = pattern.properties[propIndex];
  4223. this.enterPattern(prop, onIdent);
  4224. }
  4225. }
  4226. /**
  4227. * @param {ArrayPattern} pattern object pattern
  4228. * @param {OnIdent} onIdent callback
  4229. */
  4230. enterArrayPattern(pattern, onIdent) {
  4231. for (
  4232. let elementIndex = 0, len = pattern.elements.length;
  4233. elementIndex < len;
  4234. elementIndex++
  4235. ) {
  4236. const element = pattern.elements[elementIndex];
  4237. if (element) {
  4238. this.enterPattern(element, onIdent);
  4239. }
  4240. }
  4241. }
  4242. /**
  4243. * @param {RestElement} pattern object pattern
  4244. * @param {OnIdent} onIdent callback
  4245. */
  4246. enterRestElement(pattern, onIdent) {
  4247. this.enterPattern(pattern.argument, onIdent);
  4248. }
  4249. /**
  4250. * @param {AssignmentPattern} pattern object pattern
  4251. * @param {OnIdent} onIdent callback
  4252. */
  4253. enterAssignmentPattern(pattern, onIdent) {
  4254. this.enterPattern(pattern.left, onIdent);
  4255. }
  4256. /**
  4257. * @param {Expression | SpreadElement | PrivateIdentifier | Super} expression expression node
  4258. * @returns {BasicEvaluatedExpression} evaluation result
  4259. */
  4260. evaluateExpression(expression) {
  4261. try {
  4262. const hook = this.hooks.evaluate.get(expression.type);
  4263. if (hook !== undefined) {
  4264. const result = hook.call(expression);
  4265. if (result !== undefined && result !== null) {
  4266. result.setExpression(expression);
  4267. return result;
  4268. }
  4269. }
  4270. } catch (err) {
  4271. // eslint-disable-next-line no-console
  4272. console.warn(err);
  4273. // ignore error
  4274. }
  4275. return new BasicEvaluatedExpression()
  4276. .setRange(/** @type {Range} */ (expression.range))
  4277. .setExpression(expression);
  4278. }
  4279. /**
  4280. * @param {Expression} expression expression
  4281. * @returns {string} parsed string
  4282. */
  4283. parseString(expression) {
  4284. switch (expression.type) {
  4285. case "BinaryExpression":
  4286. if (expression.operator === "+") {
  4287. return (
  4288. this.parseString(/** @type {Expression} */ (expression.left)) +
  4289. this.parseString(expression.right)
  4290. );
  4291. }
  4292. break;
  4293. case "Literal":
  4294. return String(expression.value);
  4295. }
  4296. throw new Error(
  4297. `${expression.type} is not supported as parameter for require`
  4298. );
  4299. }
  4300. /** @typedef {{ range?: Range, value: string, code: boolean, conditional: false | CalculatedStringResult[] }} CalculatedStringResult */
  4301. /**
  4302. * @param {Expression} expression expression
  4303. * @returns {CalculatedStringResult} result
  4304. */
  4305. parseCalculatedString(expression) {
  4306. switch (expression.type) {
  4307. case "BinaryExpression":
  4308. if (expression.operator === "+") {
  4309. const left = this.parseCalculatedString(
  4310. /** @type {Expression} */
  4311. (expression.left)
  4312. );
  4313. const right = this.parseCalculatedString(expression.right);
  4314. if (left.code) {
  4315. return {
  4316. range: left.range,
  4317. value: left.value,
  4318. code: true,
  4319. conditional: false
  4320. };
  4321. } else if (right.code) {
  4322. return {
  4323. range: [
  4324. /** @type {Range} */
  4325. (left.range)[0],
  4326. right.range
  4327. ? right.range[1]
  4328. : /** @type {Range} */ (left.range)[1]
  4329. ],
  4330. value: left.value + right.value,
  4331. code: true,
  4332. conditional: false
  4333. };
  4334. }
  4335. return {
  4336. range: [
  4337. /** @type {Range} */
  4338. (left.range)[0],
  4339. /** @type {Range} */
  4340. (right.range)[1]
  4341. ],
  4342. value: left.value + right.value,
  4343. code: false,
  4344. conditional: false
  4345. };
  4346. }
  4347. break;
  4348. case "ConditionalExpression": {
  4349. const consequent = this.parseCalculatedString(expression.consequent);
  4350. const alternate = this.parseCalculatedString(expression.alternate);
  4351. /** @type {CalculatedStringResult[]} */
  4352. const items = [];
  4353. if (consequent.conditional) {
  4354. items.push(...consequent.conditional);
  4355. } else if (!consequent.code) {
  4356. items.push(consequent);
  4357. } else {
  4358. break;
  4359. }
  4360. if (alternate.conditional) {
  4361. items.push(...alternate.conditional);
  4362. } else if (!alternate.code) {
  4363. items.push(alternate);
  4364. } else {
  4365. break;
  4366. }
  4367. return {
  4368. range: undefined,
  4369. value: "",
  4370. code: true,
  4371. conditional: items
  4372. };
  4373. }
  4374. case "Literal":
  4375. return {
  4376. range: expression.range,
  4377. value: String(expression.value),
  4378. code: false,
  4379. conditional: false
  4380. };
  4381. }
  4382. return {
  4383. range: undefined,
  4384. value: "",
  4385. code: true,
  4386. conditional: false
  4387. };
  4388. }
  4389. /**
  4390. * @param {string | Buffer | PreparsedAst} source the source to parse
  4391. * @param {ParserState} state the parser state
  4392. * @returns {ParserState} the parser state
  4393. */
  4394. parse(source, state) {
  4395. if (source === null) {
  4396. throw new Error("source must not be null");
  4397. }
  4398. if (Buffer.isBuffer(source)) {
  4399. source = source.toString("utf8");
  4400. }
  4401. let ast;
  4402. /** @type {Comment[]} */
  4403. let comments;
  4404. /** @type {Set<number>} */
  4405. let semicolons;
  4406. if (typeof source === "object") {
  4407. semicolons = new Set();
  4408. ast = /** @type {Program} */ (source);
  4409. comments = source.comments;
  4410. if (source.semicolons) {
  4411. // Forward semicolon information from the preparsed AST if present
  4412. // This ensures the output is consistent with that of a fresh AST
  4413. for (const pos of source.semicolons) {
  4414. semicolons.add(pos);
  4415. }
  4416. }
  4417. } else {
  4418. ({ ast, comments, semicolons } = JavascriptParser._parse(
  4419. source,
  4420. {
  4421. sourceType: this.sourceType,
  4422. locations: true,
  4423. ranges: true,
  4424. comments: true,
  4425. semicolons: true
  4426. },
  4427. this.options.parse
  4428. ));
  4429. }
  4430. const oldScope = this.scope;
  4431. const oldState = this.state;
  4432. const oldComments = this.comments;
  4433. const oldSemicolons = this.semicolons;
  4434. const oldStatementPath = this.statementPath;
  4435. const oldPrevStatement = this.prevStatement;
  4436. this.scope = {
  4437. topLevelScope: true,
  4438. inTry: false,
  4439. inShorthand: false,
  4440. inTaggedTemplateTag: false,
  4441. isStrict: false,
  4442. isAsmJs: false,
  4443. terminated: undefined,
  4444. definitions: new StackedMap()
  4445. };
  4446. this.state = state;
  4447. this.comments = comments;
  4448. this.semicolons = semicolons;
  4449. this.statementPath = [];
  4450. this.prevStatement = undefined;
  4451. if (this.hooks.program.call(ast, comments) === undefined) {
  4452. this.destructuringAssignmentProperties = new WeakMap();
  4453. this.detectMode(ast.body);
  4454. this.modulePreWalkStatements(ast.body);
  4455. this.preWalkStatements(ast.body);
  4456. this.prevStatement = undefined;
  4457. this.blockPreWalkStatements(ast.body);
  4458. this.prevStatement = undefined;
  4459. this.walkStatements(ast.body);
  4460. this.destructuringAssignmentProperties = undefined;
  4461. }
  4462. this.hooks.finish.call(ast, comments);
  4463. this.scope = oldScope;
  4464. this.state = oldState;
  4465. this.comments = oldComments;
  4466. this.semicolons = oldSemicolons;
  4467. this.statementPath = oldStatementPath;
  4468. this.prevStatement = oldPrevStatement;
  4469. return state;
  4470. }
  4471. /**
  4472. * @param {string} source source code
  4473. * @returns {BasicEvaluatedExpression} evaluation result
  4474. */
  4475. evaluate(source) {
  4476. const { ast } = JavascriptParser._parse(
  4477. `(${source})`,
  4478. { sourceType: this.sourceType },
  4479. this.options.parse
  4480. );
  4481. if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") {
  4482. throw new Error("evaluate: Source is not a expression");
  4483. }
  4484. return this.evaluateExpression(ast.body[0].expression);
  4485. }
  4486. /**
  4487. * @param {Expression | Declaration | PrivateIdentifier | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | null | undefined} expr an expression
  4488. * @param {number} commentsStartPos source position from which annotation comments are checked
  4489. * @returns {boolean} true, when the expression is pure
  4490. */
  4491. isPure(expr, commentsStartPos) {
  4492. if (!expr) return true;
  4493. const result = this.hooks.isPure
  4494. .for(expr.type)
  4495. .call(expr, commentsStartPos);
  4496. if (typeof result === "boolean") return result;
  4497. switch (expr.type) {
  4498. // TODO handle more cases
  4499. case "ClassDeclaration":
  4500. case "ClassExpression": {
  4501. if (expr.body.type !== "ClassBody") return false;
  4502. if (
  4503. expr.superClass &&
  4504. !this.isPure(expr.superClass, /** @type {Range} */ (expr.range)[0])
  4505. ) {
  4506. return false;
  4507. }
  4508. const items = expr.body.body;
  4509. return items.every((item) => {
  4510. if (item.type === "StaticBlock") {
  4511. return false;
  4512. }
  4513. if (
  4514. item.computed &&
  4515. item.key &&
  4516. !this.isPure(
  4517. item.key,
  4518. /** @type {Range} */
  4519. (item.range)[0]
  4520. )
  4521. ) {
  4522. return false;
  4523. }
  4524. if (
  4525. item.static &&
  4526. item.value &&
  4527. !this.isPure(
  4528. item.value,
  4529. item.key
  4530. ? /** @type {Range} */ (item.key.range)[1]
  4531. : /** @type {Range} */ (item.range)[0]
  4532. )
  4533. ) {
  4534. return false;
  4535. }
  4536. if (
  4537. expr.superClass &&
  4538. item.type === "MethodDefinition" &&
  4539. item.kind === "constructor"
  4540. ) {
  4541. return false;
  4542. }
  4543. return true;
  4544. });
  4545. }
  4546. case "FunctionDeclaration":
  4547. case "FunctionExpression":
  4548. case "ArrowFunctionExpression":
  4549. case "ThisExpression":
  4550. case "Literal":
  4551. case "TemplateLiteral":
  4552. case "Identifier":
  4553. case "PrivateIdentifier":
  4554. return true;
  4555. case "VariableDeclaration":
  4556. return expr.declarations.every((decl) =>
  4557. this.isPure(decl.init, /** @type {Range} */ (decl.range)[0])
  4558. );
  4559. case "ConditionalExpression":
  4560. return (
  4561. this.isPure(expr.test, commentsStartPos) &&
  4562. this.isPure(
  4563. expr.consequent,
  4564. /** @type {Range} */ (expr.test.range)[1]
  4565. ) &&
  4566. this.isPure(
  4567. expr.alternate,
  4568. /** @type {Range} */ (expr.consequent.range)[1]
  4569. )
  4570. );
  4571. case "LogicalExpression":
  4572. return (
  4573. this.isPure(expr.left, commentsStartPos) &&
  4574. this.isPure(expr.right, /** @type {Range} */ (expr.left.range)[1])
  4575. );
  4576. case "SequenceExpression":
  4577. return expr.expressions.every((expr) => {
  4578. const pureFlag = this.isPure(expr, commentsStartPos);
  4579. commentsStartPos = /** @type {Range} */ (expr.range)[1];
  4580. return pureFlag;
  4581. });
  4582. case "CallExpression": {
  4583. const pureFlag =
  4584. /** @type {Range} */ (expr.range)[0] - commentsStartPos > 12 &&
  4585. this.getComments([
  4586. commentsStartPos,
  4587. /** @type {Range} */ (expr.range)[0]
  4588. ]).some(
  4589. (comment) =>
  4590. comment.type === "Block" &&
  4591. /^\s*(?:#|@)__PURE__\s*$/.test(comment.value)
  4592. );
  4593. if (!pureFlag) return false;
  4594. commentsStartPos = /** @type {Range} */ (expr.callee.range)[1];
  4595. return expr.arguments.every((arg) => {
  4596. if (arg.type === "SpreadElement") return false;
  4597. const pureFlag = this.isPure(arg, commentsStartPos);
  4598. commentsStartPos = /** @type {Range} */ (arg.range)[1];
  4599. return pureFlag;
  4600. });
  4601. }
  4602. }
  4603. const evaluated = this.evaluateExpression(expr);
  4604. return !evaluated.couldHaveSideEffects();
  4605. }
  4606. /**
  4607. * @param {Range} range range
  4608. * @returns {Comment[]} comments in the range
  4609. */
  4610. getComments(range) {
  4611. const [rangeStart, rangeEnd] = range;
  4612. /**
  4613. * @param {Comment} comment comment
  4614. * @param {number} needle needle
  4615. * @returns {number} compared
  4616. */
  4617. const compare = (comment, needle) =>
  4618. /** @type {Range} */ (comment.range)[0] - needle;
  4619. const comments = /** @type {Comment[]} */ (this.comments);
  4620. let idx = binarySearchBounds.ge(comments, rangeStart, compare);
  4621. /** @type {Comment[]} */
  4622. const commentsInRange = [];
  4623. while (
  4624. comments[idx] &&
  4625. /** @type {Range} */ (comments[idx].range)[1] <= rangeEnd
  4626. ) {
  4627. commentsInRange.push(comments[idx]);
  4628. idx++;
  4629. }
  4630. return commentsInRange;
  4631. }
  4632. /**
  4633. * @param {number} pos source code position
  4634. * @returns {boolean} true when a semicolon has been inserted before this position, false if not
  4635. */
  4636. isAsiPosition(pos) {
  4637. const currentStatement =
  4638. /** @type {StatementPath} */
  4639. (this.statementPath)[
  4640. /** @type {StatementPath} */
  4641. (this.statementPath).length - 1
  4642. ];
  4643. if (currentStatement === undefined) throw new Error("Not in statement");
  4644. const range = /** @type {Range} */ (currentStatement.range);
  4645. return (
  4646. // Either asking directly for the end position of the current statement
  4647. (range[1] === pos &&
  4648. /** @type {Set<number>} */ (this.semicolons).has(pos)) ||
  4649. // Or asking for the start position of the current statement,
  4650. // here we have to check multiple things
  4651. (range[0] === pos &&
  4652. // is there a previous statement which might be relevant?
  4653. this.prevStatement !== undefined &&
  4654. // is the end position of the previous statement an ASI position?
  4655. /** @type {Set<number>} */ (this.semicolons).has(
  4656. /** @type {Range} */ (this.prevStatement.range)[1]
  4657. ))
  4658. );
  4659. }
  4660. /**
  4661. * @param {number} pos source code position
  4662. * @returns {void}
  4663. */
  4664. setAsiPosition(pos) {
  4665. /** @type {Set<number>} */ (this.semicolons).add(pos);
  4666. }
  4667. /**
  4668. * @param {number} pos source code position
  4669. * @returns {void}
  4670. */
  4671. unsetAsiPosition(pos) {
  4672. /** @type {Set<number>} */ (this.semicolons).delete(pos);
  4673. }
  4674. /**
  4675. * @param {Expression} expr expression
  4676. * @returns {boolean} true, when the expression is a statement level expression
  4677. */
  4678. isStatementLevelExpression(expr) {
  4679. const currentStatement =
  4680. /** @type {StatementPath} */
  4681. (this.statementPath)[
  4682. /** @type {StatementPath} */
  4683. (this.statementPath).length - 1
  4684. ];
  4685. return (
  4686. expr === currentStatement ||
  4687. (currentStatement.type === "ExpressionStatement" &&
  4688. currentStatement.expression === expr)
  4689. );
  4690. }
  4691. /**
  4692. * @param {string} name name
  4693. * @param {Tag} tag tag info
  4694. * @returns {TagData | undefined} tag data
  4695. */
  4696. getTagData(name, tag) {
  4697. const info = this.scope.definitions.get(name);
  4698. if (info instanceof VariableInfo) {
  4699. let tagInfo = info.tagInfo;
  4700. while (tagInfo !== undefined) {
  4701. if (tagInfo.tag === tag) return tagInfo.data;
  4702. tagInfo = tagInfo.next;
  4703. }
  4704. }
  4705. }
  4706. /**
  4707. * @param {string} name name
  4708. * @param {Tag} tag tag info
  4709. * @param {TagData=} data data
  4710. * @param {VariableInfoFlagsType=} flags flags
  4711. */
  4712. tagVariable(name, tag, data, flags = VariableInfoFlags.Tagged) {
  4713. const oldInfo = this.scope.definitions.get(name);
  4714. /** @type {VariableInfo} */
  4715. let newInfo;
  4716. if (oldInfo === undefined) {
  4717. newInfo = new VariableInfo(this.scope, name, flags, {
  4718. tag,
  4719. data,
  4720. next: undefined
  4721. });
  4722. } else if (oldInfo instanceof VariableInfo) {
  4723. newInfo = new VariableInfo(
  4724. oldInfo.declaredScope,
  4725. oldInfo.name,
  4726. /** @type {VariableInfoFlagsType} */ (oldInfo.flags | flags),
  4727. {
  4728. tag,
  4729. data,
  4730. next: oldInfo.tagInfo
  4731. }
  4732. );
  4733. } else {
  4734. newInfo = new VariableInfo(oldInfo, name, flags, {
  4735. tag,
  4736. data,
  4737. next: undefined
  4738. });
  4739. }
  4740. this.scope.definitions.set(name, newInfo);
  4741. }
  4742. /**
  4743. * @param {string} name variable name
  4744. */
  4745. defineVariable(name) {
  4746. const oldInfo = this.scope.definitions.get(name);
  4747. // Don't redefine variable in same scope to keep existing tags
  4748. if (
  4749. oldInfo instanceof VariableInfo &&
  4750. oldInfo.declaredScope === this.scope
  4751. ) {
  4752. return;
  4753. }
  4754. this.scope.definitions.set(name, this.scope);
  4755. }
  4756. /**
  4757. * @param {string} name variable name
  4758. */
  4759. undefineVariable(name) {
  4760. this.scope.definitions.delete(name);
  4761. }
  4762. /**
  4763. * @param {string} name variable name
  4764. * @returns {boolean} true, when variable is defined
  4765. */
  4766. isVariableDefined(name) {
  4767. const info = this.scope.definitions.get(name);
  4768. if (info === undefined) return false;
  4769. if (info instanceof VariableInfo) {
  4770. return !info.isFree();
  4771. }
  4772. return true;
  4773. }
  4774. /**
  4775. * @param {string} name variable name
  4776. * @returns {ExportedVariableInfo} info for this variable
  4777. */
  4778. getVariableInfo(name) {
  4779. const value = this.scope.definitions.get(name);
  4780. if (value === undefined) {
  4781. return name;
  4782. }
  4783. return value;
  4784. }
  4785. /**
  4786. * @param {string} name variable name
  4787. * @param {ExportedVariableInfo} variableInfo new info for this variable
  4788. * @returns {void}
  4789. */
  4790. setVariable(name, variableInfo) {
  4791. if (typeof variableInfo === "string") {
  4792. if (variableInfo === name) {
  4793. this.scope.definitions.delete(name);
  4794. } else {
  4795. this.scope.definitions.set(
  4796. name,
  4797. new VariableInfo(
  4798. this.scope,
  4799. variableInfo,
  4800. VariableInfoFlags.Free,
  4801. undefined
  4802. )
  4803. );
  4804. }
  4805. } else {
  4806. this.scope.definitions.set(name, variableInfo);
  4807. }
  4808. }
  4809. /**
  4810. * @param {TagInfo} tagInfo tag info
  4811. * @returns {VariableInfo} variable info
  4812. */
  4813. evaluatedVariable(tagInfo) {
  4814. return new VariableInfo(
  4815. this.scope,
  4816. undefined,
  4817. VariableInfoFlags.Evaluated,
  4818. tagInfo
  4819. );
  4820. }
  4821. /**
  4822. * @param {Range} range range of the comment
  4823. * @returns {{ options: Record<string, EXPECTED_ANY> | null, errors: (Error & { comment: Comment })[] | null }} result
  4824. */
  4825. parseCommentOptions(range) {
  4826. const comments = this.getComments(range);
  4827. if (comments.length === 0) {
  4828. return EMPTY_COMMENT_OPTIONS;
  4829. }
  4830. /** @type {Record<string, EXPECTED_ANY>} */
  4831. const options = {};
  4832. /** @type {(Error & { comment: Comment })[]} */
  4833. const errors = [];
  4834. for (const comment of comments) {
  4835. const { value } = comment;
  4836. if (value && webpackCommentRegExp.test(value)) {
  4837. // try compile only if webpack options comment is present
  4838. try {
  4839. for (let [key, val] of Object.entries(
  4840. vm.runInContext(
  4841. `(function(){return {${value}};})()`,
  4842. this.magicCommentContext
  4843. )
  4844. )) {
  4845. if (typeof val === "object" && val !== null) {
  4846. val =
  4847. val.constructor.name === "RegExp"
  4848. ? new RegExp(val)
  4849. : JSON.parse(JSON.stringify(val));
  4850. }
  4851. options[key] = val;
  4852. }
  4853. } catch (err) {
  4854. const newErr = new Error(String(/** @type {Error} */ (err).message));
  4855. newErr.stack = String(/** @type {Error} */ (err).stack);
  4856. Object.assign(newErr, { comment });
  4857. errors.push(/** @type {(Error & { comment: Comment })} */ (newErr));
  4858. }
  4859. }
  4860. }
  4861. return { options, errors };
  4862. }
  4863. /**
  4864. * @param {Expression | Super} expression a member expression
  4865. * @returns {{ members: Members, object: Expression | Super, membersOptionals: MembersOptionals, memberRanges: MemberRanges }} member names (reverse order) and remaining object
  4866. */
  4867. extractMemberExpressionChain(expression) {
  4868. /** @type {Node} */
  4869. let expr = expression;
  4870. /** @type {Members} */
  4871. const members = [];
  4872. /** @type {MembersOptionals} */
  4873. const membersOptionals = [];
  4874. /** @type {MemberRanges} */
  4875. const memberRanges = [];
  4876. while (expr.type === "MemberExpression") {
  4877. if (expr.computed) {
  4878. if (expr.property.type !== "Literal") break;
  4879. members.push(`${expr.property.value}`); // the literal
  4880. memberRanges.push(/** @type {Range} */ (expr.object.range)); // the range of the expression fragment before the literal
  4881. } else {
  4882. if (expr.property.type !== "Identifier") break;
  4883. members.push(expr.property.name); // the identifier
  4884. memberRanges.push(/** @type {Range} */ (expr.object.range)); // the range of the expression fragment before the identifier
  4885. }
  4886. membersOptionals.push(expr.optional);
  4887. expr = expr.object;
  4888. }
  4889. return {
  4890. members,
  4891. membersOptionals,
  4892. memberRanges,
  4893. object: expr
  4894. };
  4895. }
  4896. /**
  4897. * @param {string} varName variable name
  4898. * @returns {{ name: string, info: VariableInfo | string } | undefined} name of the free variable and variable info for that
  4899. */
  4900. getFreeInfoFromVariable(varName) {
  4901. const info = this.getVariableInfo(varName);
  4902. /** @type {string} */
  4903. let name;
  4904. if (info instanceof VariableInfo && info.name) {
  4905. if (!info.isFree()) return;
  4906. name = info.name;
  4907. } else if (typeof info !== "string") {
  4908. return;
  4909. } else {
  4910. name = info;
  4911. }
  4912. return { info, name };
  4913. }
  4914. /**
  4915. * @param {string} varName variable name
  4916. * @returns {{ name: string, info: VariableInfo | string } | undefined} name of the free variable and variable info for that
  4917. */
  4918. getNameInfoFromVariable(varName) {
  4919. const info = this.getVariableInfo(varName);
  4920. /** @type {string} */
  4921. let name;
  4922. if (info instanceof VariableInfo && info.name) {
  4923. if (!info.isFree() && !info.isTagged()) return;
  4924. name = info.name;
  4925. } else if (typeof info !== "string") {
  4926. return;
  4927. } else {
  4928. name = info;
  4929. }
  4930. return { info, name };
  4931. }
  4932. /** @typedef {{ type: "call", call: CallExpression, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => CalleeMembers, name: string, getMembers: () => Members, getMembersOptionals: () => MembersOptionals, getMemberRanges: () => MemberRanges }} CallExpressionInfo */
  4933. /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => Members, getMembersOptionals: () => MembersOptionals, getMemberRanges: () => MemberRanges }} ExpressionExpressionInfo */
  4934. /**
  4935. * @param {Expression | Super} expression a member expression
  4936. * @param {number} allowedTypes which types should be returned, presented in bit mask
  4937. * @returns {CallExpressionInfo | ExpressionExpressionInfo | undefined} expression info
  4938. */
  4939. getMemberExpressionInfo(expression, allowedTypes) {
  4940. const { object, members, membersOptionals, memberRanges } =
  4941. this.extractMemberExpressionChain(expression);
  4942. switch (object.type) {
  4943. case "CallExpression": {
  4944. if ((allowedTypes & ALLOWED_MEMBER_TYPES_CALL_EXPRESSION) === 0) return;
  4945. let callee = object.callee;
  4946. let rootMembers = EMPTY_ARRAY;
  4947. if (callee.type === "MemberExpression") {
  4948. ({ object: callee, members: rootMembers } =
  4949. this.extractMemberExpressionChain(callee));
  4950. }
  4951. const rootName = getRootName(callee);
  4952. if (!rootName) return;
  4953. const result = this.getNameInfoFromVariable(rootName);
  4954. if (!result) return;
  4955. const { info: rootInfo, name: resolvedRoot } = result;
  4956. const calleeName = objectAndMembersToName(resolvedRoot, rootMembers);
  4957. return {
  4958. type: "call",
  4959. call: object,
  4960. calleeName,
  4961. rootInfo,
  4962. getCalleeMembers: memoize(() => rootMembers.reverse()),
  4963. name: objectAndMembersToName(`${calleeName}()`, members),
  4964. getMembers: memoize(() => members.reverse()),
  4965. getMembersOptionals: memoize(() => membersOptionals.reverse()),
  4966. getMemberRanges: memoize(() => memberRanges.reverse())
  4967. };
  4968. }
  4969. case "Identifier":
  4970. case "MetaProperty":
  4971. case "ThisExpression": {
  4972. if ((allowedTypes & ALLOWED_MEMBER_TYPES_EXPRESSION) === 0) return;
  4973. const rootName = getRootName(object);
  4974. if (!rootName) return;
  4975. const result = this.getNameInfoFromVariable(rootName);
  4976. if (!result) return;
  4977. const { info: rootInfo, name: resolvedRoot } = result;
  4978. return {
  4979. type: "expression",
  4980. name: objectAndMembersToName(resolvedRoot, members),
  4981. rootInfo,
  4982. getMembers: memoize(() => members.reverse()),
  4983. getMembersOptionals: memoize(() => membersOptionals.reverse()),
  4984. getMemberRanges: memoize(() => memberRanges.reverse())
  4985. };
  4986. }
  4987. }
  4988. }
  4989. /**
  4990. * @param {Expression} expression an expression
  4991. * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => Members } | undefined} name info
  4992. */
  4993. getNameForExpression(expression) {
  4994. return this.getMemberExpressionInfo(
  4995. expression,
  4996. ALLOWED_MEMBER_TYPES_EXPRESSION
  4997. );
  4998. }
  4999. /**
  5000. * @param {Compilation} compilation compilation
  5001. * @param {Module} module module
  5002. * @returns {ParseFunction | undefined} parser
  5003. */
  5004. static _getModuleParseFunction(compilation, module) {
  5005. // Get from module if available
  5006. if (
  5007. module instanceof NormalModule &&
  5008. module.parser instanceof JavascriptParser
  5009. ) {
  5010. return module.parser.options.parse;
  5011. }
  5012. // Fallback to the global javascript parse function
  5013. if (typeof compilation.options.module.parser.javascript !== "undefined") {
  5014. return compilation.options.module.parser.javascript.parse;
  5015. }
  5016. }
  5017. /**
  5018. * @param {string} code source code
  5019. * @param {InternalParseOptions} options parsing options
  5020. * @param {ParseFunction=} customParse custom function to parse
  5021. * @returns {ParseResult} parse result
  5022. */
  5023. static _parse(code, options, customParse) {
  5024. const type = options ? options.sourceType : "module";
  5025. /** @type {ParseOptions} */
  5026. const parserOptions = {
  5027. ...defaultParserOptions,
  5028. allowReturnOutsideFunction: type === "script",
  5029. ...options,
  5030. sourceType: type === "auto" ? "module" : type
  5031. };
  5032. /**
  5033. * @param {string} code source code
  5034. * @param {ParseOptions} options parsing options
  5035. * @returns {ParseResult} parse result
  5036. */
  5037. const internalParse = (code, options) => {
  5038. if (typeof customParse === "function") {
  5039. return customParse(code, options);
  5040. }
  5041. /** @type {Comment[]} */
  5042. const comments = [];
  5043. if (options.comments) {
  5044. /** @type {AcornOptions} */
  5045. (options).onComment = comments;
  5046. }
  5047. /** @type {Set<number>} */
  5048. const semicolons = new Set();
  5049. if (options.semicolons) {
  5050. /** @type {AcornOptions} */
  5051. (options).onInsertedSemicolon = (pos) => semicolons.add(pos);
  5052. }
  5053. const ast =
  5054. /** @type {Program} */
  5055. (parser.parse(code, /** @type {AcornOptions} */ (options)));
  5056. return { ast, comments, semicolons };
  5057. };
  5058. /** @type {Program | undefined} */
  5059. let ast;
  5060. /** @type {Comment[] | undefined} */
  5061. let comments;
  5062. /** @type {Set<number> | undefined} */
  5063. let semicolons;
  5064. let error;
  5065. let threw = false;
  5066. try {
  5067. ({ ast, comments, semicolons } = internalParse(code, parserOptions));
  5068. } catch (err) {
  5069. error = err;
  5070. threw = true;
  5071. }
  5072. if (threw && type === "auto") {
  5073. parserOptions.sourceType = "script";
  5074. parserOptions.allowReturnOutsideFunction = true;
  5075. try {
  5076. ({ ast, comments, semicolons } = internalParse(code, parserOptions));
  5077. threw = false;
  5078. } catch (_err) {
  5079. // we use the error from first parse try
  5080. // so nothing to do here
  5081. }
  5082. }
  5083. if (threw) {
  5084. throw error;
  5085. }
  5086. return /** @type {ParseResult} */ ({ ast, comments, semicolons });
  5087. }
  5088. /**
  5089. * @param {((BaseParser: typeof AcornParser) => typeof AcornParser)[]} plugins parser plugin
  5090. * @returns {typeof JavascriptParser} parser
  5091. */
  5092. static extend(...plugins) {
  5093. parser = parser.extend(...plugins);
  5094. return JavascriptParser;
  5095. }
  5096. }
  5097. module.exports = JavascriptParser;
  5098. module.exports.ALLOWED_MEMBER_TYPES_ALL = ALLOWED_MEMBER_TYPES_ALL;
  5099. module.exports.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION =
  5100. ALLOWED_MEMBER_TYPES_CALL_EXPRESSION;
  5101. module.exports.ALLOWED_MEMBER_TYPES_EXPRESSION =
  5102. ALLOWED_MEMBER_TYPES_EXPRESSION;
  5103. module.exports.VariableInfo = VariableInfo;
  5104. module.exports.VariableInfoFlags = VariableInfoFlags;
  5105. module.exports.getImportAttributes = getImportAttributes;