ConstPlugin.js 15 KB

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