Skip to content

Commit

Permalink
enhance collapse_vars (#4864)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexlamsl committed Apr 24, 2021
1 parent 9b8deff commit 10dd9d4
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 2 deletions.
15 changes: 13 additions & 2 deletions lib/compress.js
Expand Up @@ -1856,6 +1856,7 @@ merge(Compressor.prototype, {
case 0:
hit = true;
if (assign_used) return node;
if (node !== candidate) return node;
if (node instanceof AST_VarDef) return node;
def.replaced++;
var parent = multi_replacer.parent();
Expand Down Expand Up @@ -1957,7 +1958,9 @@ merge(Compressor.prototype, {
for (var i = stat_index; !abort && i < statements.length; i++) {
if (!statements[i].transform(multi_replacer)) statements.splice(i--, 1);
}
if (candidate instanceof AST_VarDef) {
if (candidate !== hit_stack[hit_stack.length - 1]) {
replaced = false;
} else if (candidate instanceof AST_VarDef) {
replaced = !compressor.exposed(def) && def.references.length == def.replaced;
}
value_def.single_use = false;
Expand Down Expand Up @@ -2546,15 +2549,23 @@ merge(Compressor.prototype, {
}
}

function mangleable_var(value) {
function mangleable_var(rhs) {
if (force_single) {
force_single = false;
return;
}
var value = rhs instanceof AST_Assign && rhs.operator == "=" ? rhs.left : rhs;
if (!(value instanceof AST_SymbolRef)) return;
var def = value.definition();
if (def.undeclared) return;
if (is_arguments(def)) return;
if (value !== rhs) {
if (value.is_immutable()) return;
var referenced = def.references.length - def.replaced;
if (referenced < 2) return;
candidate = candidate.clone();
candidate[candidate instanceof AST_Assign ? "right" : "value"] = value;
}
return value_def = def;
}

Expand Down
61 changes: 61 additions & 0 deletions test/compress/collapse_vars.js
Expand Up @@ -8064,6 +8064,67 @@ mangleable_var: {
expect_stdout: "PASS"
}

mangleable_assignment_1: {
options = {
collapse_vars: true,
unused: true,
}
input: {
var o = {
p: function() {
return 6;
},
};
(function() {
var a, b = a = o.p();
console.log(a * (b / a + b));
})();
}
expect: {
var o = {
p: function() {
return 6;
},
};
(function() {
var a;
a = o.p();
console.log(a * (a / a + a));
})();
}
expect_stdout: "42"
}

mangleable_assignment_2: {
options = {
collapse_vars: true,
unused: true,
}
input: {
var o = {
p: function() {
return 6;
},
};
(function(a, b) {
b = a = o.p();
console.log(a * (b / a + b));
})();
}
expect: {
var o = {
p: function() {
return 6;
},
};
(function(a, b) {
a = o.p();
console.log(a * (a / a + a));
})();
}
expect_stdout: "42"
}

issue_3884_1: {
options = {
collapse_vars: true,
Expand Down

0 comments on commit 10dd9d4

Please sign in to comment.