diff --git a/core/src/main/java/org/teavm/ast/optimization/OptimizingVisitor.java b/core/src/main/java/org/teavm/ast/optimization/OptimizingVisitor.java index 280617112..25f892c17 100644 --- a/core/src/main/java/org/teavm/ast/optimization/OptimizingVisitor.java +++ b/core/src/main/java/org/teavm/ast/optimization/OptimizingVisitor.java @@ -246,7 +246,7 @@ class OptimizingVisitor implements StatementVisitor, ExprVisitor { pushLocation(expr.getLocation()); try { expr.getCondition().acceptVisitor(this); - Expr cond = resultExpr; + Expr cond = optimizeCondition(resultExpr); Statement barrier = addBarrier(); expr.getConsequent().acceptVisitor(this); @@ -786,7 +786,7 @@ class OptimizingVisitor implements StatementVisitor, ExprVisitor { @Override public void visit(ConditionalStatement statement) { statement.getCondition().acceptVisitor(this); - statement.setCondition(resultExpr); + statement.setCondition(optimizeCondition(resultExpr)); List consequent = processSequence(statement.getConsequent()); List alternative = processSequence(statement.getAlternative()); if (consequent.isEmpty()) { @@ -871,7 +871,14 @@ class OptimizingVisitor implements StatementVisitor, ExprVisitor { List newDefault = processSequence(statement.getDefaultClause()); statement.getDefaultClause().clear(); statement.getDefaultClause().addAll(newDefault); - resultStmt = statement; + + if (statement.getClauses().isEmpty()) { + SequentialStatement seq = new SequentialStatement(); + seq.getSequence().addAll(statement.getDefaultClause()); + resultStmt = seq; + } else { + resultStmt = statement; + } } @Override @@ -1074,4 +1081,19 @@ class OptimizingVisitor implements StatementVisitor, ExprVisitor { return false; } + + private Expr optimizeCondition(Expr expr) { + if (expr instanceof BinaryExpr) { + BinaryExpr binary = (BinaryExpr) expr; + if (isZero(((BinaryExpr) expr).getSecondOperand())) { + switch (binary.getOperation()) { + case EQUALS: + return ExprOptimizer.invert(binary.getFirstOperand()); + case NOT_EQUALS: + return binary.getFirstOperand(); + } + } + } + return expr; + } } diff --git a/core/src/main/java/org/teavm/backend/javascript/rendering/StatementRenderer.java b/core/src/main/java/org/teavm/backend/javascript/rendering/StatementRenderer.java index f823c1677..5a85eb571 100644 --- a/core/src/main/java/org/teavm/backend/javascript/rendering/StatementRenderer.java +++ b/core/src/main/java/org/teavm/backend/javascript/rendering/StatementRenderer.java @@ -1354,6 +1354,9 @@ public class StatementRenderer implements ExprVisitor, StatementVisitor { precedence = Precedence.CONDITIONAL.next(); expr.getExpr().acceptVisitor(this); writer.append(" instanceof ").appendClass(clsName); + if (needsParentheses) { + writer.append(')'); + } if (expr.getLocation() != null) { popLocation(); }