Java 类com.sun.source.tree.CaseTree 实例源码

项目:incubator-netbeans    文件:TranslateIdentifier.java   
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;
}
项目:incubator-netbeans    文件:IntroduceHint.java   
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);
}
项目:javaide    文件:JavaInputAstVisitor.java   
@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;
}
项目:javaide    文件:JavaInputAstVisitor.java   
@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;
}
项目:openjdk9    文件:CompletenessStressTest.java   
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;
}
项目:error-prone    文件:Enclosing.java   
@Override
public boolean matches(T unused, VisitorState state) {
  TreePath pathToEnclosing = state.findPathToEnclosing(CaseTree.class, BlockTree.class);
  if (pathToEnclosing == null) {
    return false;
  }
  Tree enclosing = pathToEnclosing.getLeaf();
  state = state.withPath(pathToEnclosing);
  if (enclosing instanceof BlockTree) {
    return blockTreeMatcher.matches((BlockTree) enclosing, state);
  } else if (enclosing instanceof CaseTree) {
    return caseTreeMatcher.matches((CaseTree) enclosing, state);
  } else {
    // findEnclosing given two types must return something of one of those types
    throw new IllegalStateException("enclosing tree not a BlockTree or CaseTree");
  }
}
项目:error-prone    文件:Reachability.java   
/**
 * Returns true if the given case tree can complete normally, as defined by JLS 14.21.
 *
 * <p>An exception is made for {@code System.exit}, which cannot complete normally in practice.
 */
public static boolean canCompleteNormally(CaseTree caseTree) {
  List<? extends StatementTree> statements = caseTree.getStatements();
  if (statements.isEmpty()) {
    return true;
  }
  // We only care whether the last statement completes; javac would have already
  // reported an error if that statement wasn't reachable, and the answer is
  // independent of any preceding statements.
  // TODO(cushon): This isn't really making an exception for System.exit in the prior statements.
  return canCompleteNormally(getLast(statements));
}
项目:error-prone    文件:ControlFlowVisitor.java   
@Override
public Result visitSwitch(SwitchTree node, BreakContext cxt) {
  Result result = null;
  boolean seenDefault = false;
  cxt.loopDepth++;
  try {
    for (CaseTree caseTree : node.getCases()) {
      if (caseTree.getExpression() == null) {
        seenDefault = true;
      }

      if (result == null) {
        result = caseTree.accept(this, cxt);
      } else {
        result = result.or(caseTree.accept(this, cxt));
      }
    }
    if (!seenDefault) {
      result = result.or(NEVER_EXITS);
    }
    return result;
  } finally {
    cxt.loopDepth--;
  }
}
项目:error-prone    文件:DeadException.java   
@Override
protected Iterable<? extends StatementTree> getChildNodes(T tree, VisitorState state) {
  Tree enclosing = state.findEnclosing(CaseTree.class, BlockTree.class);
  if (enclosing == null) {
    return ImmutableList.of();
  }
  if (enclosing instanceof BlockTree) {
    return ((BlockTree) enclosing).getStatements();
  } else if (enclosing instanceof CaseTree) {
    return ((CaseTree) enclosing).getStatements();
  } else {
    // findEnclosing given two types must return something of one of those types
    throw new IllegalStateException("enclosing tree not a BlockTree or CaseTree");
  }
}
项目:error-prone    文件:WildcardImport.java   
/**
 * Add an import for {@code owner}, and qualify all on demand imported references to members of
 * owner by owner's simple name.
 */
