Parser.js 47KB

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