From e7d6dd2ea24c1566ae3c79f67d74065ae11bbd7c Mon Sep 17 00:00:00 2001 From: "Alex Lam S.L" Date: Sat, 29 Jan 2022 11:28:19 +0000 Subject: [PATCH] fix corner case in `unused` (#5323) fixes #5322 --- lib/compress.js | 34 +++++++++++++++++++++------------- test/compress/classes.js | 27 +++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 13 deletions(-) diff --git a/lib/compress.js b/lib/compress.js index abc1592a..b8dc80ec 100644 --- a/lib/compress.js +++ b/lib/compress.js @@ -6507,28 +6507,29 @@ Compressor.prototype.compress = function(node) { if (scope === self) { if (node instanceof AST_DefClass) { var def = node.name.definition(); - if ((!drop_funcs || def.exported) && !(def.id in in_use_ids)) { + var drop = drop_funcs && !def.exported; + if (!drop && !(def.id in in_use_ids)) { in_use_ids[def.id] = true; in_use.push(def); } if (node.extends) node.extends.walk(tw); - var is_export = false; - if (tw.parent() instanceof AST_ExportDefault) { - is_export = true; - export_defaults[def.id] = true; - } + var used = tw.parent() instanceof AST_ExportDefault; + if (used) export_defaults[def.id] = true; + var values = []; node.properties.forEach(function(prop) { if (prop.key instanceof AST_Node) prop.key.walk(tw); - if (!prop.value) return; - if (is_export || prop instanceof AST_ClassField && prop.static) { - var save_scope = scope; - scope = node; - prop.value.walk(tw); - scope = save_scope; + var value = prop.value; + if (!value) return; + if (prop instanceof AST_ClassField && prop.static) { + if (!used && value.contains_this()) used = true; + walk_class_prop(value); } else { - initializations.add(def.id, prop.value); + values.push(value); } }); + values.forEach(drop && used ? walk_class_prop : function(value) { + initializations.add(def.id, value); + }); return true; } if (node instanceof AST_LambdaDefinition) { @@ -6594,6 +6595,13 @@ Compressor.prototype.compress = function(node) { } } return scan_ref_scoped(node, descend, true); + + function walk_class_prop(value) { + var save_scope = scope; + scope = node; + value.walk(tw); + scope = save_scope; + } }); tw.directives = Object.create(compressor.directives); self.walk(tw); diff --git a/test/compress/classes.js b/test/compress/classes.js index 4e613fc4..4471663d 100644 --- a/test/compress/classes.js +++ b/test/compress/classes.js @@ -2449,3 +2449,30 @@ issue_5294_4: { expect_stdout: "PASS" node_version: ">=12" } + +issue_5322: { + options = { + toplevel: true, + unused: true, + } + input: { + var a = 41; + class A { + static p() { + console.log(++a); + } + static q = this.p(); + } + } + expect: { + var a = 41; + (class { + static p() { + console.log(++a); + } + static q = this.p(); + }); + } + expect_stdout: "42" + node_version: ">=12" +}