ConstPlugin.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const ConstDependency = require("./dependencies/ConstDependency");
  7. const NullFactory = require("./NullFactory");
  8. const ParserHelpers = require("./ParserHelpers");
  9. const getQuery = request => {
  10. const i = request.indexOf("?");
  11. return i !== -1 ? request.substr(i) : "";
  12. };
  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. apply(compiler) {
  107. compiler.hooks.compilation.tap(
  108. "ConstPlugin",
  109. (compilation, { normalModuleFactory }) => {
  110. compilation.dependencyFactories.set(ConstDependency, new NullFactory());
  111. compilation.dependencyTemplates.set(
  112. ConstDependency,
  113. new ConstDependency.Template()
  114. );
  115. const handler = parser => {
  116. parser.hooks.statementIf.tap("ConstPlugin", statement => {
  117. const param = parser.evaluateExpression(statement.test);
  118. const bool = param.asBool();
  119. if (typeof bool === "boolean") {
  120. if (statement.test.type !== "Literal") {
  121. const dep = new ConstDependency(`${bool}`, param.range);
  122. dep.loc = statement.loc;
  123. parser.state.current.addDependency(dep);
  124. }
  125. const branchToRemove = bool
  126. ? statement.alternate
  127. : statement.consequent;
  128. if (branchToRemove) {
  129. // Before removing the dead branch, the hoisted declarations
  130. // must be collected.
  131. //
  132. // Given the following code:
  133. //
  134. // if (true) f() else g()
  135. // if (false) {
  136. // function f() {}
  137. // const g = function g() {}
  138. // if (someTest) {
  139. // let a = 1
  140. // var x, {y, z} = obj
  141. // }
  142. // } else {
  143. // …
  144. // }
  145. //
  146. // the generated code is:
  147. //
  148. // if (true) f() else {}
  149. // if (false) {
  150. // var f, x, y, z; (in loose mode)
  151. // var x, y, z; (in strict mode)
  152. // } else {
  153. // …
  154. // }
  155. //
  156. // NOTE: When code runs in strict mode, `var` declarations
  157. // are hoisted but `function` declarations don't.
  158. //
  159. let declarations;
  160. if (parser.scope.isStrict) {
  161. // If the code runs in strict mode, variable declarations
  162. // using `var` must be hoisted.
  163. declarations = getHoistedDeclarations(branchToRemove, false);
  164. } else {
  165. // Otherwise, collect all hoisted declaration.
  166. declarations = getHoistedDeclarations(branchToRemove, true);
  167. }
  168. let replacement;
  169. if (declarations.length > 0) {
  170. replacement = `{ var ${declarations.join(", ")}; }`;
  171. } else {
  172. replacement = "{}";
  173. }
  174. const dep = new ConstDependency(
  175. replacement,
  176. branchToRemove.range
  177. );
  178. dep.loc = branchToRemove.loc;
  179. parser.state.current.addDependency(dep);
  180. }
  181. return bool;
  182. }
  183. });
  184. parser.hooks.expressionConditionalOperator.tap(
  185. "ConstPlugin",
  186. expression => {
  187. const param = parser.evaluateExpression(expression.test);
  188. const bool = param.asBool();
  189. if (typeof bool === "boolean") {
  190. if (expression.test.type !== "Literal") {
  191. const dep = new ConstDependency(` ${bool}`, param.range);
  192. dep.loc = expression.loc;
  193. parser.state.current.addDependency(dep);
  194. }
  195. // Expressions do not hoist.
  196. // It is safe to remove the dead branch.
  197. //
  198. // Given the following code:
  199. //
  200. // false ? someExpression() : otherExpression();
  201. //
  202. // the generated code is:
  203. //
  204. // false ? undefined : otherExpression();
  205. //
  206. const branchToRemove = bool
  207. ? expression.alternate
  208. : expression.consequent;
  209. const dep = new ConstDependency(
  210. "undefined",
  211. branchToRemove.range
  212. );
  213. dep.loc = branchToRemove.loc;
  214. parser.state.current.addDependency(dep);
  215. return bool;
  216. }
  217. }
  218. );
  219. parser.hooks.evaluateIdentifier
  220. .for("__resourceQuery")
  221. .tap("ConstPlugin", expr => {
  222. if (!parser.state.module) return;
  223. return ParserHelpers.evaluateToString(
  224. getQuery(parser.state.module.resource)
  225. )(expr);
  226. });
  227. parser.hooks.expression
  228. .for("__resourceQuery")
  229. .tap("ConstPlugin", () => {
  230. if (!parser.state.module) return;
  231. parser.state.current.addVariable(
  232. "__resourceQuery",
  233. JSON.stringify(getQuery(parser.state.module.resource))
  234. );
  235. return true;
  236. });
  237. };
  238. normalModuleFactory.hooks.parser
  239. .for("javascript/auto")
  240. .tap("ConstPlugin", handler);
  241. normalModuleFactory.hooks.parser
  242. .for("javascript/dynamic")
  243. .tap("ConstPlugin", handler);
  244. normalModuleFactory.hooks.parser
  245. .for("javascript/esm")
  246. .tap("ConstPlugin", handler);
  247. }
  248. );
  249. }
  250. }
  251. module.exports = ConstPlugin;