JavascriptParser.js 138 KB

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