private static void qualifiedNameFix(
    final SuggestedFix.Builder fix, final Symbol owner, VisitorState state) {
  fix.addImport(owner.getQualifiedName().toString());
  final JCCompilationUnit unit = (JCCompilationUnit) state.getPath().getCompilationUnit();
  new TreePathScanner<Void, Void>() {
    @Override
    public Void visitIdentifier(IdentifierTree tree, Void unused) {
      Symbol sym = ASTHelpers.getSymbol(tree);
      if (sym == null) {
        return null;
      }
      Tree parent = getCurrentPath().getParentPath().getLeaf();
      if (parent.getKind() == Tree.Kind.CASE
          && ((CaseTree) parent).getExpression().equals(tree)
          && sym.owner.getKind() == ElementKind.ENUM) {
        // switch cases can refer to enum constants by simple name without importing them
        return null;
      }
      if (sym.owner.equals(owner) && unit.starImportScope.includes(sym)) {
        fix.prefixWith(tree, owner.getSimpleName() + ".");
      }
      return null;
    }
  }.scan(unit, null);
}
项目:error-prone    文件:MissingCasesInEnumSwitch.java   
@Override
public Description matchSwitch(SwitchTree tree, VisitorState state) {
  Type switchType = ASTHelpers.getType(tree.getExpression());
  if (switchType.asElement().getKind() != ElementKind.ENUM) {
    return Description.NO_MATCH;
  }
  // default case is present
  if (tree.getCases().stream().anyMatch(c -> c.getExpression() == null)) {
    return Description.NO_MATCH;
  }
  ImmutableSet<String> handled =
      tree.getCases()
          .stream()
          .map(CaseTree::getExpression)
          .filter(IdentifierTree.class::isInstance)
          .map(e -> ((IdentifierTree) e).getName().toString())
          .collect(toImmutableSet());
  Set<String> unhandled = Sets.difference(ASTHelpers.enumValues(switchType.asElement()), handled);
  if (unhandled.isEmpty()) {
    return Description.NO_MATCH;
  }
  return buildDescription(tree).setMessage(buildMessage(unhandled)).build();
}
项目:checker-framework    文件:FenumVisitor.java   
@Override
public Void visitSwitch(SwitchTree node, Void p) {
    ExpressionTree expr = node.getExpression();
    AnnotatedTypeMirror exprType = atypeFactory.getAnnotatedType(expr);

    for (CaseTree caseExpr : node.getCases()) {
        ExpressionTree realCaseExpr = caseExpr.getExpression();
        if (realCaseExpr != null) {
            AnnotatedTypeMirror caseType = atypeFactory.getAnnotatedType(realCaseExpr);

            this.commonAssignmentCheck(exprType, caseType, caseExpr,
                    "switch.type.incompatible", false);
        }
    }
    return super.visitSwitch(node, p);
}
项目:bazel    文件:CFGBuilder.java   
private void buildCase(CaseTree tree, int index) {
    final Label thisBodyL = caseBodyLabels[index];
    final Label nextBodyL = caseBodyLabels[index + 1];
    final Label nextCaseL = new Label();

    ExpressionTree exprTree = tree.getExpression();
    if (exprTree != null) {
        Node expr = scan(exprTree, p);
        CaseNode test = new CaseNode(tree, switchExpr, expr, env.getTypeUtils());
        extendWithNode(test);
        extendWithExtendedNode(new ConditionalJump(thisBodyL, nextCaseL));
    }
    addLabelForNextNode(thisBodyL);
    for (StatementTree stmt : tree.getStatements()) {
        scan(stmt, p);
    }
    extendWithExtendedNode(new UnconditionalJump(nextBodyL));
    addLabelForNextNode(nextCaseL);
}
项目:incubator-netbeans    文件:TreeDuplicator.java   
@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;
}
项目:incubator-netbeans    文件:VeryPretty.java   
private java.util.List<? extends StatementTree> getStatements(Tree tree) {
    switch (tree.getKind()) {
        case BLOCK: return ((BlockTree) tree).getStatements();
        case CASE: return ((CaseTree) tree).getStatements();
        default: return null;
    }
}
项目:incubator-netbeans    文件:CopyFinder.java   
public Boolean visitCase(CaseTree node, TreePath p) {
    if (p == null) {
        super.visitCase(node, p);
        return false;
    }

    CaseTree ct = (CaseTree) p.getLeaf();

    if (!scan(node.getExpression(), ct.getExpression(), p))
        return false;

    return checkLists(node.getStatements(), ct.getStatements(), p);
}
项目:incubator-netbeans    文件:CopyFinder.java   
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());
    }
}
项目:incubator-netbeans    文件:WorkingCopy.java   
/**
 * 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;
}
项目:incubator-netbeans    文件:SwitchTest.java   
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);
}
项目:incubator-netbeans    文件:SemanticHighlighterBase.java   
@Override
public Void visitSwitch(SwitchTree node, EnumSet<UseTypes> p) {
    scan(node.getExpression(), EnumSet.of(UseTypes.READ));
    for (CaseTree ct : node.getCases()) {
        scan(ct, null);
    }
    return null;
}
项目:incubator-netbeans    文件:SemanticHighlighterBase.java   
@Override
public Void visitCase(CaseTree tree, EnumSet<UseTypes> p) {
    if (tree.getExpression() != null && tree.getExpression().getKind() == Kind.IDENTIFIER) {
        handlePossibleIdentifier(new TreePath(getCurrentPath(), tree.getExpression()), EnumSet.of(UseTypes.READ));
    }

    return super.visitCase(tree, null);
}
项目:incubator-netbeans    文件:JavaFixUtilities.java   
@Override
public Number visitCase(CaseTree node, Void p) {
    List<? extends StatementTree> statements = (List<? extends StatementTree>) resolveMultiParameters(node.getStatements());
    CaseTree nue = make.Case(node.getExpression(), statements);

    rewrite(node, nue);
    return super.visitCase(node, p);
}
项目:incubator-netbeans    文件:JavaFixUtilities.java   
@Override
public Number visitSwitch(SwitchTree node, Void p) {
    List<? extends CaseTree> cases = (List<? extends CaseTree>) resolveMultiParameters(node.getCases());
    SwitchTree nue = make.Switch(node.getExpression(), cases);

    rewrite(node, nue);
    return super.visitSwitch(node, p);
}
项目:incubator-netbeans    文件:CyclomaticComplexityVisitor.java   
/**
 * 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;
}
项目:incubator-netbeans    文件:TreeNode.java   
@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;
}
项目:incubator-netbeans    文件:IntroduceHint.java   
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());
    }
}
项目:incubator-netbeans    文件:Utilities.java   
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;
}
项目:incubator-netbeans    文件:Utilities.java   
@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;
}
项目:incubator-netbeans    文件:Utilities.java   
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);
    }
}
项目:incubator-netbeans    文件:ExpectedTypeResolver.java   
@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;
}
项目:incubator-netbeans    文件:Tiny.java   
@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);
}
项目:incubator-netbeans    文件:IntroduceClass.java   
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.EMPTY_LIST;
            }
    }
    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;
}
项目:openjdk-jdk10    文件:CompletenessStressTest.java   
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;
}
项目:error-prone    文件:PlaceholderUnificationVisitor.java   
@Override
public Choice<State<JCCase>> visitCase(final CaseTree node, State<?> state) {
  return chooseSubtrees(
      state,
      s -> unifyStatements(node.getStatements(), s),
      stmts -> maker().Case((JCExpression) node.getExpression(), stmts));
}
项目:checker-framework    文件:CaseNode.java   
public CaseNode(CaseTree tree, Node switchExpr, Node caseExpr, Types types) {
    super(types.getNoType(TypeKind.NONE));
    assert tree.getKind().equals(Kind.CASE);
    this.tree = tree;
    this.switchExpr = switchExpr;
    this.caseExpr = caseExpr;
}
项目:checker-framework    文件:CFGBuilder.java   
@Override
public Node visitCase(CaseTree tree, Void p) {
    assert switchExpr != null : "no switch expression in case";

    Tree exprTree = tree.getExpression();
    if (exprTree != null) {
        // a case with a constant expression
        Label thisBlockL = new Label();
        Label nextCaseL = new Label();

        Node expr = scan(exprTree, p);
        CaseNode test = new CaseNode(tree, switchExpr, expr, env.getTypeUtils());
        extendWithNode(test);
        extendWithExtendedNode(new ConditionalJump(thisBlockL,
                nextCaseL));
        addLabelForNextNode(thisBlockL);
        for (StatementTree stmt : tree.getStatements()) {
            scan(stmt, p);
        }
        addLabelForNextNode(nextCaseL);
    } else {
        // the default case
        for (StatementTree stmt : tree.getStatements()) {
            scan(stmt, p);
        }
    }
    return null;
}
项目:bazel    文件:CaseNode.java   
public CaseNode(CaseTree tree, Node switchExpr, Node caseExpr, Types types) {
    super(types.getNoType(TypeKind.NONE));
    assert tree.getKind().equals(Kind.CASE);
    this.tree = tree;
    this.switchExpr = switchExpr;
    this.caseExpr = caseExpr;
}
项目:incubator-netbeans    文件:GeneratorUtilities.java   
@Override
public Object visitCase(CaseTree node, Object p) {
    return scan(node.getStatements(), p);
}
项目:incubator-netbeans    文件:SwitchTest.java   
public void testAddCase1() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    String test = "public class Test {\n" +
                  "    void m(int p) {\n" +
                  "        switch (p) {\n" +
                  "            case 0:\n" +
                  "                System.err.println(1);\n" +
                  "                break;\n" +
                  "            ca|se 2:\n" +
                  "                System.err.println(2);\n" +
                  "                break;\n" +
                  "        }\n" +
                  "    }\n" +
                  "}\n";
    String golden = "public class Test {\n" +
                    "    void m(int p) {\n" +
                    "        switch (p) {\n" +
                    "            case 0:\n" +
                    "                System.err.println(1);\n" +
                    "                break;\n" +
                    "            case 1:\n" +
                    "            case 2:\n" +
                    "            case 3:\n" +
                    "                System.err.println(2);\n" +
                    "                break;\n" +
                    "        }\n" +
                    "    }\n" +
                    "}\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);
            SwitchTree st = (SwitchTree) node.getParentPath().getLeaf();
            List<CaseTree> newCases = new LinkedList<CaseTree>();
            newCases.add(st.getCases().get(0));
            newCases.add(make.Case(make.Literal(1), Collections.<StatementTree>emptyList()));
            newCases.add(make.Case(make.Literal(2), Collections.<StatementTree>emptyList()));
            newCases.add(make.Case(make.Literal(3), st.getCases().get(1).getStatements()));
            copy.rewrite(st, make.Switch(st.getExpression(), newCases));
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:SwitchTest.java   
public void testSwitch2If() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    String test = "public class Test {\n" +
                  "    void m(int p, int thmbPaneWidth) {\n" +
                    "        switch (p) {\n" +
                    "            case 0:\n" +
                    "                int width = thmbPaneWidth,\n" +
                    "                        height = (int) (thmbPaneWidth * 1.2),\n" +
                    "                        left = 0,\n" +
                    "                        top = 0;\n" +
                    "                break;\n" +
                    "        }\n" +
                  "    }\n" +
                  "}\n";
    String golden = "public class Test {\n" +
                    "    void m(int p, int thmbPaneWidth) {\n" +
                  "        if (p == 0) {\n" +
                  "            int width = thmbPaneWidth,\n" +
                  "                    height = (int) (thmbPaneWidth * 1.2),\n" +
                  "                    left = 0,\n" +
                  "                    top = 0;\n" +
                  "        }\n" +
                    "    }\n" +
                    "}\n";
    TestUtilities.copyStringToFile(testFile, test.replace("|", ""));
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        public void run(final WorkingCopy copy) throws IOException {
            if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) {
                return;
            }
            final TreeMaker make = copy.getTreeMaker();
            new ErrorAwareTreePathScanner<Void, Void>() {
                @Override public Void visitCase(CaseTree node, Void p) {
                    IfTree nue = make.If(make.Binary(Kind.EQUAL_TO, make.Identifier("p"), make.Literal(0)), make.Block(node.getStatements().subList(0, node.getStatements().size() - 1), false), null);
                    copy.rewrite(getCurrentPath().getParentPath().getLeaf(), nue);
                    return super.visitCase(node, p);
                }
            }.scan(copy.getCompilationUnit(), null);
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}