Java Code Examples for com.sun.source.tree.IfTree#getElseStatement()

The following examples show how to use com.sun.source.tree.IfTree#getElseStatement() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Flow.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Boolean visitBlock(BlockTree node, ConstructorData p) {
    List<? extends StatementTree> statements = new ArrayList<StatementTree>(node.getStatements());
    
    for (int i = 0; i < statements.size(); i++) {
        StatementTree st = statements.get(i);
        
        if (st.getKind() == Kind.IF) {
            IfTree it = (IfTree) st; 
            if (it.getElseStatement() == null && Utilities.exitsFromAllBranchers(info, new TreePath(new TreePath(getCurrentPath(), it), it.getThenStatement()))) {
                generalizedIf(it.getCondition(), it.getThenStatement(), statements.subList(i + 1, statements.size()), false);
                break;
            }
        }
        
        scan(st, null);
    }
    
    return null;
}
 
Example 2
Source File: EmptyStatements.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Hint(displayName = "#LBL_Empty_IF", description = "#DSC_Empty_IF", category = "empty", hintKind = Hint.Kind.INSPECTION, severity = Severity.VERIFIER, suppressWarnings = SUPPRESS_WARNINGS_KEY, id = "EmptyStatements_IF", enabled = false)
@TriggerTreeKind(Tree.Kind.EMPTY_STATEMENT)
public static ErrorDescription forIF(HintContext ctx) {
    final TreePath treePath = ctx.getPath();

    Tree parent = treePath.getParentPath().getLeaf();        
    if (!EnumSet.of(Kind.IF).contains(parent.getKind())) {
        return null;
    }
    
    TreePath treePathForWarning = treePath;
    IfTree it = (IfTree) parent;
    if (it.getThenStatement() != null
            && it.getThenStatement().getKind() == Tree.Kind.EMPTY_STATEMENT) {
        treePathForWarning = treePath.getParentPath();
            }
    if (it.getElseStatement() != null
            && it.getElseStatement().getKind() == Tree.Kind.EMPTY_STATEMENT) {
        treePathForWarning = treePath;
            }
    
    final List<Fix> fixes = new ArrayList<>();
    fixes.add(FixFactory.createSuppressWarningsFix(ctx.getInfo(), treePathForWarning, SUPPRESS_WARNINGS_KEY));
    
    return createErrorDescription(ctx, parent, fixes, parent.getKind());
}
 
Example 3
Source File: Ifs.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Hint(id="org.netbeans.modules.java.hints.suggestions.InvertIf", displayName = "#DN_InvertIf", description = "#DESC_InvertIf", category = "suggestions", hintKind= Hint.Kind.ACTION)
@UseOptions(SHOW_ELSE_MISSING)
@TriggerPattern(value = "if ($cond) $then; else $else$;")
@Messages({"ERR_InvertIf=Invert If",
           "FIX_InvertIf=Invert If"})
public static ErrorDescription computeWarning(HintContext ctx) {
    TreePath cond = ctx.getVariables().get("$cond");
    long conditionEnd = ctx.getInfo().getTrees().getSourcePositions().getEndPosition(cond.getCompilationUnit(), cond.getParentPath().getLeaf());
    if (ctx.getCaretLocation() > conditionEnd) return null;

    // parenthesized, then if
    TreePath ifPath = cond.getParentPath().getParentPath();
    if (ifPath.getLeaf().getKind() != Tree.Kind.IF) {
        return null;
    }
    IfTree iv = (IfTree)ifPath.getLeaf();
    if (iv.getElseStatement() == null && 
        !ctx.getPreferences().getBoolean(SHOW_ELSE_MISSING, SHOW_ELSE_MISSING_DEFAULT)) {
        return null;
    }
    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_InvertIf(), new FixImpl(ctx.getInfo(), ctx.getPath()).toEditorFix());
}
 
Example 4
Source File: Ifs.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(final TransformationContext ctx) throws Exception {
    IfTree toRewrite = (IfTree) ctx.getPath().getLeaf();
    StatementTree elseStatement = toRewrite.getElseStatement();
    if (toRewrite.getCondition() == null ||
        toRewrite.getCondition().getKind() != Tree.Kind.PARENTHESIZED) {
        return;
    }
    ParenthesizedTree ptt = (ParenthesizedTree)toRewrite.getCondition();
    if (ptt.getExpression() == null) {
        return;
    }
    if (elseStatement == null) elseStatement = ctx.getWorkingCopy().getTreeMaker().Block(Collections.<StatementTree>emptyList(), false);
    
    ctx.getWorkingCopy().rewrite(toRewrite, ctx.getWorkingCopy().getTreeMaker().If(toRewrite.getCondition(), elseStatement, toRewrite.getThenStatement()));
    ExpressionTree negated = Utilities.negate(
            ctx.getWorkingCopy().getTreeMaker(), ptt.getExpression(), ptt);
    ctx.getWorkingCopy().rewrite(ptt.getExpression(), negated);
}
 
