improve AST_For.init & AST_Switch.expression compression (#2546)

This commit is contained in:
Alex Lam S.L 2017-12-01 12:53:59 +08:00 committed by GitHub
parent 09b320e8a5
commit f6610baaa8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 50 additions and 8 deletions

View File

@ -1436,7 +1436,7 @@ merge(Compressor.prototype, {
if (!abort) {
if (stat.init) stat.init = cons_seq(stat.init);
else {
stat.init = prev.body.drop_side_effect_free(compressor);
stat.init = prev.body;
n--;
}
}
@ -3105,6 +3105,9 @@ merge(Compressor.prototype, {
OPT(AST_For, function(self, compressor){
if (!compressor.option("loops")) return self;
if (compressor.option("side_effects") && self.init) {
self.init = self.init.drop_side_effect_free(compressor);
}
if (self.condition) {
var cond = self.condition.evaluate(compressor);
if (!(cond instanceof AST_Node)) {
@ -3286,11 +3289,15 @@ merge(Compressor.prototype, {
if (!compressor.option("switches")) return self;
var branch;
var value = self.expression.evaluate(compressor);
if (value !== self.expression) {
var expression = make_node_from_constant(value, self.expression).transform(compressor);
self.expression = best_of_expression(expression, self.expression);
if (!(value instanceof AST_Node)) {
var orig = self.expression;
self.expression = make_node_from_constant(value, orig);
self.expression = best_of_expression(self.expression.transform(compressor), orig);
}
if (!compressor.option("dead_code")) return self;
if (value instanceof AST_Node) {
value = self.expression.tail_node().evaluate(compressor);
}
var decl = [];
var body = [];
var default_branch;
@ -3303,7 +3310,7 @@ merge(Compressor.prototype, {
} else {
eliminate_branch(branch, body[body.length - 1]);
}
} else if (value !== self.expression) {
} else if (!(value instanceof AST_Node)) {
var exp = branch.expression.evaluate(compressor);
if (exp === value) {
exact_match = branch;

View File

@ -452,3 +452,19 @@ in_parenthesis_2: {
}
expect_exact: 'for(function(){"foo"in{}};0;);'
}
init_side_effects: {
options = {
loops: true,
side_effects: true,
};
input: {
for (function() {}(), i = 0; i < 5; i++) console.log(i);
for (function() {}(); i < 10; i++) console.log(i);
}
expect: {
for (i = 0; i < 5; i++) console.log(i);
for (; i < 10; i++) console.log(i);
}
expect_stdout: true
}

View File

@ -252,13 +252,12 @@ negate_iife_for: {
input: {
(function() {})();
for (i = 0; i < 5; i++) console.log(i);
(function() {})();
for (; i < 5; i++) console.log(i);
for (; i < 10; i++) console.log(i);
}
expect: {
for (!function() {}(), i = 0; i < 5; i++) console.log(i);
for (function() {}(); i < 5; i++) console.log(i);
for (!function() {}(); i < 10; i++) console.log(i);
}
expect_stdout: true
}

View File

@ -817,3 +817,23 @@ issue_1758: {
}
expect_stdout: "0 3"
}
issue_2535: {
options = {
evaluate: true,
dead_code: true,
switches: true,
}
input: {
switch(w(), 42) {
case 13: x();
case 42: y();
default: z();
}
}
expect: {
w(), 42;
y();
z();
}
}