InnerGraphPlugin.js 14 KB

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