fix: avoid empty block for unused statement

This commit is contained in:
hai-x 2025-08-17 23:07:04 +08:00 committed by GitHub
parent 8db97f863f
commit 90ae8af3d1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 12 additions and 5 deletions

View File

@ -180,7 +180,7 @@ class ConstPlugin {
? statement.alternate
: statement.consequent;
if (branchToRemove) {
this.eliminateUnusedStatement(parser, branchToRemove);
this.eliminateUnusedStatement(parser, branchToRemove, true);
}
return bool;
}
@ -193,7 +193,7 @@ class ConstPlugin {
) {
return;
}
this.eliminateUnusedStatement(parser, statement);
this.eliminateUnusedStatement(parser, statement, false);
return true;
});
parser.hooks.expressionConditionalOperator.tap(
@ -509,9 +509,10 @@ class ConstPlugin {
* Eliminate an unused statement.
* @param {JavascriptParser} parser the parser
* @param {Statement} statement the statement to remove
* @param {boolean} alwaysInBlock whether to always generate curly brackets
* @returns {void}
*/
eliminateUnusedStatement(parser, statement) {
eliminateUnusedStatement(parser, statement, alwaysInBlock) {
// Before removing the unused branch, the hoisted declarations
// must be collected.
//
@ -545,8 +546,14 @@ class ConstPlugin {
const declarations = parser.scope.isStrict
? getHoistedDeclarations(statement, false)
: getHoistedDeclarations(statement, true);
const replacement =
declarations.length > 0 ? `{ var ${declarations.join(", ")}; }` : "{}";
const inBlock = alwaysInBlock || statement.type === "BlockStatement";
let replacement = inBlock ? "{" : "";
replacement +=
declarations.length > 0 ? ` var ${declarations.join(", ")}; ` : "";
replacement += inBlock ? "}" : "";
const dep = new ConstDependency(
`// removed by dead control flow\n${replacement}`,
/** @type {Range} */ (statement.range)