ConstPlugin.js 16 KB

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