Skip to content

Commit

Permalink
feat(es/minifier): Implement optional catch binding (#9657)
Browse files Browse the repository at this point in the history
**Description:**

I think removing `!v.declared_as_catch_param` is safe, since I can't think of a bad case:
1. for the vars in the params of catch-clause, we prevent the removal if `self.options.ecma < EsVersion::Es2019 || !self.options.unused` is not satisfied.
2. for the usages or re-declarations with the same var name in the body of catch-clause, I think it's safe to remove them.


**Related issue:**

 - Closes #8966
  • Loading branch information
CPunisher authored Oct 20, 2024
1 parent 4cbe33c commit f70b842
Show file tree
Hide file tree
Showing 7 changed files with 25 additions and 9 deletions.
6 changes: 6 additions & 0 deletions .changeset/plenty-frogs-live.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
swc_ecma_minifier: patch
swc_core: patch
---

feat(es/minifier): Implement optional catch binding
15 changes: 15 additions & 0 deletions crates/swc_ecma_minifier/src/compress/optimize/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2876,6 +2876,21 @@ impl VisitMut for Optimizer<'_> {
n.finalizer.visit_mut_with(self);
}

fn visit_mut_catch_clause(&mut self, n: &mut CatchClause) {
n.visit_mut_children_with(self);

if self.options.ecma < EsVersion::Es2019 || !self.options.unused {
return;
}

if let Some(param) = &mut n.param {
self.take_pat_if_unused(param, None, false);
if param.is_invalid() {
n.param = None;
}
}
}

#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
fn visit_mut_unary_expr(&mut self, n: &mut UnaryExpr) {
let ctx = Ctx {
Expand Down
1 change: 0 additions & 1 deletion crates/swc_ecma_minifier/src/compress/optimize/unused.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,6 @@ impl Optimizer<'_> {
&& v.usage_count == 0
&& !v.reassigned
&& v.property_mutation_count == 0
&& !v.declared_as_catch_param
{
self.changed = true;
report_change!(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ function f1() {
return 1;
} catch (ex) {
return 2;
} finally {
} finally{
return 3;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ var a = 1;
function f() {
try {
x();
} catch (a) {
var a;
}
} catch (a) {}
}
f();
console.log(a);
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ var a = 1;
!function() {
try {
x();
} catch (a) {
var a;
}
} catch (a) {}
}();
console.log(a);
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
var a = "FAIL";
(function () {
(function() {
try {
throw 1;
} catch (o) {
Expand Down

0 comments on commit f70b842

Please sign in to comment.