From 719fb9672bef059761247f93eab2bf009bdf8e89 Mon Sep 17 00:00:00 2001 From: Boshen Date: Sun, 7 Jul 2024 01:25:54 +0800 Subject: [PATCH] fix(minifier): omit dce `undefined` which can be a shadowed variable (#4073) ``` // Shadowed `undefined` as a variable should not be erased. test( "function foo(undefined) { if (!undefined) { } }", "function foo(undefined){if(!undefined){}}", ); ``` I'm not using the cheap `ident.reference_id.get().is_some()` here yet because I don't know what I'm doing - how should minifier consume `Semantic`? --- crates/oxc_minifier/src/compressor/ast_util.rs | 3 ++- crates/oxc_minifier/tests/oxc/remove_dead_code.rs | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/oxc_minifier/src/compressor/ast_util.rs b/crates/oxc_minifier/src/compressor/ast_util.rs index ba10b60412282..ef7cc418cbd29 100644 --- a/crates/oxc_minifier/src/compressor/ast_util.rs +++ b/crates/oxc_minifier/src/compressor/ast_util.rs @@ -485,7 +485,8 @@ pub fn get_boolean_value(expr: &Expression) -> Option { .map(|cooked| !cooked.is_empty()) } Expression::Identifier(ident) => { - if expr.is_undefined() || ident.name == "NaN" { + /* `undefined` can be a shadowed variable expr.is_undefined() || */ + if ident.name == "NaN" { Some(false) } else if ident.name == "Infinity" { Some(true) diff --git a/crates/oxc_minifier/tests/oxc/remove_dead_code.rs b/crates/oxc_minifier/tests/oxc/remove_dead_code.rs index fec6508ecef46..95f50d377dad3 100644 --- a/crates/oxc_minifier/tests/oxc/remove_dead_code.rs +++ b/crates/oxc_minifier/tests/oxc/remove_dead_code.rs @@ -41,4 +41,10 @@ fn remove_dead_code() { test("!!false ? foo : bar;", "bar"); test("!!true ? foo : bar;", "foo"); + + // Shadowed `undefined` as a variable should not be erased. + test( + "function foo(undefined) { if (!undefined) { } }", + "function foo(undefined){if(!undefined){}}", + ); }