FlagDependencyUsagePlugin.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Dependency = require("./Dependency");
  7. const { UsageState } = require("./ExportsInfo");
  8. const ModuleGraphConnection = require("./ModuleGraphConnection");
  9. const { STAGE_DEFAULT } = require("./OptimizationStages");
  10. const ArrayQueue = require("./util/ArrayQueue");
  11. const TupleQueue = require("./util/TupleQueue");
  12. const TupleSet = require("./util/TupleSet");
  13. const { getEntryRuntime, mergeRuntimeOwned } = require("./util/runtime");
  14. /** @import Compiler from "./Compiler" */
  15. /** @import DependenciesBlock from "./DependenciesBlock" */
  16. /** @import { ReferencedExport, ReferencedExports } from "./Dependency" */
  17. /** @import ExportsInfo from "./ExportsInfo" */
  18. /** @import Module from "./Module" */
  19. /** @import { RuntimeSpec } from "./util/runtime" */
  20. const {
  21. NO_EXPORTS_REFERENCED,
  22. EXPORTS_OBJECT_REFERENCED,
  23. EXPORTS_OBJECT_REFERENCED_MANGLEABLE
  24. } = Dependency;
  25. const PLUGIN_NAME = "FlagDependencyUsagePlugin";
  26. const PLUGIN_LOGGER_NAME = `webpack.${PLUGIN_NAME}`;
  27. // Hoisted stateless predicates for setUsedConditionally on the innermost
  28. // used-export loop, so they aren't re-allocated per export.
  29. /**
  30. * @param {import("./ExportsInfo").UsageStateType} used usage state
  31. * @returns {boolean} whether unused
  32. */
  33. const IS_UNUSED = (used) => used === UsageState.Unused;
  34. /**
  35. * @param {import("./ExportsInfo").UsageStateType} used usage state
  36. * @returns {boolean} whether not used
  37. */
  38. const IS_NOT_USED = (used) => used !== UsageState.Used;
  39. class FlagDependencyUsagePlugin {
  40. /**
  41. * Creates an instance of FlagDependencyUsagePlugin.
  42. * @param {boolean} global do a global analysis instead of per runtime
  43. * @param {boolean=} mangleEscapingNamespaces keep exports mangleable when a module's namespace object escapes
  44. */
  45. constructor(global, mangleEscapingNamespaces = false) {
  46. /** @type {boolean} */
  47. this.global = global;
  48. /** @type {boolean} */
  49. this.mangleEscapingNamespaces = mangleEscapingNamespaces;
  50. }
  51. /**
  52. * Applies the plugin by registering its hooks on the compiler.
  53. * @param {Compiler} compiler the compiler instance
  54. * @returns {void}
  55. */
  56. apply(compiler) {
  57. compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
  58. const moduleGraph = compilation.moduleGraph;
  59. compilation.hooks.optimizeDependencies.tap(
  60. { name: PLUGIN_NAME, stage: STAGE_DEFAULT },
  61. (modules) => {
  62. if (compilation.moduleMemCaches) {
  63. throw new Error(
  64. "optimization.usedExports can't be used with cacheUnaffected as export usage is a global effect"
  65. );
  66. }
  67. const logger = compilation.getLogger(PLUGIN_LOGGER_NAME);
  68. /** @type {Map<ExportsInfo, Module>} */
  69. const exportInfoToModuleMap = new Map();
  70. /** @type {TupleQueue<Module, RuntimeSpec>} */
  71. const queue = new TupleQueue();
  72. /** @type {TupleSet<Module, RuntimeSpec> | undefined} */
  73. let walkedSideEffectFreeModules;
  74. /**
  75. * Process referenced module.
  76. * @param {Module} module module to process
  77. * @param {ReferencedExports} usedExports list of used exports
  78. * @param {RuntimeSpec} runtime part of which runtime
  79. * @returns {void}
  80. */
  81. const processReferencedModule = (module, usedExports, runtime) => {
  82. const exportsInfo = moduleGraph.getExportsInfo(module);
  83. if (usedExports === EXPORTS_OBJECT_REFERENCED_MANGLEABLE) {
  84. // The whole namespace object escapes via a reference that codegen
  85. // can materialize as a decoupled namespace object. When all exports
  86. // are statically known we keep them mangleable instead of marking
  87. // them used-in-unknown-way.
  88. if (
  89. this.mangleEscapingNamespaces &&
  90. module.buildMeta &&
  91. module.buildMeta.exportsType === "namespace" &&
  92. exportsInfo.otherExportsInfo.provided === false
  93. ) {
  94. let changed = exportsInfo.setAllKnownExportsUsed(runtime);
  95. // The whole namespace object is observed as a value, so the
  96. // module must stay a real ES module namespace at runtime
  97. // (keep __esModule / the namespace object, i.e. `r()`).
  98. if (
  99. exportsInfo
  100. .getExportInfo("__esModule")
  101. .setUsed(UsageState.Used, runtime)
  102. ) {
  103. changed = true;
  104. }
  105. // Exports must keep a real binding (not be inlined) so member
  106. // access on the namespace has ES namespace semantics, e.g.
  107. // `delete ns.x` hits a non-configurable property and throws.
  108. for (const exportInfo of exportsInfo.ownedExports) {
  109. exportInfo.canInlineUse = false;
  110. }
  111. if (changed) {
  112. queue.enqueue(module, runtime);
  113. }
  114. } else if (exportsInfo.setUsedInUnknownWay(runtime)) {
  115. queue.enqueue(module, runtime);
  116. }
  117. return;
  118. }
  119. if (usedExports.length > 0) {
  120. if (!module.buildMeta || !module.buildMeta.exportsType) {
  121. if (exportsInfo.setUsedWithoutInfo(runtime)) {
  122. queue.enqueue(module, runtime);
  123. }
  124. return;
  125. }
  126. for (const usedExportInfo of usedExports) {
  127. /** @type {string[]} */
  128. let usedExport;
  129. let canMangle = true;
  130. let canInline = true;
  131. if (Array.isArray(usedExportInfo)) {
  132. usedExport = usedExportInfo;
  133. } else {
  134. usedExport = usedExportInfo.name;
  135. canMangle = usedExportInfo.canMangle !== false;
  136. canInline = usedExportInfo.canInline !== false;
  137. }
  138. if (usedExport.length === 0) {
  139. if (exportsInfo.setUsedInUnknownWay(runtime)) {
  140. queue.enqueue(module, runtime);
  141. }
  142. } else {
  143. let currentExportsInfo = exportsInfo;
  144. for (let i = 0; i < usedExport.length; i++) {
  145. const exportInfo = currentExportsInfo.getExportInfo(
  146. usedExport[i]
  147. );
  148. if (canMangle === false) {
  149. exportInfo.canMangleUse = false;
  150. }
  151. if (exportInfo.canInlineUse === undefined) {
  152. exportInfo.canInlineUse = canInline;
  153. } else if (!canInline) {
  154. exportInfo.canInlineUse = false;
  155. }
  156. const lastOne = i === usedExport.length - 1;
  157. if (!lastOne) {
  158. const nestedInfo = exportInfo.getNestedExportsInfo();
  159. if (nestedInfo) {
  160. if (
  161. exportInfo.setUsedConditionally(
  162. IS_UNUSED,
  163. UsageState.OnlyPropertiesUsed,
  164. runtime
  165. )
  166. ) {
  167. const currentModule =
  168. currentExportsInfo === exportsInfo
  169. ? module
  170. : exportInfoToModuleMap.get(currentExportsInfo);
  171. if (currentModule) {
  172. queue.enqueue(currentModule, runtime);
  173. }
  174. }
  175. currentExportsInfo = nestedInfo;
  176. continue;
  177. }
  178. }
  179. if (
  180. exportInfo.setUsedConditionally(
  181. IS_NOT_USED,
  182. UsageState.Used,
  183. runtime
  184. )
  185. ) {
  186. const currentModule =
  187. currentExportsInfo === exportsInfo
  188. ? module
  189. : exportInfoToModuleMap.get(currentExportsInfo);
  190. if (currentModule) {
  191. queue.enqueue(currentModule, runtime);
  192. }
  193. }
  194. break;
  195. }
  196. }
  197. }
  198. } else if (
  199. module.factoryMeta !== undefined &&
  200. module.factoryMeta.sideEffectFree
  201. ) {
  202. // Nothing is used and the module has no side effects, so it is
  203. // not used for them either. An active connection still evaluates
  204. // it, so keep walking it to count the references it makes itself.
  205. if (walkedSideEffectFreeModules === undefined) {
  206. walkedSideEffectFreeModules = new TupleSet();
  207. }
  208. if (!walkedSideEffectFreeModules.has(module, runtime)) {
  209. walkedSideEffectFreeModules.add(module, runtime);
  210. queue.enqueue(module, runtime);
  211. }
  212. } else if (exportsInfo.setUsedForSideEffectsOnly(runtime)) {
  213. queue.enqueue(module, runtime);
  214. }
  215. };
  216. /**
  217. * Processes the provided module.
  218. * @param {DependenciesBlock} module the module
  219. * @param {RuntimeSpec} runtime part of which runtime
  220. * @returns {void}
  221. */
  222. const processModule = (module, runtime) => {
  223. /** @typedef {Map<string, string[] | ReferencedExport>} ExportMaps */
  224. /** @type {Map<Module, ReferencedExports | ExportMaps>} */
  225. const map = new Map();
  226. // Modules whose whole namespace object escapes in a mangleable way.
  227. // Tracked separately so specific member references are still merged
  228. // (and marked used) instead of being dropped by the escape marker.
  229. // Lazily allocated — usually empty.
  230. /** @type {Set<Module> | undefined} */
  231. let mangleableEscapeModules;
  232. /** @type {ArrayQueue<DependenciesBlock>} */
  233. const queue = new ArrayQueue();
  234. queue.enqueue(module);
  235. for (;;) {
  236. const block = queue.dequeue();
  237. if (block === undefined) break;
  238. for (const b of block.blocks) {
  239. if (b.groupOptions && b.groupOptions.entryOptions) {
  240. processModule(
  241. b,
  242. this.global
  243. ? undefined
  244. : b.groupOptions.entryOptions.runtime || undefined
  245. );
  246. } else {
  247. queue.enqueue(b);
  248. }
  249. }
  250. for (const dep of block.dependencies) {
  251. const connection = moduleGraph.getConnection(dep);
  252. if (!connection || !connection.module) {
  253. continue;
  254. }
  255. const activeState = connection.getActiveState(runtime);
  256. if (activeState === false) continue;
  257. const { module } = connection;
  258. if (activeState === ModuleGraphConnection.TRANSITIVE_ONLY) {
  259. processModule(module, runtime);
  260. continue;
  261. }
  262. const oldReferencedExports = map.get(module);
  263. if (oldReferencedExports === EXPORTS_OBJECT_REFERENCED) {
  264. continue;
  265. }
  266. const referencedExports =
  267. compilation.getDependencyReferencedExports(dep, runtime);
  268. // The non-mangleable whole-object reference is the most
  269. // conservative result and always wins.
  270. if (referencedExports === EXPORTS_OBJECT_REFERENCED) {
  271. map.set(module, EXPORTS_OBJECT_REFERENCED);
  272. if (mangleableEscapeModules) {
  273. mangleableEscapeModules.delete(module);
  274. }
  275. continue;
  276. }
  277. // A mangleable whole-object escape keeps the module's exports
  278. // mangleable (applied after the merge). Unlike the conservative
  279. // marker it must not drop specific member references: those still
  280. // need their own (possibly non-existent) export marked used so
  281. // they render as a qualified access, not a bare `undefined`.
  282. if (
  283. referencedExports === EXPORTS_OBJECT_REFERENCED_MANGLEABLE
  284. ) {
  285. if (mangleableEscapeModules === undefined) {
  286. mangleableEscapeModules = new Set();
  287. }
  288. mangleableEscapeModules.add(module);
  289. continue;
  290. }
  291. if (
  292. oldReferencedExports === undefined ||
  293. oldReferencedExports === NO_EXPORTS_REFERENCED
  294. ) {
  295. map.set(module, referencedExports);
  296. } else if (
  297. oldReferencedExports !== undefined &&
  298. referencedExports === NO_EXPORTS_REFERENCED
  299. ) {
  300. continue;
  301. } else {
  302. /** @type {undefined | ExportMaps} */
  303. let exportsMap;
  304. if (Array.isArray(oldReferencedExports)) {
  305. exportsMap = new Map();
  306. for (const item of oldReferencedExports) {
  307. if (Array.isArray(item)) {
  308. exportsMap.set(item.join("\n"), item);
  309. } else {
  310. exportsMap.set(item.name.join("\n"), item);
  311. }
  312. }
  313. map.set(module, exportsMap);
  314. } else {
  315. exportsMap = oldReferencedExports;
  316. }
  317. for (const item of referencedExports) {
  318. if (Array.isArray(item)) {
  319. const key = item.join("\n");
  320. const oldItem = exportsMap.get(key);
  321. if (oldItem === undefined) {
  322. exportsMap.set(key, item);
  323. }
  324. // if oldItem is already an array we have to do nothing
  325. // if oldItem is an ReferencedExport object, we don't have to do anything
  326. // as canMangle defaults to true for arrays
  327. } else {
  328. const key = item.name.join("\n");
  329. const oldItem = exportsMap.get(key);
  330. if (oldItem === undefined || Array.isArray(oldItem)) {
  331. exportsMap.set(key, item);
  332. } else {
  333. exportsMap.set(key, {
  334. name: item.name,
  335. canMangle: item.canMangle && oldItem.canMangle,
  336. canInline: item.canInline && oldItem.canInline
  337. });
  338. }
  339. }
  340. }
  341. }
  342. }
  343. }
  344. for (const [module, referencedExports] of map) {
  345. if (Array.isArray(referencedExports)) {
  346. processReferencedModule(module, referencedExports, runtime);
  347. } else {
  348. processReferencedModule(
  349. module,
  350. [...referencedExports.values()],
  351. runtime
  352. );
  353. }
  354. }
  355. if (mangleableEscapeModules) {
  356. for (const module of mangleableEscapeModules) {
  357. processReferencedModule(
  358. module,
  359. EXPORTS_OBJECT_REFERENCED_MANGLEABLE,
  360. runtime
  361. );
  362. }
  363. }
  364. };
  365. logger.time("initialize exports usage");
  366. for (const module of modules) {
  367. const exportsInfo = moduleGraph.getExportsInfo(module);
  368. exportInfoToModuleMap.set(exportsInfo, module);
  369. exportsInfo.setHasUseInfo();
  370. }
  371. logger.timeEnd("initialize exports usage");
  372. logger.time("trace exports usage in graph");
  373. /**
  374. * Process entry dependency.
  375. * @param {Dependency} dep dependency
  376. * @param {RuntimeSpec} runtime runtime
  377. */
  378. const processEntryDependency = (dep, runtime) => {
  379. const module = moduleGraph.getModule(dep);
  380. if (module) {
  381. processReferencedModule(module, NO_EXPORTS_REFERENCED, runtime);
  382. }
  383. };
  384. /** @type {RuntimeSpec} */
  385. let globalRuntime;
  386. for (const [
  387. entryName,
  388. { dependencies: deps, includeDependencies: includeDeps, options }
  389. ] of compilation.entries) {
  390. const runtime = this.global
  391. ? undefined
  392. : getEntryRuntime(compilation, entryName, options);
  393. for (const dep of deps) {
  394. processEntryDependency(dep, runtime);
  395. }
  396. for (const dep of includeDeps) {
  397. processEntryDependency(dep, runtime);
  398. }
  399. globalRuntime = mergeRuntimeOwned(globalRuntime, runtime);
  400. }
  401. for (const dep of compilation.globalEntry.dependencies) {
  402. processEntryDependency(dep, globalRuntime);
  403. }
  404. for (const dep of compilation.globalEntry.includeDependencies) {
  405. processEntryDependency(dep, globalRuntime);
  406. }
  407. while (queue.length) {
  408. const [module, runtime] = /** @type {[Module, RuntimeSpec]} */ (
  409. queue.dequeue()
  410. );
  411. processModule(module, runtime);
  412. }
  413. logger.timeEnd("trace exports usage in graph");
  414. }
  415. );
  416. });
  417. }
  418. }
  419. module.exports = FlagDependencyUsagePlugin;