Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure switch branches reordering happens only for constant branch expressions #1092

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/compress/index.js
Expand Up @@ -1606,7 +1606,7 @@ def_optimize(AST_Switch, function(self, compressor) {
// that way the next micro-optimization will merge them.
// ** bail micro-optimization if not a simple switch case with breaks
if (body.every((branch, i) =>
(branch === default_or_exact || !branch.expression.has_side_effects(compressor))
(branch === default_or_exact || branch.expression instanceof AST_Constant)
&& (branch.body.length === 0 || aborts(branch) || body.length - 1 === i))
) {
for (let i = 0; i < body.length; i++) {
Expand Down
36 changes: 36 additions & 0 deletions test/compress/switch.js
Expand Up @@ -2594,6 +2594,42 @@ collapse_same_branches_not_in_a_row_ensure_no_side_effects: {
}
expect_stdout: ["2"]
}

collapse_same_branches_not_in_a_row_ensure_no_evaluate_elad: {
options = {
switches: true,
dead_code: true
}
input: {
let i = 1;
switch (true) {
case 3 == i:
console.log(i);
break;
case 5 == i:
console.log(5);
break;
case 1 == i:
console.log(i);
break;
Comment on lines +2606 to +2614
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: I'm not sure this properly catches the bug (but the output isn't optimized, so it's not a hard blocker). We need to test that non-mutually-exclusive branches are correct:

Suggested change
case 3 == i:
console.log(i);
break;
case 5 == i:
console.log(5);
break;
case 1 == i:
console.log(i);
break;
case 3 == i:
console.log('equals');
break;
case 5 > i:
console.log('greater than');
break;
case 1 == i:
console.log('equals');
break;

This case should log 'greater than', but if we did the optimization, it would log equals (because the 1 == i would have been moved up).

}
}
expect: {
let i = 1;
switch (true) {
case 3 == i:
console.log(i);
break;
case 5 == i:
console.log(5);
break;
case 1 == i:
console.log(i);
}
}
expect_stdout: ["1"]
}

collapse_same_branches_not_in_a_row_even_if_last_case_without_abort: {
options = {
switches: true,
Expand Down