ConstPlugin.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const CachedConstDependency = require("./dependencies/CachedConstDependency");
  7. const ConstDependency = require("./dependencies/ConstDependency");
  8. const { evaluateToString } = require("./javascript/JavascriptParserHelpers");
  9. const { parseResource } = require("./util/identifier");
  10. /** @typedef {import("estree").Expression} ExpressionNode */
  11. /** @typedef {import("estree").Super} SuperNode */
  12. /** @typedef {import("./Compiler")} Compiler */
  13. const collectDeclaration = (declarations, pattern) => {
  14. const stack = [pattern];
  15. while (stack.length > 0) {
  16. const node = stack.pop();
  17. switch (node.type) {
  18. case "Identifier":
  19. declarations.add(node.name);
  20. break;
  21. case "ArrayPattern":
  22. for (const element of node.elements) {
  23. if (element) {
  24. stack.push(element);
  25. }
  26. }
  27. break;
  28. case "AssignmentPattern":
  29. stack.push(node.left);
  30. break;
  31. case "ObjectPattern":
  32. for (const property of node.properties) {
  33. stack.push(property.value);
  34. }
  35. break;
  36. case "RestElement":
  37. stack.push(node.argument);
  38. break;
  39. }
  40. }
  41. };
  42. const getHoistedDeclarations = (branch, includeFunctionDeclarations) => {
  43. const declarations = new Set();
  44. const stack = [branch];
  45. while (stack.length > 0) {
  46. const node = stack.pop();
  47. // Some node could be `null` or `undefined`.
  48. if (!node) continue;
  49. switch (node.type) {
  50. // Walk through control statements to look for hoisted declarations.
  51. // Some branches are skipped since they do not allow declarations.
  52. case "BlockStatement":
  53. for (const stmt of node.body) {
  54. stack.push(stmt);
  55. }
  56. break;
  57. case "IfStatement":
  58. stack.push(node.consequent);
  59. stack.push(node.alternate);
  60. break;
  61. case "ForStatement":
  62. stack.push(node.init);
  63. stack.push(node.body);
  64. break;
  65. case "ForInStatement":
  66. case "ForOfStatement":
  67. stack.push(node.left);
  68. stack.push(node.body);
  69. break;
  70. case "DoWhileStatement":
  71. case "WhileStatement":
  72. case "LabeledStatement":
  73. stack.push(node.body);
  74. break;
  75. case "SwitchStatement":
  76. for (const cs of node.cases) {
  77. for (const consequent of cs.consequent) {
  78. stack.push(consequent);
  79. }
  80. }
  81. break;
  82. case "TryStatement":
  83. stack.push(node.block);
  84. if (node.handler) {
  85. stack.push(node.handler.body);
  86. }
  87. stack.push(node.finalizer);
  88. break;
  89. case "FunctionDeclaration":
  90. if (includeFunctionDeclarations) {
  91. collectDeclaration(declarations, node.id);
  92. }
  93. break;
  94. case "VariableDeclaration":
  95. if (node.kind === "var") {
  96. for (const decl of node.declarations) {
  97. collectDeclaration(declarations, decl.id);
  98. }
  99. }
  100. break;
  101. }
  102. }
  103. return Array.from(declarations);
  104. };
  105. class ConstPlugin {
  106. /**
  107. * Apply the plugin
  108. * @param {Compiler} compiler the compiler instance
  109. * @returns {void}
  110. */
  111. apply(compiler) {
  112. const cachedParseResource = parseResource.bindCache(compiler.root);
  113. compiler.hooks.compilation.tap(
  114. "ConstPlugin",
  115. (compilation, { normalModuleFactory }) => {
  116. compilation.dependencyTemplates.set(
  117. ConstDependency,
  118. new ConstDependency.Template()
  119. );
  120. compilation.dependencyTemplates.set(
  121. CachedConstDependency,
  122. new CachedConstDependency.Template()
  123. );
  124. const handler = parser => {
  125. parser.hooks.statementIf.tap("ConstPlugin", statement => {
  126. if (parser.scope.isAsmJs) return;
  127. const param = parser.evaluateExpression(statement.test);
  128. const bool = param.asBool();
  129. if (typeof bool === "boolean") {
  130. if (!param.couldHaveSideEffects()) {
  131. const dep = new ConstDependency(`${bool}`, param.range);
  132. dep.loc = statement.loc;
  133. parser.state.module.addPresentationalDependency(dep);
  134. } else {
  135. parser.walkExpression(statement.test);
  136. }
  137. const branchToRemove = bool
  138. ? statement.alternate
  139. : statement.consequent;
  140. if (branchToRemove) {
  141. // Before removing the dead branch, the hoisted declarations
  142. // must be collected.
  143. //
  144. // Given the following code:
  145. //
  146. // if (true) f() else g()
  147. // if (false) {
  148. // function f() {}
  149. // const g = function g() {}
  150. // if (someTest) {
  151. // let a = 1
  152. // var x, {y, z} = obj
  153. // }
  154. // } else {
  155. // …
  156. // }
  157. //
  158. // the generated code is:
  159. //
  160. // if (true) f() else {}
  161. // if (false) {
  162. // var f, x, y, z; (in loose mode)
  163. // var x, y, z; (in strict mode)
  164. // } else {
  165. // …
  166. // }
  167. //
  168. // NOTE: When code runs in strict mode, `var` declarations
  169. // are hoisted but `function` declarations don't.
  170. //
  171. let declarations;
  172. if (parser.scope.isStrict) {
  173. // If the code runs in strict mode, variable declarations
  174. // using `var` must be hoisted.
  175. declarations = getHoistedDeclarations(branchToRemove, false);
  176. } else {
  177. // Otherwise, collect all hoisted declaration.
  178. declarations = getHoistedDeclarations(branchToRemove, true);
  179. }
  180. let replacement;
  181. if (declarations.length > 0) {
  182. replacement = `{ var ${declarations.join(", ")}; }`;
  183. } else {
  184. replacement = "{}";
  185. }
  186. const dep = new ConstDependency(
  187. replacement,
  188. branchToRemove.range
  189. );
  190. dep.loc = branchToRemove.loc;
  191. parser.state.module.addPresentationalDependency(dep);
  192. }
  193. return bool;
  194. }
  195. });
  196. parser.hooks.expressionConditionalOperator.tap(
  197. "ConstPlugin",
  198. expression => {
  199. if (parser.scope.isAsmJs) return;
  200. const param = parser.evaluateExpression(expression.test);
  201. const bool = param.asBool();
  202. if (typeof bool === "boolean") {
  203. if (!param.couldHaveSideEffects()) {
  204. const dep = new ConstDependency(` ${bool}`, param.range);
  205. dep.loc = expression.loc;
  206. parser.state.module.addPresentationalDependency(dep);
  207. } else {
  208. parser.walkExpression(expression.test);
  209. }
  210. // Expressions do not hoist.
  211. // It is safe to remove the dead branch.
  212. //
  213. // Given the following code:
  214. //
  215. // false ? someExpression() : otherExpression();
  216. //
  217. // the generated code is:
  218. //
  219. // false ? 0 : otherExpression();
  220. //
  221. const branchToRemove = bool
  222. ? expression.alternate
  223. : expression.consequent;
  224. const dep = new ConstDependency("0", branchToRemove.range);
  225. dep.loc = branchToRemove.loc;
  226. parser.state.module.addPresentationalDependency(dep);
  227. return bool;
  228. }
  229. }
  230. );
  231. parser.hooks.expressionLogicalOperator.tap(
  232. "ConstPlugin",
  233. expression => {
  234. if (parser.scope.isAsmJs) return;
  235. if (
  236. expression.operator === "&&" ||
  237. expression.operator === "||"
  238. ) {
  239. const param = parser.evaluateExpression(expression.left);
  240. const bool = param.asBool();
  241. if (typeof bool === "boolean") {
  242. // Expressions do not hoist.
  243. // It is safe to remove the dead branch.
  244. //
  245. // ------------------------------------------
  246. //
  247. // Given the following code:
  248. //
  249. // falsyExpression() && someExpression();
  250. //
  251. // the generated code is:
  252. //
  253. // falsyExpression() && false;
  254. //
  255. // ------------------------------------------
  256. //
  257. // Given the following code:
  258. //
  259. // truthyExpression() && someExpression();
  260. //
  261. // the generated code is:
  262. //
  263. // true && someExpression();
  264. //
  265. // ------------------------------------------
  266. //
  267. // Given the following code:
  268. //
  269. // truthyExpression() || someExpression();
  270. //
  271. // the generated code is:
  272. //
  273. // truthyExpression() || false;
  274. //
  275. // ------------------------------------------
  276. //
  277. // Given the following code:
  278. //
  279. // falsyExpression() || someExpression();
  280. //
  281. // the generated code is:
  282. //
  283. // false && someExpression();
  284. //
  285. const keepRight =
  286. (expression.operator === "&&" && bool) ||
  287. (expression.operator === "||" && !bool);
  288. if (
  289. !param.couldHaveSideEffects() &&
  290. (param.isBoolean() || keepRight)
  291. ) {
  292. // for case like
  293. //
  294. // return'development'===process.env.NODE_ENV&&'foo'
  295. //
  296. // we need a space before the bool to prevent result like
  297. //
  298. // returnfalse&&'foo'
  299. //
  300. const dep = new ConstDependency(` ${bool}`, param.range);
  301. dep.loc = expression.loc;
  302. parser.state.module.addPresentationalDependency(dep);
  303. } else {
  304. parser.walkExpression(expression.left);
  305. }
  306. if (!keepRight) {
  307. const dep = new ConstDependency(
  308. "0",
  309. expression.right.range
  310. );
  311. dep.loc = expression.loc;
  312. parser.state.module.addPresentationalDependency(dep);
  313. }
  314. return keepRight;
  315. }
  316. } else if (expression.operator === "??") {
  317. const param = parser.evaluateExpression(expression.left);
  318. const keepRight = param.asNullish();
  319. if (typeof keepRight === "boolean") {
  320. // ------------------------------------------
  321. //
  322. // Given the following code:
  323. //
  324. // nonNullish ?? someExpression();
  325. //
  326. // the generated code is:
  327. //
  328. // nonNullish ?? 0;
  329. //
  330. // ------------------------------------------
  331. //
  332. // Given the following code:
  333. //
  334. // nullish ?? someExpression();
  335. //
  336. // the generated code is:
  337. //
  338. // null ?? someExpression();
  339. //
  340. if (!param.couldHaveSideEffects() && keepRight) {
  341. // cspell:word returnnull
  342. // for case like
  343. //
  344. // return('development'===process.env.NODE_ENV&&null)??'foo'
  345. //
  346. // we need a space before the bool to prevent result like
  347. //
  348. // returnnull??'foo'
  349. //
  350. const dep = new ConstDependency(" null", param.range);
  351. dep.loc = expression.loc;
  352. parser.state.module.addPresentationalDependency(dep);
  353. } else {
  354. const dep = new ConstDependency(
  355. "0",
  356. expression.right.range
  357. );
  358. dep.loc = expression.loc;
  359. parser.state.module.addPresentationalDependency(dep);
  360. parser.walkExpression(expression.left);
  361. }
  362. return keepRight;
  363. }
  364. }
  365. }
  366. );
  367. parser.hooks.optionalChaining.tap("ConstPlugin", expr => {
  368. /** @type {ExpressionNode[]} */
  369. const optionalExpressionsStack = [];
  370. /** @type {ExpressionNode|SuperNode} */
  371. let next = expr.expression;
  372. while (
  373. next.type === "MemberExpression" ||
  374. next.type === "CallExpression"
  375. ) {
  376. if (next.type === "MemberExpression") {
  377. if (next.optional) {
  378. // SuperNode can not be optional
  379. optionalExpressionsStack.push(
  380. /** @type {ExpressionNode} */ (next.object)
  381. );
  382. }
  383. next = next.object;
  384. } else {
  385. if (next.optional) {
  386. // SuperNode can not be optional
  387. optionalExpressionsStack.push(
  388. /** @type {ExpressionNode} */ (next.callee)
  389. );
  390. }
  391. next = next.callee;
  392. }
  393. }
  394. while (optionalExpressionsStack.length) {
  395. const expression = optionalExpressionsStack.pop();
  396. const evaluated = parser.evaluateExpression(expression);
  397. if (evaluated.asNullish()) {
  398. // ------------------------------------------
  399. //
  400. // Given the following code:
  401. //
  402. // nullishMemberChain?.a.b();
  403. //
  404. // the generated code is:
  405. //
  406. // undefined;
  407. //
  408. // ------------------------------------------
  409. //
  410. const dep = new ConstDependency(" undefined", expr.range);
  411. dep.loc = expr.loc;
  412. parser.state.module.addPresentationalDependency(dep);
  413. return true;
  414. }
  415. }
  416. });
  417. parser.hooks.evaluateIdentifier
  418. .for("__resourceQuery")
  419. .tap("ConstPlugin", expr => {
  420. if (parser.scope.isAsmJs) return;
  421. if (!parser.state.module) return;
  422. return evaluateToString(
  423. cachedParseResource(parser.state.module.resource).query
  424. )(expr);
  425. });
  426. parser.hooks.expression
  427. .for("__resourceQuery")
  428. .tap("ConstPlugin", expr => {
  429. if (parser.scope.isAsmJs) return;
  430. if (!parser.state.module) return;
  431. const dep = new CachedConstDependency(
  432. JSON.stringify(
  433. cachedParseResource(parser.state.module.resource).query
  434. ),
  435. expr.range,
  436. "__resourceQuery"
  437. );
  438. dep.loc = expr.loc;
  439. parser.state.module.addPresentationalDependency(dep);
  440. return true;
  441. });
  442. parser.hooks.evaluateIdentifier
  443. .for("__resourceFragment")
  444. .tap("ConstPlugin", expr => {
  445. if (parser.scope.isAsmJs) return;
  446. if (!parser.state.module) return;
  447. return evaluateToString(
  448. cachedParseResource(parser.state.module.resource).fragment
  449. )(expr);
  450. });
  451. parser.hooks.expression
  452. .for("__resourceFragment")
  453. .tap("ConstPlugin", expr => {
  454. if (parser.scope.isAsmJs) return;
  455. if (!parser.state.module) return;
  456. const dep = new CachedConstDependency(
  457. JSON.stringify(
  458. cachedParseResource(parser.state.module.resource).fragment
  459. ),
  460. expr.range,
  461. "__resourceFragment"
  462. );
  463. dep.loc = expr.loc;
  464. parser.state.module.addPresentationalDependency(dep);
  465. return true;
  466. });
  467. };
  468. normalModuleFactory.hooks.parser
  469. .for("javascript/auto")
  470. .tap("ConstPlugin", handler);
  471. normalModuleFactory.hooks.parser
  472. .for("javascript/dynamic")
  473. .tap("ConstPlugin", handler);
  474. normalModuleFactory.hooks.parser
  475. .for("javascript/esm")
  476. .tap("ConstPlugin", handler);
  477. }
  478. );
  479. }
  480. }
  481. module.exports = ConstPlugin;