com.sun.source.tree.CaseTree Java Examples

The following examples show how to use com.sun.source.tree.CaseTree. 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: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitSwitch(SwitchTree node, Void unused) {
    sync(node);
    token("switch");
    builder.space();
    token("(");
    scan(skipParen(node.getExpression()), null);
    token(")");
    builder.space();
    tokenBreakTrailingComment("{", plusTwo);
    builder.blankLineWanted(BlankLineWanted.NO);
    builder.open(plusTwo);
    boolean first = true;
    for (CaseTree caseTree : node.getCases()) {
        if (!first) {
            builder.blankLineWanted(BlankLineWanted.PRESERVE);
        }
        scan(caseTree, null);
        first = false;
    }
    builder.close();
    builder.forcedBreak();
    builder.blankLineWanted(BlankLineWanted.NO);
    token("}", plusFour);
    return null;
}
 
Example #2
Source File: IntroduceHint.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static void removeFromParent(WorkingCopy parameter, TreePath what) throws IllegalAccessException {
    final TreeMaker make = parameter.getTreeMaker();
    Tree parentTree = what.getParentPath().getLeaf();
    Tree original = what.getLeaf();
    Tree newParent;

    switch (parentTree.getKind()) {
        case BLOCK:
            newParent = make.removeBlockStatement((BlockTree) parentTree, (StatementTree) original);
            break;
        case CASE:
            newParent = make.removeCaseStatement((CaseTree) parentTree, (StatementTree) original);
            break;
        case CLASS:
        case ENUM:
        case INTERFACE:
            newParent = make.removeClassMember((ClassTree)parentTree, original);
            break;
        default:
            throw new IllegalAccessException(parentTree.getKind().toString());
    }

    parameter.rewrite(parentTree, newParent);
}
 
Example #3
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Void visitCase(CaseTree node, Void unused) {
    sync(node);
    markForPartialFormat();
    builder.forcedBreak();
    if (node.getExpression() == null) {
        token("default", plusTwo);
        token(":");
    } else {
        token("case", plusTwo);
        builder.space();
        scan(node.getExpression(), null);
        token(":");
    }
    builder.open(plusTwo);
    try {
        // don't partially format within case groups
        inExpression.addLast(true);
        visitStatements(node.getStatements());
    } finally {
        inExpression.removeLast();
    }
    builder.close();
    return null;
}
 
Example #4
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Void visitSwitch(SwitchTree node, Void unused) {
    sync(node);
    token("switch");
    builder.space();
    token("(");
    scan(skipParen(node.getExpression()), null);
    token(")");
    builder.space();
    tokenBreakTrailingComment("{", plusTwo);
    builder.blankLineWanted(BlankLineWanted.NO);
    builder.open(plusTwo);
    boolean first = true;
    for (CaseTree caseTree : node.getCases()) {
        if (!first) {
            builder.blankLineWanted(BlankLineWanted.PRESERVE);
        }
        scan(caseTree, null);
        first = false;
    }
    builder.close();
    builder.forcedBreak();
    builder.blankLineWanted(BlankLineWanted.NO);
    token("}", plusFour);
    return null;
}
 
Example #5
Source File: TranslateIdentifier.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Void visitIdentifier(IdentifierTree node, Void p) {
    TreePath path = getCurrentPath();
    Element element = info.getTrees().getElement(path);
    
    if (element != null && element.asType().getKind() != TypeKind.ERROR) {
        // solve the imports only when declared type!!!
        if (element.getKind().isClass() || element.getKind().isInterface()
                || (element.getKind().isField() && ((Symbol) element).isStatic())) {
            Tree parent = path.getParentPath() != null ? path.getParentPath().getLeaf() : null;
            
            if (   (parent != null && parent.getKind() == Kind.CASE && ((CaseTree) parent).getExpression() == node && element.getKind() == ElementKind.ENUM_CONSTANT)
                || (path.getCompilationUnit() != null && ((Symbol) element).enclClass() != null && path.getCompilationUnit().getSourceFile() == ((Symbol) element).enclClass().sourcefile)) {
                translateMap.put(node, make.Identifier(element.getSimpleName()));
            } else {
                translateMap.put(node, make.QualIdent(element));
            }
        } 
    }
    
    return null;
}
 