Example 5
Source File: MethodMetrics.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Object visitReturn(ReturnTree node, Object p) {
    TreePath path = getCurrentPath();
    TreePath parentPath = path.getParentPath();
    if (suppress) {
        return  super.visitReturn(node, p);
    }
    if (ignoreGuards && parentPath != null) {
        Tree parentTree = parentPath.getLeaf();
        TreePath branchPath = path;
        while (parentTree.getKind() == Tree.Kind.BLOCK) {
            branchPath = parentPath;
            parentPath = parentPath.getParentPath();
            parentTree = parentPath.getLeaf();
        }
        if (parentTree.getKind() == Tree.Kind.IF) {
            IfTree ifTree = (IfTree)parentTree;
            StatementTree trueTree = ifTree.getThenStatement() == branchPath.getLeaf() ? 
                    ifTree.getThenStatement() : ifTree.getElseStatement();
            if (trueTree == node) {
                return  super.visitReturn(node, p);
            }
            if (trueTree.getKind() == Tree.Kind.BLOCK) {
                BlockTree bt = (BlockTree)trueTree;
                if (bt.getStatements().size() == 1) {
                    return  super.visitReturn(node, p);
                }
            }
        }
    }
    returnCount++;
    return super.visitReturn(node, p);
}
 
Example 6
Source File: Refactorer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private List<ProspectiveOperation> getIfListRepresentation( StatementTree tree, boolean last) {
    IfTree ifTree = (IfTree) tree;
    List<ProspectiveOperation> ls = new ArrayList<ProspectiveOperation>();
    if (ifTree.getElseStatement() == null) {

        StatementTree then = ifTree.getThenStatement();
        if (isOneStatementBlock(then)) {
            then = ((BlockTree) then).getStatements().get(0);
        }
        if (then.getKind() == Tree.Kind.RETURN) {
            ReturnTree returnTree = (ReturnTree) then;
            ExpressionTree returnExpression = returnTree.getExpression();
            if (returnExpression.getKind() == Tree.Kind.BOOLEAN_LITERAL && ((LiteralTree) returnExpression).getValue().equals(true)) {
                ls.addAll(ProspectiveOperation.createOperator(ifTree, ProspectiveOperation.OperationType.ANYMATCH, this.preconditionsChecker, this.workingCopy));
            } else if (returnExpression.getKind() == Tree.Kind.BOOLEAN_LITERAL && ((LiteralTree) returnExpression).getValue().equals(false)) {
                ls.addAll(ProspectiveOperation.createOperator(ifTree, ProspectiveOperation.OperationType.NONEMATCH, this.preconditionsChecker, this.workingCopy));
            }
        } else {
            ls.addAll(ProspectiveOperation.createOperator(ifTree, ProspectiveOperation.OperationType.FILTER, this.preconditionsChecker, this.workingCopy));
            ls.addAll(getListRepresentation(ifTree.getThenStatement(), last));
        }
    } else {

        ls.addAll(ProspectiveOperation.createOperator(ifTree, ProspectiveOperation.OperationType.MAP, this.preconditionsChecker, this.workingCopy));
    }
    return ls;
}
 
Example 7
Source File: RemoveSurroundingCodeAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean insideElse(CompilationController controller, IfTree ifTree, int caretPosition) {
    if (ifTree.getElseStatement() == null) {
        return false;
    }
    SourcePositions sp = controller.getTrees().getSourcePositions();
    int end = (int) sp.getEndPosition(controller.getCompilationUnit(), ifTree.getThenStatement());
    return end > 0 && caretPosition > end;
}
 
Example 8
Source File: ExpressionScanner.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Tree> visitIf(IfTree node, ExpressionScanner.ExpressionsInfo p) {
    List<Tree> cond = null;
    Tree lastCond = null;
    if (acceptsTree(node)) {
        cond = scan(node.getCondition(), p);
        if (cond != null) {
            lastCond = cond.get(cond.size() - 1);
        }
    }
    StatementTree thent = node.getThenStatement();
    StatementTree elset = node.getElseStatement();
    List<Tree> thenr = null;
    if (isCurrentTree(thent)) {
        thenr = scan(thent, p);
        if (lastCond != null && thenr != null) {
            p.addNextExpression(lastCond, thenr.get(0));
        }
    }
    List<Tree> elser = null;
    if (isCurrentTree(elset)) {
        elser = scan(elset, p);
        if (lastCond != null && elser != null) {
            p.addNextExpression(lastCond, elser.get(0));
        }
    }
    return reduce(reduce(cond, thenr), elser);
}
 
