enhance conditionals (#5575)

This commit is contained in:
Alex Lam S.L
2022-07-25 18:49:45 +01:00
committed by GitHub
parent fc7678c115
commit 996836b67e
2 changed files with 115 additions and 4 deletions

View File

@@ -9662,10 +9662,20 @@ Compressor.prototype.compress = function(node) {
var alt_index = last_index(alt_stats);
for (var stats = []; body_index >= 0 && alt_index >= 0;) {
var stat = body_stats[body_index];
if (!stat.equals(alt_stats[alt_index])) break;
var alt_stat = alt_stats[alt_index];
if (stat.equals(alt_stat)) {
body_stats.splice(body_index--, 1);
alt_stats.splice(alt_index--, 1);
stats.unshift(stat);
} else {
if (!(stat instanceof AST_SimpleStatement)) break;
if (!(alt_stat instanceof AST_SimpleStatement)) break;
var expr = stat.body.tail_node();
if (!expr.equals(alt_stat.body.tail_node())) break;
body_index = pop_expr(body_stats, stat.body, body_index);
alt_index = pop_expr(alt_stats, alt_stat.body, alt_index);
stats.unshift(make_node(AST_SimpleStatement, expr, { body: expr }));
}
}
if (stats.length > 0) {
self.body = body_stats.length > 0 ? make_node(AST_BlockStatement, self, {
@@ -9692,6 +9702,17 @@ Compressor.prototype.compress = function(node) {
return index;
}
function pop_expr(stats, body, index) {
if (body instanceof AST_Sequence) {
stats[index] = make_node(AST_SimpleStatement, body, {
body: make_sequence(body, body.expressions.slice(0, -1)),
});
} else {
stats.splice(index--, 1);
}
return index;
}
function sequencesize(stat, defuns, var_defs, refs) {
if (stat == null) return [];
if (stat instanceof AST_BlockStatement) {

View File

@@ -278,6 +278,96 @@ merge_tail_2: {
]
}
merge_tail_sequence_1: {
options = {
conditionals: true,
}
input: {
function f(a) {
var b = "foo";
if (a) {
while (console.log("bar"));
console.log(b);
} else {
c = "baz";
while (console.log(c));
console.log("bar"),
console.log(b);
var c;
}
}
f();
f(42);
}
expect: {
function f(a) {
var b = "foo";
if (a)
while (console.log("bar"));
else {
c = "baz";
while (console.log(c));
console.log("bar");
var c;
}
console.log(b);
}
f();
f(42);
}
expect_stdout: [
"baz",
"bar",
"foo",
"bar",
"foo",
]
}
merge_tail_sequence_2: {
options = {
conditionals: true,
}
input: {
function f(a) {
var b = "foo";
if (a) {
console.log("bar");
console.log(b);
} else {
c = "baz";
while (console.log(c));
console.log("bar"),
console.log(b);
var c;
}
}
f();
f(42);
}
expect: {
function f(a) {
var b = "foo";
if (!a) {
c = "baz";
while (console.log(c));
var c;
}
console.log("bar");
console.log(b);
}
f();
f(42);
}
expect_stdout: [
"baz",
"bar",
"foo",
"bar",
"foo",
]
}
cond_1: {
options = {
conditionals: true,