Java Code Examples for com.sun.source.tree.CaseTree#getStatements()

The following examples show how to use com.sun.source.tree.CaseTree#getStatements() . 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: CopyFinder.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static List<? extends StatementTree> getStatements(TreePath firstLeaf) {
    switch (firstLeaf.getParentPath().getLeaf().getKind()) {
        case BLOCK:
            return ((BlockTree) firstLeaf.getParentPath().getLeaf()).getStatements();
        case CASE:
            CaseTree caseTree = (CaseTree) firstLeaf.getParentPath().getLeaf();
            if (caseTree.getStatements() != null) {
                return caseTree.getStatements();
            } else if (TreeShims.getBody(caseTree) instanceof StatementTree) {
                return Collections.singletonList((StatementTree) TreeShims.getBody(caseTree));
            } else {
                return null;
            }
        default:
            return Collections.singletonList((StatementTree) firstLeaf.getLeaf());
    }
}
 
Example 2
Source File: VarCompoundDeclarationTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Fix compound variable declaration in switch-case statement.
 * array type.
 * @throws IOException
 */
private void rewriteCaseStatement() throws IOException {

    JavaSource js = getJavaSource();
    assertNotNull(js);

    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            SwitchTree st = (SwitchTree) method.getBody().getStatements().get(1);
            
            CaseTree ct = st.getCases().get(0);
            List<? extends StatementTree> statements = ct.getStatements();
                    
            for (int current = 0; current < statements.size(); current++) {
                StatementTree t = (StatementTree) statements.get(current);
                if (t instanceof VariableTree) {
                    VariableTree oldVariableTree = (VariableTree) t;
                    VariableTree newVariableTree = make.Variable(
                            oldVariableTree.getModifiers(),
                            oldVariableTree.getName(),
                            make.Type("var"), // NOI18N
                            oldVariableTree.getInitializer()
                    );
                    workingCopy.rewrite(oldVariableTree, newVariableTree);

                }

            }
        }
    };

    js.runModificationTask(task).commit();
}
 
Example 3
Source File: CyclomaticComplexityVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Do not add complexity for empty cases - they merge with the
 * following one.
 */
@Override
public Object visitCase(CaseTree node, Object p) {
    if (node.getStatements() != null) {
        complexity++;
    }
    boolean saveFlag = switchCase;
    switchCase = true;
    Object o = super.visitCase(node, p);
    this.switchCase = saveFlag;
    return o;
}
 
Example 4
Source File: ConvertSwitchToRuleSwitch.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind(Tree.Kind.SWITCH)
@Messages({"ERR_ConvertSwitchToRuleSwitch=Convert switch to rule switch", "ERR_ConvertSwitchToSwitchExpression=Convert to switch expression"})
public static ErrorDescription switch2RuleSwitch(HintContext ctx) {
    if (Utilities.isJDKVersionLower(SWITCH_RULE_PREVIEW_JDK_VERSION) && !CompilerOptionsQuery.getOptions(ctx.getInfo().getFileObject()).getArguments().contains("--enable-preview"))
        return null;
    SwitchTree st = (SwitchTree) ctx.getPath().getLeaf();
    boolean completesNormally = false;
    boolean wasDefault = false;
    boolean wasEmpty = false;
    for (CaseTree ct : st.getCases()) {
        if (ct.getStatements() == null) //TODO: test
            return null;
        if (completesNormally) {
            if (!wasEmpty) //fall-through from a non-empty case
                return null;
            if (wasDefault) //fall-through from default to a case
                return null;
            if (!wasDefault && ct.getExpression() == null) //fall-through from a case to default
                return null;
        }
        completesNormally = Utilities.completesNormally(ctx.getInfo(), new TreePath(ctx.getPath(), ct));
        wasDefault = ct.getExpression() == null;
        wasEmpty = ct.getStatements().isEmpty();
    }
    if (wasDefault && Utilities.isCompatibleWithSwitchExpression(st)) {
        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_ConvertSwitchToSwitchExpression(), new FixImpl1(ctx.getInfo(), ctx.getPath()).toEditorFix());
    } else {
        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_ConvertSwitchToRuleSwitch(), new FixImpl(ctx.getInfo(), ctx.getPath()).toEditorFix());
    }
}
 