Example 9
Source File: ModelBuilder.java    From vertx-codetrans with Apache License 2.0 5 votes vote down vote up
private StatementModel build(List<ConditionalBlockModel> conditionals, IfTree node, VisitContext context) {
  ExpressionModel condition = scan(node.getCondition(), context);
  StatementModel body = scan(node.getThenStatement(), context);
  conditionals.add(new ConditionalBlockModel(condition, body));
  StatementTree elseStatement = node.getElseStatement();
  if (elseStatement != null) {
    if (elseStatement instanceof IfTree) {
      IfTree next = (IfTree) elseStatement;
      return build(conditionals, next, context);
    } else {
      return scan(node.getElseStatement(), context);
    }
  }
  return null;
}
 
Example 10
Source File: IfTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testEmptyElseBlock() throws Exception {
    testFile = new File(getWorkDir(), "IfTest.java");        
    TestUtilities.copyStringToFile(testFile, 
        "package foo.bar;\n" +
        "\n" +
        "public class IfTest {\n" +
        "    public void test(boolean b) {\n" +
        "        if( b ) {\n" +
        "        } else\n" +
        "            System.err.println(\"Hrebejk je hrebec.\");\n" +
        "    }\n" +
        "}\n"
        );
    String golden =
        "package foo.bar;\n" +
        "\n" +
        "public class IfTest {\n" +
        "    public void test(boolean b) {\n" +
        "        if( b ) {\n" +
        "        } else {\n" +
        "        }\n" +
        "    }\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            IfTree oldIf = (IfTree)method.getBody().getStatements().get(0);
            BlockTree block = make.Block(Collections.<StatementTree>emptyList(), false);
            StatementTree oldElse = oldIf.getElseStatement();
            workingCopy.rewrite(oldElse, block);
        }

        public void cancel() {
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 11
Source File: Braces.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy copy = ctx.getWorkingCopy();
    TreePath path = ctx.getPath();
    if ( path != null ) {

        TreeMaker make = copy.getTreeMaker();
        Tree oldTree = path.getLeaf();

        oldTree = GeneratorUtilities.get(copy).importComments(oldTree, copy.getCompilationUnit());

        switch( oldTree.getKind() ) {
        case FOR_LOOP:
            ForLoopTree oldFor = (ForLoopTree)oldTree;
            StatementTree oldBlock = oldFor.getStatement();
            BlockTree newBlock = make.Block(Collections.<StatementTree>singletonList(oldBlock), false);
            copy.rewrite(oldBlock, newBlock);
            break;
        case ENHANCED_FOR_LOOP:
            EnhancedForLoopTree oldEnhancedFor = (EnhancedForLoopTree)oldTree;
            oldBlock = oldEnhancedFor.getStatement();
            newBlock = make.Block(Collections.<StatementTree>singletonList(oldBlock), false);
            copy.rewrite(oldBlock, newBlock);
            break;
        case WHILE_LOOP:
            WhileLoopTree oldWhile = (WhileLoopTree)oldTree;
            oldBlock = oldWhile.getStatement();
            newBlock = make.Block(Collections.<StatementTree>singletonList(oldBlock), false);
            copy.rewrite(oldBlock, newBlock);
            break;
        case DO_WHILE_LOOP:
            DoWhileLoopTree oldDoWhile = (DoWhileLoopTree)oldTree;
            oldBlock = oldDoWhile.getStatement();
            newBlock = make.Block(Collections.<StatementTree>singletonList(oldBlock), false);
            copy.rewrite(oldBlock, newBlock);
            break;
        case IF:
            IfTree oldIf = (IfTree)oldTree;
            if ( fixThen ) {
                oldBlock = oldIf.getThenStatement();
                newBlock = make.Block(Collections.<StatementTree>singletonList(oldBlock), false);
                copy.rewrite(oldBlock, newBlock);
            }
            if ( fixElse ) {
                oldBlock = oldIf.getElseStatement();
                newBlock = make.Block(Collections.<StatementTree>singletonList(oldBlock), false);
                copy.rewrite(oldBlock, newBlock);
            }

        }
    }
}
 