Example #6
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitCase(CaseTree node, Void unused) {
  sync(node);
  markForPartialFormat();
  builder.forcedBreak();
  if (node.getExpression() == null) {
    token("default", plusTwo);
    token(":");
  } else {
    token("case", plusTwo);
    builder.space();
    scan(node.getExpression(), null);
    token(":");
  }
  builder.open(plusTwo);
  visitStatements(node.getStatements());
  builder.close();
  return null;
}
 
Example #7
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 6 votes vote down vote up
protected void visitSwitch(ExpressionTree expression, List<? extends CaseTree> cases) {
  token("switch");
  builder.space();
  token("(");
  scan(skipParen(expression), null);
  token(")");
  builder.space();
  tokenBreakTrailingComment("{", plusTwo);
  builder.blankLineWanted(BlankLineWanted.NO);
  builder.open(plusTwo);
  boolean first = true;
  for (CaseTree caseTree : cases) {
    if (!first) {
      builder.blankLineWanted(BlankLineWanted.PRESERVE);
    }
    scan(caseTree, null);
    first = false;
  }
  builder.close();
  builder.forcedBreak();
  builder.blankLineWanted(BlankLineWanted.NO);
  token("}", plusFour);
}
 
Example #8
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 #9
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitCase(CaseTree node, Void unused) {
    sync(node);
    markForPartialFormat();
    builder.forcedBreak();
    if (node.getExpression() == null) {
        token("default", plusTwo);
        token(":");
    } else {
        token("case", plusTwo);
        builder.space();
        scan(node.getExpression(), null);
        token(":");
    }
    builder.open(plusTwo);
    try {
        // don't partially format within case groups
        inExpression.addLast(true);
        visitStatements(node.getStatements());
    } finally {
        inExpression.removeLast();
    }
    builder.close();
    return null;
}
 
Example #10
Source File: TreeNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitCase(CaseTree tree, List<Node> d) {
    List<Node> below = new ArrayList<Node>();
    
    addCorrespondingType(below);
    addCorrespondingComments(below);
    super.visitCase(tree, below);
    
    d.add(new TreeNode(info, getCurrentPath(), below));
    return null;
}
 
Example #11
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 #12
Source File: TreeDiffer.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitCase(CaseTree expected, Tree actual) {
  Optional<CaseTree> other = checkTypeAndCast(expected, actual);
  if (!other.isPresent()) {
    addTypeMismatch(expected, actual);
    return null;
  }

  scan(expected.getExpression(), other.get().getExpression());
  parallelScan(expected.getStatements(), other.get().getStatements());
  return null;
}
 
Example #13
Source File: IntroduceHint.java    From netbeans with Apache License 2.0 5 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:
            return ((CaseTree) firstLeaf.getParentPath().getLeaf()).getStatements();
        default:
            return Collections.singletonList((StatementTree) firstLeaf.getLeaf());
    }
}
 
Example #14
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 #15
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static @NonNull Collection<? extends TreePath> resolveFieldGroup(@NonNull CompilationInfo info, @NonNull TreePath variable) {
    Tree leaf = variable.getLeaf();

    if (leaf.getKind() != Kind.VARIABLE) {
        return Collections.singleton(variable);
    }

    TreePath parentPath = variable.getParentPath();
    Iterable<? extends Tree> children;

    switch (parentPath.getLeaf().getKind()) {
        case BLOCK: children = ((BlockTree) parentPath.getLeaf()).getStatements(); break;
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            children = ((ClassTree) parentPath.getLeaf()).getMembers(); break;
        case CASE:  children = ((CaseTree) parentPath.getLeaf()).getStatements(); break;
        default:    children = Collections.singleton(leaf); break;
    }

    List<TreePath> result = new LinkedList<TreePath>();
    ModifiersTree currentModifiers = ((VariableTree) leaf).getModifiers();

    for (Tree c : children) {
        if (c.getKind() != Kind.VARIABLE) continue;

        if (((VariableTree) c).getModifiers() == currentModifiers) {
            result.add(new TreePath(parentPath, c));
        }
    }
    
    return result;
}
 
