Parser.js 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  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 = require("tapable");
  9. const json5 = require("json5");
  10. const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
  11. function joinRanges(startRange, endRange) {
  12. if(!endRange) return startRange;
  13. if(!startRange) return endRange;
  14. return [startRange[0], endRange[1]];
  15. }
  16. const ECMA_VERSION = 2017;
  17. const POSSIBLE_AST_OPTIONS = [{
  18. ranges: true,
  19. locations: true,
  20. ecmaVersion: ECMA_VERSION,
  21. sourceType: "module",
  22. plugins: {
  23. dynamicImport: true
  24. }
  25. }, {
  26. ranges: true,
  27. locations: true,
  28. ecmaVersion: ECMA_VERSION,
  29. sourceType: "script",
  30. plugins: {
  31. dynamicImport: true
  32. }
  33. }];
  34. class Parser extends Tapable {
  35. constructor(options) {
  36. super();
  37. this.options = options;
  38. this.scope = undefined;
  39. this.state = undefined;
  40. this.comments = undefined;
  41. this.initializeEvaluating();
  42. }
  43. initializeEvaluating() {
  44. this.plugin("evaluate Literal", expr => {
  45. switch(typeof expr.value) {
  46. case "number":
  47. return new BasicEvaluatedExpression().setNumber(expr.value).setRange(expr.range);
  48. case "string":
  49. return new BasicEvaluatedExpression().setString(expr.value).setRange(expr.range);
  50. case "boolean":
  51. return new BasicEvaluatedExpression().setBoolean(expr.value).setRange(expr.range);
  52. }
  53. if(expr.value === null)
  54. return new BasicEvaluatedExpression().setNull().setRange(expr.range);
  55. if(expr.value instanceof RegExp)
  56. return new BasicEvaluatedExpression().setRegExp(expr.value).setRange(expr.range);
  57. });
  58. this.plugin("evaluate LogicalExpression", function(expr) {
  59. let left;
  60. let leftAsBool;
  61. let right;
  62. if(expr.operator === "&&") {
  63. left = this.evaluateExpression(expr.left);
  64. leftAsBool = left && left.asBool();
  65. if(leftAsBool === false) return left.setRange(expr.range);
  66. if(leftAsBool !== true) return;
  67. right = this.evaluateExpression(expr.right);
  68. return right.setRange(expr.range);
  69. } else if(expr.operator === "||") {
  70. left = this.evaluateExpression(expr.left);
  71. leftAsBool = left && left.asBool();
  72. if(leftAsBool === true) return left.setRange(expr.range);
  73. if(leftAsBool !== false) return;
  74. right = this.evaluateExpression(expr.right);
  75. return right.setRange(expr.range);
  76. }
  77. });
  78. this.plugin("evaluate BinaryExpression", function(expr) {
  79. let left;
  80. let right;
  81. let res;
  82. if(expr.operator === "+") {
  83. left = this.evaluateExpression(expr.left);
  84. right = this.evaluateExpression(expr.right);
  85. if(!left || !right) return;
  86. res = new BasicEvaluatedExpression();
  87. if(left.isString()) {
  88. if(right.isString()) {
  89. res.setString(left.string + right.string);
  90. } else if(right.isNumber()) {
  91. res.setString(left.string + right.number);
  92. } else if(right.isWrapped() && right.prefix && right.prefix.isString()) {
  93. res.setWrapped(
  94. new BasicEvaluatedExpression()
  95. .setString(left.string + right.prefix.string)
  96. .setRange(joinRanges(left.range, right.prefix.range)),
  97. right.postfix);
  98. } else if(right.isWrapped()) {
  99. res.setWrapped(
  100. new BasicEvaluatedExpression()
  101. .setString(left.string)
  102. .setRange(left.range),
  103. right.postfix);
  104. } else {
  105. res.setWrapped(left, null);
  106. }
  107. } else if(left.isNumber()) {
  108. if(right.isString()) {
  109. res.setString(left.number + right.string);
  110. } else if(right.isNumber()) {
  111. res.setNumber(left.number + right.number);
  112. }
  113. } else if(left.isWrapped()) {
  114. if(left.postfix && left.postfix.isString() && right.isString()) {
  115. res.setWrapped(left.prefix,
  116. new BasicEvaluatedExpression()
  117. .setString(left.postfix.string + right.string)
  118. .setRange(joinRanges(left.postfix.range, right.range))
  119. );
  120. } else if(left.postfix && left.postfix.isString() && right.isNumber()) {
  121. res.setWrapped(left.prefix,
  122. new BasicEvaluatedExpression()
  123. .setString(left.postfix.string + right.number)
  124. .setRange(joinRanges(left.postfix.range, right.range))
  125. );
  126. } else if(right.isString()) {
  127. res.setWrapped(left.prefix, right);
  128. } else if(right.isNumber()) {
  129. res.setWrapped(left.prefix,
  130. new BasicEvaluatedExpression()
  131. .setString(right.number + "")
  132. .setRange(right.range));
  133. } else {
  134. res.setWrapped(left.prefix, new BasicEvaluatedExpression());
  135. }
  136. } else {
  137. if(right.isString()) {
  138. res.setWrapped(null, right);
  139. }
  140. }
  141. res.setRange(expr.range);
  142. return res;
  143. } else if(expr.operator === "-") {
  144. left = this.evaluateExpression(expr.left);
  145. right = this.evaluateExpression(expr.right);
  146. if(!left || !right) return;
  147. if(!left.isNumber() || !right.isNumber()) return;
  148. res = new BasicEvaluatedExpression();
  149. res.setNumber(left.number - right.number);
  150. res.setRange(expr.range);
  151. return res;
  152. } else if(expr.operator === "*") {
  153. left = this.evaluateExpression(expr.left);
  154. right = this.evaluateExpression(expr.right);
  155. if(!left || !right) return;
  156. if(!left.isNumber() || !right.isNumber()) return;
  157. res = new BasicEvaluatedExpression();
  158. res.setNumber(left.number * right.number);
  159. res.setRange(expr.range);
  160. return res;
  161. } else if(expr.operator === "/") {
  162. left = this.evaluateExpression(expr.left);
  163. right = this.evaluateExpression(expr.right);
  164. if(!left || !right) return;
  165. if(!left.isNumber() || !right.isNumber()) return;
  166. res = new BasicEvaluatedExpression();
  167. res.setNumber(left.number / right.number);
  168. res.setRange(expr.range);
  169. return res;
  170. } else if(expr.operator === "**") {
  171. left = this.evaluateExpression(expr.left);
  172. right = this.evaluateExpression(expr.right);
  173. if(!left || !right) return;
  174. if(!left.isNumber() || !right.isNumber()) return;
  175. res = new BasicEvaluatedExpression();
  176. res.setNumber(Math.pow(left.number, right.number));
  177. res.setRange(expr.range);
  178. return res;
  179. } else if(expr.operator === "==" || expr.operator === "===") {
  180. left = this.evaluateExpression(expr.left);
  181. right = this.evaluateExpression(expr.right);
  182. if(!left || !right) return;
  183. res = new BasicEvaluatedExpression();
  184. res.setRange(expr.range);
  185. if(left.isString() && right.isString()) {
  186. return res.setBoolean(left.string === right.string);
  187. } else if(left.isNumber() && right.isNumber()) {
  188. return res.setBoolean(left.number === right.number);
  189. } else if(left.isBoolean() && right.isBoolean()) {
  190. return res.setBoolean(left.bool === right.bool);
  191. }
  192. } else if(expr.operator === "!=" || expr.operator === "!==") {
  193. left = this.evaluateExpression(expr.left);
  194. right = this.evaluateExpression(expr.right);
  195. if(!left || !right) return;
  196. res = new BasicEvaluatedExpression();
  197. res.setRange(expr.range);
  198. if(left.isString() && right.isString()) {
  199. return res.setBoolean(left.string !== right.string);
  200. } else if(left.isNumber() && right.isNumber()) {
  201. return res.setBoolean(left.number !== right.number);
  202. } else if(left.isBoolean() && right.isBoolean()) {
  203. return res.setBoolean(left.bool !== right.bool);
  204. }
  205. } else if(expr.operator === "&") {
  206. left = this.evaluateExpression(expr.left);
  207. right = this.evaluateExpression(expr.right);
  208. if(!left || !right) return;
  209. if(!left.isNumber() || !right.isNumber()) return;
  210. res = new BasicEvaluatedExpression();
  211. res.setNumber(left.number & right.number);
  212. res.setRange(expr.range);
  213. return res;
  214. } else if(expr.operator === "|") {
  215. left = this.evaluateExpression(expr.left);
  216. right = this.evaluateExpression(expr.right);
  217. if(!left || !right) return;
  218. if(!left.isNumber() || !right.isNumber()) return;
  219. res = new BasicEvaluatedExpression();
  220. res.setNumber(left.number | right.number);
  221. res.setRange(expr.range);
  222. return res;
  223. } else if(expr.operator === "^") {
  224. left = this.evaluateExpression(expr.left);
  225. right = this.evaluateExpression(expr.right);
  226. if(!left || !right) return;
  227. if(!left.isNumber() || !right.isNumber()) return;
  228. res = new BasicEvaluatedExpression();
  229. res.setNumber(left.number ^ right.number);
  230. res.setRange(expr.range);
  231. return res;
  232. } else if(expr.operator === ">>>") {
  233. left = this.evaluateExpression(expr.left);
  234. right = this.evaluateExpression(expr.right);
  235. if(!left || !right) return;
  236. if(!left.isNumber() || !right.isNumber()) return;
  237. res = new BasicEvaluatedExpression();
  238. res.setNumber(left.number >>> right.number);
  239. res.setRange(expr.range);
  240. return res;
  241. } else if(expr.operator === ">>") {
  242. left = this.evaluateExpression(expr.left);
  243. right = this.evaluateExpression(expr.right);
  244. if(!left || !right) return;
  245. if(!left.isNumber() || !right.isNumber()) return;
  246. res = new BasicEvaluatedExpression();
  247. res.setNumber(left.number >> right.number);
  248. res.setRange(expr.range);
  249. return res;
  250. } else if(expr.operator === "<<") {
  251. left = this.evaluateExpression(expr.left);
  252. right = this.evaluateExpression(expr.right);
  253. if(!left || !right) return;
  254. if(!left.isNumber() || !right.isNumber()) return;
  255. res = new BasicEvaluatedExpression();
  256. res.setNumber(left.number << right.number);
  257. res.setRange(expr.range);
  258. return res;
  259. }
  260. });
  261. this.plugin("evaluate UnaryExpression", function(expr) {
  262. if(expr.operator === "typeof") {
  263. let res;
  264. let name;
  265. if(expr.argument.type === "Identifier") {
  266. name = this.scope.renames["$" + expr.argument.name] || expr.argument.name;
  267. if(this.scope.definitions.indexOf(name) === -1) {
  268. res = this.applyPluginsBailResult1("evaluate typeof " + name, expr);
  269. if(res !== undefined) return res;
  270. }
  271. }
  272. if(expr.argument.type === "MemberExpression") {
  273. const exprName = this.getNameForExpression(expr.argument);
  274. if(exprName && exprName.free) {
  275. res = this.applyPluginsBailResult1("evaluate typeof " + exprName.name, expr);
  276. if(res !== undefined) return res;
  277. }
  278. }
  279. if(expr.argument.type === "FunctionExpression") {
  280. return new BasicEvaluatedExpression().setString("function").setRange(expr.range);
  281. }
  282. const arg = this.evaluateExpression(expr.argument);
  283. if(arg.isString() || arg.isWrapped()) return new BasicEvaluatedExpression().setString("string").setRange(expr.range);
  284. else if(arg.isNumber()) return new BasicEvaluatedExpression().setString("number").setRange(expr.range);
  285. else if(arg.isBoolean()) return new BasicEvaluatedExpression().setString("boolean").setRange(expr.range);
  286. else if(arg.isArray() || arg.isConstArray() || arg.isRegExp()) return new BasicEvaluatedExpression().setString("object").setRange(expr.range);
  287. } else if(expr.operator === "!") {
  288. const argument = this.evaluateExpression(expr.argument);
  289. if(!argument) return;
  290. if(argument.isBoolean()) {
  291. return new BasicEvaluatedExpression().setBoolean(!argument.bool).setRange(expr.range);
  292. } else if(argument.isTruthy()) {
  293. return new BasicEvaluatedExpression().setBoolean(false).setRange(expr.range);
  294. } else if(argument.isFalsy()) {
  295. return new BasicEvaluatedExpression().setBoolean(true).setRange(expr.range);
  296. } else if(argument.isString()) {
  297. return new BasicEvaluatedExpression().setBoolean(!argument.string).setRange(expr.range);
  298. } else if(argument.isNumber()) {
  299. return new BasicEvaluatedExpression().setBoolean(!argument.number).setRange(expr.range);
  300. }
  301. } else if(expr.operator === "~") {
  302. const argument = this.evaluateExpression(expr.argument);
  303. if(!argument) return;
  304. if(!argument.isNumber()) return;
  305. const res = new BasicEvaluatedExpression();
  306. res.setNumber(~argument.number);
  307. res.setRange(expr.range);
  308. return res;
  309. }
  310. });
  311. this.plugin("evaluate typeof undefined", function(expr) {
  312. return new BasicEvaluatedExpression().setString("undefined").setRange(expr.range);
  313. });
  314. this.plugin("evaluate Identifier", function(expr) {
  315. const name = this.scope.renames["$" + expr.name] || expr.name;
  316. if(this.scope.definitions.indexOf(expr.name) === -1) {
  317. const result = this.applyPluginsBailResult1("evaluate Identifier " + name, expr);
  318. if(result) return result;
  319. return new BasicEvaluatedExpression().setIdentifier(name).setRange(expr.range);
  320. } else {
  321. return this.applyPluginsBailResult1("evaluate defined Identifier " + name, expr);
  322. }
  323. });
  324. this.plugin("evaluate ThisExpression", function(expr) {
  325. const name = this.scope.renames.$this;
  326. if(name) {
  327. const result = this.applyPluginsBailResult1("evaluate Identifier " + name, expr);
  328. if(result) return result;
  329. return new BasicEvaluatedExpression().setIdentifier(name).setRange(expr.range);
  330. }
  331. });
  332. this.plugin("evaluate MemberExpression", function(expression) {
  333. let exprName = this.getNameForExpression(expression);
  334. if(exprName) {
  335. if(exprName.free) {
  336. const result = this.applyPluginsBailResult1("evaluate Identifier " + exprName.name, expression);
  337. if(result) return result;
  338. return new BasicEvaluatedExpression().setIdentifier(exprName.name).setRange(expression.range);
  339. } else {
  340. return this.applyPluginsBailResult1("evaluate defined Identifier " + exprName.name, expression);
  341. }
  342. }
  343. });
  344. this.plugin("evaluate CallExpression", function(expr) {
  345. if(expr.callee.type !== "MemberExpression") return;
  346. if(expr.callee.property.type !== (expr.callee.computed ? "Literal" : "Identifier")) return;
  347. const param = this.evaluateExpression(expr.callee.object);
  348. if(!param) return;
  349. const property = expr.callee.property.name || expr.callee.property.value;
  350. return this.applyPluginsBailResult("evaluate CallExpression ." + property, expr, param);
  351. });
  352. this.plugin("evaluate CallExpression .replace", function(expr, param) {
  353. if(!param.isString()) return;
  354. if(expr.arguments.length !== 2) return;
  355. let arg1 = this.evaluateExpression(expr.arguments[0]);
  356. let arg2 = this.evaluateExpression(expr.arguments[1]);
  357. if(!arg1.isString() && !arg1.isRegExp()) return;
  358. arg1 = arg1.regExp || arg1.string;
  359. if(!arg2.isString()) return;
  360. arg2 = arg2.string;
  361. return new BasicEvaluatedExpression().setString(param.string.replace(arg1, arg2)).setRange(expr.range);
  362. });
  363. ["substr", "substring"].forEach(fn => {
  364. this.plugin("evaluate CallExpression ." + fn, function(expr, param) {
  365. if(!param.isString()) return;
  366. let arg1;
  367. let result, str = param.string;
  368. switch(expr.arguments.length) {
  369. case 1:
  370. arg1 = this.evaluateExpression(expr.arguments[0]);
  371. if(!arg1.isNumber()) return;
  372. result = str[fn](arg1.number);
  373. break;
  374. case 2:
  375. {
  376. arg1 = this.evaluateExpression(expr.arguments[0]);
  377. const arg2 = this.evaluateExpression(expr.arguments[1]);
  378. if(!arg1.isNumber()) return;
  379. if(!arg2.isNumber()) return;
  380. result = str[fn](arg1.number, arg2.number);
  381. break;
  382. }
  383. default:
  384. return;
  385. }
  386. return new BasicEvaluatedExpression().setString(result).setRange(expr.range);
  387. });
  388. });
  389. /**
  390. * @param {string} kind "cooked" | "raw"
  391. * @param {any[]} quasis quasis
  392. * @param {any[]} expressions expressions
  393. * @return {BasicEvaluatedExpression[]} Simplified template
  394. */
  395. function getSimplifiedTemplateResult(kind, quasis, expressions) {
  396. const parts = [];
  397. for(let i = 0; i < quasis.length; i++) {
  398. parts.push(new BasicEvaluatedExpression().setString(quasis[i].value[kind]).setRange(quasis[i].range));
  399. if(i > 0) {
  400. const prevExpr = parts[parts.length - 2],
  401. lastExpr = parts[parts.length - 1];
  402. const expr = this.evaluateExpression(expressions[i - 1]);
  403. if(!(expr.isString() || expr.isNumber())) continue;
  404. prevExpr.setString(prevExpr.string + (expr.isString() ? expr.string : expr.number) + lastExpr.string);
  405. prevExpr.setRange([prevExpr.range[0], lastExpr.range[1]]);
  406. parts.pop();
  407. }
  408. }
  409. return parts;
  410. }
  411. this.plugin("evaluate TemplateLiteral", function(node) {
  412. const parts = getSimplifiedTemplateResult.call(this, "cooked", node.quasis, node.expressions);
  413. if(parts.length === 1) {
  414. return parts[0].setRange(node.range);
  415. }
  416. return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range);
  417. });
  418. this.plugin("evaluate TaggedTemplateExpression", function(node) {
  419. if(this.evaluateExpression(node.tag).identifier !== "String.raw") return;
  420. const parts = getSimplifiedTemplateResult.call(this, "raw", node.quasi.quasis, node.quasi.expressions);
  421. return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range);
  422. });
  423. this.plugin("evaluate CallExpression .concat", function(expr, param) {
  424. if(!param.isString() && !param.isWrapped()) return;
  425. let stringSuffix = null;
  426. let hasUnknownParams = false;
  427. for(let i = expr.arguments.length - 1; i >= 0; i--) {
  428. const argExpr = this.evaluateExpression(expr.arguments[i]);
  429. if(!argExpr.isString() && !argExpr.isNumber()) {
  430. hasUnknownParams = true;
  431. break;
  432. }
  433. const value = argExpr.isString() ? argExpr.string : "" + argExpr.number;
  434. const newString = value + (stringSuffix ? stringSuffix.string : "");
  435. const newRange = [argExpr.range[0], (stringSuffix || argExpr).range[1]];
  436. stringSuffix = new BasicEvaluatedExpression().setString(newString).setRange(newRange);
  437. }
  438. if(hasUnknownParams) {
  439. const prefix = param.isString() ? param : param.prefix;
  440. return new BasicEvaluatedExpression().setWrapped(prefix, stringSuffix).setRange(expr.range);
  441. } else if(param.isWrapped()) {
  442. const postfix = stringSuffix || param.postfix;
  443. return new BasicEvaluatedExpression().setWrapped(param.prefix, postfix).setRange(expr.range);
  444. } else {
  445. const newString = param.string + (stringSuffix ? stringSuffix.string : "");
  446. return new BasicEvaluatedExpression().setString(newString).setRange(expr.range);
  447. }
  448. });
  449. this.plugin("evaluate CallExpression .split", function(expr, param) {
  450. if(!param.isString()) return;
  451. if(expr.arguments.length !== 1) return;
  452. let result;
  453. const arg = this.evaluateExpression(expr.arguments[0]);
  454. if(arg.isString()) {
  455. result = param.string.split(arg.string);
  456. } else if(arg.isRegExp()) {
  457. result = param.string.split(arg.regExp);
  458. } else return;
  459. return new BasicEvaluatedExpression().setArray(result).setRange(expr.range);
  460. });
  461. this.plugin("evaluate ConditionalExpression", function(expr) {
  462. const condition = this.evaluateExpression(expr.test);
  463. const conditionValue = condition.asBool();
  464. let res;
  465. if(conditionValue === undefined) {
  466. const consequent = this.evaluateExpression(expr.consequent);
  467. const alternate = this.evaluateExpression(expr.alternate);
  468. if(!consequent || !alternate) return;
  469. res = new BasicEvaluatedExpression();
  470. if(consequent.isConditional())
  471. res.setOptions(consequent.options);
  472. else
  473. res.setOptions([consequent]);
  474. if(alternate.isConditional())
  475. res.addOptions(alternate.options);
  476. else
  477. res.addOptions([alternate]);
  478. } else {
  479. res = this.evaluateExpression(conditionValue ? expr.consequent : expr.alternate);
  480. }
  481. res.setRange(expr.range);
  482. return res;
  483. });
  484. this.plugin("evaluate ArrayExpression", function(expr) {
  485. const items = expr.elements.map(function(element) {
  486. return element !== null && this.evaluateExpression(element);
  487. }, this);
  488. if(!items.every(Boolean)) return;
  489. return new BasicEvaluatedExpression().setItems(items).setRange(expr.range);
  490. });
  491. }
  492. getRenameIdentifier(expr) {
  493. const result = this.evaluateExpression(expr);
  494. if(!result) return;
  495. if(result.isIdentifier()) return result.identifier;
  496. return;
  497. }
  498. walkClass(classy) {
  499. if(classy.superClass)
  500. this.walkExpression(classy.superClass);
  501. if(classy.body && classy.body.type === "ClassBody") {
  502. classy.body.body.forEach(methodDefinition => {
  503. if(methodDefinition.type === "MethodDefinition")
  504. this.walkMethodDefinition(methodDefinition);
  505. });
  506. }
  507. }
  508. walkMethodDefinition(methodDefinition) {
  509. if(methodDefinition.computed && methodDefinition.key)
  510. this.walkExpression(methodDefinition.key);
  511. if(methodDefinition.value)
  512. this.walkExpression(methodDefinition.value);
  513. }
  514. // Prewalking iterates the scope for variable declarations
  515. prewalkStatements(statements) {
  516. for(let index = 0, len = statements.length; index < len; index++) {
  517. const statement = statements[index];
  518. this.prewalkStatement(statement);
  519. }
  520. }
  521. // Walking iterates the statements and expressions and processes them
  522. walkStatements(statements) {
  523. for(let index = 0, len = statements.length; index < len; index++) {
  524. const statement = statements[index];
  525. this.walkStatement(statement);
  526. }
  527. }
  528. prewalkStatement(statement) {
  529. const handler = this["prewalk" + statement.type];
  530. if(handler)
  531. handler.call(this, statement);
  532. }
  533. walkStatement(statement) {
  534. if(this.applyPluginsBailResult1("statement", statement) !== undefined) return;
  535. const handler = this["walk" + statement.type];
  536. if(handler)
  537. handler.call(this, statement);
  538. }
  539. // Real Statements
  540. prewalkBlockStatement(statement) {
  541. this.prewalkStatements(statement.body);
  542. }
  543. walkBlockStatement(statement) {
  544. this.walkStatements(statement.body);
  545. }
  546. walkExpressionStatement(statement) {
  547. this.walkExpression(statement.expression);
  548. }
  549. prewalkIfStatement(statement) {
  550. this.prewalkStatement(statement.consequent);
  551. if(statement.alternate)
  552. this.prewalkStatement(statement.alternate);
  553. }
  554. walkIfStatement(statement) {
  555. const result = this.applyPluginsBailResult1("statement if", statement);
  556. if(result === undefined) {
  557. this.walkExpression(statement.test);
  558. this.walkStatement(statement.consequent);
  559. if(statement.alternate)
  560. this.walkStatement(statement.alternate);
  561. } else {
  562. if(result)
  563. this.walkStatement(statement.consequent);
  564. else if(statement.alternate)
  565. this.walkStatement(statement.alternate);
  566. }
  567. }
  568. prewalkLabeledStatement(statement) {
  569. this.prewalkStatement(statement.body);
  570. }
  571. walkLabeledStatement(statement) {
  572. const result = this.applyPluginsBailResult1("label " + statement.label.name, statement);
  573. if(result !== true)
  574. this.walkStatement(statement.body);
  575. }
  576. prewalkWithStatement(statement) {
  577. this.prewalkStatement(statement.body);
  578. }
  579. walkWithStatement(statement) {
  580. this.walkExpression(statement.object);
  581. this.walkStatement(statement.body);
  582. }
  583. prewalkSwitchStatement(statement) {
  584. this.prewalkSwitchCases(statement.cases);
  585. }
  586. walkSwitchStatement(statement) {
  587. this.walkExpression(statement.discriminant);
  588. this.walkSwitchCases(statement.cases);
  589. }
  590. walkTerminatingStatement(statement) {
  591. if(statement.argument)
  592. this.walkExpression(statement.argument);
  593. }
  594. walkReturnStatement(statement) {
  595. this.walkTerminatingStatement(statement);
  596. }
  597. walkThrowStatement(statement) {
  598. this.walkTerminatingStatement(statement);
  599. }
  600. prewalkTryStatement(statement) {
  601. this.prewalkStatement(statement.block);
  602. }
  603. walkTryStatement(statement) {
  604. if(this.scope.inTry) {
  605. this.walkStatement(statement.block);
  606. } else {
  607. this.scope.inTry = true;
  608. this.walkStatement(statement.block);
  609. this.scope.inTry = false;
  610. }
  611. if(statement.handler)
  612. this.walkCatchClause(statement.handler);
  613. if(statement.finalizer)
  614. this.walkStatement(statement.finalizer);
  615. }
  616. prewalkWhileStatement(statement) {
  617. this.prewalkStatement(statement.body);
  618. }
  619. walkWhileStatement(statement) {
  620. this.walkExpression(statement.test);
  621. this.walkStatement(statement.body);
  622. }
  623. prewalkDoWhileStatement(statement) {
  624. this.prewalkStatement(statement.body);
  625. }
  626. walkDoWhileStatement(statement) {
  627. this.walkStatement(statement.body);
  628. this.walkExpression(statement.test);
  629. }
  630. prewalkForStatement(statement) {
  631. if(statement.init) {
  632. if(statement.init.type === "VariableDeclaration")
  633. this.prewalkStatement(statement.init);
  634. }
  635. this.prewalkStatement(statement.body);
  636. }
  637. walkForStatement(statement) {
  638. if(statement.init) {
  639. if(statement.init.type === "VariableDeclaration")
  640. this.walkStatement(statement.init);
  641. else
  642. this.walkExpression(statement.init);
  643. }
  644. if(statement.test)
  645. this.walkExpression(statement.test);
  646. if(statement.update)
  647. this.walkExpression(statement.update);
  648. this.walkStatement(statement.body);
  649. }
  650. prewalkForInStatement(statement) {
  651. if(statement.left.type === "VariableDeclaration")
  652. this.prewalkStatement(statement.left);
  653. this.prewalkStatement(statement.body);
  654. }
  655. walkForInStatement(statement) {
  656. if(statement.left.type === "VariableDeclaration")
  657. this.walkStatement(statement.left);
  658. else
  659. this.walkExpression(statement.left);
  660. this.walkExpression(statement.right);
  661. this.walkStatement(statement.body);
  662. }
  663. prewalkForOfStatement(statement) {
  664. if(statement.left.type === "VariableDeclaration")
  665. this.prewalkStatement(statement.left);
  666. this.prewalkStatement(statement.body);
  667. }
  668. walkForOfStatement(statement) {
  669. if(statement.left.type === "VariableDeclaration")
  670. this.walkStatement(statement.left);
  671. else
  672. this.walkExpression(statement.left);
  673. this.walkExpression(statement.right);
  674. this.walkStatement(statement.body);
  675. }
  676. // Declarations
  677. prewalkFunctionDeclaration(statement) {
  678. if(statement.id) {
  679. this.scope.renames["$" + statement.id.name] = undefined;
  680. this.scope.definitions.push(statement.id.name);
  681. }
  682. }
  683. walkFunctionDeclaration(statement) {
  684. statement.params.forEach(param => {
  685. this.walkPattern(param);
  686. });
  687. this.inScope(statement.params, () => {
  688. if(statement.body.type === "BlockStatement") {
  689. this.prewalkStatement(statement.body);
  690. this.walkStatement(statement.body);
  691. } else {
  692. this.walkExpression(statement.body);
  693. }
  694. });
  695. }
  696. prewalkImportDeclaration(statement) {
  697. const source = statement.source.value;
  698. this.applyPluginsBailResult("import", statement, source);
  699. statement.specifiers.forEach(function(specifier) {
  700. const name = specifier.local.name;
  701. this.scope.renames["$" + name] = undefined;
  702. this.scope.definitions.push(name);
  703. switch(specifier.type) {
  704. case "ImportDefaultSpecifier":
  705. this.applyPluginsBailResult("import specifier", statement, source, "default", name);
  706. break;
  707. case "ImportSpecifier":
  708. this.applyPluginsBailResult("import specifier", statement, source, specifier.imported.name, name);
  709. break;
  710. case "ImportNamespaceSpecifier":
  711. this.applyPluginsBailResult("import specifier", statement, source, null, name);
  712. break;
  713. }
  714. }, this);
  715. }
  716. prewalkExportNamedDeclaration(statement) {
  717. let source;
  718. if(statement.source) {
  719. source = statement.source.value;
  720. this.applyPluginsBailResult("export import", statement, source);
  721. } else {
  722. this.applyPluginsBailResult1("export", statement);
  723. }
  724. if(statement.declaration) {
  725. if(/Expression$/.test(statement.declaration.type)) {
  726. throw new Error("Doesn't occur?");
  727. } else {
  728. if(!this.applyPluginsBailResult("export declaration", statement, statement.declaration)) {
  729. const pos = this.scope.definitions.length;
  730. this.prewalkStatement(statement.declaration);
  731. const newDefs = this.scope.definitions.slice(pos);
  732. for(let index = newDefs.length - 1; index >= 0; index--) {
  733. const def = newDefs[index];
  734. this.applyPluginsBailResult("export specifier", statement, def, def, index);
  735. }
  736. }
  737. }
  738. }
  739. if(statement.specifiers) {
  740. for(let specifierIndex = 0; specifierIndex < statement.specifiers.length; specifierIndex++) {
  741. const specifier = statement.specifiers[specifierIndex];
  742. switch(specifier.type) {
  743. case "ExportSpecifier":
  744. {
  745. const name = specifier.exported.name;
  746. if(source)
  747. this.applyPluginsBailResult("export import specifier", statement, source, specifier.local.name, name, specifierIndex);
  748. else
  749. this.applyPluginsBailResult("export specifier", statement, specifier.local.name, name, specifierIndex);
  750. break;
  751. }
  752. }
  753. }
  754. }
  755. }
  756. walkExportNamedDeclaration(statement) {
  757. if(statement.declaration) {
  758. this.walkStatement(statement.declaration);
  759. }
  760. }
  761. prewalkExportDefaultDeclaration(statement) {
  762. if(/Declaration$/.test(statement.declaration.type)) {
  763. const pos = this.scope.definitions.length;
  764. this.prewalkStatement(statement.declaration);
  765. const newDefs = this.scope.definitions.slice(pos);
  766. for(let index = 0, len = newDefs.length; index < len; index++) {
  767. const def = newDefs[index];
  768. this.applyPluginsBailResult("export specifier", statement, def, "default");
  769. }
  770. }
  771. }
  772. walkExportDefaultDeclaration(statement) {
  773. this.applyPluginsBailResult1("export", statement);
  774. if(/Declaration$/.test(statement.declaration.type)) {
  775. if(!this.applyPluginsBailResult("export declaration", statement, statement.declaration)) {
  776. this.walkStatement(statement.declaration);
  777. }
  778. } else {
  779. this.walkExpression(statement.declaration);
  780. if(!this.applyPluginsBailResult("export expression", statement, statement.declaration)) {
  781. this.applyPluginsBailResult("export specifier", statement, statement.declaration, "default");
  782. }
  783. }
  784. }
  785. prewalkExportAllDeclaration(statement) {
  786. const source = statement.source.value;
  787. this.applyPluginsBailResult("export import", statement, source);
  788. this.applyPluginsBailResult("export import specifier", statement, source, null, null, 0);
  789. }
  790. prewalkVariableDeclaration(statement) {
  791. if(statement.declarations)
  792. this.prewalkVariableDeclarators(statement.declarations);
  793. }
  794. walkVariableDeclaration(statement) {
  795. if(statement.declarations)
  796. this.walkVariableDeclarators(statement.declarations);
  797. }
  798. prewalkClassDeclaration(statement) {
  799. if(statement.id) {
  800. this.scope.renames["$" + statement.id.name] = undefined;
  801. this.scope.definitions.push(statement.id.name);
  802. }
  803. }
  804. walkClassDeclaration(statement) {
  805. this.walkClass(statement);
  806. }
  807. prewalkSwitchCases(switchCases) {
  808. for(let index = 0, len = switchCases.length; index < len; index++) {
  809. const switchCase = switchCases[index];
  810. this.prewalkStatements(switchCase.consequent);
  811. }
  812. }
  813. walkSwitchCases(switchCases) {
  814. for(let index = 0, len = switchCases.length; index < len; index++) {
  815. const switchCase = switchCases[index];
  816. if(switchCase.test) {
  817. this.walkExpression(switchCase.test);
  818. }
  819. this.walkStatements(switchCase.consequent);
  820. }
  821. }
  822. walkCatchClause(catchClause) {
  823. this.inScope([catchClause.param], () => {
  824. this.prewalkStatement(catchClause.body);
  825. this.walkStatement(catchClause.body);
  826. });
  827. }
  828. prewalkVariableDeclarators(declarators) {
  829. declarators.forEach(declarator => {
  830. switch(declarator.type) {
  831. case "VariableDeclarator":
  832. {
  833. this.enterPattern(declarator.id, (name, decl) => {
  834. if(!this.applyPluginsBailResult1("var-" + declarator.kind + " " + name, decl)) {
  835. if(!this.applyPluginsBailResult1("var " + name, decl)) {
  836. this.scope.renames["$" + name] = undefined;
  837. if(this.scope.definitions.indexOf(name) < 0)
  838. this.scope.definitions.push(name);
  839. }
  840. }
  841. });
  842. break;
  843. }
  844. }
  845. });
  846. }
  847. walkVariableDeclarators(declarators) {
  848. declarators.forEach(declarator => {
  849. switch(declarator.type) {
  850. case "VariableDeclarator":
  851. {
  852. const renameIdentifier = declarator.init && this.getRenameIdentifier(declarator.init);
  853. if(renameIdentifier && declarator.id.type === "Identifier" && this.applyPluginsBailResult1("can-rename " + renameIdentifier, declarator.init)) {
  854. // renaming with "var a = b;"
  855. if(!this.applyPluginsBailResult1("rename " + renameIdentifier, declarator.init)) {
  856. this.scope.renames["$" + declarator.id.name] = this.scope.renames["$" + renameIdentifier] || renameIdentifier;
  857. const idx = this.scope.definitions.indexOf(declarator.id.name);
  858. if(idx >= 0) this.scope.definitions.splice(idx, 1);
  859. }
  860. } else {
  861. this.walkPattern(declarator.id);
  862. if(declarator.init)
  863. this.walkExpression(declarator.init);
  864. }
  865. break;
  866. }
  867. }
  868. });
  869. }
  870. walkPattern(pattern) {
  871. if(pattern.type === "Identifier")
  872. return;
  873. if(this["walk" + pattern.type])
  874. this["walk" + pattern.type](pattern);
  875. }
  876. walkAssignmentPattern(pattern) {
  877. this.walkExpression(pattern.right);
  878. this.walkPattern(pattern.left);
  879. }
  880. walkObjectPattern(pattern) {
  881. for(let i = 0, len = pattern.properties.length; i < len; i++) {
  882. const prop = pattern.properties[i];
  883. if(prop) {
  884. if(prop.computed)
  885. this.walkExpression(prop.key);
  886. if(prop.value)
  887. this.walkPattern(prop.value);
  888. }
  889. }
  890. }
  891. walkArrayPattern(pattern) {
  892. for(let i = 0, len = pattern.elements.length; i < len; i++) {
  893. const element = pattern.elements[i];
  894. if(element)
  895. this.walkPattern(element);
  896. }
  897. }
  898. walkRestElement(pattern) {
  899. this.walkPattern(pattern.argument);
  900. }
  901. walkExpressions(expressions) {
  902. for(let expressionsIndex = 0, len = expressions.length; expressionsIndex < len; expressionsIndex++) {
  903. const expression = expressions[expressionsIndex];
  904. if(expression)
  905. this.walkExpression(expression);
  906. }
  907. }
  908. walkExpression(expression) {
  909. if(this["walk" + expression.type])
  910. return this["walk" + expression.type](expression);
  911. }
  912. walkAwaitExpression(expression) {
  913. const argument = expression.argument;
  914. if(this["walk" + argument.type])
  915. return this["walk" + argument.type](argument);
  916. }
  917. walkArrayExpression(expression) {
  918. if(expression.elements)
  919. this.walkExpressions(expression.elements);
  920. }
  921. walkSpreadElement(expression) {
  922. if(expression.argument)
  923. this.walkExpression(expression.argument);
  924. }
  925. walkObjectExpression(expression) {
  926. for(let propIndex = 0, len = expression.properties.length; propIndex < len; propIndex++) {
  927. const prop = expression.properties[propIndex];
  928. if(prop.computed)
  929. this.walkExpression(prop.key);
  930. if(prop.shorthand)
  931. this.scope.inShorthand = true;
  932. this.walkExpression(prop.value);
  933. if(prop.shorthand)
  934. this.scope.inShorthand = false;
  935. }
  936. }
  937. walkFunctionExpression(expression) {
  938. expression.params.forEach(param => {
  939. this.walkPattern(param);
  940. });
  941. this.inScope(expression.params, () => {
  942. if(expression.body.type === "BlockStatement") {
  943. this.prewalkStatement(expression.body);
  944. this.walkStatement(expression.body);
  945. } else {
  946. this.walkExpression(expression.body);
  947. }
  948. });
  949. }
  950. walkArrowFunctionExpression(expression) {
  951. expression.params.forEach(param => {
  952. this.walkPattern(param);
  953. });
  954. this.inScope(expression.params, () => {
  955. if(expression.body.type === "BlockStatement") {
  956. this.prewalkStatement(expression.body);
  957. this.walkStatement(expression.body);
  958. } else {
  959. this.walkExpression(expression.body);
  960. }
  961. });
  962. }
  963. walkSequenceExpression(expression) {
  964. if(expression.expressions)
  965. this.walkExpressions(expression.expressions);
  966. }
  967. walkUpdateExpression(expression) {
  968. this.walkExpression(expression.argument);
  969. }
  970. walkUnaryExpression(expression) {
  971. if(expression.operator === "typeof") {
  972. const exprName = this.getNameForExpression(expression.argument);
  973. if(exprName && exprName.free) {
  974. const result = this.applyPluginsBailResult1("typeof " + exprName.name, expression);
  975. if(result === true)
  976. return;
  977. }
  978. }
  979. this.walkExpression(expression.argument);
  980. }
  981. walkLeftRightExpression(expression) {
  982. this.walkExpression(expression.left);
  983. this.walkExpression(expression.right);
  984. }
  985. walkBinaryExpression(expression) {
  986. this.walkLeftRightExpression(expression);
  987. }
  988. walkLogicalExpression(expression) {
  989. this.walkLeftRightExpression(expression);
  990. }
  991. walkAssignmentExpression(expression) {
  992. const renameIdentifier = this.getRenameIdentifier(expression.right);
  993. if(expression.left.type === "Identifier" && renameIdentifier && this.applyPluginsBailResult1("can-rename " + renameIdentifier, expression.right)) {
  994. // renaming "a = b;"
  995. if(!this.applyPluginsBailResult1("rename " + renameIdentifier, expression.right)) {
  996. this.scope.renames["$" + expression.left.name] = renameIdentifier;
  997. const idx = this.scope.definitions.indexOf(expression.left.name);
  998. if(idx >= 0) this.scope.definitions.splice(idx, 1);
  999. }
  1000. } else if(expression.left.type === "Identifier") {
  1001. if(!this.applyPluginsBailResult1("assigned " + expression.left.name, expression)) {
  1002. this.walkExpression(expression.right);
  1003. }
  1004. this.scope.renames["$" + expression.left.name] = undefined;
  1005. if(!this.applyPluginsBailResult1("assign " + expression.left.name, expression)) {
  1006. this.walkExpression(expression.left);
  1007. }
  1008. } else {
  1009. this.walkExpression(expression.right);
  1010. this.walkPattern(expression.left);
  1011. this.enterPattern(expression.left, (name, decl) => {
  1012. this.scope.renames["$" + name] = undefined;
  1013. });
  1014. }
  1015. }
  1016. walkConditionalExpression(expression) {
  1017. const result = this.applyPluginsBailResult1("expression ?:", expression);
  1018. if(result === undefined) {
  1019. this.walkExpression(expression.test);
  1020. this.walkExpression(expression.consequent);
  1021. if(expression.alternate)
  1022. this.walkExpression(expression.alternate);
  1023. } else {
  1024. if(result)
  1025. this.walkExpression(expression.consequent);
  1026. else if(expression.alternate)
  1027. this.walkExpression(expression.alternate);
  1028. }
  1029. }
  1030. walkNewExpression(expression) {
  1031. const callee = this.evaluateExpression(expression.callee);
  1032. if(callee.isIdentifier()) {
  1033. const result = this.applyPluginsBailResult("new " + callee.identifier, expression);
  1034. if(result === true) {
  1035. return;
  1036. }
  1037. }
  1038. this.walkExpression(expression.callee);
  1039. if(expression.arguments)
  1040. this.walkExpressions(expression.arguments);
  1041. }
  1042. walkYieldExpression(expression) {
  1043. if(expression.argument)
  1044. this.walkExpression(expression.argument);
  1045. }
  1046. walkTemplateLiteral(expression) {
  1047. if(expression.expressions)
  1048. this.walkExpressions(expression.expressions);
  1049. }
  1050. walkTaggedTemplateExpression(expression) {
  1051. if(expression.tag)
  1052. this.walkExpression(expression.tag);
  1053. if(expression.quasi && expression.quasi.expressions)
  1054. this.walkExpressions(expression.quasi.expressions);
  1055. }
  1056. walkClassExpression(expression) {
  1057. this.walkClass(expression);
  1058. }
  1059. walkCallExpression(expression) {
  1060. let result;
  1061. function walkIIFE(functionExpression, options, currentThis) {
  1062. function renameArgOrThis(argOrThis) {
  1063. const renameIdentifier = this.getRenameIdentifier(argOrThis);
  1064. if(renameIdentifier && this.applyPluginsBailResult1("can-rename " + renameIdentifier, argOrThis)) {
  1065. if(!this.applyPluginsBailResult1("rename " + renameIdentifier, argOrThis))
  1066. return renameIdentifier;
  1067. }
  1068. this.walkExpression(argOrThis);
  1069. }
  1070. const params = functionExpression.params;
  1071. const renameThis = currentThis ? renameArgOrThis.call(this, currentThis) : null;
  1072. const args = options.map(renameArgOrThis, this);
  1073. this.inScope(params.filter(function(identifier, idx) {
  1074. return !args[idx];
  1075. }), () => {
  1076. if(renameThis) {
  1077. this.scope.renames.$this = renameThis;
  1078. }
  1079. for(let i = 0; i < args.length; i++) {
  1080. const param = args[i];
  1081. if(!param) continue;
  1082. if(!params[i] || params[i].type !== "Identifier") continue;
  1083. this.scope.renames["$" + params[i].name] = param;
  1084. }
  1085. if(functionExpression.body.type === "BlockStatement") {
  1086. this.prewalkStatement(functionExpression.body);
  1087. this.walkStatement(functionExpression.body);
  1088. } else
  1089. this.walkExpression(functionExpression.body);
  1090. });
  1091. }
  1092. if(expression.callee.type === "MemberExpression" &&
  1093. expression.callee.object.type === "FunctionExpression" &&
  1094. !expression.callee.computed &&
  1095. (["call", "bind"]).indexOf(expression.callee.property.name) >= 0 &&
  1096. expression.arguments &&
  1097. expression.arguments.length > 0
  1098. ) {
  1099. // (function(...) { }.call/bind(?, ...))
  1100. walkIIFE.call(this, expression.callee.object, expression.arguments.slice(1), expression.arguments[0]);
  1101. } else if(expression.callee.type === "FunctionExpression" && expression.arguments) {
  1102. // (function(...) { }(...))
  1103. walkIIFE.call(this, expression.callee, expression.arguments);
  1104. } else if(expression.callee.type === "Import") {
  1105. result = this.applyPluginsBailResult1("import-call", expression);
  1106. if(result === true)
  1107. return;
  1108. if(expression.arguments)
  1109. this.walkExpressions(expression.arguments);
  1110. } else {
  1111. const callee = this.evaluateExpression(expression.callee);
  1112. if(callee.isIdentifier()) {
  1113. result = this.applyPluginsBailResult1("call " + callee.identifier, expression);
  1114. if(result === true)
  1115. return;
  1116. let identifier = callee.identifier.replace(/\.[^.]+$/, ".*");
  1117. if(identifier !== callee.identifier) {
  1118. result = this.applyPluginsBailResult1("call " + identifier, expression);
  1119. if(result === true)
  1120. return;
  1121. }
  1122. }
  1123. if(expression.callee)
  1124. this.walkExpression(expression.callee);
  1125. if(expression.arguments)
  1126. this.walkExpressions(expression.arguments);
  1127. }
  1128. }
  1129. walkMemberExpression(expression) {
  1130. const exprName = this.getNameForExpression(expression);
  1131. if(exprName && exprName.free) {
  1132. let result = this.applyPluginsBailResult1("expression " + exprName.name, expression);
  1133. if(result === true)
  1134. return;
  1135. result = this.applyPluginsBailResult1("expression " + exprName.nameGeneral, expression);
  1136. if(result === true)
  1137. return;
  1138. }
  1139. this.walkExpression(expression.object);
  1140. if(expression.computed === true)
  1141. this.walkExpression(expression.property);
  1142. }
  1143. walkIdentifier(expression) {
  1144. if(this.scope.definitions.indexOf(expression.name) === -1) {
  1145. const result = this.applyPluginsBailResult1("expression " + (this.scope.renames["$" + expression.name] || expression.name), expression);
  1146. if(result === true)
  1147. return;
  1148. }
  1149. }
  1150. inScope(params, fn) {
  1151. const oldScope = this.scope;
  1152. this.scope = {
  1153. inTry: false,
  1154. inShorthand: false,
  1155. definitions: oldScope.definitions.slice(),
  1156. renames: Object.create(oldScope.renames)
  1157. };
  1158. this.scope.renames.$this = undefined;
  1159. for(let paramIndex = 0, len = params.length; paramIndex < len; paramIndex++) {
  1160. const param = params[paramIndex];
  1161. if(typeof param !== "string") {
  1162. this.enterPattern(param, param => {
  1163. this.scope.renames["$" + param] = undefined;
  1164. this.scope.definitions.push(param);
  1165. });
  1166. } else {
  1167. this.scope.renames["$" + param] = undefined;
  1168. this.scope.definitions.push(param);
  1169. }
  1170. }
  1171. fn();
  1172. this.scope = oldScope;
  1173. }
  1174. enterPattern(pattern, onIdent) {
  1175. if(pattern && this["enter" + pattern.type])
  1176. this["enter" + pattern.type](pattern, onIdent);
  1177. }
  1178. enterIdentifier(pattern, onIdent) {
  1179. onIdent(pattern.name, pattern);
  1180. }
  1181. enterObjectPattern(pattern, onIdent) {
  1182. for(let propIndex = 0, len = pattern.properties.length; propIndex < len; propIndex++) {
  1183. const prop = pattern.properties[propIndex];
  1184. this.enterPattern(prop.value, onIdent);
  1185. }
  1186. }
  1187. enterArrayPattern(pattern, onIdent) {
  1188. for(let elementIndex = 0, len = pattern.elements.length; elementIndex < len; elementIndex++) {
  1189. const element = pattern.elements[elementIndex];
  1190. this.enterPattern(element, onIdent);
  1191. }
  1192. }
  1193. enterRestElement(pattern, onIdent) {
  1194. this.enterPattern(pattern.argument, onIdent);
  1195. }
  1196. enterAssignmentPattern(pattern, onIdent) {
  1197. this.enterPattern(pattern.left, onIdent);
  1198. }
  1199. evaluateExpression(expression) {
  1200. try {
  1201. const result = this.applyPluginsBailResult1("evaluate " + expression.type, expression);
  1202. if(result !== undefined)
  1203. return result;
  1204. } catch(e) {
  1205. console.warn(e);
  1206. // ignore error
  1207. }
  1208. return new BasicEvaluatedExpression().setRange(expression.range);
  1209. }
  1210. parseString(expression) {
  1211. switch(expression.type) {
  1212. case "BinaryExpression":
  1213. if(expression.operator === "+")
  1214. return this.parseString(expression.left) + this.parseString(expression.right);
  1215. break;
  1216. case "Literal":
  1217. return expression.value + "";
  1218. }
  1219. throw new Error(expression.type + " is not supported as parameter for require");
  1220. }
  1221. parseCalculatedString(expression) {
  1222. switch(expression.type) {
  1223. case "BinaryExpression":
  1224. if(expression.operator === "+") {
  1225. const left = this.parseCalculatedString(expression.left);
  1226. const right = this.parseCalculatedString(expression.right);
  1227. if(left.code) {
  1228. return {
  1229. range: left.range,
  1230. value: left.value,
  1231. code: true
  1232. };
  1233. } else if(right.code) {
  1234. return {
  1235. range: [left.range[0], right.range ? right.range[1] : left.range[1]],
  1236. value: left.value + right.value,
  1237. code: true
  1238. };
  1239. } else {
  1240. return {
  1241. range: [left.range[0], right.range[1]],
  1242. value: left.value + right.value
  1243. };
  1244. }
  1245. }
  1246. break;
  1247. case "ConditionalExpression":
  1248. {
  1249. const consequent = this.parseCalculatedString(expression.consequent);
  1250. const alternate = this.parseCalculatedString(expression.alternate);
  1251. const items = [];
  1252. if(consequent.conditional)
  1253. Array.prototype.push.apply(items, consequent.conditional);
  1254. else if(!consequent.code)
  1255. items.push(consequent);
  1256. else break;
  1257. if(alternate.conditional)
  1258. Array.prototype.push.apply(items, alternate.conditional);
  1259. else if(!alternate.code)
  1260. items.push(alternate);
  1261. else break;
  1262. return {
  1263. value: "",
  1264. code: true,
  1265. conditional: items
  1266. };
  1267. }
  1268. case "Literal":
  1269. return {
  1270. range: expression.range,
  1271. value: expression.value + ""
  1272. };
  1273. }
  1274. return {
  1275. value: "",
  1276. code: true
  1277. };
  1278. }
  1279. parseStringArray(expression) {
  1280. if(expression.type !== "ArrayExpression") {
  1281. return [this.parseString(expression)];
  1282. }
  1283. const arr = [];
  1284. if(expression.elements)
  1285. expression.elements.forEach(function(expr) {
  1286. arr.push(this.parseString(expr));
  1287. }, this);
  1288. return arr;
  1289. }
  1290. parseCalculatedStringArray(expression) {
  1291. if(expression.type !== "ArrayExpression") {
  1292. return [this.parseCalculatedString(expression)];
  1293. }
  1294. const arr = [];
  1295. if(expression.elements)
  1296. expression.elements.forEach(function(expr) {
  1297. arr.push(this.parseCalculatedString(expr));
  1298. }, this);
  1299. return arr;
  1300. }
  1301. parse(source, initialState) {
  1302. let ast;
  1303. const comments = [];
  1304. for(let i = 0, len = POSSIBLE_AST_OPTIONS.length; i < len; i++) {
  1305. if(!ast) {
  1306. try {
  1307. comments.length = 0;
  1308. POSSIBLE_AST_OPTIONS[i].onComment = comments;
  1309. ast = acorn.parse(source, POSSIBLE_AST_OPTIONS[i]);
  1310. } catch(e) {
  1311. // ignore the error
  1312. }
  1313. }
  1314. }
  1315. if(!ast) {
  1316. // for the error
  1317. ast = acorn.parse(source, {
  1318. ranges: true,
  1319. locations: true,
  1320. ecmaVersion: ECMA_VERSION,
  1321. sourceType: "module",
  1322. plugins: {
  1323. dynamicImport: true
  1324. },
  1325. onComment: comments
  1326. });
  1327. }
  1328. if(!ast || typeof ast !== "object")
  1329. throw new Error("Source couldn't be parsed");
  1330. const oldScope = this.scope;
  1331. const oldState = this.state;
  1332. const oldComments = this.comments;
  1333. this.scope = {
  1334. inTry: false,
  1335. definitions: [],
  1336. renames: {}
  1337. };
  1338. const state = this.state = initialState || {};
  1339. this.comments = comments;
  1340. if(this.applyPluginsBailResult("program", ast, comments) === undefined) {
  1341. this.prewalkStatements(ast.body);
  1342. this.walkStatements(ast.body);
  1343. }
  1344. this.scope = oldScope;
  1345. this.state = oldState;
  1346. this.comments = oldComments;
  1347. return state;
  1348. }
  1349. evaluate(source) {
  1350. const ast = acorn.parse("(" + source + ")", {
  1351. ranges: true,
  1352. locations: true,
  1353. ecmaVersion: ECMA_VERSION,
  1354. sourceType: "module",
  1355. plugins: {
  1356. dynamicImport: true
  1357. }
  1358. });
  1359. if(!ast || typeof ast !== "object" || ast.type !== "Program")
  1360. throw new Error("evaluate: Source couldn't be parsed");
  1361. if(ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement")
  1362. throw new Error("evaluate: Source is not a expression");
  1363. return this.evaluateExpression(ast.body[0].expression);
  1364. }
  1365. getComments(range) {
  1366. return this.comments.filter(comment => comment.range[0] >= range[0] && comment.range[1] <= range[1]);
  1367. }
  1368. getCommentOptions(range) {
  1369. const comments = this.getComments(range);
  1370. if(comments.length === 0) return null;
  1371. const options = comments.map(comment => {
  1372. try {
  1373. return json5.parse(`{${comment.value}}`);
  1374. } catch(e) {
  1375. return {};
  1376. }
  1377. });
  1378. return options.reduce((o, i) => Object.assign(o, i), {});
  1379. }
  1380. getNameForExpression(expression) {
  1381. let expr = expression;
  1382. const exprName = [];
  1383. while(expr.type === "MemberExpression" && expr.property.type === (expr.computed ? "Literal" : "Identifier")) {
  1384. exprName.push(expr.computed ? expr.property.value : expr.property.name);
  1385. expr = expr.object;
  1386. }
  1387. let free;
  1388. if(expr.type === "Identifier") {
  1389. free = this.scope.definitions.indexOf(expr.name) === -1;
  1390. exprName.push(this.scope.renames["$" + expr.name] || expr.name);
  1391. } else if(expr.type === "ThisExpression" && this.scope.renames.$this) {
  1392. free = true;
  1393. exprName.push(this.scope.renames.$this);
  1394. } else if(expr.type === "ThisExpression") {
  1395. free = false;
  1396. exprName.push("this");
  1397. } else {
  1398. return null;
  1399. }
  1400. let prefix = "";
  1401. for(let i = exprName.length - 1; i >= 1; i--)
  1402. prefix += exprName[i] + ".";
  1403. const name = prefix + exprName[0];
  1404. const nameGeneral = prefix + "*";
  1405. return {
  1406. name,
  1407. nameGeneral,
  1408. free
  1409. };
  1410. }
  1411. }
  1412. Parser.ECMA_VERSION = ECMA_VERSION;
  1413. module.exports = Parser;