InnerGraphPlugin.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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_ESM
  9. } = require("../ModuleTypeConstants");
  10. const PureExpressionDependency = require("../dependencies/PureExpressionDependency");
  11. const InnerGraph = require("./InnerGraph");
  12. /** @typedef {import("estree").ClassDeclaration} ClassDeclarationNode */
  13. /** @typedef {import("estree").ClassExpression} ClassExpressionNode */
  14. /** @typedef {import("estree").Node} Node */
  15. /** @typedef {import("estree").VariableDeclarator} VariableDeclaratorNode */
  16. /** @typedef {import("../Compiler")} Compiler */
  17. /** @typedef {import("../Dependency")} Dependency */
  18. /** @typedef {import("../dependencies/HarmonyImportSpecifierDependency")} HarmonyImportSpecifierDependency */
  19. /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
  20. /** @typedef {import("./InnerGraph").InnerGraph} InnerGraph */
  21. /** @typedef {import("./InnerGraph").TopLevelSymbol} TopLevelSymbol */
  22. const { topLevelSymbolTag } = InnerGraph;
  23. const PLUGIN_NAME = "InnerGraphPlugin";
  24. class InnerGraphPlugin {
  25. /**
  26. * Apply the plugin
  27. * @param {Compiler} compiler the compiler instance
  28. * @returns {void}
  29. */
  30. apply(compiler) {
  31. compiler.hooks.compilation.tap(
  32. PLUGIN_NAME,
  33. (compilation, { normalModuleFactory }) => {
  34. const logger = compilation.getLogger("webpack.InnerGraphPlugin");
  35. compilation.dependencyTemplates.set(
  36. PureExpressionDependency,
  37. new PureExpressionDependency.Template()
  38. );
  39. /**
  40. * @param {JavascriptParser} parser the parser
  41. * @param {Object} parserOptions options
  42. * @returns {void}
  43. */
  44. const handler = (parser, parserOptions) => {
  45. const onUsageSuper = sup => {
  46. InnerGraph.onUsage(parser.state, usedByExports => {
  47. switch (usedByExports) {
  48. case undefined:
  49. case true:
  50. return;
  51. default: {
  52. const dep = new PureExpressionDependency(sup.range);
  53. dep.loc = sup.loc;
  54. dep.usedByExports = usedByExports;
  55. parser.state.module.addDependency(dep);
  56. break;
  57. }
  58. }
  59. });
  60. };
  61. parser.hooks.program.tap(PLUGIN_NAME, () => {
  62. InnerGraph.enable(parser.state);
  63. });
  64. parser.hooks.finish.tap(PLUGIN_NAME, () => {
  65. if (!InnerGraph.isEnabled(parser.state)) return;
  66. logger.time("infer dependency usage");
  67. InnerGraph.inferDependencyUsage(parser.state);
  68. logger.timeAggregate("infer dependency usage");
  69. });
  70. // During prewalking the following datastructures are filled with
  71. // nodes that have a TopLevelSymbol assigned and
  72. // variables are tagged with the assigned TopLevelSymbol
  73. // We differ 3 types of nodes:
  74. // 1. full statements (export default, function declaration)
  75. // 2. classes (class declaration, class expression)
  76. // 3. variable declarators (const x = ...)
  77. /** @type {WeakMap<Node, TopLevelSymbol>} */
  78. const statementWithTopLevelSymbol = new WeakMap();
  79. /** @type {WeakMap<Node, Node>} */
  80. const statementPurePart = new WeakMap();
  81. /** @type {WeakMap<ClassExpressionNode | ClassDeclarationNode, TopLevelSymbol>} */
  82. const classWithTopLevelSymbol = new WeakMap();
  83. /** @type {WeakMap<VariableDeclaratorNode, TopLevelSymbol>} */
  84. const declWithTopLevelSymbol = new WeakMap();
  85. /** @type {WeakSet<VariableDeclaratorNode>} */
  86. const pureDeclarators = new WeakSet();
  87. // The following hooks are used during prewalking:
  88. parser.hooks.preStatement.tap(PLUGIN_NAME, statement => {
  89. if (!InnerGraph.isEnabled(parser.state)) return;
  90. if (parser.scope.topLevelScope === true) {
  91. if (statement.type === "FunctionDeclaration") {
  92. const name = statement.id ? statement.id.name : "*default*";
  93. const fn = InnerGraph.tagTopLevelSymbol(parser, name);
  94. statementWithTopLevelSymbol.set(statement, fn);
  95. return true;
  96. }
  97. }
  98. });
  99. parser.hooks.blockPreStatement.tap(PLUGIN_NAME, statement => {
  100. if (!InnerGraph.isEnabled(parser.state)) return;
  101. if (parser.scope.topLevelScope === true) {
  102. if (statement.type === "ClassDeclaration") {
  103. const name = statement.id ? statement.id.name : "*default*";
  104. const fn = InnerGraph.tagTopLevelSymbol(parser, name);
  105. classWithTopLevelSymbol.set(statement, fn);
  106. return true;
  107. }
  108. if (statement.type === "ExportDefaultDeclaration") {
  109. const name = "*default*";
  110. const fn = InnerGraph.tagTopLevelSymbol(parser, name);
  111. const decl = statement.declaration;
  112. if (
  113. decl.type === "ClassExpression" ||
  114. decl.type === "ClassDeclaration"
  115. ) {
  116. classWithTopLevelSymbol.set(decl, fn);
  117. } else if (parser.isPure(decl, statement.range[0])) {
  118. statementWithTopLevelSymbol.set(statement, fn);
  119. if (
  120. !decl.type.endsWith("FunctionExpression") &&
  121. !decl.type.endsWith("Declaration") &&
  122. decl.type !== "Literal"
  123. ) {
  124. statementPurePart.set(statement, decl);
  125. }
  126. }
  127. }
  128. }
  129. });
  130. parser.hooks.preDeclarator.tap(PLUGIN_NAME, (decl, statement) => {
  131. if (!InnerGraph.isEnabled(parser.state)) return;
  132. if (
  133. parser.scope.topLevelScope === true &&
  134. decl.init &&
  135. decl.id.type === "Identifier"
  136. ) {
  137. const name = decl.id.name;
  138. if (decl.init.type === "ClassExpression") {
  139. const fn = InnerGraph.tagTopLevelSymbol(parser, name);
  140. classWithTopLevelSymbol.set(decl.init, fn);
  141. } else if (parser.isPure(decl.init, decl.id.range[1])) {
  142. const fn = InnerGraph.tagTopLevelSymbol(parser, name);
  143. declWithTopLevelSymbol.set(decl, fn);
  144. if (
  145. !decl.init.type.endsWith("FunctionExpression") &&
  146. decl.init.type !== "Literal"
  147. ) {
  148. pureDeclarators.add(decl);
  149. }
  150. return true;
  151. }
  152. }
  153. });
  154. // During real walking we set the TopLevelSymbol state to the assigned
  155. // TopLevelSymbol by using the fill datastructures.
  156. // In addition to tracking TopLevelSymbols, we sometimes need to
  157. // add a PureExpressionDependency. This is needed to skip execution
  158. // of pure expressions, even when they are not dropped due to
  159. // minimizing. Otherwise symbols used there might not exist anymore
  160. // as they are removed as unused by this optimization
  161. // When we find a reference to a TopLevelSymbol, we register a
  162. // TopLevelSymbol dependency from TopLevelSymbol in state to the
  163. // referenced TopLevelSymbol. This way we get a graph of all
  164. // TopLevelSymbols.
  165. // The following hooks are called during walking:
  166. parser.hooks.statement.tap(PLUGIN_NAME, statement => {
  167. if (!InnerGraph.isEnabled(parser.state)) return;
  168. if (parser.scope.topLevelScope === true) {
  169. InnerGraph.setTopLevelSymbol(parser.state, undefined);
  170. const fn = statementWithTopLevelSymbol.get(statement);
  171. if (fn) {
  172. InnerGraph.setTopLevelSymbol(parser.state, fn);
  173. const purePart = statementPurePart.get(statement);
  174. if (purePart) {
  175. InnerGraph.onUsage(parser.state, usedByExports => {
  176. switch (usedByExports) {
  177. case undefined:
  178. case true:
  179. return;
  180. default: {
  181. const dep = new PureExpressionDependency(
  182. purePart.range
  183. );
  184. dep.loc = statement.loc;
  185. dep.usedByExports = usedByExports;
  186. parser.state.module.addDependency(dep);
  187. break;
  188. }
  189. }
  190. });
  191. }
  192. }
  193. }
  194. });
  195. parser.hooks.classExtendsExpression.tap(
  196. PLUGIN_NAME,
  197. (expr, statement) => {
  198. if (!InnerGraph.isEnabled(parser.state)) return;
  199. if (parser.scope.topLevelScope === true) {
  200. const fn = classWithTopLevelSymbol.get(statement);
  201. if (
  202. fn &&
  203. parser.isPure(
  204. expr,
  205. statement.id ? statement.id.range[1] : statement.range[0]
  206. )
  207. ) {
  208. InnerGraph.setTopLevelSymbol(parser.state, fn);
  209. onUsageSuper(expr);
  210. }
  211. }
  212. }
  213. );
  214. parser.hooks.classBodyElement.tap(
  215. PLUGIN_NAME,
  216. (element, classDefinition) => {
  217. if (!InnerGraph.isEnabled(parser.state)) return;
  218. if (parser.scope.topLevelScope === true) {
  219. const fn = classWithTopLevelSymbol.get(classDefinition);
  220. if (fn) {
  221. InnerGraph.setTopLevelSymbol(parser.state, undefined);
  222. }
  223. }
  224. }
  225. );
  226. parser.hooks.classBodyValue.tap(
  227. PLUGIN_NAME,
  228. (expression, element, classDefinition) => {
  229. if (!InnerGraph.isEnabled(parser.state)) return;
  230. if (parser.scope.topLevelScope === true) {
  231. const fn = classWithTopLevelSymbol.get(classDefinition);
  232. if (fn) {
  233. if (
  234. !element.static ||
  235. parser.isPure(
  236. expression,
  237. element.key ? element.key.range[1] : element.range[0]
  238. )
  239. ) {
  240. InnerGraph.setTopLevelSymbol(parser.state, fn);
  241. if (element.type !== "MethodDefinition" && element.static) {
  242. InnerGraph.onUsage(parser.state, usedByExports => {
  243. switch (usedByExports) {
  244. case undefined:
  245. case true:
  246. return;
  247. default: {
  248. const dep = new PureExpressionDependency(
  249. expression.range
  250. );
  251. dep.loc = expression.loc;
  252. dep.usedByExports = usedByExports;
  253. parser.state.module.addDependency(dep);
  254. break;
  255. }
  256. }
  257. });
  258. }
  259. } else {
  260. InnerGraph.setTopLevelSymbol(parser.state, undefined);
  261. }
  262. }
  263. }
  264. }
  265. );
  266. parser.hooks.declarator.tap(PLUGIN_NAME, (decl, statement) => {
  267. if (!InnerGraph.isEnabled(parser.state)) return;
  268. const fn = declWithTopLevelSymbol.get(decl);
  269. if (fn) {
  270. InnerGraph.setTopLevelSymbol(parser.state, fn);
  271. if (pureDeclarators.has(decl)) {
  272. if (decl.init.type === "ClassExpression") {
  273. if (decl.init.superClass) {
  274. onUsageSuper(decl.init.superClass);
  275. }
  276. } else {
  277. InnerGraph.onUsage(parser.state, usedByExports => {
  278. switch (usedByExports) {
  279. case undefined:
  280. case true:
  281. return;
  282. default: {
  283. const dep = new PureExpressionDependency(
  284. decl.init.range
  285. );
  286. dep.loc = decl.loc;
  287. dep.usedByExports = usedByExports;
  288. parser.state.module.addDependency(dep);
  289. break;
  290. }
  291. }
  292. });
  293. }
  294. }
  295. parser.walkExpression(decl.init);
  296. InnerGraph.setTopLevelSymbol(parser.state, undefined);
  297. return true;
  298. }
  299. });
  300. parser.hooks.expression
  301. .for(topLevelSymbolTag)
  302. .tap(PLUGIN_NAME, () => {
  303. const topLevelSymbol = /** @type {TopLevelSymbol} */ (
  304. parser.currentTagData
  305. );
  306. const currentTopLevelSymbol = InnerGraph.getTopLevelSymbol(
  307. parser.state
  308. );
  309. InnerGraph.addUsage(
  310. parser.state,
  311. topLevelSymbol,
  312. currentTopLevelSymbol || true
  313. );
  314. });
  315. parser.hooks.assign.for(topLevelSymbolTag).tap(PLUGIN_NAME, expr => {
  316. if (!InnerGraph.isEnabled(parser.state)) return;
  317. if (expr.operator === "=") return true;
  318. });
  319. };
  320. normalModuleFactory.hooks.parser
  321. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  322. .tap(PLUGIN_NAME, handler);
  323. normalModuleFactory.hooks.parser
  324. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  325. .tap(PLUGIN_NAME, handler);
  326. compilation.hooks.finishModules.tap(PLUGIN_NAME, () => {
  327. logger.timeAggregateEnd("infer dependency usage");
  328. });
  329. }
  330. );
  331. }
  332. }
  333. module.exports = InnerGraphPlugin;