InnerGraphPlugin.js 13 KB

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