fix corner case in `unused` (#5272)
authorAlex Lam S.L <alexlamsl@gmail.com>
Fri, 7 Jan 2022 06:33:42 +0000 (06:33 +0000)
committerGitHub <noreply@github.com>
Fri, 7 Jan 2022 06:33:42 +0000 (14:33 +0800)
fixes #5271

lib/compress.js
test/compress/drop-unused.js

index 09b725b..32cd445 100644 (file)
@@ -6577,7 +6577,6 @@ Compressor.prototype.compress = function(node) {
             }
         });
         // pass 3: we should drop declarations not in_use
-        var trim_defns = [];
         var unused_fn_names = [];
         var calls_to_drop_args = [];
         var fns_with_marked_args = [];
@@ -6822,14 +6821,16 @@ Compressor.prototype.compress = function(node) {
                     var sym = def.name.definition();
                     var drop_sym = is_var ? can_drop_symbol(def.name) : is_safe_lexical(sym);
                     if (!drop_sym || !drop_vars || sym.id in in_use_ids) {
-                        if (value && (indexOf_assign(sym, def) < 0 || self_assign(value.tail_node()))) {
+                        var index;
+                        if (value && ((index = indexOf_assign(sym, def)) < 0 || self_assign(value.tail_node()))) {
                             value = value.drop_side_effect_free(compressor);
                             if (value) {
                                 AST_Node.warn("Side effects in definition of variable {name} [{file}:{line},{col}]", template(def.name));
                                 side_effects.push(value);
                             }
-                            value = null;
-                            trim_defns.push(def);
+                            def = def.clone();
+                            def.value = value = null;
+                            if (index >= 0) assign_in_use[sym.id][index] = def;
                         }
                         var old_def, fn;
                         if (!value && !(node instanceof AST_Let)) {
@@ -7114,9 +7115,6 @@ Compressor.prototype.compress = function(node) {
             && self.body[0].value == "use strict") {
             self.body.length = 0;
         }
-        trim_defns.forEach(function(def) {
-            def.value = null;
-        });
         unused_fn_names.forEach(function(fn) {
             fn.name = null;
         });
index 324c8f3..36aa2a9 100644 (file)
@@ -3561,3 +3561,29 @@ issue_5224: {
     }
     expect_stdout: "Infinity"
 }
+
+issue_5271: {
+    options = {
+        evaluate: true,
+        reduce_vars: true,
+        toplevel: true,
+        unused: true,
+    }
+    input: {
+        function f() {
+            do {
+                var a = b = 0 ^ f, b = b;
+            } while (console.log(42 - b));
+        }
+        f();
+    }
+    expect: {
+        (function f() {
+            do {
+                var b;
+                b = 0 ^ f;
+            } while (console.log(42 - b));
+        })();
+    }
+    expect_stdout: "42"
+}