Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Optimize various switch statements (#1044)
* Optimize various switch statements 1. This implements full case folding for equivalent branches 2. This implements default collapsing when all cases are "default" The default collapsing is hard to describe, but easy to demonstrate: ```js switch (expression) { case 1: case 2: case 3: default: doSomething(); } ``` Because all of the case `expression`s are side-effect free, we can consider just the case bodies. Because all cases fall through to the last branch, we can check to see if this branch is always guaranteed to run due to a `default` branch. If everything is good, we can eliminate the switch statement entirely. I've hit this a few times when programming TypeScript. I tend to write exhaustive type checking, and a times that leads to code like: ```js switch (type) { case "Foo": case "Bar": if (process.env.NODE_ENV !== 'production') { throw new Error('invariant failed!'); } default: doSomething(type); } ``` In production builds, I I strip the invariant checks out for file size (my tests should have caught if it were ever possible to hit those cases). And this used to leave me with large useless switch statements: ```js switch (type) { case "Foo": case "Bar": default: doSomething(type); } ``` This creates the "all cases are default" behavior, which I'd really like to have minimized. * Prune branches that are empty at the end of a switch * Convert simple switch statements into if statements * Keep cases that can skip a side-effect * tmp * Collapse constants into default and tests * Fix issues with side-effects * Add test for non-break abortions in if-else * add some tests * Collapse inert bodies * Remove useless branch check The branch can't be the default, because it would have already been handled by the switch removal code. Co-authored-by: fabiosantoscode <fabiosantosart@gmail.com>
- Loading branch information
1 parent
9c0481f
commit 75df7e0
Showing
5 changed files
with
2,112 additions
and
128 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.