Example #16
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean visitSwitch(SwitchTree node, Void p) {
    boolean lastCaseExit = false;
    boolean defaultSeen = false;
    Set<Element> enumValues = null;
    
    if (node.getExpression() != null) {
        TypeMirror exprType = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
        if (isValidType(exprType) && exprType.getKind() == TypeKind.DECLARED) {
            Element el = ((DeclaredType)exprType).asElement();
            enumValues = new HashSet<>();
            for (Element f : el.getEnclosedElements()) {
                if (f.getKind() == ElementKind.ENUM_CONSTANT) {
                    enumValues.add(f);
                }
            }
        }
    }
    for (CaseTree ct : node.getCases()) {
        Boolean res = scan(ct, null);
        if (res == Boolean.FALSE) {
            return res;
        }
        lastCaseExit = res == Boolean.TRUE;
        if (ct.getExpression() == null) {
            defaultSeen = true;
        } else if (enumValues != null ) {
            TreePath casePath = new TreePath(getCurrentPath(), ct);
            Element v = info.getTrees().getElement(new TreePath(
                    casePath, ct.getExpression()));
            if (v != null) {
                enumValues.remove(v);
            }
        }
    }
    if (enumValues != null && enumValues.isEmpty()) {
        defaultSeen = true;
    }
    return lastCaseExit == Boolean.TRUE && defaultSeen;
}
 
Example #17
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static List<TreePath> getStatementPaths(TreePath firstLeaf) {
    switch (firstLeaf.getParentPath().getLeaf().getKind()) {
        case BLOCK:
            return getTreePaths(firstLeaf.getParentPath(), ((BlockTree) firstLeaf.getParentPath().getLeaf()).getStatements());
        case CASE:
            return getTreePaths(firstLeaf.getParentPath(), ((CaseTree) firstLeaf.getParentPath().getLeaf()).getStatements());
        default:
            return Collections.singletonList(firstLeaf);
    }
}
 
Example #18
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 #19
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<? extends TypeMirror> visitSwitch(SwitchTree node, Object p) {
    if (theExpression == null) {
        initExpression(node.getExpression());
    }
    for (CaseTree cs : node.getCases()) {
        if (cs.getExpression() != null) {
            TreePath casePath = new TreePath(getCurrentPath(), cs);
            TypeMirror caseType = info.getTrees().getTypeMirror(new TreePath(casePath, cs.getExpression()));
            return Collections.singletonList(caseType);
        }
    }
    // cannot determine
    return null;
}
 
Example #20
Source File: Tiny.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath tp = ctx.getPath();
    Tree parent = tp.getParentPath().getLeaf();
    List<? extends StatementTree> statements;

    switch (parent.getKind()) {
        case BLOCK: statements = ((BlockTree) parent).getStatements(); break;
        case CASE: statements = ((CaseTree) parent).getStatements(); break;
        default: throw new IllegalStateException(parent.getKind().name());
    }

    VariableTree var = (VariableTree) tp.getLeaf();
    int current = statements.indexOf(tp.getLeaf());
    TreeMaker make = wc.getTreeMaker();
    List<StatementTree> newStatements = new ArrayList<StatementTree>();

    newStatements.addAll(statements.subList(0, current));
    newStatements.add(
        make.asReplacementOf(
            make.Variable(var.getModifiers(), var.getName(), var.getType(), null),
            var)
    );
    newStatements.add(make.ExpressionStatement(make.Assignment(make.Identifier(var.getName()), var.getInitializer())));
    newStatements.addAll(statements.subList(current + 1, statements.size()));

    Tree target;

    switch (parent.getKind()) {
        case BLOCK: target = make.Block(newStatements, ((BlockTree) parent).isStatic()); break;
        case CASE: target = make.Case(((CaseTree) parent).getExpression(), newStatements); break;
        default: throw new IllegalStateException(parent.getKind().name());
    }

    wc.rewrite(parent, target);
}
 
Example #21
Source File: IntroduceClass.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<? extends StatementTree> getStatements(TreePath firstLeaf) {
    Tree parentsLeaf = firstLeaf.getLeaf();
    List<? extends StatementTree> statements;
    switch (parentsLeaf.getKind()) {
        case BLOCK:
            statements = ((BlockTree) parentsLeaf).getStatements();
            break;
        case CASE:
            statements = ((CaseTree) parentsLeaf).getStatements();
            break;
        default:
            Tree first = firstLeaf.getLeaf();
            if (Tree.Kind.EXPRESSION_STATEMENT.equals(first.getKind())) {
                statements = Collections.singletonList((StatementTree) firstLeaf.getLeaf());
            } else {
                statements = Collections.emptyList();
            }
    }
    int s = statements.size();
    boolean haveOriginalStatements = true;
    while (s > 0 && ";".equals(statements.get(--s).toString().trim())) {
        if (haveOriginalStatements) {
            statements = new ArrayList<>(statements);
            haveOriginalStatements = false;
        }
        statements.remove(s);
    }
    return statements;
}
 
