From c94624f36cf57e27836097cdf0d462e41b4f24d3 Mon Sep 17 00:00:00 2001 From: "Alex Lam S.L" Date: Mon, 3 Jan 2022 20:18:41 +0000 Subject: [PATCH] fix corner case in `collapse_vars` (#5261) fixes #5260 --- lib/compress.js | 6 +++++- test/compress/const.js | 35 +++++++++++++++++++++++++++++++++++ test/compress/let.js | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) diff --git a/lib/compress.js b/lib/compress.js index 308a711b..64ec5c4b 100644 --- a/lib/compress.js +++ b/lib/compress.js @@ -2051,7 +2051,7 @@ Compressor.prototype.compress = function(node) { if (node instanceof AST_BlockScope && !(node instanceof AST_Scope) && !(node.variables && node.variables.all(function(def) { - return !lvalues.has(def.name); + return !enclosed.has(def.name) && !lvalues.has(def.name); }))) { var replace = can_replace; can_replace = false; @@ -2149,6 +2149,7 @@ Compressor.prototype.compress = function(node) { var read_toplevel = false; var modify_toplevel = false; // Locate symbols which may execute code outside of scanning range + var enclosed = new Dictionary(); var well_defined = true; var lvalues = get_lvalues(candidate); var lhs_local = is_lhs_local(lhs); @@ -3010,6 +3011,9 @@ Compressor.prototype.compress = function(node) { break; } } + node.enclosed.forEach(function(def) { + if (def.scope !== node) enclosed.set(def.name, true); + }); return true; } else if (find_arguments && node instanceof AST_Sub) { scope.each_argname(function(argname) { diff --git a/test/compress/const.js b/test/compress/const.js index 96210a55..1beccfcd 100644 --- a/test/compress/const.js +++ b/test/compress/const.js @@ -1752,3 +1752,38 @@ issue_5254: { "bar", ] } + +issue_5260: { + options = { + collapse_vars: true, + } + input: { + "use strict"; + var a = "foo", o; + while (console.log("bar")); + o = { + baz: function(b) { + console.log(a, b); + }, + }; + for (const a in o) + o[a](a); + } + expect: { + "use strict"; + var a = "foo", o; + while (console.log("bar")); + o = { + baz: function(b) { + console.log(a, b); + }, + }; + for (const a in o) + o[a](a); + } + expect_stdout: [ + "bar", + "foo baz", + ] + node_version: ">=4" +} diff --git a/test/compress/let.js b/test/compress/let.js index a689fd5c..d3718923 100644 --- a/test/compress/let.js +++ b/test/compress/let.js @@ -1906,3 +1906,38 @@ issue_5254: { ] node_version: ">=4" } + +issue_5260: { + options = { + collapse_vars: true, + } + input: { + "use strict"; + var a = "foo", o; + while (console.log("bar")); + o = { + baz: function(b) { + console.log(a, b); + }, + }; + for (let a in o) + o[a](a); + } + expect: { + "use strict"; + var a = "foo", o; + while (console.log("bar")); + o = { + baz: function(b) { + console.log(a, b); + }, + }; + for (let a in o) + o[a](a); + } + expect_stdout: [ + "bar", + "foo baz", + ] + node_version: ">=4" +}