Example 12
Source File: Tiny.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Hint(displayName = "#DN_indentation", description = "#DESC_indentation", category="bugs", suppressWarnings="SuspiciousIndentAfterControlStatement", options=Options.QUERY)
@TriggerTreeKind({Kind.IF, Kind.WHILE_LOOP, Kind.FOR_LOOP, Kind.ENHANCED_FOR_LOOP})
public static ErrorDescription indentation(HintContext ctx) {
    Tree firstStatement;
    Tree found = ctx.getPath().getLeaf();
    
    switch (found.getKind()) {
        case IF:
            IfTree it = (IfTree) found;
            if (it.getElseStatement() != null) firstStatement = it.getElseStatement();
            else firstStatement = it.getThenStatement();
            break;
        case WHILE_LOOP:
            firstStatement = ((WhileLoopTree) found).getStatement();
            break;
        case FOR_LOOP:
            firstStatement = ((ForLoopTree) found).getStatement();
            break;
        case ENHANCED_FOR_LOOP:
            firstStatement = ((EnhancedForLoopTree) found).getStatement();
            break;
        default:
            return null;
    }
    
    if (firstStatement != null && firstStatement.getKind() == Kind.BLOCK) {
        return null;
    }
    
    Tree parent = ctx.getPath().getParentPath().getLeaf();
    List<? extends Tree> parentStatements;
    
    switch (parent.getKind()) {
        case BLOCK: parentStatements = ((BlockTree) parent).getStatements(); break;
        case CASE: parentStatements = ((CaseTree) parent).getStatements(); break;
        default: return null;
    }
    
    int index = parentStatements.indexOf(found);
    
    if (index < 0 || index + 1 >= parentStatements.size()) return null;
    
    Tree secondStatement = parentStatements.get(index + 1);
    int firstIndent = indent(ctx, firstStatement);
    int secondIndent = indent(ctx, secondStatement);
    
    if (firstIndent == (-1) || secondIndent == (-1) || firstIndent != secondIndent) return null;
    
    return ErrorDescriptionFactory.forTree(ctx, secondStatement, Bundle.ERR_indentation());
}
 
Example 13
Source File: DoubleCheck.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Checks, that the two if statements test the same variable. Returns the tree that references
 * the guard variable if the two ifs are the same, or {@code null} if the ifs do not match.
 * @param info
 * @param statementTP
 * @param secondTP
 * @return 
 */
private static TreePath sameIfAndValidate(CompilationInfo info, TreePath statementTP, TreePath secondTP, TreePath[] fieldRef) {
    StatementTree statement = (StatementTree) statementTP.getLeaf();
    
    if (statement.getKind() != Kind.IF) {
        return null;
    }
    
    IfTree first = (IfTree)statement;
    IfTree second = (IfTree) secondTP.getLeaf();
    
    if (first.getElseStatement() != null) {
        return null;
    }
    if (second.getElseStatement() != null) {
        return null;
    }
    
    TreePath varFirst = equalToNull(new TreePath(statementTP, first.getCondition()));
    TreePath varSecond = equalToNull(new TreePath(secondTP, second.getCondition()));
    
    if (varFirst == null || varSecond == null) {
        return null;
    }

    Element firstVariable = info.getTrees().getElement(varFirst);
    Element secondVariable = info.getTrees().getElement(varSecond);
    Element target = firstVariable;
    if (firstVariable != null && firstVariable.equals(secondVariable)) {
        TreePath var = info.getTrees().getPath(firstVariable);
        if (info.getSourceVersion().compareTo(SourceVersion.RELEASE_5) < 0) {
            fieldRef[0] = var;
            return varFirst;
        }
        if (firstVariable.getKind() == ElementKind.LOCAL_VARIABLE) {
            // check how the variable was assigned:
            TreePath methodPath = Utilities.findTopLevelBlock(varFirst);
            FlowResult fr = Flow.assignmentsForUse(info, methodPath, new AtomicBoolean(false));
            Iterable<? extends TreePath> itp = fr.getAssignmentsForUse().get(varFirst.getLeaf());
            
            if (itp != null) {
                Iterator<? extends TreePath> i = itp.iterator();
                if (i.hasNext()) {
                    TreePath v = i.next();
                    if (!i.hasNext()) {
                        // if the local variable has exactly one possible value,
                        // use it as the field 
                        target = info.getTrees().getElement(v);
                        if (target != null && target.getKind() == ElementKind.FIELD) {
                            var = info.getTrees().getPath(target);
                            if (!sameCompilationUnit(var, varFirst)) {
                                // the variable is somewhere ... 
                                var = info.getTrees().getPath(firstVariable);
                            }
                        }
                    }
                }
            }
        }
        fieldRef[0] = var;
        return varFirst;
    }
    
    return null;
}