Exemplo n.º 1
0
 private void buildSwitchStatement(SwitchStatementTree tree) {
   // FIXME useless node created for default cases.
   SwitchStatementTree switchStatementTree = tree;
   Block switchSuccessor = currentBlock;
   // process condition
   currentBlock = createBlock();
   currentBlock.terminator = switchStatementTree;
   switches.addLast(currentBlock);
   build(switchStatementTree.expression());
   // process body
   currentBlock = createBlock(switchSuccessor);
   breakTargets.addLast(switchSuccessor);
   if (!switchStatementTree.cases().isEmpty()) {
     CaseGroupTree firstCase = switchStatementTree.cases().get(0);
     for (CaseGroupTree caseGroupTree : Lists.reverse(switchStatementTree.cases())) {
       build(caseGroupTree.body());
       switches.getLast().successors.add(currentBlock);
       if (!caseGroupTree.equals(firstCase)) {
         // No block predecessing the first case group.
         currentBlock = createBlock(currentBlock);
       }
     }
   }
   breakTargets.removeLast();
   // process condition
   currentBlock = switches.removeLast();
 }
 private static CaseLabelTree getLastLabel(SwitchStatementTree switchStatementTree) {
   if (!switchStatementTree.cases().isEmpty()) {
     List<CaseLabelTree> labels =
         switchStatementTree.cases().get(switchStatementTree.cases().size() - 1).labels();
     if (!labels.isEmpty()) {
       return labels.get(labels.size() - 1);
     }
   }
   return null;
 }
 @Override
 public void visitNode(Tree tree) {
   SwitchStatementTree switchStatementTree = (SwitchStatementTree) tree;
   CaseLabelTree defaultLabel = getDefaultLabel(switchStatementTree);
   CaseLabelTree lastLabel = getLastLabel(switchStatementTree);
   if (defaultLabel == null) {
     reportIssue(switchStatementTree.switchKeyword(), "Add a default case to this switch.");
   } else if (!defaultLabel.equals(lastLabel)) {
     reportIssue(defaultLabel, "Move this default to the end of the switch.");
   }
 }
 private static CaseLabelTree getDefaultLabel(SwitchStatementTree switchStatementTree) {
   for (CaseGroupTree caseGroupTree : switchStatementTree.cases()) {
     for (CaseLabelTree caseLabelTree : caseGroupTree.labels()) {
       if (JavaKeyword.DEFAULT.getValue().equals(caseLabelTree.caseOrDefaultKeyword().text())) {
         return caseLabelTree;
       }
     }
   }
   return null;
 }
  @Override
  public void visitSwitchStatement(SwitchStatementTree tree) {
    int count = 0;
    for (CaseGroupTree caseGroup : tree.cases()) {
      count += caseGroup.labels().size();
    }
    if (count < 3) {
      context.addIssue(
          tree,
          ruleKey,
          "Replace this \"switch\" statement by \"if\" statements to increase readability.");
    }

    super.visitSwitchStatement(tree);
  }