fix(minifier): drop side-effect-free additions (#25639)

An unused addition can be side-effect-free even when constant folding keeps it. This happens when replacing the expression with its exact constant value would make the output longer.

For example, constant folding correctly keeps `0.1 + 0.2` instead of expanding it to `0.30000000000000004`. But when the result is unused, the whole expression can be removed.

This PR checks the existing side-effect analysis before running the string-addition cleanup. It removes the whole addition when it is safe. Additions that can run code or throw still use the existing cleanup and are preserved when needed.

Tests cover both the removable numeric addition and an addition containing `foo()` that must stay.

Verified with the full `oxc_minifier` test suite (652 passed, 34 ignored), Clippy, formatting, minsize, and allocation checks. Minsize and allocation snapshots are unchanged.

AI-assisted by OpenAI Codex.
This commit is contained in:
Dunqing committed 2026-08-18 07:59:10 +00:00
1 parent 691a1f0135
commit ab81f3f7f8
2 files changed
+6

No files matched your search

@@ -613,6 +613,9 @@ impl<'a> PeepholeOptimizations {
}
}
BinaryOperator::Addition => {
if !e.may_have_side_effects(ctx) {
return true;
}
Self::fold_string_addition_chain(e, ctx);
matches!(e, Expression::StringLiteral(_))
}
@@ -436,6 +436,9 @@ fn test_fold_binary_expression() {
test("v = function(a, b) { 'a' + +b }", "v = function(a, b) { '' + +b }"); // can be improved to `+b`
test_same("v = function(a, b) { a + ('' + b) }");
test("v = function(a, b, c) { a + ('' + (b === c)) }", "v = function(a, b, c) { a + '' }");
test("0.1 + 0.2", "");
test_same("v = function(a) { a + ('' + foo()) }");
}
#[test]