enhance booleans (#5043)

This commit is contained in:
Alex Lam S.L
2021-06-30 20:05:52 +01:00
committed by GitHub
parent 611abff49f
commit 1b745494ce
2 changed files with 71 additions and 9 deletions

View File

@@ -8239,7 +8239,10 @@ merge(Compressor.prototype, {
}
function mark_duplicate_condition(compressor, node) {
var level = 0, child, parent = compressor.self();
var child;
var level = 0;
var negated = false;
var parent = compressor.self();
if (!is_statement(parent)) while (true) {
child = parent;
parent = compressor.parent(level++);
@@ -8248,16 +8251,24 @@ merge(Compressor.prototype, {
if (!lazy_op[op]) return;
var left = parent.left;
if (left === child) continue;
if (node.equivalent_to(left)) node[op == "&&" ? "truthy" : "falsy"] = true;
if (match(left)) switch (op) {
case "&&":
node[negated ? "falsy" : "truthy"] = true;
break;
case "||":
case "??":
node[negated ? "truthy" : "falsy"] = true;
break;
}
} else if (parent instanceof AST_Conditional) {
var cond = parent.condition;
if (cond === child) continue;
if (node.equivalent_to(cond)) switch (child) {
if (match(cond)) switch (child) {
case parent.consequent:
node.truthy = true;
node[negated ? "falsy" : "truthy"] = true;
break;
case parent.alternative:
node.falsy = true;
node[negated ? "truthy" : "falsy"] = true;
break;
}
} else if (parent instanceof AST_Exit) {
@@ -8277,17 +8288,26 @@ merge(Compressor.prototype, {
if (parent instanceof AST_BlockStatement) {
if (parent.body[0] === child) continue;
} else if (parent instanceof AST_If) {
if (node.equivalent_to(parent.condition)) switch (child) {
if (match(parent.condition)) switch (child) {
case parent.body:
node.truthy = true;
node[negated ? "falsy" : "truthy"] = true;
break;
case parent.alternative:
node.falsy = true;
node[negated ? "truthy" : "falsy"] = true;
break;
}
}
return;
}
function match(cond) {
if (node.equivalent_to(cond)) return true;
if (!(cond instanceof AST_UnaryPrefix)) return false;
if (cond.operator != "!") return false;
if (!node.equivalent_to(cond.expression)) return false;
negated = true;
return true;
}
}
OPT(AST_If, function(self, compressor) {

View File

@@ -406,6 +406,27 @@ conditional_chain: {
expect_stdout: "PASS"
}
negated_if: {
options = {
booleans: true,
conditionals: true,
side_effects: true,
}
input: {
console.log(function(a) {
if (!a)
return a ? "FAIL" : "PASS";
}(!console));
}
expect: {
console.log(function(a) {
if (!a)
return "PASS";
}(!console));
}
expect_stdout: "PASS"
}
issue_3465_1: {
options = {
booleans: true,
@@ -635,7 +656,7 @@ issue_5028_3: {
expect_stdout: "-1"
}
issue_5041: {
issue_5041_1: {
options = {
booleans: true,
conditionals: true,
@@ -655,3 +676,24 @@ issue_5041: {
}
expect_stdout: "PASS"
}
issue_5041_2: {
options = {
booleans: true,
conditionals: true,
}
input: {
var a;
if (!a)
if (a = 42)
if (a)
console.log("PASS");
else
console.log("FAIL");
}
expect: {
var a;
a || (a = 42) && (a ? console.log("PASS") : console.log("FAIL"));
}
expect_stdout: "PASS"
}