Example #22
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 #23
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private TreeNode convertCase(CaseTree node, TreePath parent) {
  // Case statements are converted in convertSwitch().
  SwitchCase newNode = new SwitchCase();
  ExpressionTree expressionTree = node.getExpression();
  if (expressionTree != null) {
    newNode.setExpression((Expression) convert(expressionTree, getTreePath(parent, node)));
  } else {
    newNode.setIsDefault(true);
  }
  return newNode;
}
 
Example #24
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 #25
Source File: Java14InputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitCase(CaseTree node, Void unused) {
  sync(node);
  markForPartialFormat();
  builder.forcedBreak();
  if (node.getExpressions().isEmpty()) {
    token("default", plusTwo);
  } else {
    token("case", plusTwo);
    builder.space();
    boolean first = true;
    for (ExpressionTree expression : node.getExpressions()) {
      if (!first) {
        token(",");
        builder.space();
      }
      scan(expression, null);
      first = false;
    }
  }
  switch (node.getCaseKind()) {
    case STATEMENT:
      token(":");
      builder.open(plusTwo);
      visitStatements(node.getStatements());
      builder.close();
      break;
    case RULE:
      builder.space();
      token("-");
      token(">");
      builder.space();
      scan(node.getBody(), null);
      builder.guessToken(";");
      break;
    default:
      throw new AssertionError(node.getCaseKind());
  }
  return null;
}
 
Example #26
Source File: TreeDuplicator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Tree visitCase(CaseTree tree, Void p) {
    CaseTree n = make.Case(tree.getExpression(), tree.getStatements());
    model.setType(n, model.getType(tree));
    comments.copyComments(tree, n);
    model.setPos(n, model.getPos(tree));
    return n;
}
 
Example #27
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 #28
Source File: SwitchTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void test158129() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    String test = "public class Test { void m(int p) { switch (p) { ca|se 0: } } }";
    // XXX whitespace "public class Test { void m(int p) { switch (p) { case 0: break; } } }"
    String golden = "public class Test { void m(int p) { switch (p) { case 0:break;\n } } }";
    final int index = test.indexOf("|");
    assertTrue(index != -1);
    TestUtilities.copyStringToFile(testFile, test.replace("|", ""));
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy copy) throws IOException {
            if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) {
                return;
            }
            TreeMaker make = copy.getTreeMaker();
            TreePath node = copy.getTreeUtilities().pathFor(index);
            assertTrue(node.getLeaf().getKind() == Kind.CASE);
            CaseTree original = (CaseTree) node.getLeaf();
            List<StatementTree> st = new ArrayList<StatementTree>();
            st.addAll(original.getStatements());
            st.add(make.Break(null));
            CaseTree modified = make.Case(original.getExpression(), st);
            copy.rewrite(original, modified);
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #29
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 #30
Source File: WorkingCopy.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves all fields that belong to the same field group. 
 */
private static @NonNull List<? extends Tree> collectFieldGroup(@NonNull CompilationInfo info, 
        @NonNull TreePath parentPath, Tree leaf) {
    Iterable<? extends Tree> children;

    switch (parentPath.getLeaf().getKind()) {
        case BLOCK: children = ((BlockTree) parentPath.getLeaf()).getStatements(); break;
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            children = ((ClassTree) parentPath.getLeaf()).getMembers(); break;
        case CASE:  children = ((CaseTree) parentPath.getLeaf()).getStatements(); break;
        default:    children = Collections.singleton(leaf); break;
    }

    List<Tree> result = new LinkedList<>();
    ModifiersTree currentModifiers = ((VariableTree) leaf).getModifiers();

    for (Tree c : children) {
        if (c.getKind() != Kind.VARIABLE) continue;

        if (((VariableTree) c).getModifiers() == currentModifiers) {
            result.add(c);
        }
    }
    
    return result;
}