SideEffectsFlagPlugin.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  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_DYNAMIC,
  9. JAVASCRIPT_MODULE_TYPE_ESM
  10. } = require("../ModuleTypeConstants");
  11. const { STAGE_DEFAULT } = require("../OptimizationStages");
  12. const HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency");
  13. const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency");
  14. const HarmonyImportSpecifierDependency = require("../dependencies/HarmonyImportSpecifierDependency");
  15. const { ImportPhaseUtils } = require("../dependencies/ImportPhase");
  16. const formatLocation = require("../util/formatLocation");
  17. const { dirname, join, readJson, relative } = require("../util/fs");
  18. const { getGlobToRegExpSource } = require("../util/globUtils");
  19. const {
  20. NODE_MODULES_REGEXP,
  21. WINDOWS_PATH_SEPARATOR_REGEXP,
  22. relativePathToRequest
  23. } = require("../util/identifier");
  24. const { CompilerHintNotationRegExp } = require("../util/magicComment");
  25. /**
  26. * @import {
  27. * MaybeNamedClassDeclaration,
  28. * MaybeNamedFunctionDeclaration,
  29. * ModuleDeclaration,
  30. * Statement,
  31. * CallExpression
  32. * } from "estree"
  33. */
  34. /** @import Compiler from "../Compiler" */
  35. /** @import Module, { BuildMeta } from "../Module" */
  36. /**
  37. * @import {
  38. * JavascriptModuleBuildInfo
  39. * } from "../javascript/JavascriptModule"
  40. */
  41. /** @import ModuleGraphConnection from "../ModuleGraphConnection" */
  42. /** @import { ExportInfo, TargetItemWithConnection } from "../ExportsInfo" */
  43. /** @import JavascriptParser, { Range } from "../javascript/JavascriptParser" */
  44. /** @import { InputFileSystem } from "../util/fs" */
  45. /** @import { CreateData, ResolveData } from "../NormalModuleFactory" */
  46. /**
  47. * @import {
  48. * JavascriptParserOptions
  49. * } from "../../declarations/WebpackOptions"
  50. */
  51. /**
  52. * Defines the export in module type used by this module.
  53. * @typedef {object} ExportInModule
  54. * @property {Module} module the module
  55. * @property {string} exportName the name of the export
  56. * @property {boolean} checked if the export is conditional
  57. */
  58. /** @typedef {NonNullable<CreateData["resourceResolveData"]>} ResourceResolveData */
  59. /** @typedef {string | boolean | string[] | undefined} SideEffectsFlagValue */
  60. /** @typedef {Map<string, RegExp>} CacheItem */
  61. /**
  62. * @typedef {object} ResolvedSideEffectsFlag
  63. * @property {SideEffectsFlagValue} sideEffects package.json sideEffects value
  64. * @property {string} relativePath path relative to the owning package root
  65. */
  66. /**
  67. * @typedef {object} OwningSideEffectsFlag
  68. * @property {SideEffectsFlagValue} sideEffects package.json sideEffects value
  69. * @property {string} packageRoot directory of the declaring package.json
  70. */
  71. /**
  72. * A finished ancestor walk, kept per descriptionFileRoot. The package.json
  73. * paths it consulted are replayed as dependencies for every module reusing it.
  74. * @typedef {object} OwningSideEffectsFlagWalk
  75. * @property {OwningSideEffectsFlag | null} owning declaring package, `null` when the walk found none
  76. * @property {string[]} read package.json files the walk read
  77. * @property {string[]} missing package.json files the walk did not find
  78. */
  79. /** @typedef {Map<string, OwningSideEffectsFlagWalk>} OwningSideEffectsFlagCache */
  80. /**
  81. * Whether a resolved re-export target is reached through an `import defer` edge.
  82. * Such edges must not be collapsed by the side-effect-free barrel optimization:
  83. * the source module has to keep being reached through the barrel's cached
  84. * deferred namespace so deferred-namespace identity and evaluation semantics are
  85. * preserved.
  86. * @param {ModuleGraphConnection | undefined} connection the target connection
  87. * @returns {boolean} true when the target connection is a deferred import
  88. */
  89. const isDeferredTargetConnection = (connection) =>
  90. connection !== undefined &&
  91. connection.dependency instanceof HarmonyImportDependency &&
  92. ImportPhaseUtils.isDefer(connection.dependency.phase);
  93. /** @type {WeakMap<Compiler, CacheItem>} */
  94. const globToRegexpCache = new WeakMap();
  95. /** @type {WeakMap<Compiler, OwningSideEffectsFlagCache>} */
  96. const owningSideEffectsFlagCache = new WeakMap();
  97. /** @type {WeakMap<Partial<CreateData>, ResolvedSideEffectsFlag>} */
  98. const resolvedSideEffectsFlags = new WeakMap();
  99. /**
  100. * Whether a failed ancestor package.json read means nothing is there, as
  101. * opposed to something being there that cannot be used.
  102. * @param {NodeJS.ErrnoException | SyntaxError | Error} err error from readJson
  103. * @returns {boolean} true when no file was found at that path
  104. */
  105. const isMissingPackageJsonError = (err) =>
  106. "code" in err && err.code === "ENOENT";
  107. /**
  108. * Returns a regular expression.
  109. * @param {string} glob the pattern
  110. * @param {CacheItem} cache the glob to RegExp cache
  111. * @returns {RegExp} a regular expression
  112. */
  113. const globToRegexp = (glob, cache) => {
  114. const cacheEntry = cache.get(glob);
  115. if (cacheEntry !== undefined) return cacheEntry;
  116. if (!glob.includes("/")) {
  117. glob = `**/${glob}`;
  118. }
  119. const regexpSource = getGlobToRegExpSource()(glob);
  120. const regexp = new RegExp(`^(\\./)?${regexpSource}$`);
  121. cache.set(glob, regexp);
  122. return regexp;
  123. };
  124. /**
  125. * @param {JavascriptParser} parser parser
  126. * @param {number} start start position
  127. * @param {number} end end position
  128. * @returns {boolean} if annotation is found in the range
  129. */
  130. const hasNoSideEffectsNotation = (parser, start, end) => {
  131. // Fast path
  132. if (end - start < 18) return false;
  133. const comments = parser.getComments([start, end]);
  134. return comments.some(
  135. (c) =>
  136. c.type === "Block" &&
  137. CompilerHintNotationRegExp.NoSideEffects.test(c.value)
  138. );
  139. };
  140. const PLUGIN_NAME = "SideEffectsFlagPlugin";
  141. const notSideEffectsTag = Symbol("NoSideEffects");
  142. /** @type {(target: { module: Module }) => boolean} */
  143. const RETURNS_FALSE = () => false;
  144. /**
  145. * Resolve sideEffects from the package that declares it, inheriting past a nested
  146. * package.json that declares none. Globs are rebased on the declaring package root,
  147. * and each package.json the walk consults becomes a dependency of the resolve.
  148. * @param {InputFileSystem} fs file system
  149. * @param {ResolveData} resolveData resolve data
  150. * @param {string} descriptionFileRoot root directory of the nearest description file
  151. * @param {OwningSideEffectsFlagCache} owningCache walk cache keyed by descriptionFileRoot
  152. * @param {(result?: ResolvedSideEffectsFlag) => void} callback callback
  153. * @returns {void}
  154. */
  155. const resolveSideEffectsFlag = (
  156. fs,
  157. resolveData,
  158. descriptionFileRoot,
  159. owningCache,
  160. callback
  161. ) => {
  162. const resolveInfo = /** @type {ResourceResolveData} */ (
  163. resolveData.createData.resourceResolveData
  164. );
  165. const descriptionFileData =
  166. /** @type {NonNullable<ResourceResolveData["descriptionFileData"]>} */ (
  167. resolveInfo.descriptionFileData
  168. );
  169. const relativePath = /** @type {string} */ (resolveInfo.relativePath);
  170. if (descriptionFileData.sideEffects !== undefined) {
  171. return callback({
  172. sideEffects: /** @type {SideEffectsFlagValue} */ (
  173. descriptionFileData.sideEffects
  174. ),
  175. relativePath
  176. });
  177. }
  178. // Named package with no sideEffects: do not inherit from outside.
  179. if (descriptionFileData.name !== undefined) {
  180. return callback();
  181. }
  182. // Only inherit for a file living under node_modules; app-local nests keep shadowing.
  183. // Read the resolved path so a symlinked package flags all of its files alike.
  184. if (
  185. typeof resolveInfo.path !== "string" ||
  186. !NODE_MODULES_REGEXP.test(resolveInfo.path)
  187. ) {
  188. return callback();
  189. }
  190. // stays in descriptionFileRoot's space, which is the space packageRoot is found in
  191. const resourcePath = join(fs, descriptionFileRoot, relativePath);
  192. /**
  193. * @param {OwningSideEffectsFlagWalk} walk finished walk
  194. * @returns {void}
  195. */
  196. const finishFromWalk = (walk) => {
  197. for (const file of walk.read) resolveData.fileDependencies.add(file);
  198. for (const file of walk.missing) resolveData.missingDependencies.add(file);
  199. const owning = walk.owning;
  200. if (owning === null) return callback();
  201. const ancestorRelative = relative(
  202. fs,
  203. owning.packageRoot,
  204. resourcePath
  205. ).replace(WINDOWS_PATH_SEPARATOR_REGEXP, "/");
  206. return callback({
  207. sideEffects: owning.sideEffects,
  208. relativePath: relativePathToRequest(ancestorRelative)
  209. });
  210. };
  211. const cached = owningCache.get(descriptionFileRoot);
  212. if (cached !== undefined) {
  213. return finishFromWalk(cached);
  214. }
  215. /** @type {string[]} */
  216. const read = [];
  217. /** @type {string[]} */
  218. const missing = [];
  219. /**
  220. * @param {OwningSideEffectsFlag | null} owning declaring package or null
  221. * @returns {void}
  222. */
  223. const done = (owning) => {
  224. /** @type {OwningSideEffectsFlagWalk} */
  225. const walk = { owning, read, missing };
  226. owningCache.set(descriptionFileRoot, walk);
  227. return finishFromWalk(walk);
  228. };
  229. let dir = dirname(fs, descriptionFileRoot);
  230. const next = () => {
  231. const parent = dirname(fs, dir);
  232. if (!parent || parent === dir) return done(null);
  233. const baseName = relative(fs, parent, dir).replace(
  234. WINDOWS_PATH_SEPARATOR_REGEXP,
  235. "/"
  236. );
  237. // Do not inherit an application's sideEffects across an install boundary.
  238. if (baseName === "node_modules") return done(null);
  239. const packageJsonPath = join(fs, dir, "package.json");
  240. readJson(fs, packageJsonPath, (err, data) => {
  241. if (err) {
  242. if (!isMissingPackageJsonError(err)) {
  243. // it is there but unreadable, so what it declares is unknown:
  244. // decline rather than let an outer flag speak for it
  245. read.push(packageJsonPath);
  246. return done(null);
  247. }
  248. missing.push(packageJsonPath);
  249. dir = parent;
  250. return next();
  251. }
  252. read.push(packageJsonPath);
  253. if (!data || typeof data !== "object" || Array.isArray(data)) {
  254. dir = parent;
  255. return next();
  256. }
  257. if (data.sideEffects !== undefined) {
  258. return done({
  259. sideEffects: /** @type {SideEffectsFlagValue} */ (data.sideEffects),
  260. packageRoot: dir
  261. });
  262. }
  263. // An unnamed manifest deeper in the package keeps the walk going; a named one
  264. // is a package of its own, and its silence is its answer.
  265. if (data.name !== undefined) return done(null);
  266. dir = parent;
  267. next();
  268. });
  269. };
  270. next();
  271. };
  272. /**
  273. * Detects if the module is "pure single-star passthrough": one whose entire export
  274. * surface is exactly one `export * from "x"` (no named/local/default-bearing
  275. * exports, no second star). For such a module `export * from "passthrough"` is
  276. * equivalent to `export * from "x"`, so the passthrough can be skipped.
  277. * @param {Module} module the candidate passthrough module
  278. * @returns {boolean} true when the module is a pure single-star passthrough
  279. */
  280. const moduleHasSingleStarReexport = (module) => {
  281. /** @type {HarmonyExportImportedSpecifierDependency | undefined} */
  282. let starReexportDep;
  283. for (const dep of module.dependencies) {
  284. if (!(dep instanceof HarmonyExportImportedSpecifierDependency)) continue;
  285. // a named re-export (`export { x } from` / `export * as ns from`) means
  286. // the module owns names a star into its source wouldn't reproduce
  287. if (dep.name !== null) return false;
  288. // any named/local export populates the shared activeExports set
  289. if (dep.activeExports.size !== 0) return false;
  290. // more than one `export *` can't be collapsed to a single source
  291. if (dep.allStarExports && dep.allStarExports.dependencies.length !== 1) {
  292. return false;
  293. }
  294. starReexportDep = dep;
  295. }
  296. if (starReexportDep === undefined) return false;
  297. return true;
  298. };
  299. class SideEffectsFlagPlugin {
  300. /**
  301. * Creates an instance of SideEffectsFlagPlugin.
  302. * @param {boolean} analyseSource analyse source code for side effects
  303. */
  304. constructor(analyseSource = true) {
  305. /** @type {boolean} */
  306. this._analyseSource = analyseSource;
  307. }
  308. /**
  309. * Applies the plugin by registering its hooks on the compiler.
  310. * @param {Compiler} compiler the compiler instance
  311. * @returns {void}
  312. */
  313. apply(compiler) {
  314. let cache = globToRegexpCache.get(compiler.root);
  315. if (cache === undefined) {
  316. cache = new Map();
  317. globToRegexpCache.set(compiler.root, cache);
  318. }
  319. let owningCache = owningSideEffectsFlagCache.get(compiler.root);
  320. if (owningCache === undefined) {
  321. owningCache = new Map();
  322. owningSideEffectsFlagCache.set(compiler.root, owningCache);
  323. }
  324. compiler.hooks.compilation.tap(
  325. PLUGIN_NAME,
  326. (compilation, { normalModuleFactory }) => {
  327. const moduleGraph = compilation.moduleGraph;
  328. normalModuleFactory.hooks.afterResolve.tapAsync(
  329. PLUGIN_NAME,
  330. (resolveData, callback) => {
  331. const inputFileSystem = compiler.inputFileSystem;
  332. if (!inputFileSystem) return callback();
  333. const { createData } = resolveData;
  334. const resolveInfo = createData.resourceResolveData;
  335. if (
  336. !resolveInfo ||
  337. !resolveInfo.descriptionFileData ||
  338. !resolveInfo.relativePath
  339. ) {
  340. return callback();
  341. }
  342. const descriptionFileRoot =
  343. resolveInfo.descriptionFileRoot ||
  344. (resolveInfo.descriptionFilePath
  345. ? dirname(inputFileSystem, resolveInfo.descriptionFilePath)
  346. : undefined);
  347. if (descriptionFileRoot === undefined) return callback();
  348. resolveSideEffectsFlag(
  349. inputFileSystem,
  350. resolveData,
  351. descriptionFileRoot,
  352. owningCache,
  353. (resolved) => {
  354. if (resolved !== undefined) {
  355. resolvedSideEffectsFlags.set(createData, resolved);
  356. }
  357. callback();
  358. }
  359. );
  360. }
  361. );
  362. normalModuleFactory.hooks.module.tap(PLUGIN_NAME, (module, data) => {
  363. const resolved = resolvedSideEffectsFlags.get(data);
  364. if (resolved !== undefined) {
  365. if (module.factoryMeta === undefined) {
  366. module.factoryMeta = {};
  367. }
  368. const hasSideEffects = SideEffectsFlagPlugin.moduleHasSideEffects(
  369. resolved.relativePath,
  370. resolved.sideEffects,
  371. /** @type {CacheItem} */ (cache)
  372. );
  373. module.factoryMeta.sideEffectFree = !hasSideEffects;
  374. }
  375. return module;
  376. });
  377. normalModuleFactory.hooks.module.tap(PLUGIN_NAME, (module, data) => {
  378. const settings = data.settings;
  379. if (typeof settings.sideEffects === "boolean") {
  380. if (module.factoryMeta === undefined) {
  381. module.factoryMeta = {};
  382. }
  383. module.factoryMeta.sideEffectFree = !settings.sideEffects;
  384. }
  385. return module;
  386. });
  387. if (this._analyseSource) {
  388. /**
  389. * Processes the provided parser.
  390. * @param {JavascriptParser} parser the parser
  391. * @returns {void}
  392. */
  393. const applySideEffectsStmtHandler = (parser) => {
  394. /** @type {undefined | Statement | ModuleDeclaration | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} */
  395. let sideEffectsStatement;
  396. parser.hooks.program.tap(PLUGIN_NAME, () => {
  397. sideEffectsStatement = undefined;
  398. });
  399. parser.hooks.statement.tap(
  400. { name: PLUGIN_NAME, stage: -100 },
  401. (statement) => {
  402. if (sideEffectsStatement) return;
  403. if (parser.scope.topLevelScope !== true) return;
  404. switch (statement.type) {
  405. case "ExpressionStatement":
  406. if (
  407. !parser.isPure(
  408. statement.expression,
  409. /** @type {Range} */
  410. (statement.range)[0]
  411. )
  412. ) {
  413. sideEffectsStatement = statement;
  414. }
  415. break;
  416. case "IfStatement":
  417. case "WhileStatement":
  418. case "DoWhileStatement":
  419. if (
  420. !parser.isPure(
  421. statement.test,
  422. /** @type {Range} */
  423. (statement.range)[0]
  424. )
  425. ) {
  426. sideEffectsStatement = statement;
  427. }
  428. // statement hook will be called for child statements too
  429. break;
  430. case "ForStatement":
  431. if (
  432. !parser.isPure(
  433. statement.init,
  434. /** @type {Range} */ (statement.range)[0]
  435. ) ||
  436. !parser.isPure(
  437. statement.test,
  438. statement.init
  439. ? /** @type {Range} */ (statement.init.range)[1]
  440. : /** @type {Range} */ (statement.range)[0]
  441. ) ||
  442. !parser.isPure(
  443. statement.update,
  444. statement.test
  445. ? /** @type {Range} */ (statement.test.range)[1]
  446. : statement.init
  447. ? /** @type {Range} */ (statement.init.range)[1]
  448. : /** @type {Range} */ (statement.range)[0]
  449. )
  450. ) {
  451. sideEffectsStatement = statement;
  452. }
  453. // statement hook will be called for child statements too
  454. break;
  455. case "SwitchStatement":
  456. if (
  457. !parser.isPure(
  458. statement.discriminant,
  459. /** @type {Range} */
  460. (statement.range)[0]
  461. )
  462. ) {
  463. sideEffectsStatement = statement;
  464. }
  465. // statement hook will be called for child statements too
  466. break;
  467. case "VariableDeclaration":
  468. case "ClassDeclaration":
  469. case "FunctionDeclaration":
  470. if (
  471. !parser.isPure(
  472. statement,
  473. /** @type {Range} */ (statement.range)[0]
  474. )
  475. ) {
  476. sideEffectsStatement = statement;
  477. }
  478. break;
  479. case "ExportNamedDeclaration":
  480. case "ExportDefaultDeclaration":
  481. if (
  482. !parser.isPure(
  483. statement.declaration,
  484. /** @type {Range} */
  485. (statement.range)[0]
  486. )
  487. ) {
  488. sideEffectsStatement = statement;
  489. }
  490. break;
  491. case "LabeledStatement":
  492. case "BlockStatement":
  493. // statement hook will be called for child statements too
  494. break;
  495. case "EmptyStatement":
  496. break;
  497. case "ExportAllDeclaration":
  498. case "ImportDeclaration":
  499. // imports will be handled by the dependencies
  500. break;
  501. default:
  502. sideEffectsStatement = statement;
  503. break;
  504. }
  505. }
  506. );
  507. parser.hooks.finish.tap(PLUGIN_NAME, () => {
  508. if (sideEffectsStatement === undefined) {
  509. /** @type {BuildMeta} */
  510. (parser.state.module.buildMeta).sideEffectFree = true;
  511. } else {
  512. const type = sideEffectsStatement.type;
  513. const loc = parser.getLocation(sideEffectsStatement);
  514. moduleGraph
  515. .getOptimizationBailout(parser.state.module)
  516. .push(
  517. () =>
  518. `Statement (${type}) with side effects in source code at ${formatLocation(
  519. loc
  520. )}`
  521. );
  522. }
  523. });
  524. };
  525. /**
  526. * @param {JavascriptParser} parser the parser
  527. * @param {JavascriptParserOptions} parserOptions the parser options
  528. * @returns {void}
  529. */
  530. const applyNoSideEffectsNotationHandler = (parser, parserOptions) => {
  531. /** @type {Set<string> | undefined} */
  532. let pureFunctions;
  533. const pureFunctionsFromOption =
  534. parserOptions &&
  535. Array.isArray(parserOptions.pureFunctions) &&
  536. parserOptions.pureFunctions.length > 0
  537. ? new Set(parserOptions.pureFunctions)
  538. : undefined;
  539. parser.hooks.program.tap(PLUGIN_NAME, () => {
  540. pureFunctions = undefined;
  541. });
  542. /**
  543. * @param {string} name function name
  544. */
  545. const markPure = (name) => {
  546. if (pureFunctions === undefined) pureFunctions = new Set();
  547. else if (pureFunctions.has(name)) return;
  548. parser.tagVariable(name, notSideEffectsTag, {});
  549. pureFunctions.add(name);
  550. };
  551. // Detect on function declarations
  552. // Covers:
  553. // 1. function foo
  554. // 2. export function foo
  555. // 3. export default function foo
  556. // 4. export default function / export default () => {} (anonymous)
  557. parser.hooks.preStatementByType
  558. .for("FunctionDeclaration")
  559. .tap(PLUGIN_NAME, (statement) => {
  560. if (parser.scope.topLevelScope !== true) return;
  561. if (statement.type !== "FunctionDeclaration") {
  562. return;
  563. }
  564. const name = statement.id ? statement.id.name : "default";
  565. if (
  566. pureFunctionsFromOption &&
  567. pureFunctionsFromOption.has(name)
  568. ) {
  569. markPure(name);
  570. return;
  571. }
  572. const commentsStart = parser.prevStatement
  573. ? /** @type {Range} */ (parser.prevStatement.range)[1]
  574. : 0;
  575. if (
  576. hasNoSideEffectsNotation(
  577. parser,
  578. commentsStart,
  579. /** @type {Range} */ (statement.range)[0]
  580. )
  581. ) {
  582. markPure(name);
  583. }
  584. });
  585. // Detect on variable declarations with function init
  586. parser.hooks.preDeclarator.tap(PLUGIN_NAME, (decl, statement) => {
  587. if (parser.scope.topLevelScope !== true) return;
  588. if (decl.id.type !== "Identifier") return;
  589. if (
  590. pureFunctionsFromOption &&
  591. pureFunctionsFromOption.has(decl.id.name)
  592. ) {
  593. markPure(decl.id.name);
  594. return;
  595. }
  596. if (!decl.init) return;
  597. if (!decl.init.type.endsWith("FunctionExpression")) return;
  598. let hasAnnotation = false;
  599. // Before the VariableDeclaration (only for const)
  600. if (statement.kind === "const") {
  601. const commentsStart = parser.prevStatement
  602. ? /** @type {Range} */ (parser.prevStatement.range)[1]
  603. : 0;
  604. hasAnnotation = hasNoSideEffectsNotation(
  605. parser,
  606. commentsStart,
  607. /** @type {Range} */ (statement.range)[0]
  608. );
  609. }
  610. if (!hasAnnotation) {
  611. hasAnnotation = hasNoSideEffectsNotation(
  612. parser,
  613. /** @type {Range} */ (decl.id.range)[1],
  614. /** @type {Range} */ (decl.init.range)[0]
  615. );
  616. }
  617. if (hasAnnotation) {
  618. markPure(decl.id.name);
  619. }
  620. });
  621. if (pureFunctionsFromOption) {
  622. parser.hooks.blockPreStatementByType
  623. .for("ExportDefaultDeclaration")
  624. .tap(PLUGIN_NAME, (statement) => {
  625. if (parser.scope.topLevelScope !== true) return;
  626. if (
  627. statement.type === "ExportDefaultDeclaration" &&
  628. pureFunctionsFromOption.has("default")
  629. ) {
  630. const decl = statement.declaration;
  631. if (
  632. decl.type === "ArrowFunctionExpression" ||
  633. decl.type === "FunctionExpression"
  634. ) {
  635. markPure("default");
  636. }
  637. }
  638. });
  639. }
  640. parser.hooks.isPure
  641. .for("CallExpression")
  642. .tap(PLUGIN_NAME, (expression, commentsStartPos) => {
  643. const expr = /** @type {CallExpression} */ (expression);
  644. if (expr.callee.type !== "Identifier") return;
  645. if (!parser.getTagData(expr.callee.name, notSideEffectsTag)) {
  646. return;
  647. }
  648. commentsStartPos = /** @type {Range} */ (expr.callee.range)[1];
  649. return expr.arguments.every((arg) => {
  650. if (arg.type === "SpreadElement") return false;
  651. const pure = parser.isPure(arg, commentsStartPos);
  652. commentsStartPos = /** @type {Range} */ (arg.range)[1];
  653. return pure;
  654. });
  655. });
  656. parser.hooks.finish.tap(PLUGIN_NAME, () => {
  657. if (pureFunctions === undefined || pureFunctions.size === 0) {
  658. return;
  659. }
  660. const buildInfo = /** @type {JavascriptModuleBuildInfo} */ (
  661. parser.state.module.buildInfo
  662. );
  663. if (buildInfo.pureFunctions) {
  664. for (const fn of pureFunctions) {
  665. buildInfo.pureFunctions.add(fn);
  666. }
  667. } else {
  668. buildInfo.pureFunctions = pureFunctions;
  669. }
  670. });
  671. };
  672. for (const key of [
  673. JAVASCRIPT_MODULE_TYPE_AUTO,
  674. JAVASCRIPT_MODULE_TYPE_ESM,
  675. JAVASCRIPT_MODULE_TYPE_DYNAMIC
  676. ]) {
  677. normalModuleFactory.hooks.parser
  678. .for(key)
  679. .tap(PLUGIN_NAME, (parser, parserOptions) => {
  680. applyNoSideEffectsNotationHandler(parser, parserOptions);
  681. applySideEffectsStmtHandler(parser);
  682. });
  683. }
  684. }
  685. compilation.hooks.optimizeDependencies.tap(
  686. {
  687. name: PLUGIN_NAME,
  688. stage: STAGE_DEFAULT
  689. },
  690. (modules) => {
  691. const logger = compilation.getLogger(
  692. "webpack.SideEffectsFlagPlugin"
  693. );
  694. logger.time("update dependencies");
  695. /** @type {Set<Module>} */
  696. const optimizedModules = new Set();
  697. // Only defer builds must protect deferred re-export barrels;
  698. // skip the per-target check entirely otherwise.
  699. const deferEnabled =
  700. compilation.options.experiments.deferImport === true;
  701. // Re-export resolution is idempotent within a pass, so cache it
  702. // per export info: a shared barrel imported by many modules
  703. // resolves each name once instead of once per consumer.
  704. /** @type {Map<InstanceType<ExportInfo>, TargetItemWithConnection | null>} */
  705. const reexportTargetCache = new Map();
  706. // Dependencies don't change within the pass, so the passthrough
  707. // check is cached per module across all moveTarget filter calls.
  708. /** @type {Map<Module, boolean>} */
  709. const singleStarReexportCache = new Map();
  710. /**
  711. * Cached variant of moduleHasSingleStarReexport.
  712. * @param {Module} module the candidate passthrough module
  713. * @returns {boolean} true when the module is a pure single-star passthrough
  714. */
  715. const hasSingleStarReexport = (module) => {
  716. let result = singleStarReexportCache.get(module);
  717. if (result === undefined) {
  718. result = moduleHasSingleStarReexport(module);
  719. singleStarReexportCache.set(module, result);
  720. }
  721. return result;
  722. };
  723. /**
  724. * Optimize incoming connections.
  725. * @param {Module} module module
  726. */
  727. const optimizeIncomingConnections = (module) => {
  728. if (optimizedModules.has(module)) return;
  729. optimizedModules.add(module);
  730. if (module.getSideEffectsConnectionState(moduleGraph) === false) {
  731. const exportsInfo = moduleGraph.getExportsInfo(module);
  732. for (const connection of moduleGraph.getIncomingConnections(
  733. module
  734. )) {
  735. const dep = connection.dependency;
  736. /** @type {boolean} */
  737. let isReexport;
  738. if (
  739. (isReexport =
  740. dep instanceof
  741. HarmonyExportImportedSpecifierDependency) ||
  742. (dep instanceof HarmonyImportSpecifierDependency &&
  743. !dep.namespaceObjectAsContext)
  744. ) {
  745. if (connection.originModule !== null) {
  746. optimizeIncomingConnections(connection.originModule);
  747. }
  748. if (isReexport) {
  749. if (!dep.name && !hasSingleStarReexport(module)) continue;
  750. const infos = dep.name
  751. ? // Named re-exports resolve their single target here;
  752. // e.g. `export * as foo from "mod"` / `export { dep as name } from "mod"`
  753. [
  754. moduleGraph.getExportInfo(
  755. /** @type {Module} */ (connection.originModule),
  756. dep.name
  757. )
  758. ]
  759. : moduleGraph.getExportsInfo(
  760. /** @type {Module} */ (connection.originModule)
  761. ).exports;
  762. for (const exportInfo of infos) {
  763. const immediate = exportInfo.getTarget(
  764. moduleGraph,
  765. RETURNS_FALSE
  766. );
  767. if (
  768. immediate === undefined ||
  769. immediate.connection.dependency !== dep
  770. ) {
  771. continue;
  772. }
  773. exportInfo.moveTarget(
  774. moduleGraph,
  775. (candidate) =>
  776. candidate.module.getSideEffectsConnectionState(
  777. moduleGraph
  778. ) === false &&
  779. // Keep a deferred re-export's barrel (see below).
  780. (!deferEnabled ||
  781. !isDeferredTargetConnection(
  782. candidate.connection
  783. )) &&
  784. (Boolean(dep.name) ||
  785. hasSingleStarReexport(
  786. /** @type {Module} */ (candidate.module)
  787. )),
  788. ({
  789. module: newModule,
  790. export: exportName,
  791. connection: targetConnection
  792. }) => {
  793. moduleGraph.updateModule(dep, newModule);
  794. moduleGraph.updateParent(
  795. dep,
  796. targetConnection,
  797. /** @type {Module} */ (connection.originModule)
  798. );
  799. moduleGraph.addExplanation(
  800. dep,
  801. "(skipped side-effect-free modules)"
  802. );
  803. const ids = dep.getIds(moduleGraph);
  804. if (ids.length) {
  805. dep.setIds(
  806. moduleGraph,
  807. exportName
  808. ? [...exportName, ...ids.slice(1)]
  809. : ids.slice(1)
  810. );
  811. }
  812. return /** @type {ModuleGraphConnection} */ (
  813. moduleGraph.getConnection(dep)
  814. );
  815. }
  816. );
  817. }
  818. continue;
  819. }
  820. const ids = dep.getIds(moduleGraph);
  821. if (ids.length > 0) {
  822. const exportInfo = exportsInfo.getExportInfo(ids[0]);
  823. let target = reexportTargetCache.get(exportInfo);
  824. if (target === undefined) {
  825. target =
  826. exportInfo.getTarget(
  827. moduleGraph,
  828. ({ module }) =>
  829. module.getSideEffectsConnectionState(
  830. moduleGraph
  831. ) === false
  832. ) || null;
  833. reexportTargetCache.set(exportInfo, target);
  834. }
  835. if (!target) continue;
  836. // A deferred re-export must keep its side-effect-free
  837. // barrel: collapsing it here would turn the cached
  838. // deferred namespace (`.z`) into an eager import of the
  839. // source module, breaking deferred-namespace identity
  840. // and evaluation semantics.
  841. if (
  842. deferEnabled &&
  843. isDeferredTargetConnection(target.connection)
  844. ) {
  845. continue;
  846. }
  847. moduleGraph.updateModule(dep, target.module);
  848. moduleGraph.updateParent(
  849. dep,
  850. /** @type {ModuleGraphConnection} */ (
  851. target.connection
  852. ),
  853. /** @type {Module} */ (connection.originModule)
  854. );
  855. moduleGraph.addExplanation(
  856. dep,
  857. "(skipped side-effect-free modules)"
  858. );
  859. dep.setIds(
  860. moduleGraph,
  861. target.export
  862. ? [...target.export, ...ids.slice(1)]
  863. : ids.slice(1)
  864. );
  865. }
  866. }
  867. }
  868. }
  869. };
  870. for (const module of modules) {
  871. optimizeIncomingConnections(module);
  872. }
  873. moduleGraph.finishUpdateParent();
  874. logger.timeEnd("update dependencies");
  875. }
  876. );
  877. }
  878. );
  879. }
  880. /**
  881. * Module has side effects.
  882. * @param {string} moduleName the module name
  883. * @param {SideEffectsFlagValue} flagValue the flag value
  884. * @param {CacheItem} cache cache for glob to regexp
  885. * @returns {boolean | undefined} true, when the module has side effects, undefined or false when not
  886. */
  887. static moduleHasSideEffects(moduleName, flagValue, cache) {
  888. switch (typeof flagValue) {
  889. case "undefined":
  890. return true;
  891. case "boolean":
  892. return flagValue;
  893. case "string":
  894. return globToRegexp(flagValue, cache).test(moduleName);
  895. case "object":
  896. return flagValue.some((glob) =>
  897. SideEffectsFlagPlugin.moduleHasSideEffects(moduleName, glob, cache)
  898. );
  899. }
  900. }
  901. }
  902. module.exports = SideEffectsFlagPlugin;