Browse Source

Merge pull request #465 from rollup/skip-dead-conditional-expression-branches

Skip dead branches of a conditional expression.
gh-669
Rich Harris 9 years ago
parent
commit
6200ade8f3
  1. 11
      src/Module.js
  2. 2
      test/function/skips-dead-branches-f/_config.js
  3. 9
      test/function/skips-dead-branches-g/_config.js
  4. 6
      test/function/skips-dead-branches-g/main.js

11
src/Module.js

@ -300,7 +300,7 @@ export default class Module {
}
walk( ast, {
enter: node => {
enter: (node, parent, prop) => {
// eliminate dead branches early
if ( node.type === 'IfStatement' ) {
if ( isFalsy( node.test ) ) {
@ -310,6 +310,15 @@ export default class Module {
this.magicString.overwrite( node.alternate.start, node.alternate.end, '{}' );
node.alternate = emptyBlockStatement( node.alternate.start, node.alternate.end );
}
} else if ( node.type === 'ConditionalExpression' ) {
if ( isFalsy( node.test ) ) {
this.magicString.remove( node.start, node.alternate.start );
parent[prop] = node.alternate;
} else if ( isTruthy( node.test ) ) {
this.magicString.remove( node.start, node.consequent.start );
this.magicString.remove( node.consequent.end, node.end );
parent[prop] = node.consequent;
}
}
this.magicString.addSourcemapLocation( node.start );

2
test/function/skips-dead-branches-f/_config.js

@ -1,7 +1,7 @@
var assert = require( 'assert' );
module.exports = {
description: 'skips a dead branch (g)',
description: 'skips a dead branch (f)',
code: function ( code ) {
assert.equal( code.indexOf( 'obj.foo = function' ), -1, code );
}

9
test/function/skips-dead-branches-g/_config.js

@ -0,0 +1,9 @@
var assert = require( 'assert' );
module.exports = {
description: 'skips a dead conditional expression branch (g)',
code: function ( code ) {
assert.ok( code.indexOf( 'var c = a;' ) >= 0, code );
assert.ok( code.indexOf( 'var d = b;' ) >= 0, code );
}
};

6
test/function/skips-dead-branches-g/main.js

@ -0,0 +1,6 @@
var a = 0;
var b = 1;
var c = true ? a : b;
var d = false ? a : b;
console.log( c + d );
Loading…
Cancel
Save