JavascriptParser.js 133 KB

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