GeezerVison is showing github.com — feat: support `#__NO_SIDE_EFFECTS__` annotation by hai-x · Pull Request #20775 · webpack/webpack
feat: support #__NO_SIDE_EFFECTS__ annotation
#20775
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.js
(9)
.md
(1)
.ts
(1)
All 3 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,5 @@
---
"webpack": minor
---
Support the `#__NO_SIDE_EFFECTS__` annotation to mark functions as pure for better tree-shaking.
Original file line number
Diff line number
Diff line change
Expand Up
@@ -13,6 +13,7 @@ const Parser = require("../Parser");
const StackedMap = require("../util/StackedMap");
const binarySearchBounds = require("../util/binarySearchBounds");
const {
CompilerHintNotationRegExp,
createMagicCommentContext,
webpackCommentRegExp
} = require("../util/magicComment");
Expand Down
Expand Up
@@ -584,7 +585,7 @@ class JavascriptParser extends Parser {
"exportName",
"index"
]),
/** @type {SyncBailHook<[VariableDeclarator, Statement ], boolean | void>} */
/** @type {SyncBailHook<[VariableDeclarator, VariableDeclaration ], boolean | void>} */
preDeclarator: new SyncBailHook(["declarator", "statement"]),
/** @type {SyncBailHook<[VariableDeclarator, Statement], boolean | void>} */
declarator: new SyncBailHook(["declarator", "statement"]),
Expand Down
Expand Up
@@ -1584,8 +1585,8 @@ class JavascriptParser extends Parser {
)
);
this.hooks.evaluate.for("CallExpression").tap(CLASS_NAME, (_expr ) => {
const expr = /** @type {CallExpression} */ (_expr );
this.hooks.evaluate.for("CallExpression").tap(CLASS_NAME, (expression ) => {
const expr = /** @type {CallExpression} */ (expression );
if (
expr.callee.type === "MemberExpression" &&
expr.callee.property.type ===
Expand Down
Expand Up
@@ -4908,6 +4909,7 @@ class JavascriptParser extends Parser {
this.destructuringAssignmentProperties = new WeakMap();
this.detectMode(ast.body);
this.modulePreWalkStatements(ast.body);
this.prevStatement = undefined;
Comment thread
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more .
do we need it here right?
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more .
Yeah, it's one bug fix. When we enter parsing for an import/export statement of module, prevStatement will be assigned, but currently it's never cleared then. This causes incorrect behavior in anything that relies on prevStatement at preWalk stage.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
alexander-akait reacted with thumbs up emoji
this.preWalkStatements(ast.body);
this.prevStatement = undefined;
this.blockPreWalkStatements(ast.body);
Expand Down
Expand Up
@@ -5060,7 +5062,7 @@ class JavascriptParser extends Parser {
]).some(
(comment) =>
comment.type === "Block" &&
/^\s*(?:#|@)__PURE__\s*$/ .test(comment.value)
CompilerHintNotationRegExp.Pure .test(comment.value)
);
if (!pureFlag) return false;
commentsStartPos = /** @type {Range} */ (expr.callee.range)[1];
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -145,7 +145,7 @@ module.exports.getDependencyUsedByExportsCondition = (
/** @type {Module} */
(moduleGraph.getParentModule(dependency));
const exportsInfo = moduleGraph.getExportsInfo(selfModule);
return (connections , runtime) => {
return (_connections , runtime) => {
for (const exportName of usedByExports) {
if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) {
return true;
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -15,11 +15,13 @@ const { STAGE_DEFAULT } = require("../OptimizationStages");
const HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency");
const HarmonyImportSpecifierDependency = require("../dependencies/HarmonyImportSpecifierDependency");
const formatLocation = require("../formatLocation");
const { CompilerHintNotationRegExp } = require("../util/magicComment");
/** @typedef {import("estree").MaybeNamedClassDeclaration} MaybeNamedClassDeclaration */
/** @typedef {import("estree").MaybeNamedFunctionDeclaration} MaybeNamedFunctionDeclaration */
/** @typedef {import("estree").ModuleDeclaration} ModuleDeclaration */
/** @typedef {import("estree").Statement} Statement */
/** @typedef {import("estree").CallExpression} CallExpression */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("../Module")} Module */
Expand Down
Expand Up
@@ -63,6 +65,24 @@ const globToRegexp = (glob, cache) => {
return regexp;
};
/**
* @param {JavascriptParser} parser parser
* @param {number} start start position
* @param {number} end end position
* @returns {boolean} if annotation is found in the range
*/
const hasNoSideEffectsNotation = (parser, start, end) => {
// Fast path
if (end - start < 18) return false;
const comments = parser.getComments([start, end]);
return comments.some(
(c) =>
c.type === "Block" &&
CompilerHintNotationRegExp.NoSideEffects.test(c.value)
);
};
const PLUGIN_NAME = "SideEffectsFlagPlugin";
class SideEffectsFlagPlugin {
Expand Down
Expand Up
@@ -129,7 +149,7 @@ class SideEffectsFlagPlugin {
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
const parserHandler = (parser) => {
const applySideEffectsStmtHandler = (parser) => {
/** @type {undefined | Statement | ModuleDeclaration | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} */
let sideEffectsStatement;
parser.hooks.program.tap(PLUGIN_NAME, () => {
Expand Down
Expand Up
@@ -260,14 +280,102 @@ class SideEffectsFlagPlugin {
}
});
};
/**
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
const applyNoSideEffectsNotationHandler = (parser) => {
/** @type {Set<string>} */
let noSideEffectsFnNames;
parser.hooks.program.tap(PLUGIN_NAME, () => {
noSideEffectsFnNames = new Set();
});
// Detect on function declarations
// Covers:
// 1. function foo
// 2. export function foo
// 3. export default function foo
parser.hooks.preStatement.tap(PLUGIN_NAME, (statement) => {
if (parser.scope.topLevelScope !== true) return;
if (statement.type !== "FunctionDeclaration" || !statement.id) {
return;
}
const commentsStart = parser.prevStatement
? /** @type {Range} */ (parser.prevStatement.range)[1]
: 0;
if (
hasNoSideEffectsNotation(
parser,
commentsStart,
/** @type {Range} */ (statement.range)[0]
)
) {
noSideEffectsFnNames.add(statement.id.name);
}
});
// Detect on variable declarations with function init
parser.hooks.preDeclarator.tap(PLUGIN_NAME, (decl, statement) => {
if (parser.scope.topLevelScope !== true) return;
if (!decl.init || decl.id.type !== "Identifier") return;
if (!decl.init.type.endsWith("FunctionExpression")) return;
let hasAnnotation = false;
// Before the VariableDeclaration (only for const)
if (statement.kind === "const") {
const commentsStart = parser.prevStatement
? /** @type {Range} */ (parser.prevStatement.range)[1]
: 0;
hasAnnotation = hasNoSideEffectsNotation(
parser,
commentsStart,
/** @type {Range} */ (statement.range)[0]
);
}
if (!hasAnnotation) {
hasAnnotation = hasNoSideEffectsNotation(
parser,
/** @type {Range} */ (decl.id.range)[1],
/** @type {Range} */ (decl.init.range)[0]
);
}
if (hasAnnotation) {
noSideEffectsFnNames.add(decl.id.name);
}
});
// Mark calls to annotated functions as pure
parser.hooks.isPure
.for("CallExpression")
.tap(PLUGIN_NAME, (expression, commentsStartPos) => {
const expr = /** @type {CallExpression} */ (expression);
if (expr.callee.type !== "Identifier") return;
if (!noSideEffectsFnNames.has(expr.callee.name)) return;
commentsStartPos = /** @type {Range} */ (expr.callee.range)[1];
for (const arg of expr.arguments) {
if (arg.type === "SpreadElement") return;
if (!parser.isPure(arg, commentsStartPos)) return;
commentsStartPos = /** @type {Range} */ (arg.range)[1];
}
return true;
});
};
for (const key of [
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_ESM,
JAVASCRIPT_MODULE_TYPE_DYNAMIC
]) {
normalModuleFactory.hooks.parser
.for(key)
.tap(PLUGIN_NAME, parserHandler);
.tap(PLUGIN_NAME, (parser) => {
applyNoSideEffectsNotationHandler(parser);
applySideEffectsStmtHandler(parser);
});
}
}
compilation.hooks.optimizeDependencies.tap(
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -9,18 +9,21 @@ const memoize = require("./memoize");
const getVm = memoize(() => require("vm"));
// regexp to match at least one "magic comment"
module.exports.CompilerHintNotationRegExp = Object.freeze({
Pure: /^\s*(?:#|@)__PURE__\s*$/,
NoSideEffects: /^\s*[#@]__NO_SIDE_EFFECTS__\s*$/
});
/**
* regexp to match at least one "magic comment"
* @returns {import("vm").Context} magic comment context
*/
module.exports.createMagicCommentContext = () =>
getVm().createContext(undefined, {
name: "Webpack Magic Comment Parser",
codeGeneration: { strings: false, wasm: false }
});
module.exports.webpackCommentRegExp = new RegExp(
/(^|\W)webpack[A-Z][A-Za-z]+:/
);
// regexp to match at least one "magic comment"
/**
* Returns magic comment context.
* @returns {import("vm").Context} magic comment context
*/
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,68 @@
import { a, b, c, d, effect_e, effect_f, effect_g, effect_h, i } from "./inner";
/*#__NO_SIDE_EFFECTS__*/
function fnA(args) {
return args;
}
/*#__NO_SIDE_EFFECTS__*/
export function fnB(args) {
return args;
}
var fnC = /*#__NO_SIDE_EFFECTS__*/ (args) => {
return args;
};
/*@__NO_SIDE_EFFECTS__*/
const fnD = (args) => {
return args;
};
/*#__NO_SIDE_EFFECTS__*/
var fnE = (args) => {
return args;
};
/**
* This is a jsdoc comment, with no side effects annotation
*
* @param {any} args
* @__NO_SIDE_EFFECTS__
*/
const fnF = (args) => {
return args;
};
// This annotation gets ignored
/** @__NO_SIDE_EFFECTS__ */
let fnG = (args) => {
return args;
};
function fnH(args) {
return args;
}
/*#__NO_SIDE_EFFECTS__*/
export default function fnI(args) {
return args;
}
const fnAll = () => {
return a + b + c + d;
};
export const callA = fnA(a);
export const callB = fnB(b);
export const callC = fnC(c);
export const callD = fnD(d);
export const callE = fnE(effect_e);
export const callF = fnF(effect_f);
export const callG = fnG(effect_g);
export const callH = fnH(effect_h);
export const callI = fnI(i);
export const callAll = /*#__PURE__*/ fnAll();
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,27 @@
"use strict";
const createTestCases = require("../_helpers/createTestCases");
module.exports = createTestCases({
nothing: {
usedExports: [],
expect: {
"./inner": ["effect_e", "effect_f", "effect_g", "effect_h"]
}
},
all: {
usedExports: ["callAll"],
expect: {
"./inner": [
"a",
"b",
"c",
"d",
"effect_e",
"effect_f",
"effect_g",
"effect_h"
]
}
}
});
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,5 @@
import "./pure";
it("should not include unused assets", () => {
expect(__webpack_modules__["./pure.js"]).not.toBeDefined();
});
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,23 @@
/*#__NO_SIDE_EFFECTS__*/
function fn1(args) {
return args;
}
/*@__NO_SIDE_EFFECTS__*/
function fn2(args) {
return args;
}
/*@__NO_SIDE_EFFECTS__*/
const fn3 = (args) => {
return args;
};
var fn4 = /*@__NO_SIDE_EFFECTS__*/ (args) => {
return args;
};
fn1();
fn2();
fn3();
fn4();
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,6 @@
"use strict";
/** @type {import("../../../../").Configuration} */
module.exports = {
mode: "production"
};
Original file line number
Diff line number
Diff line change
Expand Up
@@ -9834,7 +9834,7 @@ declare class JavascriptParser extends ParserClass {
boolean | void
>;
preDeclarator: SyncBailHook<
[VariableDeclarator, Statement ],
[VariableDeclarator, VariableDeclaration ],
boolean | void
>;
declarator: SyncBailHook<[VariableDeclarator, Statement], boolean | void>;
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.