diff --git a/src/ast/nodes/IfStatement.js b/src/ast/nodes/IfStatement.js index 9e6f0fc..fe83a78 100644 --- a/src/ast/nodes/IfStatement.js +++ b/src/ast/nodes/IfStatement.js @@ -1,6 +1,16 @@ import Statement from './shared/Statement.js'; import { UNKNOWN } from '../values.js'; +// Statement types which may contain if-statements as direct children. +const statementsWithIfStatements = new Set([ + 'DoWhileStatement', + 'ForInStatement', + 'ForOfStatement', + 'ForStatement', + 'IfStatement', + 'WhileStatement' +]); + // TODO DRY this out export default class IfStatement extends Statement { initialise ( scope ) { @@ -14,7 +24,9 @@ export default class IfStatement extends Statement { else if ( this.testValue ) { this.consequent.initialise( scope ); this.alternate = null; - } else { + } + + else { if ( this.alternate ) this.alternate.initialise( scope ); this.consequent = null; } @@ -41,9 +53,18 @@ export default class IfStatement extends Statement { code.remove( this.start, this.consequent.start ); code.remove( this.consequent.end, this.end ); this.consequent.render( code, es ); - } else { + } + + else { code.remove( this.start, this.alternate ? this.alternate.start : this.next || this.end ); - if ( this.alternate ) this.alternate.render( code, es ); + + if ( this.alternate ) { + this.alternate.render( code, es ); + } + + else if ( statementsWithIfStatements.has( this.parent.type ) ) { + code.insertRight( this.start, '{}' ); + } } } } diff --git a/test/function/if-statement-with-false-condition/_config.js b/test/function/if-statement-with-false-condition/_config.js new file mode 100644 index 0000000..b7eda7a --- /dev/null +++ b/test/function/if-statement-with-false-condition/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'if statements with false condition do not break render (#973)' +}; diff --git a/test/function/if-statement-with-false-condition/main.js b/test/function/if-statement-with-false-condition/main.js new file mode 100644 index 0000000..59bf4fd --- /dev/null +++ b/test/function/if-statement-with-false-condition/main.js @@ -0,0 +1,47 @@ +export function whileIf(x) { + while (x) + if (false) + // replaced with {} + x = 0; +} + +export function whileBlockIf(x) { + while (x) { + if (false) + // removed + x = 0; + } +} + +export function ifWhile(x) { + if (x) + while (false) + // not optimized + x = 0; +} + +export function ifFalseElse(x) { + if (false) { + // removed + } else { + // kept + } +} + +export function elseIfFalse(x) { + if (x) { + // kept + } else if (false) { + // replaced with {} + } +} + +export function elseIfFalseElse(x) { + if (x) { + // kept + } else if (false) { + // removed + } else { + // kept + } +}