Parser.js 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. // Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API
  7. const acorn = require("acorn-dynamic-import").default;
  8. const { Tapable, SyncBailHook, HookMap } = require("tapable");
  9. const util = require("util");
  10. const vm = require("vm");
  11. const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
  12. const StackedSetMap = require("./util/StackedSetMap");
  13. const TrackingSet = require("./util/TrackingSet");
  14. const joinRanges = (startRange, endRange) => {
  15. if (!endRange) return startRange;
  16. if (!startRange) return endRange;
  17. return [startRange[0], endRange[1]];
  18. };
  19. const defaultParserOptions = {
  20. ranges: true,
  21. locations: true,
  22. ecmaVersion: 2019,
  23. sourceType: "module",
  24. onComment: null,
  25. plugins: {
  26. dynamicImport: true
  27. }
  28. };
  29. // regexp to match at lease one "magic comment"
  30. const webpackCommentRegExp = new RegExp(/(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/);
  31. const EMPTY_ARRAY = [];
  32. const EMPTY_COMMENT_OPTIONS = {
  33. options: null,
  34. errors: null
  35. };
  36. class Parser extends Tapable {
  37. constructor(options, sourceType = "auto") {
  38. super();
  39. this.hooks = {
  40. evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])),
  41. evaluate: new HookMap(() => new SyncBailHook(["expression"])),
  42. evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])),
  43. evaluateDefinedIdentifier: new HookMap(
  44. () => new SyncBailHook(["expression"])
  45. ),
  46. evaluateCallExpressionMember: new HookMap(
  47. () => new SyncBailHook(["expression", "param"])
  48. ),
  49. statement: new SyncBailHook(["statement"]),
  50. statementIf: new SyncBailHook(["statement"]),
  51. label: new HookMap(() => new SyncBailHook(["statement"])),
  52. import: new SyncBailHook(["statement", "source"]),
  53. importSpecifier: new SyncBailHook([
  54. "statement",
  55. "source",
  56. "exportName",
  57. "identifierName"
  58. ]),
  59. export: new SyncBailHook(["statement"]),
  60. exportImport: new SyncBailHook(["statement", "source"]),
  61. exportDeclaration: new SyncBailHook(["statement", "declaration"]),
  62. exportExpression: new SyncBailHook(["statement", "declaration"]),
  63. exportSpecifier: new SyncBailHook([
  64. "statement",
  65. "identifierName",
  66. "exportName",
  67. "index"
  68. ]),
  69. exportImportSpecifier: new SyncBailHook([
  70. "statement",
  71. "source",
  72. "identifierName",
  73. "exportName",
  74. "index"
  75. ]),
  76. varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])),
  77. varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])),
  78. varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])),
  79. varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])),
  80. canRename: new HookMap(() => new SyncBailHook(["initExpression"])),
  81. rename: new HookMap(() => new SyncBailHook(["initExpression"])),
  82. assigned: new HookMap(() => new SyncBailHook(["expression"])),
  83. assign: new HookMap(() => new SyncBailHook(["expression"])),
  84. typeof: new HookMap(() => new SyncBailHook(["expression"])),
  85. importCall: new SyncBailHook(["expression"]),
  86. call: new HookMap(() => new SyncBailHook(["expression"])),
  87. callAnyMember: new HookMap(() => new SyncBailHook(["expression"])),
  88. new: new HookMap(() => new SyncBailHook(["expression"])),
  89. expression: new HookMap(() => new SyncBailHook(["expression"])),
  90. expressionAnyMember: new HookMap(() => new SyncBailHook(["expression"])),
  91. expressionConditionalOperator: new SyncBailHook(["expression"]),
  92. expressionLogicalOperator: new SyncBailHook(["expression"]),
  93. program: new SyncBailHook(["ast", "comments"])
  94. };
  95. const HOOK_MAP_COMPAT_CONFIG = {
  96. evaluateTypeof: /^evaluate typeof (.+)$/,
  97. evaluateIdentifier: /^evaluate Identifier (.+)$/,
  98. evaluateDefinedIdentifier: /^evaluate defined Identifier (.+)$/,
  99. evaluateCallExpressionMember: /^evaluate CallExpression .(.+)$/,
  100. evaluate: /^evaluate (.+)$/,
  101. label: /^label (.+)$/,
  102. varDeclarationLet: /^var-let (.+)$/,
  103. varDeclarationConst: /^var-const (.+)$/,
  104. varDeclarationVar: /^var-var (.+)$/,
  105. varDeclaration: /^var (.+)$/,
  106. canRename: /^can-rename (.+)$/,
  107. rename: /^rename (.+)$/,
  108. typeof: /^typeof (.+)$/,
  109. assigned: /^assigned (.+)$/,
  110. assign: /^assign (.+)$/,
  111. callAnyMember: /^call (.+)\.\*$/,
  112. call: /^call (.+)$/,
  113. new: /^new (.+)$/,
  114. expressionConditionalOperator: /^expression \?:$/,
  115. expressionAnyMember: /^expression (.+)\.\*$/,
  116. expression: /^expression (.+)$/
  117. };
  118. this._pluginCompat.tap("Parser", options => {
  119. for (const name of Object.keys(HOOK_MAP_COMPAT_CONFIG)) {
  120. const regexp = HOOK_MAP_COMPAT_CONFIG[name];
  121. const match = regexp.exec(options.name);
  122. if (match) {
  123. if (match[1]) {
  124. this.hooks[name].tap(
  125. match[1],
  126. options.fn.name || "unnamed compat plugin",
  127. options.fn.bind(this)
  128. );
  129. } else {
  130. this.hooks[name].tap(
  131. options.fn.name || "unnamed compat plugin",
  132. options.fn.bind(this)
  133. );
  134. }
  135. return true;
  136. }
  137. }
  138. });
  139. this.options = options;
  140. this.sourceType = sourceType;
  141. this.scope = undefined;
  142. this.state = undefined;
  143. this.comments = undefined;
  144. this.initializeEvaluating();
  145. }
  146. initializeEvaluating() {
  147. this.hooks.evaluate.for("Literal").tap("Parser", expr => {
  148. switch (typeof expr.value) {
  149. case "number":
  150. return new BasicEvaluatedExpression()
  151. .setNumber(expr.value)
  152. .setRange(expr.range);
  153. case "string":
  154. return new BasicEvaluatedExpression()
  155. .setString(expr.value)
  156. .setRange(expr.range);
  157. case "boolean":
  158. return new BasicEvaluatedExpression()
  159. .setBoolean(expr.value)
  160. .setRange(expr.range);
  161. }
  162. if (expr.value === null) {
  163. return new BasicEvaluatedExpression().setNull().setRange(expr.range);
  164. }
  165. if (expr.value instanceof RegExp) {
  166. return new BasicEvaluatedExpression()
  167. .setRegExp(expr.value)
  168. .setRange(expr.range);
  169. }
  170. });
  171. this.hooks.evaluate.for("LogicalExpression").tap("Parser", expr => {
  172. let left;
  173. let leftAsBool;
  174. let right;
  175. if (expr.operator === "&&") {
  176. left = this.evaluateExpression(expr.left);
  177. leftAsBool = left && left.asBool();
  178. if (leftAsBool === false) return left.setRange(expr.range);
  179. if (leftAsBool !== true) return;
  180. right = this.evaluateExpression(expr.right);
  181. return right.setRange(expr.range);
  182. } else if (expr.operator === "||") {
  183. left = this.evaluateExpression(expr.left);
  184. leftAsBool = left && left.asBool();
  185. if (leftAsBool === true) return left.setRange(expr.range);
  186. if (leftAsBool !== false) return;
  187. right = this.evaluateExpression(expr.right);
  188. return right.setRange(expr.range);
  189. }
  190. });
  191. this.hooks.evaluate.for("BinaryExpression").tap("Parser", expr => {
  192. let left;
  193. let right;
  194. let res;
  195. if (expr.operator === "+") {
  196. left = this.evaluateExpression(expr.left);
  197. right = this.evaluateExpression(expr.right);
  198. if (!left || !right) return;
  199. res = new BasicEvaluatedExpression();
  200. if (left.isString()) {
  201. if (right.isString()) {
  202. res.setString(left.string + right.string);
  203. } else if (right.isNumber()) {
  204. res.setString(left.string + right.number);
  205. } else if (
  206. right.isWrapped() &&
  207. right.prefix &&
  208. right.prefix.isString()
  209. ) {
  210. // "left" + ("prefix" + inner + "postfix")
  211. // => ("leftprefix" + inner + "postfix")
  212. res.setWrapped(
  213. new BasicEvaluatedExpression()
  214. .setString(left.string + right.prefix.string)
  215. .setRange(joinRanges(left.range, right.prefix.range)),
  216. right.postfix,
  217. right.wrappedInnerExpressions
  218. );
  219. } else if (right.isWrapped()) {
  220. // "left" + ([null] + inner + "postfix")
  221. // => ("left" + inner + "postfix")
  222. res.setWrapped(left, right.postfix, right.wrappedInnerExpressions);
  223. } else {
  224. // "left" + expr
  225. // => ("left" + expr + "")
  226. res.setWrapped(left, null, [right]);
  227. }
  228. } else if (left.isNumber()) {
  229. if (right.isString()) {
  230. res.setString(left.number + right.string);
  231. } else if (right.isNumber()) {
  232. res.setNumber(left.number + right.number);
  233. } else {
  234. return;
  235. }
  236. } else if (left.isWrapped()) {
  237. if (left.postfix && left.postfix.isString() && right.isString()) {
  238. // ("prefix" + inner + "postfix") + "right"
  239. // => ("prefix" + inner + "postfixright")
  240. res.setWrapped(
  241. left.prefix,
  242. new BasicEvaluatedExpression()
  243. .setString(left.postfix.string + right.string)
  244. .setRange(joinRanges(left.postfix.range, right.range)),
  245. left.wrappedInnerExpressions
  246. );
  247. } else if (
  248. left.postfix &&
  249. left.postfix.isString() &&
  250. right.isNumber()
  251. ) {
  252. // ("prefix" + inner + "postfix") + 123
  253. // => ("prefix" + inner + "postfix123")
  254. res.setWrapped(
  255. left.prefix,
  256. new BasicEvaluatedExpression()
  257. .setString(left.postfix.string + right.number)
  258. .setRange(joinRanges(left.postfix.range, right.range)),
  259. left.wrappedInnerExpressions
  260. );
  261. } else if (right.isString()) {
  262. // ("prefix" + inner + [null]) + "right"
  263. // => ("prefix" + inner + "right")
  264. res.setWrapped(left.prefix, right, left.wrappedInnerExpressions);
  265. } else if (right.isNumber()) {
  266. // ("prefix" + inner + [null]) + 123
  267. // => ("prefix" + inner + "123")
  268. res.setWrapped(
  269. left.prefix,
  270. new BasicEvaluatedExpression()
  271. .setString(right.number + "")
  272. .setRange(right.range),
  273. left.wrappedInnerExpressions
  274. );
  275. } else if (right.isWrapped()) {
  276. // ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2")
  277. // ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2")
  278. res.setWrapped(
  279. left.prefix,
  280. right.postfix,
  281. left.wrappedInnerExpressions &&
  282. right.wrappedInnerExpressions &&
  283. left.wrappedInnerExpressions
  284. .concat(left.postfix ? [left.postfix] : [])
  285. .concat(right.prefix ? [right.prefix] : [])
  286. .concat(right.wrappedInnerExpressions)
  287. );
  288. } else {
  289. // ("prefix" + inner + postfix) + expr
  290. // => ("prefix" + inner + postfix + expr + [null])
  291. res.setWrapped(
  292. left.prefix,
  293. null,
  294. left.wrappedInnerExpressions &&
  295. left.wrappedInnerExpressions.concat(
  296. left.postfix ? [left.postfix, right] : [right]
  297. )
  298. );
  299. }
  300. } else {
  301. if (right.isString()) {
  302. // left + "right"
  303. // => ([null] + left + "right")
  304. res.setWrapped(null, right, [left]);
  305. } else if (right.isWrapped()) {
  306. // left + (prefix + inner + "postfix")
  307. // => ([null] + left + prefix + inner + "postfix")
  308. res.setWrapped(
  309. null,
  310. right.postfix,
  311. right.wrappedInnerExpressions &&
  312. (right.prefix ? [left, right.prefix] : [left]).concat(
  313. right.wrappedInnerExpressions
  314. )
  315. );
  316. } else {
  317. return;
  318. }
  319. }
  320. res.setRange(expr.range);
  321. return res;
  322. } else if (expr.operator === "-") {
  323. left = this.evaluateExpression(expr.left);
  324. right = this.evaluateExpression(expr.right);
  325. if (!left || !right) return;
  326. if (!left.isNumber() || !right.isNumber()) return;
  327. res = new BasicEvaluatedExpression();
  328. res.setNumber(left.number - right.number);
  329. res.setRange(expr.range);
  330. return res;
  331. } else if (expr.operator === "*") {
  332. left = this.evaluateExpression(expr.left);
  333. right = this.evaluateExpression(expr.right);
  334. if (!left || !right) return;
  335. if (!left.isNumber() || !right.isNumber()) return;
  336. res = new BasicEvaluatedExpression();
  337. res.setNumber(left.number * right.number);
  338. res.setRange(expr.range);
  339. return res;
  340. } else if (expr.operator === "/") {
  341. left = this.evaluateExpression(expr.left);
  342. right = this.evaluateExpression(expr.right);
  343. if (!left || !right) return;
  344. if (!left.isNumber() || !right.isNumber()) return;
  345. res = new BasicEvaluatedExpression();
  346. res.setNumber(left.number / right.number);
  347. res.setRange(expr.range);
  348. return res;
  349. } else if (expr.operator === "**") {
  350. left = this.evaluateExpression(expr.left);
  351. right = this.evaluateExpression(expr.right);
  352. if (!left || !right) return;
  353. if (!left.isNumber() || !right.isNumber()) return;
  354. res = new BasicEvaluatedExpression();
  355. res.setNumber(Math.pow(left.number, right.number));
  356. res.setRange(expr.range);
  357. return res;
  358. } else if (expr.operator === "==" || expr.operator === "===") {
  359. left = this.evaluateExpression(expr.left);
  360. right = this.evaluateExpression(expr.right);
  361. if (!left || !right) return;
  362. res = new BasicEvaluatedExpression();
  363. res.setRange(expr.range);
  364. if (left.isString() && right.isString()) {
  365. return res.setBoolean(left.string === right.string);
  366. } else if (left.isNumber() && right.isNumber()) {
  367. return res.setBoolean(left.number === right.number);
  368. } else if (left.isBoolean() && right.isBoolean()) {
  369. return res.setBoolean(left.bool === right.bool);
  370. }
  371. } else if (expr.operator === "!=" || expr.operator === "!==") {
  372. left = this.evaluateExpression(expr.left);
  373. right = this.evaluateExpression(expr.right);
  374. if (!left || !right) return;
  375. res = new BasicEvaluatedExpression();
  376. res.setRange(expr.range);
  377. if (left.isString() && right.isString()) {
  378. return res.setBoolean(left.string !== right.string);
  379. } else if (left.isNumber() && right.isNumber()) {
  380. return res.setBoolean(left.number !== right.number);
  381. } else if (left.isBoolean() && right.isBoolean()) {
  382. return res.setBoolean(left.bool !== right.bool);
  383. }
  384. } else if (expr.operator === "&") {
  385. left = this.evaluateExpression(expr.left);
  386. right = this.evaluateExpression(expr.right);
  387. if (!left || !right) return;
  388. if (!left.isNumber() || !right.isNumber()) return;
  389. res = new BasicEvaluatedExpression();
  390. res.setNumber(left.number & right.number);
  391. res.setRange(expr.range);
  392. return res;
  393. } else if (expr.operator === "|") {
  394. left = this.evaluateExpression(expr.left);
  395. right = this.evaluateExpression(expr.right);
  396. if (!left || !right) return;
  397. if (!left.isNumber() || !right.isNumber()) return;
  398. res = new BasicEvaluatedExpression();
  399. res.setNumber(left.number | right.number);
  400. res.setRange(expr.range);
  401. return res;
  402. } else if (expr.operator === "^") {
  403. left = this.evaluateExpression(expr.left);
  404. right = this.evaluateExpression(expr.right);
  405. if (!left || !right) return;
  406. if (!left.isNumber() || !right.isNumber()) return;
  407. res = new BasicEvaluatedExpression();
  408. res.setNumber(left.number ^ right.number);
  409. res.setRange(expr.range);
  410. return res;
  411. } else if (expr.operator === ">>>") {
  412. left = this.evaluateExpression(expr.left);
  413. right = this.evaluateExpression(expr.right);
  414. if (!left || !right) return;
  415. if (!left.isNumber() || !right.isNumber()) return;
  416. res = new BasicEvaluatedExpression();
  417. res.setNumber(left.number >>> right.number);
  418. res.setRange(expr.range);
  419. return res;
  420. } else if (expr.operator === ">>") {
  421. left = this.evaluateExpression(expr.left);
  422. right = this.evaluateExpression(expr.right);
  423. if (!left || !right) return;
  424. if (!left.isNumber() || !right.isNumber()) return;
  425. res = new BasicEvaluatedExpression();
  426. res.setNumber(left.number >> right.number);
  427. res.setRange(expr.range);
  428. return res;
  429. } else if (expr.operator === "<<") {
  430. left = this.evaluateExpression(expr.left);
  431. right = this.evaluateExpression(expr.right);
  432. if (!left || !right) return;
  433. if (!left.isNumber() || !right.isNumber()) return;
  434. res = new BasicEvaluatedExpression();
  435. res.setNumber(left.number << right.number);
  436. res.setRange(expr.range);
  437. return res;
  438. }
  439. });
  440. this.hooks.evaluate.for("UnaryExpression").tap("Parser", expr => {
  441. if (expr.operator === "typeof") {
  442. let res;
  443. let name;
  444. if (expr.argument.type === "Identifier") {
  445. name =
  446. this.scope.renames.get(expr.argument.name) || expr.argument.name;
  447. if (!this.scope.definitions.has(name)) {
  448. const hook = this.hooks.evaluateTypeof.get(name);
  449. if (hook !== undefined) {
  450. res = hook.call(expr);
  451. if (res !== undefined) return res;
  452. }
  453. }
  454. }
  455. if (expr.argument.type === "MemberExpression") {
  456. const exprName = this.getNameForExpression(expr.argument);
  457. if (exprName && exprName.free) {
  458. const hook = this.hooks.evaluateTypeof.get(exprName.name);
  459. if (hook !== undefined) {
  460. res = hook.call(expr);
  461. if (res !== undefined) return res;
  462. }
  463. }
  464. }
  465. if (expr.argument.type === "FunctionExpression") {
  466. return new BasicEvaluatedExpression()
  467. .setString("function")
  468. .setRange(expr.range);
  469. }
  470. const arg = this.evaluateExpression(expr.argument);
  471. if (arg.isString() || arg.isWrapped()) {
  472. return new BasicEvaluatedExpression()
  473. .setString("string")
  474. .setRange(expr.range);
  475. }
  476. if (arg.isNumber()) {
  477. return new BasicEvaluatedExpression()
  478. .setString("number")
  479. .setRange(expr.range);
  480. }
  481. if (arg.isBoolean()) {
  482. return new BasicEvaluatedExpression()
  483. .setString("boolean")
  484. .setRange(expr.range);
  485. }
  486. if (arg.isArray() || arg.isConstArray() || arg.isRegExp()) {
  487. return new BasicEvaluatedExpression()
  488. .setString("object")
  489. .setRange(expr.range);
  490. }
  491. } else if (expr.operator === "!") {
  492. const argument = this.evaluateExpression(expr.argument);
  493. if (!argument) return;
  494. if (argument.isBoolean()) {
  495. return new BasicEvaluatedExpression()
  496. .setBoolean(!argument.bool)
  497. .setRange(expr.range);
  498. }
  499. if (argument.isTruthy()) {
  500. return new BasicEvaluatedExpression()
  501. .setBoolean(false)
  502. .setRange(expr.range);
  503. }
  504. if (argument.isFalsy()) {
  505. return new BasicEvaluatedExpression()
  506. .setBoolean(true)
  507. .setRange(expr.range);
  508. }
  509. if (argument.isString()) {
  510. return new BasicEvaluatedExpression()
  511. .setBoolean(!argument.string)
  512. .setRange(expr.range);
  513. }
  514. if (argument.isNumber()) {
  515. return new BasicEvaluatedExpression()
  516. .setBoolean(!argument.number)
  517. .setRange(expr.range);
  518. }
  519. } else if (expr.operator === "~") {
  520. const argument = this.evaluateExpression(expr.argument);
  521. if (!argument) return;
  522. if (!argument.isNumber()) return;
  523. const res = new BasicEvaluatedExpression();
  524. res.setNumber(~argument.number);
  525. res.setRange(expr.range);
  526. return res;
  527. }
  528. });
  529. this.hooks.evaluateTypeof.for("undefined").tap("Parser", expr => {
  530. return new BasicEvaluatedExpression()
  531. .setString("undefined")
  532. .setRange(expr.range);
  533. });
  534. this.hooks.evaluate.for("Identifier").tap("Parser", expr => {
  535. const name = this.scope.renames.get(expr.name) || expr.name;
  536. if (!this.scope.definitions.has(expr.name)) {
  537. const hook = this.hooks.evaluateIdentifier.get(name);
  538. if (hook !== undefined) {
  539. const result = hook.call(expr);
  540. if (result) return result;
  541. }
  542. return new BasicEvaluatedExpression()
  543. .setIdentifier(name)
  544. .setRange(expr.range);
  545. } else {
  546. const hook = this.hooks.evaluateDefinedIdentifier.get(name);
  547. if (hook !== undefined) {
  548. return hook.call(expr);
  549. }
  550. }
  551. });
  552. this.hooks.evaluate.for("ThisExpression").tap("Parser", expr => {
  553. const name = this.scope.renames.get("this");
  554. if (name) {
  555. const hook = this.hooks.evaluateIdentifier.get(name);
  556. if (hook !== undefined) {
  557. const result = hook.call(expr);
  558. if (result) return result;
  559. }
  560. return new BasicEvaluatedExpression()
  561. .setIdentifier(name)
  562. .setRange(expr.range);
  563. }
  564. });
  565. this.hooks.evaluate.for("MemberExpression").tap("Parser", expression => {
  566. let exprName = this.getNameForExpression(expression);
  567. if (exprName) {
  568. if (exprName.free) {
  569. const hook = this.hooks.evaluateIdentifier.get(exprName.name);
  570. if (hook !== undefined) {
  571. const result = hook.call(expression);
  572. if (result) return result;
  573. }
  574. return new BasicEvaluatedExpression()
  575. .setIdentifier(exprName.name)
  576. .setRange(expression.range);
  577. } else {
  578. const hook = this.hooks.evaluateDefinedIdentifier.get(exprName.name);
  579. if (hook !== undefined) {
  580. return hook.call(expression);
  581. }
  582. }
  583. }
  584. });
  585. this.hooks.evaluate.for("CallExpression").tap("Parser", expr => {
  586. if (expr.callee.type !== "MemberExpression") return;
  587. if (
  588. expr.callee.property.type !==
  589. (expr.callee.computed ? "Literal" : "Identifier")
  590. )
  591. return;
  592. const param = this.evaluateExpression(expr.callee.object);
  593. if (!param) return;
  594. const property = expr.callee.property.name || expr.callee.property.value;
  595. const hook = this.hooks.evaluateCallExpressionMember.get(property);
  596. if (hook !== undefined) {
  597. return hook.call(expr, param);
  598. }
  599. });
  600. this.hooks.evaluateCallExpressionMember
  601. .for("replace")
  602. .tap("Parser", (expr, param) => {
  603. if (!param.isString()) return;
  604. if (expr.arguments.length !== 2) return;
  605. let arg1 = this.evaluateExpression(expr.arguments[0]);
  606. let arg2 = this.evaluateExpression(expr.arguments[1]);
  607. if (!arg1.isString() && !arg1.isRegExp()) return;
  608. arg1 = arg1.regExp || arg1.string;
  609. if (!arg2.isString()) return;
  610. arg2 = arg2.string;
  611. return new BasicEvaluatedExpression()
  612. .setString(param.string.replace(arg1, arg2))
  613. .setRange(expr.range);
  614. });
  615. ["substr", "substring"].forEach(fn => {
  616. this.hooks.evaluateCallExpressionMember
  617. .for(fn)
  618. .tap("Parser", (expr, param) => {
  619. if (!param.isString()) return;
  620. let arg1;
  621. let result,
  622. str = param.string;
  623. switch (expr.arguments.length) {
  624. case 1:
  625. arg1 = this.evaluateExpression(expr.arguments[0]);
  626. if (!arg1.isNumber()) return;
  627. result = str[fn](arg1.number);
  628. break;
  629. case 2: {
  630. arg1 = this.evaluateExpression(expr.arguments[0]);
  631. const arg2 = this.evaluateExpression(expr.arguments[1]);
  632. if (!arg1.isNumber()) return;
  633. if (!arg2.isNumber()) return;
  634. result = str[fn](arg1.number, arg2.number);
  635. break;
  636. }
  637. default:
  638. return;
  639. }
  640. return new BasicEvaluatedExpression()
  641. .setString(result)
  642. .setRange(expr.range);
  643. });
  644. });
  645. /**
  646. * @param {string} kind "cooked" | "raw"
  647. * @param {TODO} templateLiteralExpr TemplateLiteral expr
  648. * @returns {{quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[]}} Simplified template
  649. */
  650. const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => {
  651. const quasis = [];
  652. const parts = [];
  653. for (let i = 0; i < templateLiteralExpr.quasis.length; i++) {
  654. const quasiExpr = templateLiteralExpr.quasis[i];
  655. const quasi = quasiExpr.value[kind];
  656. if (i > 0) {
  657. const prevExpr = parts[parts.length - 1];
  658. const expr = this.evaluateExpression(
  659. templateLiteralExpr.expressions[i - 1]
  660. );
  661. const exprAsString = expr.asString();
  662. if (typeof exprAsString === "string") {
  663. // We can merge quasi + expr + quasi when expr
  664. // is a const string
  665. prevExpr.setString(prevExpr.string + exprAsString + quasi);
  666. prevExpr.setRange([prevExpr.range[0], quasiExpr.range[1]]);
  667. // We unset the expression as it doesn't match to a single expression
  668. prevExpr.setExpression(undefined);
  669. continue;
  670. }
  671. parts.push(expr);
  672. }
  673. const part = new BasicEvaluatedExpression()
  674. .setString(quasi)
  675. .setRange(quasiExpr.range)
  676. .setExpression(quasiExpr);
  677. quasis.push(part);
  678. parts.push(part);
  679. }
  680. return {
  681. quasis,
  682. parts
  683. };
  684. };
  685. this.hooks.evaluate.for("TemplateLiteral").tap("Parser", node => {
  686. const { quasis, parts } = getSimplifiedTemplateResult("cooked", node);
  687. if (parts.length === 1) {
  688. return parts[0].setRange(node.range);
  689. }
  690. return new BasicEvaluatedExpression()
  691. .setTemplateString(quasis, parts, "cooked")
  692. .setRange(node.range);
  693. });
  694. this.hooks.evaluate.for("TaggedTemplateExpression").tap("Parser", node => {
  695. if (this.evaluateExpression(node.tag).identifier !== "String.raw") return;
  696. const { quasis, parts } = getSimplifiedTemplateResult("raw", node.quasi);
  697. if (parts.length === 1) {
  698. return parts[0].setRange(node.range);
  699. }
  700. return new BasicEvaluatedExpression()
  701. .setTemplateString(quasis, parts, "raw")
  702. .setRange(node.range);
  703. });
  704. this.hooks.evaluateCallExpressionMember
  705. .for("concat")
  706. .tap("Parser", (expr, param) => {
  707. if (!param.isString() && !param.isWrapped()) return;
  708. let stringSuffix = null;
  709. let hasUnknownParams = false;
  710. for (let i = expr.arguments.length - 1; i >= 0; i--) {
  711. const argExpr = this.evaluateExpression(expr.arguments[i]);
  712. if (!argExpr.isString() && !argExpr.isNumber()) {
  713. hasUnknownParams = true;
  714. break;
  715. }
  716. const value = argExpr.isString()
  717. ? argExpr.string
  718. : "" + argExpr.number;
  719. const newString = value + (stringSuffix ? stringSuffix.string : "");
  720. const newRange = [
  721. argExpr.range[0],
  722. (stringSuffix || argExpr).range[1]
  723. ];
  724. stringSuffix = new BasicEvaluatedExpression()
  725. .setString(newString)
  726. .setRange(newRange);
  727. }
  728. if (hasUnknownParams) {
  729. const prefix = param.isString() ? param : param.prefix;
  730. return new BasicEvaluatedExpression()
  731. .setWrapped(prefix, stringSuffix)
  732. .setRange(expr.range);
  733. } else if (param.isWrapped()) {
  734. const postfix = stringSuffix || param.postfix;
  735. return new BasicEvaluatedExpression()
  736. .setWrapped(param.prefix, postfix)
  737. .setRange(expr.range);
  738. } else {
  739. const newString =
  740. param.string + (stringSuffix ? stringSuffix.string : "");
  741. return new BasicEvaluatedExpression()
  742. .setString(newString)
  743. .setRange(expr.range);
  744. }
  745. });
  746. this.hooks.evaluateCallExpressionMember
  747. .for("split")
  748. .tap("Parser", (expr, param) => {
  749. if (!param.isString()) return;
  750. if (expr.arguments.length !== 1) return;
  751. let result;
  752. const arg = this.evaluateExpression(expr.arguments[0]);
  753. if (arg.isString()) {
  754. result = param.string.split(arg.string);
  755. } else if (arg.isRegExp()) {
  756. result = param.string.split(arg.regExp);
  757. } else {
  758. return;
  759. }
  760. return new BasicEvaluatedExpression()
  761. .setArray(result)
  762. .setRange(expr.range);
  763. });
  764. this.hooks.evaluate.for("ConditionalExpression").tap("Parser", expr => {
  765. const condition = this.evaluateExpression(expr.test);
  766. const conditionValue = condition.asBool();
  767. let res;
  768. if (conditionValue === undefined) {
  769. const consequent = this.evaluateExpression(expr.consequent);
  770. const alternate = this.evaluateExpression(expr.alternate);
  771. if (!consequent || !alternate) return;
  772. res = new BasicEvaluatedExpression();
  773. if (consequent.isConditional()) {
  774. res.setOptions(consequent.options);
  775. } else {
  776. res.setOptions([consequent]);
  777. }
  778. if (alternate.isConditional()) {
  779. res.addOptions(alternate.options);
  780. } else {
  781. res.addOptions([alternate]);
  782. }
  783. } else {
  784. res = this.evaluateExpression(
  785. conditionValue ? expr.consequent : expr.alternate
  786. );
  787. }
  788. res.setRange(expr.range);
  789. return res;
  790. });
  791. this.hooks.evaluate.for("ArrayExpression").tap("Parser", expr => {
  792. const items = expr.elements.map(element => {
  793. return element !== null && this.evaluateExpression(element);
  794. });
  795. if (!items.every(Boolean)) return;
  796. return new BasicEvaluatedExpression()
  797. .setItems(items)
  798. .setRange(expr.range);
  799. });
  800. }
  801. getRenameIdentifier(expr) {
  802. const result = this.evaluateExpression(expr);
  803. if (result && result.isIdentifier()) {
  804. return result.identifier;
  805. }
  806. }
  807. walkClass(classy) {
  808. if (classy.superClass) this.walkExpression(classy.superClass);
  809. if (classy.body && classy.body.type === "ClassBody") {
  810. const wasTopLevel = this.scope.topLevelScope;
  811. this.scope.topLevelScope = false;
  812. for (const methodDefinition of classy.body.body) {
  813. if (methodDefinition.type === "MethodDefinition") {
  814. this.walkMethodDefinition(methodDefinition);
  815. }
  816. }
  817. this.scope.topLevelScope = wasTopLevel;
  818. }
  819. }
  820. walkMethodDefinition(methodDefinition) {
  821. if (methodDefinition.computed && methodDefinition.key) {
  822. this.walkExpression(methodDefinition.key);
  823. }
  824. if (methodDefinition.value) {
  825. this.walkExpression(methodDefinition.value);
  826. }
  827. }
  828. // Prewalking iterates the scope for variable declarations
  829. prewalkStatements(statements) {
  830. for (let index = 0, len = statements.length; index < len; index++) {
  831. const statement = statements[index];
  832. this.prewalkStatement(statement);
  833. }
  834. }
  835. // Walking iterates the statements and expressions and processes them
  836. walkStatements(statements) {
  837. for (let index = 0, len = statements.length; index < len; index++) {
  838. const statement = statements[index];
  839. this.walkStatement(statement);
  840. }
  841. }
  842. prewalkStatement(statement) {
  843. switch (statement.type) {
  844. case "BlockStatement":
  845. this.prewalkBlockStatement(statement);
  846. break;
  847. case "ClassDeclaration":
  848. this.prewalkClassDeclaration(statement);
  849. break;
  850. case "DoWhileStatement":
  851. this.prewalkDoWhileStatement(statement);
  852. break;
  853. case "ExportAllDeclaration":
  854. this.prewalkExportAllDeclaration(statement);
  855. break;
  856. case "ExportDefaultDeclaration":
  857. this.prewalkExportDefaultDeclaration(statement);
  858. break;
  859. case "ExportNamedDeclaration":
  860. this.prewalkExportNamedDeclaration(statement);
  861. break;
  862. case "ForInStatement":
  863. this.prewalkForInStatement(statement);
  864. break;
  865. case "ForOfStatement":
  866. this.prewalkForOfStatement(statement);
  867. break;
  868. case "ForStatement":
  869. this.prewalkForStatement(statement);
  870. break;
  871. case "FunctionDeclaration":
  872. this.prewalkFunctionDeclaration(statement);
  873. break;
  874. case "IfStatement":
  875. this.prewalkIfStatement(statement);
  876. break;
  877. case "ImportDeclaration":
  878. this.prewalkImportDeclaration(statement);
  879. break;
  880. case "LabeledStatement":
  881. this.prewalkLabeledStatement(statement);
  882. break;
  883. case "SwitchStatement":
  884. this.prewalkSwitchStatement(statement);
  885. break;
  886. case "TryStatement":
  887. this.prewalkTryStatement(statement);
  888. break;
  889. case "VariableDeclaration":
  890. this.prewalkVariableDeclaration(statement);
  891. break;
  892. case "WhileStatement":
  893. this.prewalkWhileStatement(statement);
  894. break;
  895. case "WithStatement":
  896. this.prewalkWithStatement(statement);
  897. break;
  898. }
  899. }
  900. walkStatement(statement) {
  901. if (this.hooks.statement.call(statement) !== undefined) return;
  902. switch (statement.type) {
  903. case "BlockStatement":
  904. this.walkBlockStatement(statement);
  905. break;
  906. case "ClassDeclaration":
  907. this.walkClassDeclaration(statement);
  908. break;
  909. case "DoWhileStatement":
  910. this.walkDoWhileStatement(statement);
  911. break;
  912. case "ExportDefaultDeclaration":
  913. this.walkExportDefaultDeclaration(statement);
  914. break;
  915. case "ExportNamedDeclaration":
  916. this.walkExportNamedDeclaration(statement);
  917. break;
  918. case "ExpressionStatement":
  919. this.walkExpressionStatement(statement);
  920. break;
  921. case "ForInStatement":
  922. this.walkForInStatement(statement);
  923. break;
  924. case "ForOfStatement":
  925. this.walkForOfStatement(statement);
  926. break;
  927. case "ForStatement":
  928. this.walkForStatement(statement);
  929. break;
  930. case "FunctionDeclaration":
  931. this.walkFunctionDeclaration(statement);
  932. break;
  933. case "IfStatement":
  934. this.walkIfStatement(statement);
  935. break;
  936. case "LabeledStatement":
  937. this.walkLabeledStatement(statement);
  938. break;
  939. case "ReturnStatement":
  940. this.walkReturnStatement(statement);
  941. break;
  942. case "SwitchStatement":
  943. this.walkSwitchStatement(statement);
  944. break;
  945. case "ThrowStatement":
  946. this.walkThrowStatement(statement);
  947. break;
  948. case "TryStatement":
  949. this.walkTryStatement(statement);
  950. break;
  951. case "VariableDeclaration":
  952. this.walkVariableDeclaration(statement);
  953. break;
  954. case "WhileStatement":
  955. this.walkWhileStatement(statement);
  956. break;
  957. case "WithStatement":
  958. this.walkWithStatement(statement);
  959. break;
  960. }
  961. }
  962. // Real Statements
  963. prewalkBlockStatement(statement) {
  964. this.prewalkStatements(statement.body);
  965. }
  966. walkBlockStatement(statement) {
  967. this.walkStatements(statement.body);
  968. }
  969. walkExpressionStatement(statement) {
  970. this.walkExpression(statement.expression);
  971. }
  972. prewalkIfStatement(statement) {
  973. this.prewalkStatement(statement.consequent);
  974. if (statement.alternate) {
  975. this.prewalkStatement(statement.alternate);
  976. }
  977. }
  978. walkIfStatement(statement) {
  979. const result = this.hooks.statementIf.call(statement);
  980. if (result === undefined) {
  981. this.walkExpression(statement.test);
  982. this.walkStatement(statement.consequent);
  983. if (statement.alternate) {
  984. this.walkStatement(statement.alternate);
  985. }
  986. } else {
  987. if (result) {
  988. this.walkStatement(statement.consequent);
  989. } else if (statement.alternate) {
  990. this.walkStatement(statement.alternate);
  991. }
  992. }
  993. }
  994. prewalkLabeledStatement(statement) {
  995. this.prewalkStatement(statement.body);
  996. }
  997. walkLabeledStatement(statement) {
  998. const hook = this.hooks.label.get(statement.label.name);
  999. if (hook !== undefined) {
  1000. const result = hook.call(statement);
  1001. if (result === true) return;
  1002. }
  1003. this.walkStatement(statement.body);
  1004. }
  1005. prewalkWithStatement(statement) {
  1006. this.prewalkStatement(statement.body);
  1007. }
  1008. walkWithStatement(statement) {
  1009. this.walkExpression(statement.object);
  1010. this.walkStatement(statement.body);
  1011. }
  1012. prewalkSwitchStatement(statement) {
  1013. this.prewalkSwitchCases(statement.cases);
  1014. }
  1015. walkSwitchStatement(statement) {
  1016. this.walkExpression(statement.discriminant);
  1017. this.walkSwitchCases(statement.cases);
  1018. }
  1019. walkTerminatingStatement(statement) {
  1020. if (statement.argument) this.walkExpression(statement.argument);
  1021. }
  1022. walkReturnStatement(statement) {
  1023. this.walkTerminatingStatement(statement);
  1024. }
  1025. walkThrowStatement(statement) {
  1026. this.walkTerminatingStatement(statement);
  1027. }
  1028. prewalkTryStatement(statement) {
  1029. this.prewalkStatement(statement.block);
  1030. }
  1031. walkTryStatement(statement) {
  1032. if (this.scope.inTry) {
  1033. this.walkStatement(statement.block);
  1034. } else {
  1035. this.scope.inTry = true;
  1036. this.walkStatement(statement.block);
  1037. this.scope.inTry = false;
  1038. }
  1039. if (statement.handler) this.walkCatchClause(statement.handler);
  1040. if (statement.finalizer) this.walkStatement(statement.finalizer);
  1041. }
  1042. prewalkWhileStatement(statement) {
  1043. this.prewalkStatement(statement.body);
  1044. }
  1045. walkWhileStatement(statement) {
  1046. this.walkExpression(statement.test);
  1047. this.walkStatement(statement.body);
  1048. }
  1049. prewalkDoWhileStatement(statement) {
  1050. this.prewalkStatement(statement.body);
  1051. }
  1052. walkDoWhileStatement(statement) {
  1053. this.walkStatement(statement.body);
  1054. this.walkExpression(statement.test);
  1055. }
  1056. prewalkForStatement(statement) {
  1057. if (statement.init) {
  1058. if (statement.init.type === "VariableDeclaration") {
  1059. this.prewalkStatement(statement.init);
  1060. }
  1061. }
  1062. this.prewalkStatement(statement.body);
  1063. }
  1064. walkForStatement(statement) {
  1065. if (statement.init) {
  1066. if (statement.init.type === "VariableDeclaration") {
  1067. this.walkStatement(statement.init);
  1068. } else {
  1069. this.walkExpression(statement.init);
  1070. }
  1071. }
  1072. if (statement.test) {
  1073. this.walkExpression(statement.test);
  1074. }
  1075. if (statement.update) {
  1076. this.walkExpression(statement.update);
  1077. }
  1078. this.walkStatement(statement.body);
  1079. }
  1080. prewalkForInStatement(statement) {
  1081. if (statement.left.type === "VariableDeclaration") {
  1082. this.prewalkVariableDeclaration(statement.left);
  1083. }
  1084. this.prewalkStatement(statement.body);
  1085. }
  1086. walkForInStatement(statement) {
  1087. if (statement.left.type === "VariableDeclaration") {
  1088. this.walkVariableDeclaration(statement.left);
  1089. } else {
  1090. this.walkPattern(statement.left);
  1091. }
  1092. this.walkExpression(statement.right);
  1093. this.walkStatement(statement.body);
  1094. }
  1095. prewalkForOfStatement(statement) {
  1096. if (statement.left.type === "VariableDeclaration") {
  1097. this.prewalkVariableDeclaration(statement.left);
  1098. }
  1099. this.prewalkStatement(statement.body);
  1100. }
  1101. walkForOfStatement(statement) {
  1102. if (statement.left.type === "VariableDeclaration") {
  1103. this.walkVariableDeclaration(statement.left);
  1104. } else {
  1105. this.walkPattern(statement.left);
  1106. }
  1107. this.walkExpression(statement.right);
  1108. this.walkStatement(statement.body);
  1109. }
  1110. // Declarations
  1111. prewalkFunctionDeclaration(statement) {
  1112. if (statement.id) {
  1113. this.scope.renames.set(statement.id.name, null);
  1114. this.scope.definitions.add(statement.id.name);
  1115. }
  1116. }
  1117. walkFunctionDeclaration(statement) {
  1118. const wasTopLevel = this.scope.topLevelScope;
  1119. this.scope.topLevelScope = false;
  1120. this.inScope(statement.params, () => {
  1121. for (const param of statement.params) {
  1122. this.walkPattern(param);
  1123. }
  1124. if (statement.body.type === "BlockStatement") {
  1125. this.detectStrictMode(statement.body.body);
  1126. this.prewalkStatement(statement.body);
  1127. this.walkStatement(statement.body);
  1128. } else {
  1129. this.walkExpression(statement.body);
  1130. }
  1131. });
  1132. this.scope.topLevelScope = wasTopLevel;
  1133. }
  1134. prewalkImportDeclaration(statement) {
  1135. const source = statement.source.value;
  1136. this.hooks.import.call(statement, source);
  1137. for (const specifier of statement.specifiers) {
  1138. const name = specifier.local.name;
  1139. this.scope.renames.set(name, null);
  1140. this.scope.definitions.add(name);
  1141. switch (specifier.type) {
  1142. case "ImportDefaultSpecifier":
  1143. this.hooks.importSpecifier.call(statement, source, "default", name);
  1144. break;
  1145. case "ImportSpecifier":
  1146. this.hooks.importSpecifier.call(
  1147. statement,
  1148. source,
  1149. specifier.imported.name,
  1150. name
  1151. );
  1152. break;
  1153. case "ImportNamespaceSpecifier":
  1154. this.hooks.importSpecifier.call(statement, source, null, name);
  1155. break;
  1156. }
  1157. }
  1158. }
  1159. prewalkExportNamedDeclaration(statement) {
  1160. let source;
  1161. if (statement.source) {
  1162. source = statement.source.value;
  1163. this.hooks.exportImport.call(statement, source);
  1164. } else {
  1165. this.hooks.export.call(statement);
  1166. }
  1167. if (statement.declaration) {
  1168. if (
  1169. !this.hooks.exportDeclaration.call(statement, statement.declaration)
  1170. ) {
  1171. const originalDefinitions = this.scope.definitions;
  1172. const tracker = new TrackingSet(this.scope.definitions);
  1173. this.scope.definitions = tracker;
  1174. this.prewalkStatement(statement.declaration);
  1175. const newDefs = Array.from(tracker.getAddedItems());
  1176. this.scope.definitions = originalDefinitions;
  1177. for (let index = newDefs.length - 1; index >= 0; index--) {
  1178. const def = newDefs[index];
  1179. this.hooks.exportSpecifier.call(statement, def, def, index);
  1180. }
  1181. }
  1182. }
  1183. if (statement.specifiers) {
  1184. for (
  1185. let specifierIndex = 0;
  1186. specifierIndex < statement.specifiers.length;
  1187. specifierIndex++
  1188. ) {
  1189. const specifier = statement.specifiers[specifierIndex];
  1190. switch (specifier.type) {
  1191. case "ExportSpecifier": {
  1192. const name = specifier.exported.name;
  1193. if (source) {
  1194. this.hooks.exportImportSpecifier.call(
  1195. statement,
  1196. source,
  1197. specifier.local.name,
  1198. name,
  1199. specifierIndex
  1200. );
  1201. } else {
  1202. this.hooks.exportSpecifier.call(
  1203. statement,
  1204. specifier.local.name,
  1205. name,
  1206. specifierIndex
  1207. );
  1208. }
  1209. break;
  1210. }
  1211. }
  1212. }
  1213. }
  1214. }
  1215. walkExportNamedDeclaration(statement) {
  1216. if (statement.declaration) {
  1217. this.walkStatement(statement.declaration);
  1218. }
  1219. }
  1220. prewalkExportDefaultDeclaration(statement) {
  1221. if (statement.declaration.id) {
  1222. const originalDefinitions = this.scope.definitions;
  1223. const tracker = new TrackingSet(this.scope.definitions);
  1224. this.scope.definitions = tracker;
  1225. this.prewalkStatement(statement.declaration);
  1226. const newDefs = Array.from(tracker.getAddedItems());
  1227. this.scope.definitions = originalDefinitions;
  1228. for (let index = 0, len = newDefs.length; index < len; index++) {
  1229. const def = newDefs[index];
  1230. this.hooks.exportSpecifier.call(statement, def, "default");
  1231. }
  1232. }
  1233. }
  1234. walkExportDefaultDeclaration(statement) {
  1235. this.hooks.export.call(statement);
  1236. if (
  1237. statement.declaration.id &&
  1238. statement.declaration.type !== "FunctionExpression" &&
  1239. statement.declaration.type !== "ClassExpression"
  1240. ) {
  1241. if (
  1242. !this.hooks.exportDeclaration.call(statement, statement.declaration)
  1243. ) {
  1244. this.walkStatement(statement.declaration);
  1245. }
  1246. } else {
  1247. // Acorn parses `export default function() {}` as `FunctionDeclaration` and
  1248. // `export default class {}` as `ClassDeclaration`, both with `id = null`.
  1249. // These nodes must be treated as expressions.
  1250. if (statement.declaration.type === "FunctionDeclaration") {
  1251. this.walkFunctionDeclaration(statement.declaration);
  1252. } else if (statement.declaration.type === "ClassDeclaration") {
  1253. this.walkClassDeclaration(statement.declaration);
  1254. } else {
  1255. this.walkExpression(statement.declaration);
  1256. }
  1257. if (!this.hooks.exportExpression.call(statement, statement.declaration)) {
  1258. this.hooks.exportSpecifier.call(
  1259. statement,
  1260. statement.declaration,
  1261. "default"
  1262. );
  1263. }
  1264. }
  1265. }
  1266. prewalkExportAllDeclaration(statement) {
  1267. const source = statement.source.value;
  1268. this.hooks.exportImport.call(statement, source);
  1269. this.hooks.exportImportSpecifier.call(statement, source, null, null, 0);
  1270. }
  1271. prewalkVariableDeclaration(statement) {
  1272. const hookMap =
  1273. statement.kind === "const"
  1274. ? this.hooks.varDeclarationConst
  1275. : statement.kind === "let"
  1276. ? this.hooks.varDeclarationLet
  1277. : this.hooks.varDeclarationVar;
  1278. for (const declarator of statement.declarations) {
  1279. switch (declarator.type) {
  1280. case "VariableDeclarator": {
  1281. this.enterPattern(declarator.id, (name, decl) => {
  1282. let hook = hookMap.get(name);
  1283. if (hook === undefined || !hook.call(decl)) {
  1284. hook = this.hooks.varDeclaration.get(name);
  1285. if (hook === undefined || !hook.call(decl)) {
  1286. this.scope.renames.set(name, null);
  1287. this.scope.definitions.add(name);
  1288. }
  1289. }
  1290. });
  1291. break;
  1292. }
  1293. }
  1294. }
  1295. }
  1296. walkVariableDeclaration(statement) {
  1297. for (const declarator of statement.declarations) {
  1298. switch (declarator.type) {
  1299. case "VariableDeclarator": {
  1300. const renameIdentifier =
  1301. declarator.init && this.getRenameIdentifier(declarator.init);
  1302. if (renameIdentifier && declarator.id.type === "Identifier") {
  1303. const hook = this.hooks.canRename.get(renameIdentifier);
  1304. if (hook !== undefined && hook.call(declarator.init)) {
  1305. // renaming with "var a = b;"
  1306. const hook = this.hooks.rename.get(renameIdentifier);
  1307. if (hook === undefined || !hook.call(declarator.init)) {
  1308. this.scope.renames.set(
  1309. declarator.id.name,
  1310. this.scope.renames.get(renameIdentifier) || renameIdentifier
  1311. );
  1312. this.scope.definitions.delete(declarator.id.name);
  1313. }
  1314. break;
  1315. }
  1316. }
  1317. this.walkPattern(declarator.id);
  1318. if (declarator.init) this.walkExpression(declarator.init);
  1319. break;
  1320. }
  1321. }
  1322. }
  1323. }
  1324. prewalkClassDeclaration(statement) {
  1325. if (statement.id) {
  1326. this.scope.renames.set(statement.id.name, null);
  1327. this.scope.definitions.add(statement.id.name);
  1328. }
  1329. }
  1330. walkClassDeclaration(statement) {
  1331. this.walkClass(statement);
  1332. }
  1333. prewalkSwitchCases(switchCases) {
  1334. for (let index = 0, len = switchCases.length; index < len; index++) {
  1335. const switchCase = switchCases[index];
  1336. this.prewalkStatements(switchCase.consequent);
  1337. }
  1338. }
  1339. walkSwitchCases(switchCases) {
  1340. for (let index = 0, len = switchCases.length; index < len; index++) {
  1341. const switchCase = switchCases[index];
  1342. if (switchCase.test) {
  1343. this.walkExpression(switchCase.test);
  1344. }
  1345. this.walkStatements(switchCase.consequent);
  1346. }
  1347. }
  1348. walkCatchClause(catchClause) {
  1349. // Error binding is optional in catch clause since ECMAScript 2019
  1350. const errorBinding =
  1351. catchClause.param === null ? EMPTY_ARRAY : [catchClause.param];
  1352. this.inScope(errorBinding, () => {
  1353. this.prewalkStatement(catchClause.body);
  1354. this.walkStatement(catchClause.body);
  1355. });
  1356. }
  1357. walkPattern(pattern) {
  1358. switch (pattern.type) {
  1359. case "ArrayPattern":
  1360. this.walkArrayPattern(pattern);
  1361. break;
  1362. case "AssignmentPattern":
  1363. this.walkAssignmentPattern(pattern);
  1364. break;
  1365. case "MemberExpression":
  1366. this.walkMemberExpression(pattern);
  1367. break;
  1368. case "ObjectPattern":
  1369. this.walkObjectPattern(pattern);
  1370. break;
  1371. case "RestElement":
  1372. this.walkRestElement(pattern);
  1373. break;
  1374. }
  1375. }
  1376. walkAssignmentPattern(pattern) {
  1377. this.walkExpression(pattern.right);
  1378. this.walkPattern(pattern.left);
  1379. }
  1380. walkObjectPattern(pattern) {
  1381. for (let i = 0, len = pattern.properties.length; i < len; i++) {
  1382. const prop = pattern.properties[i];
  1383. if (prop) {
  1384. if (prop.computed) this.walkExpression(prop.key);
  1385. if (prop.value) this.walkPattern(prop.value);
  1386. }
  1387. }
  1388. }
  1389. walkArrayPattern(pattern) {
  1390. for (let i = 0, len = pattern.elements.length; i < len; i++) {
  1391. const element = pattern.elements[i];
  1392. if (element) this.walkPattern(element);
  1393. }
  1394. }
  1395. walkRestElement(pattern) {
  1396. this.walkPattern(pattern.argument);
  1397. }
  1398. walkExpressions(expressions) {
  1399. for (const expression of expressions) {
  1400. if (expression) {
  1401. this.walkExpression(expression);
  1402. }
  1403. }
  1404. }
  1405. walkExpression(expression) {
  1406. switch (expression.type) {
  1407. case "ArrayExpression":
  1408. this.walkArrayExpression(expression);
  1409. break;
  1410. case "ArrowFunctionExpression":
  1411. this.walkArrowFunctionExpression(expression);
  1412. break;
  1413. case "AssignmentExpression":
  1414. this.walkAssignmentExpression(expression);
  1415. break;
  1416. case "AwaitExpression":
  1417. this.walkAwaitExpression(expression);
  1418. break;
  1419. case "BinaryExpression":
  1420. this.walkBinaryExpression(expression);
  1421. break;
  1422. case "CallExpression":
  1423. this.walkCallExpression(expression);
  1424. break;
  1425. case "ClassExpression":
  1426. this.walkClassExpression(expression);
  1427. break;
  1428. case "ConditionalExpression":
  1429. this.walkConditionalExpression(expression);
  1430. break;
  1431. case "FunctionExpression":
  1432. this.walkFunctionExpression(expression);
  1433. break;
  1434. case "Identifier":
  1435. this.walkIdentifier(expression);
  1436. break;
  1437. case "LogicalExpression":
  1438. this.walkLogicalExpression(expression);
  1439. break;
  1440. case "MemberExpression":
  1441. this.walkMemberExpression(expression);
  1442. break;
  1443. case "NewExpression":
  1444. this.walkNewExpression(expression);
  1445. break;
  1446. case "ObjectExpression":
  1447. this.walkObjectExpression(expression);
  1448. break;
  1449. case "SequenceExpression":
  1450. this.walkSequenceExpression(expression);
  1451. break;
  1452. case "SpreadElement":
  1453. this.walkSpreadElement(expression);
  1454. break;
  1455. case "TaggedTemplateExpression":
  1456. this.walkTaggedTemplateExpression(expression);
  1457. break;
  1458. case "TemplateLiteral":
  1459. this.walkTemplateLiteral(expression);
  1460. break;
  1461. case "ThisExpression":
  1462. this.walkThisExpression(expression);
  1463. break;
  1464. case "UnaryExpression":
  1465. this.walkUnaryExpression(expression);
  1466. break;
  1467. case "UpdateExpression":
  1468. this.walkUpdateExpression(expression);
  1469. break;
  1470. case "YieldExpression":
  1471. this.walkYieldExpression(expression);
  1472. break;
  1473. }
  1474. }
  1475. walkAwaitExpression(expression) {
  1476. this.walkExpression(expression.argument);
  1477. }
  1478. walkArrayExpression(expression) {
  1479. if (expression.elements) {
  1480. this.walkExpressions(expression.elements);
  1481. }
  1482. }
  1483. walkSpreadElement(expression) {
  1484. if (expression.argument) {
  1485. this.walkExpression(expression.argument);
  1486. }
  1487. }
  1488. walkObjectExpression(expression) {
  1489. for (
  1490. let propIndex = 0, len = expression.properties.length;
  1491. propIndex < len;
  1492. propIndex++
  1493. ) {
  1494. const prop = expression.properties[propIndex];
  1495. if (prop.type === "SpreadElement") {
  1496. this.walkExpression(prop.argument);
  1497. continue;
  1498. }
  1499. if (prop.computed) {
  1500. this.walkExpression(prop.key);
  1501. }
  1502. if (prop.shorthand) {
  1503. this.scope.inShorthand = true;
  1504. }
  1505. this.walkExpression(prop.value);
  1506. if (prop.shorthand) {
  1507. this.scope.inShorthand = false;
  1508. }
  1509. }
  1510. }
  1511. walkFunctionExpression(expression) {
  1512. const wasTopLevel = this.scope.topLevelScope;
  1513. this.scope.topLevelScope = false;
  1514. this.inScope(expression.params, () => {
  1515. for (const param of expression.params) {
  1516. this.walkPattern(param);
  1517. }
  1518. if (expression.body.type === "BlockStatement") {
  1519. this.detectStrictMode(expression.body.body);
  1520. this.prewalkStatement(expression.body);
  1521. this.walkStatement(expression.body);
  1522. } else {
  1523. this.walkExpression(expression.body);
  1524. }
  1525. });
  1526. this.scope.topLevelScope = wasTopLevel;
  1527. }
  1528. walkArrowFunctionExpression(expression) {
  1529. this.inScope(expression.params, () => {
  1530. for (const param of expression.params) {
  1531. this.walkPattern(param);
  1532. }
  1533. if (expression.body.type === "BlockStatement") {
  1534. this.detectStrictMode(expression.body.body);
  1535. this.prewalkStatement(expression.body);
  1536. this.walkStatement(expression.body);
  1537. } else {
  1538. this.walkExpression(expression.body);
  1539. }
  1540. });
  1541. }
  1542. walkSequenceExpression(expression) {
  1543. if (expression.expressions) this.walkExpressions(expression.expressions);
  1544. }
  1545. walkUpdateExpression(expression) {
  1546. this.walkExpression(expression.argument);
  1547. }
  1548. walkUnaryExpression(expression) {
  1549. if (expression.operator === "typeof") {
  1550. const exprName = this.getNameForExpression(expression.argument);
  1551. if (exprName && exprName.free) {
  1552. const hook = this.hooks.typeof.get(exprName.name);
  1553. if (hook !== undefined) {
  1554. const result = hook.call(expression);
  1555. if (result === true) return;
  1556. }
  1557. }
  1558. }
  1559. this.walkExpression(expression.argument);
  1560. }
  1561. walkLeftRightExpression(expression) {
  1562. this.walkExpression(expression.left);
  1563. this.walkExpression(expression.right);
  1564. }
  1565. walkBinaryExpression(expression) {
  1566. this.walkLeftRightExpression(expression);
  1567. }
  1568. walkLogicalExpression(expression) {
  1569. const result = this.hooks.expressionLogicalOperator.call(expression);
  1570. if (result === undefined) {
  1571. this.walkLeftRightExpression(expression);
  1572. } else {
  1573. if (result) {
  1574. this.walkExpression(expression.right);
  1575. }
  1576. }
  1577. }
  1578. walkAssignmentExpression(expression) {
  1579. const renameIdentifier = this.getRenameIdentifier(expression.right);
  1580. if (expression.left.type === "Identifier" && renameIdentifier) {
  1581. const hook = this.hooks.canRename.get(renameIdentifier);
  1582. if (hook !== undefined && hook.call(expression.right)) {
  1583. // renaming "a = b;"
  1584. const hook = this.hooks.rename.get(renameIdentifier);
  1585. if (hook === undefined || !hook.call(expression.right)) {
  1586. this.scope.renames.set(expression.left.name, renameIdentifier);
  1587. this.scope.definitions.delete(expression.left.name);
  1588. }
  1589. return;
  1590. }
  1591. }
  1592. if (expression.left.type === "Identifier") {
  1593. const assignedHook = this.hooks.assigned.get(expression.left.name);
  1594. if (assignedHook === undefined || !assignedHook.call(expression)) {
  1595. this.walkExpression(expression.right);
  1596. }
  1597. this.scope.renames.set(expression.left.name, null);
  1598. const assignHook = this.hooks.assign.get(expression.left.name);
  1599. if (assignHook === undefined || !assignHook.call(expression)) {
  1600. this.walkExpression(expression.left);
  1601. }
  1602. return;
  1603. }
  1604. this.walkExpression(expression.right);
  1605. this.walkPattern(expression.left);
  1606. this.enterPattern(expression.left, (name, decl) => {
  1607. this.scope.renames.set(name, null);
  1608. });
  1609. }
  1610. walkConditionalExpression(expression) {
  1611. const result = this.hooks.expressionConditionalOperator.call(expression);
  1612. if (result === undefined) {
  1613. this.walkExpression(expression.test);
  1614. this.walkExpression(expression.consequent);
  1615. if (expression.alternate) {
  1616. this.walkExpression(expression.alternate);
  1617. }
  1618. } else {
  1619. if (result) {
  1620. this.walkExpression(expression.consequent);
  1621. } else if (expression.alternate) {
  1622. this.walkExpression(expression.alternate);
  1623. }
  1624. }
  1625. }
  1626. walkNewExpression(expression) {
  1627. const callee = this.evaluateExpression(expression.callee);
  1628. if (callee.isIdentifier()) {
  1629. const hook = this.hooks.new.get(callee.identifier);
  1630. if (hook !== undefined) {
  1631. const result = hook.call(expression);
  1632. if (result === true) {
  1633. return;
  1634. }
  1635. }
  1636. }
  1637. this.walkExpression(expression.callee);
  1638. if (expression.arguments) {
  1639. this.walkExpressions(expression.arguments);
  1640. }
  1641. }
  1642. walkYieldExpression(expression) {
  1643. if (expression.argument) {
  1644. this.walkExpression(expression.argument);
  1645. }
  1646. }
  1647. walkTemplateLiteral(expression) {
  1648. if (expression.expressions) {
  1649. this.walkExpressions(expression.expressions);
  1650. }
  1651. }
  1652. walkTaggedTemplateExpression(expression) {
  1653. if (expression.tag) {
  1654. this.walkExpression(expression.tag);
  1655. }
  1656. if (expression.quasi && expression.quasi.expressions) {
  1657. this.walkExpressions(expression.quasi.expressions);
  1658. }
  1659. }
  1660. walkClassExpression(expression) {
  1661. this.walkClass(expression);
  1662. }
  1663. _walkIIFE(functionExpression, options, currentThis) {
  1664. const renameArgOrThis = argOrThis => {
  1665. const renameIdentifier = this.getRenameIdentifier(argOrThis);
  1666. if (renameIdentifier) {
  1667. const hook = this.hooks.canRename.get(renameIdentifier);
  1668. if (hook !== undefined && hook.call(argOrThis)) {
  1669. const hook = this.hooks.rename.get(renameIdentifier);
  1670. if (hook === undefined || !hook.call(argOrThis)) {
  1671. return renameIdentifier;
  1672. }
  1673. }
  1674. }
  1675. this.walkExpression(argOrThis);
  1676. };
  1677. const params = functionExpression.params;
  1678. const renameThis = currentThis ? renameArgOrThis(currentThis) : null;
  1679. const args = options.map(renameArgOrThis);
  1680. const wasTopLevel = this.scope.topLevelScope;
  1681. this.scope.topLevelScope = false;
  1682. this.inScope(params.filter((identifier, idx) => !args[idx]), () => {
  1683. if (renameThis) {
  1684. this.scope.renames.set("this", renameThis);
  1685. }
  1686. for (let i = 0; i < args.length; i++) {
  1687. const param = args[i];
  1688. if (!param) continue;
  1689. if (!params[i] || params[i].type !== "Identifier") continue;
  1690. this.scope.renames.set(params[i].name, param);
  1691. }
  1692. if (functionExpression.body.type === "BlockStatement") {
  1693. this.prewalkStatement(functionExpression.body);
  1694. this.walkStatement(functionExpression.body);
  1695. } else {
  1696. this.walkExpression(functionExpression.body);
  1697. }
  1698. });
  1699. this.scope.topLevelScope = wasTopLevel;
  1700. }
  1701. walkCallExpression(expression) {
  1702. if (
  1703. expression.callee.type === "MemberExpression" &&
  1704. expression.callee.object.type === "FunctionExpression" &&
  1705. !expression.callee.computed &&
  1706. (expression.callee.property.name === "call" ||
  1707. expression.callee.property.name === "bind") &&
  1708. expression.arguments.length > 0
  1709. ) {
  1710. // (function(…) { }.call/bind(?, …))
  1711. this._walkIIFE(
  1712. expression.callee.object,
  1713. expression.arguments.slice(1),
  1714. expression.arguments[0]
  1715. );
  1716. } else if (expression.callee.type === "FunctionExpression") {
  1717. // (function(…) { }(…))
  1718. this._walkIIFE(expression.callee, expression.arguments, null);
  1719. } else if (expression.callee.type === "Import") {
  1720. let result = this.hooks.importCall.call(expression);
  1721. if (result === true) return;
  1722. if (expression.arguments) this.walkExpressions(expression.arguments);
  1723. } else {
  1724. const callee = this.evaluateExpression(expression.callee);
  1725. if (callee.isIdentifier()) {
  1726. const callHook = this.hooks.call.get(callee.identifier);
  1727. if (callHook !== undefined) {
  1728. let result = callHook.call(expression);
  1729. if (result === true) return;
  1730. }
  1731. let identifier = callee.identifier.replace(/\.[^.]+$/, "");
  1732. if (identifier !== callee.identifier) {
  1733. const callAnyHook = this.hooks.callAnyMember.get(identifier);
  1734. if (callAnyHook !== undefined) {
  1735. let result = callAnyHook.call(expression);
  1736. if (result === true) return;
  1737. }
  1738. }
  1739. }
  1740. if (expression.callee) this.walkExpression(expression.callee);
  1741. if (expression.arguments) this.walkExpressions(expression.arguments);
  1742. }
  1743. }
  1744. walkMemberExpression(expression) {
  1745. const exprName = this.getNameForExpression(expression);
  1746. if (exprName && exprName.free) {
  1747. const expressionHook = this.hooks.expression.get(exprName.name);
  1748. if (expressionHook !== undefined) {
  1749. const result = expressionHook.call(expression);
  1750. if (result === true) return;
  1751. }
  1752. const expressionAnyMemberHook = this.hooks.expressionAnyMember.get(
  1753. exprName.nameGeneral
  1754. );
  1755. if (expressionAnyMemberHook !== undefined) {
  1756. const result = expressionAnyMemberHook.call(expression);
  1757. if (result === true) return;
  1758. }
  1759. }
  1760. this.walkExpression(expression.object);
  1761. if (expression.computed === true) this.walkExpression(expression.property);
  1762. }
  1763. walkThisExpression(expression) {
  1764. const expressionHook = this.hooks.expression.get("this");
  1765. if (expressionHook !== undefined) {
  1766. expressionHook.call(expression);
  1767. }
  1768. }
  1769. walkIdentifier(expression) {
  1770. if (!this.scope.definitions.has(expression.name)) {
  1771. const hook = this.hooks.expression.get(
  1772. this.scope.renames.get(expression.name) || expression.name
  1773. );
  1774. if (hook !== undefined) {
  1775. const result = hook.call(expression);
  1776. if (result === true) return;
  1777. }
  1778. }
  1779. }
  1780. inScope(params, fn) {
  1781. const oldScope = this.scope;
  1782. this.scope = {
  1783. topLevelScope: oldScope.topLevelScope,
  1784. inTry: false,
  1785. inShorthand: false,
  1786. isStrict: oldScope.isStrict,
  1787. definitions: oldScope.definitions.createChild(),
  1788. renames: oldScope.renames.createChild()
  1789. };
  1790. this.scope.renames.set("this", null);
  1791. for (const param of params) {
  1792. if (typeof param !== "string") {
  1793. this.enterPattern(param, param => {
  1794. this.scope.renames.set(param, null);
  1795. this.scope.definitions.add(param);
  1796. });
  1797. } else if (param) {
  1798. this.scope.renames.set(param, null);
  1799. this.scope.definitions.add(param);
  1800. }
  1801. }
  1802. fn();
  1803. this.scope = oldScope;
  1804. }
  1805. detectStrictMode(statements) {
  1806. const isStrict =
  1807. statements.length >= 1 &&
  1808. statements[0].type === "ExpressionStatement" &&
  1809. statements[0].expression.type === "Literal" &&
  1810. statements[0].expression.value === "use strict";
  1811. if (isStrict) {
  1812. this.scope.isStrict = true;
  1813. }
  1814. }
  1815. enterPattern(pattern, onIdent) {
  1816. if (!pattern) return;
  1817. switch (pattern.type) {
  1818. case "ArrayPattern":
  1819. this.enterArrayPattern(pattern, onIdent);
  1820. break;
  1821. case "AssignmentPattern":
  1822. this.enterAssignmentPattern(pattern, onIdent);
  1823. break;
  1824. case "Identifier":
  1825. this.enterIdentifier(pattern, onIdent);
  1826. break;
  1827. case "ObjectPattern":
  1828. this.enterObjectPattern(pattern, onIdent);
  1829. break;
  1830. case "RestElement":
  1831. this.enterRestElement(pattern, onIdent);
  1832. break;
  1833. }
  1834. }
  1835. enterIdentifier(pattern, onIdent) {
  1836. onIdent(pattern.name, pattern);
  1837. }
  1838. enterObjectPattern(pattern, onIdent) {
  1839. for (
  1840. let propIndex = 0, len = pattern.properties.length;
  1841. propIndex < len;
  1842. propIndex++
  1843. ) {
  1844. const prop = pattern.properties[propIndex];
  1845. this.enterPattern(prop.value, onIdent);
  1846. }
  1847. }
  1848. enterArrayPattern(pattern, onIdent) {
  1849. for (
  1850. let elementIndex = 0, len = pattern.elements.length;
  1851. elementIndex < len;
  1852. elementIndex++
  1853. ) {
  1854. const element = pattern.elements[elementIndex];
  1855. this.enterPattern(element, onIdent);
  1856. }
  1857. }
  1858. enterRestElement(pattern, onIdent) {
  1859. this.enterPattern(pattern.argument, onIdent);
  1860. }
  1861. enterAssignmentPattern(pattern, onIdent) {
  1862. this.enterPattern(pattern.left, onIdent);
  1863. }
  1864. evaluateExpression(expression) {
  1865. try {
  1866. const hook = this.hooks.evaluate.get(expression.type);
  1867. if (hook !== undefined) {
  1868. const result = hook.call(expression);
  1869. if (result !== undefined) {
  1870. if (result) {
  1871. result.setExpression(expression);
  1872. }
  1873. return result;
  1874. }
  1875. }
  1876. } catch (e) {
  1877. console.warn(e);
  1878. // ignore error
  1879. }
  1880. return new BasicEvaluatedExpression()
  1881. .setRange(expression.range)
  1882. .setExpression(expression);
  1883. }
  1884. parseString(expression) {
  1885. switch (expression.type) {
  1886. case "BinaryExpression":
  1887. if (expression.operator === "+") {
  1888. return (
  1889. this.parseString(expression.left) +
  1890. this.parseString(expression.right)
  1891. );
  1892. }
  1893. break;
  1894. case "Literal":
  1895. return expression.value + "";
  1896. }
  1897. throw new Error(
  1898. expression.type + " is not supported as parameter for require"
  1899. );
  1900. }
  1901. parseCalculatedString(expression) {
  1902. switch (expression.type) {
  1903. case "BinaryExpression":
  1904. if (expression.operator === "+") {
  1905. const left = this.parseCalculatedString(expression.left);
  1906. const right = this.parseCalculatedString(expression.right);
  1907. if (left.code) {
  1908. return {
  1909. range: left.range,
  1910. value: left.value,
  1911. code: true,
  1912. conditional: false
  1913. };
  1914. } else if (right.code) {
  1915. return {
  1916. range: [
  1917. left.range[0],
  1918. right.range ? right.range[1] : left.range[1]
  1919. ],
  1920. value: left.value + right.value,
  1921. code: true,
  1922. conditional: false
  1923. };
  1924. } else {
  1925. return {
  1926. range: [left.range[0], right.range[1]],
  1927. value: left.value + right.value,
  1928. code: false,
  1929. conditional: false
  1930. };
  1931. }
  1932. }
  1933. break;
  1934. case "ConditionalExpression": {
  1935. const consequent = this.parseCalculatedString(expression.consequent);
  1936. const alternate = this.parseCalculatedString(expression.alternate);
  1937. const items = [];
  1938. if (consequent.conditional) {
  1939. items.push(...consequent.conditional);
  1940. } else if (!consequent.code) {
  1941. items.push(consequent);
  1942. } else {
  1943. break;
  1944. }
  1945. if (alternate.conditional) {
  1946. items.push(...alternate.conditional);
  1947. } else if (!alternate.code) {
  1948. items.push(alternate);
  1949. } else {
  1950. break;
  1951. }
  1952. return {
  1953. range: undefined,
  1954. value: "",
  1955. code: true,
  1956. conditional: items
  1957. };
  1958. }
  1959. case "Literal":
  1960. return {
  1961. range: expression.range,
  1962. value: expression.value + "",
  1963. code: false,
  1964. conditional: false
  1965. };
  1966. }
  1967. return {
  1968. range: undefined,
  1969. value: "",
  1970. code: true,
  1971. conditional: false
  1972. };
  1973. }
  1974. parse(source, initialState) {
  1975. let ast;
  1976. let comments;
  1977. if (typeof source === "object" && source !== null) {
  1978. ast = source;
  1979. comments = source.comments;
  1980. } else {
  1981. comments = [];
  1982. ast = Parser.parse(source, {
  1983. sourceType: this.sourceType,
  1984. onComment: comments
  1985. });
  1986. }
  1987. const oldScope = this.scope;
  1988. const oldState = this.state;
  1989. const oldComments = this.comments;
  1990. this.scope = {
  1991. topLevelScope: true,
  1992. inTry: false,
  1993. inShorthand: false,
  1994. isStrict: false,
  1995. definitions: new StackedSetMap(),
  1996. renames: new StackedSetMap()
  1997. };
  1998. const state = (this.state = initialState || {});
  1999. this.comments = comments;
  2000. if (this.hooks.program.call(ast, comments) === undefined) {
  2001. this.detectStrictMode(ast.body);
  2002. this.prewalkStatements(ast.body);
  2003. this.walkStatements(ast.body);
  2004. }
  2005. this.scope = oldScope;
  2006. this.state = oldState;
  2007. this.comments = oldComments;
  2008. return state;
  2009. }
  2010. evaluate(source) {
  2011. const ast = Parser.parse("(" + source + ")", {
  2012. sourceType: this.sourceType,
  2013. locations: false
  2014. });
  2015. if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") {
  2016. throw new Error("evaluate: Source is not a expression");
  2017. }
  2018. return this.evaluateExpression(ast.body[0].expression);
  2019. }
  2020. getComments(range) {
  2021. return this.comments.filter(
  2022. comment => comment.range[0] >= range[0] && comment.range[1] <= range[1]
  2023. );
  2024. }
  2025. parseCommentOptions(range) {
  2026. const comments = this.getComments(range);
  2027. if (comments.length === 0) {
  2028. return EMPTY_COMMENT_OPTIONS;
  2029. }
  2030. let options = {};
  2031. let errors = [];
  2032. for (const comment of comments) {
  2033. const { value } = comment;
  2034. if (value && webpackCommentRegExp.test(value)) {
  2035. // try compile only if webpack options comment is present
  2036. try {
  2037. const val = vm.runInNewContext(`(function(){return {${value}};})()`);
  2038. Object.assign(options, val);
  2039. } catch (e) {
  2040. e.comment = comment;
  2041. errors.push(e);
  2042. }
  2043. }
  2044. }
  2045. return { options, errors };
  2046. }
  2047. getNameForExpression(expression) {
  2048. let expr = expression;
  2049. const exprName = [];
  2050. while (
  2051. expr.type === "MemberExpression" &&
  2052. expr.property.type === (expr.computed ? "Literal" : "Identifier")
  2053. ) {
  2054. exprName.push(expr.computed ? expr.property.value : expr.property.name);
  2055. expr = expr.object;
  2056. }
  2057. let free;
  2058. if (expr.type === "Identifier") {
  2059. free = !this.scope.definitions.has(expr.name);
  2060. exprName.push(this.scope.renames.get(expr.name) || expr.name);
  2061. } else if (
  2062. expr.type === "ThisExpression" &&
  2063. this.scope.renames.get("this")
  2064. ) {
  2065. free = true;
  2066. exprName.push(this.scope.renames.get("this"));
  2067. } else if (expr.type === "ThisExpression") {
  2068. free = this.scope.topLevelScope;
  2069. exprName.push("this");
  2070. } else {
  2071. return null;
  2072. }
  2073. let prefix = "";
  2074. for (let i = exprName.length - 1; i >= 2; i--) {
  2075. prefix += exprName[i] + ".";
  2076. }
  2077. if (exprName.length > 1) {
  2078. prefix += exprName[1];
  2079. }
  2080. const name = prefix ? prefix + "." + exprName[0] : exprName[0];
  2081. const nameGeneral = prefix;
  2082. return {
  2083. name,
  2084. nameGeneral,
  2085. free
  2086. };
  2087. }
  2088. static parse(code, options) {
  2089. const type = options ? options.sourceType : "module";
  2090. const parserOptions = Object.assign(
  2091. Object.create(null),
  2092. defaultParserOptions,
  2093. options
  2094. );
  2095. if (type === "auto") {
  2096. parserOptions.sourceType = "module";
  2097. }
  2098. let ast;
  2099. let error;
  2100. let threw = false;
  2101. try {
  2102. ast = acorn.parse(code, parserOptions);
  2103. } catch (e) {
  2104. error = e;
  2105. threw = true;
  2106. }
  2107. if (threw && type === "auto") {
  2108. parserOptions.sourceType = "script";
  2109. if (Array.isArray(parserOptions.onComment)) {
  2110. parserOptions.onComment.length = 0;
  2111. }
  2112. try {
  2113. ast = acorn.parse(code, parserOptions);
  2114. threw = false;
  2115. } catch (e) {
  2116. threw = true;
  2117. }
  2118. }
  2119. if (threw) {
  2120. throw error;
  2121. }
  2122. return ast;
  2123. }
  2124. }
  2125. // TODO remove in webpack 5
  2126. Object.defineProperty(Parser.prototype, "getCommentOptions", {
  2127. configurable: false,
  2128. value: util.deprecate(
  2129. /**
  2130. * @deprecated
  2131. * @param {TODO} range Range
  2132. * @returns {void}
  2133. * @this {Parser}
  2134. */
  2135. function(range) {
  2136. return this.parseCommentOptions(range).options;
  2137. },
  2138. "Parser.getCommentOptions: Use Parser.parseCommentOptions(range) instead"
  2139. )
  2140. });
  2141. module.exports = Parser;