Example 5
Source File: DifferentCaseKindsFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    if (Utilities.isJDKVersionLower(SWITCH_RULE_PREVIEW_JDK_VERSION) && !CompilerOptionsQuery.getOptions(info.getFileObject()).getArguments().contains("--enable-preview")) {
        return null;
    }
    TreePath parentPath = treePath.getParentPath();
    List<? extends CaseTree> caseTrees = null;
    boolean flag = false;
    if(parentPath.getLeaf().getKind().toString().equals(TreeShims.SWITCH_EXPRESSION)){
        caseTrees = TreeShims.getCases(parentPath.getLeaf());            
    } else {
        flag = true;
        caseTrees = ((SwitchTree) treePath.getParentPath().getLeaf()).getCases();
    }
        boolean completesNormally = false;
        boolean wasDefault = false;
        boolean wasEmpty = false;
        for (CaseTree ct : caseTrees) {
            if (ct.getStatements() == null && TreeShims.getBody(ct) == null) {
                return null;
            } else if (flag && ct.getStatements() != null) {
                if (completesNormally) {
                    if (!wasEmpty) {//fall-through from a non-empty case
                        return null;
                    }
                    if (wasDefault) {//fall-through from default to a case
                        return null;
                    }
                    if (!wasDefault && ct.getExpression() == null) {//fall-through from a case to default
                        return null;
                    }
                }
                completesNormally = Utilities.completesNormally(info, new TreePath(treePath.getParentPath(), ct));
                wasDefault = ct.getExpression() == null;
                wasEmpty = ct.getStatements().isEmpty();
            }
        }      

    return Collections.<Fix>singletonList(new DifferentCaseKindsFix.FixImpl(info, treePath).toEditorFix());
}
 
Example 6
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<? extends StatementTree> getSwitchStatement(CaseTree ct) {
     if (ct.getStatements() != null) {
         return ct.getStatements();
     } else if (ct instanceof JCTree.JCCase) {
         return ((JCTree.JCCase) ct).stats;
     } else {
         return null;
     }
}
 
Example 7
Source File: CompletenessStressTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private boolean testBlock(StringWriter writer, SourcePositions sp, String text, CompilationUnitTree cut, BlockTree blockTree) {
    boolean success = true;
    for (StatementTree st : blockTree.getStatements()) {
        if (isLegal(st)) {
            success &= testStatement(writer, sp, text, cut, st);
        }
        if (st instanceof IfTree) {
            IfTree ifTree = (IfTree) st;
            success &= testBranch(writer, sp, text, cut, ifTree.getThenStatement());
            success &= testBranch(writer, sp, text, cut, ifTree.getElseStatement());
        } else if (st instanceof WhileLoopTree) {
            WhileLoopTree whileLoopTree = (WhileLoopTree) st;
            success &= testBranch(writer, sp, text, cut, whileLoopTree.getStatement());
        } else if (st instanceof DoWhileLoopTree) {
            DoWhileLoopTree doWhileLoopTree = (DoWhileLoopTree) st;
            success &= testBranch(writer, sp, text, cut, doWhileLoopTree.getStatement());
        } else if (st instanceof ForLoopTree) {
            ForLoopTree forLoopTree = (ForLoopTree) st;
            success &= testBranch(writer, sp, text, cut, forLoopTree.getStatement());
        } else if (st instanceof LabeledStatementTree) {
            LabeledStatementTree labelTree = (LabeledStatementTree) st;
            success &= testBranch(writer, sp, text, cut, labelTree.getStatement());
        } else if (st instanceof SwitchTree) {
            SwitchTree switchTree = (SwitchTree) st;
            for (CaseTree caseTree : switchTree.getCases()) {
                for (StatementTree statementTree : caseTree.getStatements()) {
                    success &= testBranch(writer, sp, text, cut, statementTree);
                }
            }
        }
    }
    return success;
}
 
