diff --git a/crates/oxc_minifier/src/peephole/minimize_conditions.rs b/crates/oxc_minifier/src/peephole/minimize_conditions.rs index 64baf1bb633f1..f925643c3d874 100644 --- a/crates/oxc_minifier/src/peephole/minimize_conditions.rs +++ b/crates/oxc_minifier/src/peephole/minimize_conditions.rs @@ -716,7 +716,7 @@ mod test { // Verify function deletion tracking. // test("if(!!true||function(){}) {}", "if(1) {}"); // Don't bother with FOR inits as there are normalized out. - test("for(!!true;;) foo()", "for(!0;;) foo()"); + test("for(!!true;;) foo()", "for(;;) foo()"); // These test tryMinimizeCondition test("for(;!!x;) foo()", "for(;x;) foo()"); diff --git a/crates/oxc_minifier/src/peephole/remove_dead_code.rs b/crates/oxc_minifier/src/peephole/remove_dead_code.rs index 3d73ac18a2588..52202c6c0f8a0 100644 --- a/crates/oxc_minifier/src/peephole/remove_dead_code.rs +++ b/crates/oxc_minifier/src/peephole/remove_dead_code.rs @@ -220,6 +220,21 @@ impl<'a, 'b> PeepholeOptimizations { for_stmt: &mut ForStatement<'a>, ctx: Ctx<'a, 'b>, ) -> Option> { + if let Some(init) = &mut for_stmt.init { + if let Some(init) = init.as_expression_mut() { + if self.remove_unused_expression(init, ctx) { + for_stmt.init = None; + self.mark_current_function_as_changed(); + } + } + } + if let Some(update) = &mut for_stmt.update { + if self.remove_unused_expression(update, ctx) { + for_stmt.update = None; + self.mark_current_function_as_changed(); + } + } + let test_boolean = for_stmt.test.as_ref().and_then(|test| test.evaluate_value_to_boolean(&ctx)); if for_stmt.test.as_ref().is_some_and(|test| test.may_have_side_effects(&ctx)) { @@ -591,4 +606,16 @@ mod test { test("while(true) { throw a; unreachable;}", "for(;;) throw a"); test("while(true) { return a; unreachable;}", "for(;;) return a"); } + + #[test] + fn remove_unused_expressions_in_for() { + test( + "var i; for (i = 0, 0; i < 10; i++) foo(i);", + "var i; for (i = 0; i < 10; i++) foo(i);", + ); + test( + "var i; for (i = 0; i < 10; 0, i++, 0) foo(i);", + "var i; for (i = 0; i < 10; i++) foo(i);", + ); + } } diff --git a/crates/oxc_minifier/tests/peephole/mod.rs b/crates/oxc_minifier/tests/peephole/mod.rs index cf0dfa930919e..ca634017dc828 100644 --- a/crates/oxc_minifier/tests/peephole/mod.rs +++ b/crates/oxc_minifier/tests/peephole/mod.rs @@ -57,7 +57,7 @@ fn integration() { } console.log(c, d); ", - "if ((() => console.log('effect'))(), !1) for (var c = 1, c; unknownGlobal; unknownGlobal && !0) var d; + "if ((() => console.log('effect'))(), !1) for (var c = 1, c; unknownGlobal; unknownGlobal) var d; console.log(c, d); ", );