Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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.expressionLogicalOperator.tap(
  220. "ConstPlugin",
  221. expression => {
  222. if (
  223. expression.operator === "&&" ||
  224. expression.operator === "||"
  225. ) {
  226. const param = parser.evaluateExpression(expression.left);
  227. const bool = param.asBool();
  228. if (typeof bool === "boolean") {
  229. // Expressions do not hoist.
  230. // It is safe to remove the dead branch.
  231. //
  232. // ------------------------------------------
  233. //
  234. // Given the following code:
  235. //
  236. // falsyExpression() && someExpression();
  237. //
  238. // the generated code is:
  239. //
  240. // falsyExpression() && false;
  241. //
  242. // ------------------------------------------
  243. //
  244. // Given the following code:
  245. //
  246. // truthyExpression() && someExpression();
  247. //
  248. // the generated code is:
  249. //
  250. // true && someExpression();
  251. //
  252. // ------------------------------------------
  253. //
  254. // Given the following code:
  255. //
  256. // truthyExpression() || someExpression();
  257. //
  258. // the generated code is:
  259. //
  260. // truthyExpression() || false;
  261. //
  262. // ------------------------------------------
  263. //
  264. // Given the following code:
  265. //
  266. // falsyExpression() || someExpression();
  267. //
  268. // the generated code is:
  269. //
  270. // false && someExpression();
  271. //
  272. const keepRight =
  273. (expression.operator === "&&" && bool) ||
  274. (expression.operator === "||" && !bool);
  275. if (param.isBoolean() || keepRight) {
  276. // for case like
  277. //
  278. // return'development'===process.env.NODE_ENV&&'foo'
  279. //
  280. // we need a space before the bool to prevent result like
  281. //
  282. // returnfalse&&'foo'
  283. //
  284. const dep = new ConstDependency(` ${bool}`, param.range);
  285. dep.loc = expression.loc;
  286. parser.state.current.addDependency(dep);
  287. } else {
  288. parser.walkExpression(expression.left);
  289. }
  290. if (!keepRight) {
  291. const dep = new ConstDependency(
  292. "false",
  293. expression.right.range
  294. );
  295. dep.loc = expression.loc;
  296. parser.state.current.addDependency(dep);
  297. }
  298. return keepRight;
  299. }
  300. }
  301. }
  302. );
  303. parser.hooks.evaluateIdentifier
  304. .for("__resourceQuery")
  305. .tap("ConstPlugin", expr => {
  306. if (!parser.state.module) return;
  307. return ParserHelpers.evaluateToString(
  308. getQuery(parser.state.module.resource)
  309. )(expr);
  310. });
  311. parser.hooks.expression
  312. .for("__resourceQuery")
  313. .tap("ConstPlugin", () => {
  314. if (!parser.state.module) return;
  315. parser.state.current.addVariable(
  316. "__resourceQuery",
  317. JSON.stringify(getQuery(parser.state.module.resource))
  318. );
  319. return true;
  320. });
  321. };
  322. normalModuleFactory.hooks.parser
  323. .for("javascript/auto")
  324. .tap("ConstPlugin", handler);
  325. normalModuleFactory.hooks.parser
  326. .for("javascript/dynamic")
  327. .tap("ConstPlugin", handler);
  328. normalModuleFactory.hooks.parser
  329. .for("javascript/esm")
  330. .tap("ConstPlugin", handler);
  331. }
  332. );
  333. }
  334. }
  335. module.exports = ConstPlugin;