Add ternary elimination support to the WPO pass

Summary: public

Replaces

```
__DEV__ ? foo() : bar()
```

with

```
bar()
```

for non-dev builds.

Reviewed By: davidaurelio

Differential Revision: D2663838

fb-gh-sync-id: 30fdfa72dda89fc0d340da359e0f43db2917fcf5
This commit is contained in:
Tadeu Zagallo 2015-11-17 11:10:35 -08:00 committed by facebook-github-bot-4
parent 844282c37b
commit 4ddb158c72
2 changed files with 33 additions and 13 deletions

View File

@ -103,4 +103,13 @@ describe('dead-module-elimination', () => {
require('bar');`
);
});
it('should replace falsy ternaries with alternate expression', () => {
compare(
`__DEV__ = false;
__DEV__ ? foo() : bar();
`,
`bar();`
);
});
});

View File

@ -33,6 +33,28 @@ function CallExpression(path) {
}
}
function IfStatement(path) {
const { node } = path;
if (node.test.type === 'Identifier' && node.test.name in globals) {
if (globals[node.test.name]) {
if (node.consequent.type === 'BlockStatement') {
path.replaceWithMultiple(node.consequent.body);
} else {
path.replaceWith(node.consequent);
}
} else if (node.alternate) {
if (node.alternate.type === 'BlockStatement') {
path.replaceWithMultiple(node.alternate.body);
} else {
path.replaceWith(node.alternate);
}
} else {
path.remove();
}
}
}
module.exports = function () {
var firstPass = {
AssignmentExpression(path) {
@ -60,19 +82,8 @@ module.exports = function () {
//scope.removeBinding(node.left.name);
}
},
IfStatement(path) {
const { node } = path;
if (node.test.type === 'Identifier' && node.test.name in globals) {
if (globals[node.test.name]) {
path.replaceWithMultiple(node.consequent.body);
} else if (node.alternate) {
path.replaceWithMultiple(node.alternate.body);
} else {
path.remove();
}
}
},
IfStatement,
ConditionalExpression: IfStatement,
Identifier(path) {
const { node } = path;