Example 8
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private TreeNode convertSwitch(SwitchTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  SwitchStatement newNode =
      new SwitchStatement().setExpression(convertWithoutParens(node.getExpression(), path));
  for (CaseTree switchCase : node.getCases()) {
    newNode.addStatement((SwitchCase) convert(switchCase, path));
    TreePath switchCasePath = getTreePath(path, switchCase);
    for (StatementTree s : switchCase.getStatements()) {
      newNode.addStatement((Statement) convert(s, switchCasePath));
    }
  }
  return newNode;
}
 
Example 9
Source File: SwitchExpressionTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Rewrite Switch Expression cases.
 *
 * @throws IOException
 */
private void rewriteSwitchExpression() throws IOException {

    JavaSource js = getJavaSource();
    assertNotNull(js);

    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            List<CaseTree> newCases = new ArrayList<>();
            VariableTree switcExpression = (VariableTree) ((BlockTree) method.getBody()).getStatements().get(0);
            Tree switchBlock = switcExpression.getInitializer();
            List<? extends CaseTree> cases;
            List<ExpressionTree> patterns = new ArrayList<>();
            boolean switchExpressionFlag = switchBlock.getKind().toString().equals(TreeShims.SWITCH_EXPRESSION);
            if (switchExpressionFlag) {
                cases = TreeShims.getCases(switchBlock);
            } else {
                cases = ((SwitchTree) switchBlock).getCases();
            }
            for (Iterator<? extends CaseTree> it = cases.iterator(); it.hasNext();) {
                CaseTree ct = it.next();
                patterns.addAll(TreeShims.getExpressions(ct));
                List<StatementTree> statements;
                if (ct.getStatements() == null) {
                    statements = new ArrayList<>(((JCTree.JCCase) ct).stats);
                } else {
                    statements = new ArrayList<>(ct.getStatements());
                }
                if (statements.isEmpty()) {
                    if (it.hasNext()) {
                        continue;
                    }
                }
                Set<Element> seenVariables = new HashSet<>();
                int idx = 0;
                for (StatementTree statement : new ArrayList<>(statements)) {
                    Tree body = make.Block(statements, false);
                    if (statements.size() == 1) {
                        if (statements.get(0).getKind() == Tree.Kind.EXPRESSION_STATEMENT
                                || statements.get(0).getKind() == Tree.Kind.THROW
                                || statements.get(0).getKind() == Tree.Kind.BLOCK) {
                            body = statements.get(0);
                        }
                    }
                    newCases.add(make.Case(patterns, body));
                    patterns = new ArrayList<>();
                }
            }
            workingCopy.rewrite(switchBlock, make.SwitchExpression(TreeShims.getExpressions(switchBlock).get(0), newCases));
        }

    };

    js.runModificationTask(task).commit();
}
 
Example 10
Source File: Utilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static boolean isCompatibleWithSwitchExpression(SwitchTree st) {
    boolean firstCase = true;
    Name leftTreeName = null;
    int caseCount = 0;
    List<? extends CaseTree> cases = st.getCases();

    for (CaseTree ct : cases) {
        caseCount++;
        List<StatementTree> statements = new ArrayList<>(ct.getStatements());
        switch (statements.size()) {
            case 0:
                break;
            case 1:
                if (firstCase && leftTreeName == null && statements.get(0).getKind() == Tree.Kind.RETURN) {
                    break;
                } else if (caseCount == cases.size() && statements.get(0).getKind() == Tree.Kind.EXPRESSION_STATEMENT) {
                    if (firstCase) {
                        leftTreeName = getLeftTreeName(statements.get(0));
                        if (leftTreeName == null) {
                            return false;
                        }
                        break;
                    } else {
                        if (leftTreeName != null && leftTreeName.contentEquals(getLeftTreeName(statements.get(0)))) {
                            break;
                        } else {
                            return false;
                        }
                    }
                } else {
                    return false;
                }
            case 2:
                if (statements.get(0).getKind() == Tree.Kind.EXPRESSION_STATEMENT && statements.get(1).getKind() == Tree.Kind.BREAK) {
                    if (firstCase) {
                        leftTreeName = getLeftTreeName(statements.get(0));
                        if (leftTreeName == null) {
                            return false;
                        }
                        firstCase = false;
                    }
                    if (leftTreeName != null && leftTreeName.contentEquals(getLeftTreeName(statements.get(0)))) {
                        break;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            default:
                return false;
        }
    }
    return true;
}