ConstPlugin.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. if (parser.scope.isAsmJs) return;
  118. const param = parser.evaluateExpression(statement.test);
  119. const bool = param.asBool();
  120. if (typeof bool === "boolean") {
  121. if (statement.test.type !== "Literal") {
  122. const dep = new ConstDependency(`${bool}`, param.range);
  123. dep.loc = statement.loc;
  124. parser.state.current.addDependency(dep);
  125. }
  126. const branchToRemove = bool
  127. ? statement.alternate
  128. : statement.consequent;
  129. if (branchToRemove) {
  130. // Before removing the dead branch, the hoisted declarations
  131. // must be collected.
  132. //
  133. // Given the following code:
  134. //
  135. // if (true) f() else g()
  136. // if (false) {
  137. // function f() {}
  138. // const g = function g() {}
  139. // if (someTest) {
  140. // let a = 1
  141. // var x, {y, z} = obj
  142. // }
  143. // } else {
  144. // …
  145. // }
  146. //
  147. // the generated code is:
  148. //
  149. // if (true) f() else {}
  150. // if (false) {
  151. // var f, x, y, z; (in loose mode)
  152. // var x, y, z; (in strict mode)
  153. // } else {
  154. // …
  155. // }
  156. //
  157. // NOTE: When code runs in strict mode, `var` declarations
  158. // are hoisted but `function` declarations don't.
  159. //
  160. let declarations;
  161. if (parser.scope.isStrict) {
  162. // If the code runs in strict mode, variable declarations
  163. // using `var` must be hoisted.
  164. declarations = getHoistedDeclarations(branchToRemove, false);
  165. } else {
  166. // Otherwise, collect all hoisted declaration.
  167. declarations = getHoistedDeclarations(branchToRemove, true);
  168. }
  169. let replacement;
  170. if (declarations.length > 0) {
  171. replacement = `{ var ${declarations.join(", ")}; }`;
  172. } else {
  173. replacement = "{}";
  174. }
  175. const dep = new ConstDependency(
  176. replacement,
  177. branchToRemove.range
  178. );
  179. dep.loc = branchToRemove.loc;
  180. parser.state.current.addDependency(dep);
  181. }
  182. return bool;
  183. }
  184. });
  185. parser.hooks.expressionConditionalOperator.tap(
  186. "ConstPlugin",
  187. expression => {
  188. if (parser.scope.isAsmJs) return;
  189. const param = parser.evaluateExpression(expression.test);
  190. const bool = param.asBool();
  191. if (typeof bool === "boolean") {
  192. if (expression.test.type !== "Literal") {
  193. const dep = new ConstDependency(` ${bool}`, param.range);
  194. dep.loc = expression.loc;
  195. parser.state.current.addDependency(dep);
  196. }
  197. // Expressions do not hoist.
  198. // It is safe to remove the dead branch.
  199. //
  200. // Given the following code:
  201. //
  202. // false ? someExpression() : otherExpression();
  203. //
  204. // the generated code is:
  205. //
  206. // false ? undefined : otherExpression();
  207. //
  208. const branchToRemove = bool
  209. ? expression.alternate
  210. : expression.consequent;
  211. const dep = new ConstDependency(
  212. "undefined",
  213. branchToRemove.range
  214. );
  215. dep.loc = branchToRemove.loc;
  216. parser.state.current.addDependency(dep);
  217. return bool;
  218. }
  219. }
  220. );
  221. parser.hooks.expressionLogicalOperator.tap(
  222. "ConstPlugin",
  223. expression => {
  224. if (parser.scope.isAsmJs) return;
  225. if (
  226. expression.operator === "&&" ||
  227. expression.operator === "||"
  228. ) {
  229. const param = parser.evaluateExpression(expression.left);
  230. const bool = param.asBool();
  231. if (typeof bool === "boolean") {
  232. // Expressions do not hoist.
  233. // It is safe to remove the dead branch.
  234. //
  235. // ------------------------------------------
  236. //
  237. // Given the following code:
  238. //
  239. // falsyExpression() && someExpression();
  240. //
  241. // the generated code is:
  242. //
  243. // falsyExpression() && false;
  244. //
  245. // ------------------------------------------
  246. //
  247. // Given the following code:
  248. //
  249. // truthyExpression() && someExpression();
  250. //
  251. // the generated code is:
  252. //
  253. // true && someExpression();
  254. //
  255. // ------------------------------------------
  256. //
  257. // Given the following code:
  258. //
  259. // truthyExpression() || someExpression();
  260. //
  261. // the generated code is:
  262. //
  263. // truthyExpression() || false;
  264. //
  265. // ------------------------------------------
  266. //
  267. // Given the following code:
  268. //
  269. // falsyExpression() || someExpression();
  270. //
  271. // the generated code is:
  272. //
  273. // false && someExpression();
  274. //
  275. const keepRight =
  276. (expression.operator === "&&" && bool) ||
  277. (expression.operator === "||" && !bool);
  278. if (param.isBoolean() || keepRight) {
  279. // for case like
  280. //
  281. // return'development'===process.env.NODE_ENV&&'foo'
  282. //
  283. // we need a space before the bool to prevent result like
  284. //
  285. // returnfalse&&'foo'
  286. //
  287. const dep = new ConstDependency(` ${bool}`, param.range);
  288. dep.loc = expression.loc;
  289. parser.state.current.addDependency(dep);
  290. } else {
  291. parser.walkExpression(expression.left);
  292. }
  293. if (!keepRight) {
  294. const dep = new ConstDependency(
  295. "false",
  296. expression.right.range
  297. );
  298. dep.loc = expression.loc;
  299. parser.state.current.addDependency(dep);
  300. }
  301. return keepRight;
  302. }
  303. }
  304. }
  305. );
  306. parser.hooks.evaluateIdentifier
  307. .for("__resourceQuery")
  308. .tap("ConstPlugin", expr => {
  309. if (parser.scope.isAsmJs) return;
  310. if (!parser.state.module) return;
  311. return ParserHelpers.evaluateToString(
  312. getQuery(parser.state.module.resource)
  313. )(expr);
  314. });
  315. parser.hooks.expression
  316. .for("__resourceQuery")
  317. .tap("ConstPlugin", () => {
  318. if (parser.scope.isAsmJs) return;
  319. if (!parser.state.module) return;
  320. parser.state.current.addVariable(
  321. "__resourceQuery",
  322. JSON.stringify(getQuery(parser.state.module.resource))
  323. );
  324. return true;
  325. });
  326. };
  327. normalModuleFactory.hooks.parser
  328. .for("javascript/auto")
  329. .tap("ConstPlugin", handler);
  330. normalModuleFactory.hooks.parser
  331. .for("javascript/dynamic")
  332. .tap("ConstPlugin", handler);
  333. normalModuleFactory.hooks.parser
  334. .for("javascript/esm")
  335. .tap("ConstPlugin", handler);
  336. }
  337. );
  338. }
  339. }
  340. module.exports = ConstPlugin;