com.sun.source.tree.TryTree Java Examples

The following examples show how to use com.sun.source.tree.TryTree. 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 Boolean visitTry(TryTree node, TreePath p) {
    if (p == null) {
        super.visitTry(node, p);
        return false;
    }

    TryTree at = (TryTree) p.getLeaf();

    if (!checkLists(node.getResources(), at.getResources(), p)) {
        return false;
    }
    
    if (!scan(node.getBlock(), at.getBlock(), p)) {
        return false;
    }

    if (!checkLists(node.getCatches(), at.getCatches(), p)) {
        return false;
    }

    return scan(node.getFinallyBlock(), at.getFinallyBlock(), p);
}
 
Example #2
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean visitTry(TryTree node, Void p) {
    Set<TypeMirror> caught = new HashSet<TypeMirror>();

    for (CatchTree ct : node.getCatches()) {
        TypeMirror t = info.getTrees().getTypeMirror(new TreePath(new TreePath(getCurrentPath(), ct), ct.getParameter()));

        if (t != null) {
            caught.add(t);
        }
    }

    caughtExceptions.push(Pair.of(caught, node));
    
    try {
        return scan(node.getBlock(), p) == Boolean.TRUE || scan(node.getFinallyBlock(), p) == Boolean.TRUE;
    } finally {
        caughtExceptions.pop();
    }
}
 
Example #3
Source File: MagicSurroundWithTryCatchFix.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static TreePath enclosingTry(TreePath from) {
    TreePath tryPath = from;
    while (tryPath != null
            && tryPath.getLeaf().getKind() != Kind.TRY
            && !TreeUtilities.CLASS_TREE_KINDS.contains(tryPath.getLeaf().getKind())
            && tryPath.getLeaf().getKind() != Kind.CATCH
            && tryPath.getLeaf().getKind() != Kind.LAMBDA_EXPRESSION)
        tryPath = tryPath.getParentPath();

    if (tryPath.getLeaf().getKind() == Kind.TRY) {
        TryTree tt = (TryTree) tryPath.getLeaf();
        //#104085: if the statement to be wrapped is inside a finally block of the try-catch,
        //do not attempt to extend existing catches...:
        for (Tree t : from) {
            if (tt.getFinallyBlock() == t) {
                return null;
            }
        }
        
        return tryPath;
    }
    
    return null;
}
 
Example #4
Source File: ExtraCatch.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    Tree t = ctx.getPath().getLeaf();
    if (t.getKind() != Tree.Kind.CATCH) {
        // remove a clause from the multi-catch
        removeAlternativeFromMultiCatch(ctx);
        return;
    }
    CatchTree toRemove = (CatchTree)t;
    TryTree parent = (TryTree) ctx.getPath().getParentPath().getLeaf();
    TreeMaker make = ctx.getWorkingCopy().getTreeMaker();
    
    if (parent.getResources().isEmpty() && parent.getCatches().size() == 1) {
        List<StatementTree> repl = new ArrayList<>();
        repl.addAll(parent.getBlock().getStatements());
        if (parent.getFinallyBlock() != null) {
                repl.addAll(parent.getFinallyBlock().getStatements());
        }
        Utilities.replaceStatement(ctx.getWorkingCopy(), ctx.getPath().getParentPath(), repl);
    } else {
        ctx.getWorkingCopy().rewrite(parent, make.removeTryCatch(parent, toRemove));
    }
}
 
Example #5
Source File: TryCatchFinally.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitTry(TryTree node, Collection<TreePath> trees) {
    Set<TypeMirror> caught = new HashSet<TypeMirror>();

    for (CatchTree ct : node.getCatches()) {
        TypeMirror t = info.getTrees().getTypeMirror(new TreePath(new TreePath(getCurrentPath(), ct), ct.getParameter()));

        if (t != null) {
            caught.add(t);
        }
    }

    caughtExceptions.push(caught);
    
    try {
        scan(node.getBlock(), trees);
    } finally {
        caughtExceptions.pop();
    }
    scan(node.getFinallyBlock(), trees);
    return null;
}
 
Example #6
Source File: TreeDiffer.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitTry(TryTree expected, Tree actual) {
  Optional<TryTree> other = checkTypeAndCast(expected, actual);
  if (!other.isPresent()) {
    addTypeMismatch(expected, actual);
    return null;
  }

  scan(expected.getBlock(), other.get().getBlock());
  parallelScan(expected.getCatches(), other.get().getCatches());
  scan(expected.getFinallyBlock(), other.get().getFinallyBlock());
  return null;
}
 
Example #7
Source File: ModelBuilder.java    From vertx-codetrans with Apache License 2.0 5 votes vote down vote up
@Override
public CodeModel visitTry(TryTree node, VisitContext context) {
  if (node.getCatches().size() != 1) {
    throw new UnsupportedOperationException("Expecting a single catch block");
  }
  StatementModel tryBlock = scan(node.getBlock(), context);
  StatementModel catchBlock = scan(node.getCatches().get(0).getBlock(), context);
  return new TryCatchModel(tryBlock, catchBlock);
}
 
Example #8
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * @param blockTree block of statements
 * @param state visitor state
 * @return Elements of safe init methods that are invoked as top-level statements in the method
 */
private Set<Element> getSafeInitMethods(
    BlockTree blockTree, Symbol.ClassSymbol classSymbol, VisitorState state) {
  Set<Element> result = new LinkedHashSet<>();
  List<? extends StatementTree> statements = blockTree.getStatements();
  for (StatementTree stmt : statements) {
    Element privMethodElem = getInvokeOfSafeInitMethod(stmt, classSymbol, state);
    if (privMethodElem != null) {
      result.add(privMethodElem);
    }
    // Hack: If we see a try{...}finally{...} statement, without a catch, we consider the methods
    // inside both blocks
    // as "top level" for the purposes of finding initialization methods. Any exception happening
    // there is also an
    // exception of the full method.
    if (stmt.getKind().equals(Tree.Kind.TRY)) {
      TryTree tryTree = (TryTree) stmt;
      if (tryTree.getCatches().size() == 0) {
        if (tryTree.getBlock() != null) {
          result.addAll(getSafeInitMethods(tryTree.getBlock(), classSymbol, state));
        }
        if (tryTree.getFinallyBlock() != null) {
          result.addAll(getSafeInitMethods(tryTree.getFinallyBlock(), classSymbol, state));
        }
      }
    }
  }
  return result;
}
 
Example #9
Source File: FmtImports.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void doModification(ResultIterator resultIterator) throws Exception {
    WorkingCopy copy = WorkingCopy.get(resultIterator.getParserResult());
    copy.toPhase(Phase.RESOLVED);
    CompilationUnitTree cut = copy.getCompilationUnit();
    ClassTree ct = (ClassTree) cut.getTypeDecls().get(0);
    MethodTree mt = (MethodTree) ct.getMembers().get(1);
    TreeMaker treeMaker = copy.getTreeMaker();
    BlockTree bt = mt.getBody();
    StatementTree stmt = treeMaker.Variable(treeMaker.Modifiers(EnumSet.noneOf(Modifier.class)), "is", treeMaker.QualIdent("java.io.InputStream"), treeMaker.Literal(null)); //NOI18N
    bt = treeMaker.addBlockStatement(bt, stmt);
    BlockTree tryBlock = treeMaker.Block(Collections.<StatementTree>emptyList(), false);
    ExpressionTree et = treeMaker.NewClass(null, Collections.<ExpressionTree>emptyList(), treeMaker.QualIdent("java.io.File"), Collections.singletonList(treeMaker.Literal("test.txt")), null); //NOI18N
    stmt = treeMaker.Variable(treeMaker.Modifiers(EnumSet.noneOf(Modifier.class)), "f", treeMaker.QualIdent("java.io.File"), et); //NOI18N
    tryBlock = treeMaker.addBlockStatement(tryBlock, stmt);
    et = treeMaker.NewClass(null, Collections.<ExpressionTree>emptyList(), treeMaker.QualIdent("java.io.FileInputStream"), Collections.singletonList(treeMaker.Identifier("f")), null); //NOI18N
    et = treeMaker.Assignment(treeMaker.Identifier("is"), et); //NOI18N
    tryBlock = treeMaker.addBlockStatement(tryBlock, treeMaker.ExpressionStatement(et));
    et = treeMaker.MemberSelect(treeMaker.Identifier("is"), "read"); //NOI18N
    et = treeMaker.MethodInvocation(Collections.<ExpressionTree>emptyList(), et, Collections.<ExpressionTree>emptyList());
    stmt = treeMaker.Try(treeMaker.Block(Collections.singletonList(treeMaker.ExpressionStatement(et)), false), Collections.<CatchTree>emptyList(), null);
    et = treeMaker.MethodInvocation(Collections.<ExpressionTree>emptyList(), treeMaker.MemberSelect(treeMaker.QualIdent("java.util.logging.Logger"), "getLogger"), Collections.<ExpressionTree>emptyList()); //NOI18N
    et = treeMaker.addMethodInvocationArgument((MethodInvocationTree) et, treeMaker.MethodInvocation(Collections.<ExpressionTree>emptyList(), treeMaker.MemberSelect(treeMaker.MemberSelect(treeMaker.QualIdent("org.netbeans.samples.ClassA"), "class"), "getName"), Collections.<ExpressionTree>emptyList())); //NOI18N
    et = treeMaker.MethodInvocation(Collections.<ExpressionTree>emptyList(), treeMaker.MemberSelect(et, "log"), Collections.<ExpressionTree>emptyList()); //NOI18N
    et = treeMaker.addMethodInvocationArgument((MethodInvocationTree) et, treeMaker.MemberSelect(treeMaker.QualIdent("java.util.logging.Logger"), "SEVERE")); //NOI18N
    et = treeMaker.addMethodInvocationArgument((MethodInvocationTree) et, treeMaker.Literal(null));
    et = treeMaker.addMethodInvocationArgument((MethodInvocationTree) et, treeMaker.Identifier("ex")); //NOI18N
    BlockTree catchBlock = treeMaker.Block(Collections.singletonList(treeMaker.ExpressionStatement(et)), false);
    stmt = treeMaker.addTryCatch((TryTree) stmt, treeMaker.Catch(treeMaker.Variable(treeMaker.Modifiers(EnumSet.noneOf(Modifier.class)), "ex", treeMaker.QualIdent("java.io.IOException"), null), catchBlock)); //NOI18N
    tryBlock = treeMaker.addBlockStatement(tryBlock, stmt);
    et = treeMaker.MemberSelect(treeMaker.Identifier("is"), "close"); //NOI18N
    et = treeMaker.MethodInvocation(Collections.<ExpressionTree>emptyList(), et, Collections.<ExpressionTree>emptyList());
    stmt = treeMaker.Try(treeMaker.Block(Collections.singletonList(treeMaker.ExpressionStatement(et)), false), Collections.<CatchTree>emptyList(), null);
    stmt = treeMaker.addTryCatch((TryTree) stmt, treeMaker.Catch(treeMaker.Variable(treeMaker.Modifiers(EnumSet.noneOf(Modifier.class)), "ex", treeMaker.QualIdent("java.io.IOException"), null), catchBlock)); //NOI18N
    stmt = treeMaker.Try(tryBlock, Collections.<CatchTree>emptyList(), treeMaker.Block(Collections.singletonList(stmt), false));
    stmt = treeMaker.addTryCatch((TryTree) stmt, treeMaker.Catch(treeMaker.Variable(treeMaker.Modifiers(EnumSet.noneOf(Modifier.class)), "ex", treeMaker.QualIdent("java.io.FileNotFoundException"), null), catchBlock)); //NOI18N
    bt = treeMaker.addBlockStatement(bt, stmt);
    copy.rewrite(mt.getBody(), bt);
}
 
Example #10
Source File: AddCatchFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    TreeMaker make = ctx.getWorkingCopy().getTreeMaker();
    TryTree tt = (TryTree) ctx.getPath().getLeaf();

    List<CatchTree> catches = new ArrayList<CatchTree>();
    
    catches.addAll(tt.getCatches());
    catches.addAll(MagicSurroundWithTryCatchFix.createCatches(ctx.getWorkingCopy(), make, thandles, ctx.getPath()));

    ctx.getWorkingCopy().rewrite(tt, make.Try(tt.getResources(), tt.getBlock(), catches, tt.getFinallyBlock()));
}
 
Example #11
Source File: FinalizeDoesNotCallSuper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private TryTree soleTryWithoutFinally(BlockTree block) {
    if (block.getStatements().size() != 1) return null;
    StatementTree first = block.getStatements().get(0);
    if (first.getKind() != Kind.TRY) return null;
    TryTree tt = (TryTree) first;
    if (tt.getFinallyBlock() != null) return null;
    return tt;
}
 
Example #12
Source File: FinalizeDoesNotCallSuper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    final TreeMaker tm = wc.getTreeMaker();
    TreePath tp = ctx.getPath();
    final BlockTree oldBody = ((MethodTree)tp.getLeaf()).getBody();
    if (oldBody == null) {
        return;
    }
    final List<StatementTree> newStatements = new ArrayList<StatementTree>(2);
    BlockTree superFinalize = tm.Block(
                                Collections.singletonList(
                                    tm.ExpressionStatement(
                                        tm.MethodInvocation(Collections.<ExpressionTree>emptyList(),
                                            tm.MemberSelect(
                                                tm.Identifier(SUPER),
                                                FINALIZE), Collections.<ExpressionTree>emptyList()))),
                                false);
    if (oldBody.getStatements().isEmpty()) {
        wc.rewrite(oldBody, superFinalize);
    } else {
        TryTree soleTry = soleTryWithoutFinally(oldBody);
        
        if (soleTry != null) {
            wc.rewrite(soleTry, tm.Try(soleTry.getBlock(), soleTry.getCatches(), superFinalize));
        } else {
            wc.rewrite(oldBody, tm.Block(Collections.singletonList(tm.Try(oldBody, Collections.<CatchTree>emptyList(), superFinalize)), false));
        }
    }
}
 
Example #13
Source File: UseSpecificCatch.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(JavaFix.TransformationContext ctx) throws Exception {
    CatchTree oldTree = (CatchTree)ctx.getPath().getLeaf();
    TryTree oldTry = (TryTree)ctx.getPath().getParentPath().getLeaf();
    
    WorkingCopy wcopy = ctx.getWorkingCopy();
    GeneratorUtilities gen = GeneratorUtilities.get(wcopy);
    TreeMaker mk = wcopy.getTreeMaker();
    int index = oldTry.getCatches().indexOf(oldTree);
    TryTree result = mk.removeTryCatch(oldTry, index);
    
    for (TypeMirrorHandle h : newTypes) {
        TypeMirror m = h.resolve(wcopy);
        if (m == null || m.getKind() != TypeKind.DECLARED) {
            continue;
        }
        CatchTree branch = mk.Catch(
            mk.Variable(
                oldTree.getParameter().getModifiers(),
                oldTree.getParameter().getName(),
                mk.Type(m),
                oldTree.getParameter().getInitializer()),
            oldTree.getBlock());
        gen.copyComments(oldTree, branch, true);
        result = mk.insertTryCatch(result, index++, branch);
    }
    wcopy.rewrite(oldTry, result);
}
 
Example #14
Source File: JoinCatches.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();
    List<Tree> disjointTypes = new LinkedList<Tree>();
    TryTree tt = (TryTree) tp.getLeaf();
    int first = duplicates.get(0);
    List<Integer> remainingDuplicates = duplicates.subList(1, duplicates.size());
    
    addDisjointType(disjointTypes, tt.getCatches().get(first).getParameter().getType());

    for (Integer d : remainingDuplicates) {
        addDisjointType(disjointTypes, tt.getCatches().get((int) d).getParameter().getType());
    }

    List<CatchTree> newCatches = new LinkedList<CatchTree>();
    int c = 0;

    for (CatchTree ct : tt.getCatches()) {
        if (c == first) {
            wc.rewrite(ct.getParameter().getType(), wc.getTreeMaker().UnionType(disjointTypes));
        }
        
        if (remainingDuplicates.contains(c++)) continue;

        newCatches.add(ct);
    }

    TryTree nue = wc.getTreeMaker().Try(tt.getResources(), tt.getBlock(), newCatches, tt.getFinallyBlock());

    wc.rewrite(tt, nue);
}
 
Example #15
Source File: ConvertToARM.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TryTree findNestedARM(
        final Collection<? extends StatementTree> stms,
        final StatementTree var) {
    int state = var != null ? 0 : 1;
    for (StatementTree stm : stms) {
        if (stm == var) {
            state = 1;
        }
        if (state == 1) {
            if (stm.getKind() == Kind.TRY) {
                final TryTree tryTree = (TryTree)stm;
                if (tryTree.getResources() != null && !tryTree.getResources().isEmpty()) {
                    return tryTree;
                } else {
                    final Iterator<? extends StatementTree> blkStms = tryTree.getBlock().getStatements().iterator();
                    if (blkStms.hasNext()) {
                        StatementTree bstm = blkStms.next();
                        if (bstm.getKind() == Kind.TRY) {
                            return (TryTree)bstm;
                        }
                        if (bstm.getKind() == Kind.EXPRESSION_STATEMENT && blkStms.hasNext()) {
                            bstm = blkStms.next();
                            if (bstm.getKind() == Kind.TRY) {
                                return (TryTree)bstm;
                            }
                        }
                    }
                }
            }
            if (stm != var) {
                break;
            }
        }
    }
    return null;
}
 
Example #16
Source File: TreeNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitTry(TryTree tree, List<Node> d) {
    List<Node> below = new ArrayList<Node>();
    
    addCorrespondingType(below);
    addCorrespondingComments(below);
    super.visitTry(tree, below);
    
    d.add(new TreeNode(info, getCurrentPath(), below));
    return null;
}
 
Example #17
Source File: DepthVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Object visitTry(TryTree node, Object p) {
    depth++;
    Object o = super.visitTry(node, p); 
    depth--;
    return o;
}
 
Example #18
Source File: BroadCatchBlock.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(
  displayName = "#DN_BroadCatch",
  description = "#DESC_BroadCatch",
  category = "rules15",
  customizerProvider = CF.class,
  suppressWarnings = { "BroadCatchBlock", "TooBroadCatch" },
  enabled = false
)
@TriggerPatterns({
    @TriggerPattern("try { $statements$; } catch $catches$"),
    @TriggerPattern("try { $statements$; } catch $catches$ finally { $handler$; }")
})
public static List<ErrorDescription> broadCatch(HintContext ctx) {
    if (ctx.getPath().getLeaf().getKind() != Tree.Kind.TRY) {
        return null;
    }
    TryTree tt = (TryTree)ctx.getPath().getLeaf();
    Set<TypeMirror> realExceptions = ctx.getInfo().getTreeUtilities().getUncaughtExceptions(
            new TreePath(ctx.getPath(), tt.getBlock()));
    
    CatchClauseProcessor processor = new CatchClauseProcessor(ctx.getInfo(), ctx, realExceptions);
    
    if (ctx.getPreferences().getBoolean(OPTION_EXCLUDE_COMMON, DEFAULT_EXCLUDE_COMMON)) {
        processor.excludeCommons();
    }
    if (ctx.getPreferences().getBoolean(OPTION_EXCLUDE_UMBRELLA, DEFAULT_EXCLUDE_UMBRELLA)) {
        processor.suppressUmbrellas(ctx.getPreferences().get(OPTION_UMBRELLA_LIST, DEFAULT_UMBRELLA_LIST));
    }

    processor.process(ctx.getMultiVariables().get("$catches$"));
    
    return processor.errors;
}
 
Example #19
Source File: TreeDuplicator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Tree visitTry(TryTree tree, Void p) {
    TryTree n = make.Try(tree.getResources(), tree.getBlock(), tree.getCatches(), tree.getFinallyBlock());
    model.setType(n, model.getType(tree));
    comments.copyComments(tree, n);
    model.setPos(n, model.getPos(tree));
    return n;
}
 
Example #20
Source File: JavaFixUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Number visitTry(TryTree node, Void p) {
    List<? extends Tree> resources = (List<? extends Tree>) resolveMultiParameters(node.getResources());
    List<? extends CatchTree> catches = (List<? extends CatchTree>) resolveMultiParameters(node.getCatches());
    TryTree nue = make.Try(resources, node.getBlock(), catches, node.getFinallyBlock());

    rewrite(node, nue);
    return super.visitTry(node, p);
}
 
Example #21
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
@Override
public Void visitTry(TryTree node, Void unused) {
    sync(node);
    builder.open(ZERO);
    token("try");
    builder.space();
    if (!node.getResources().isEmpty()) {
        token("(");
        builder.open(node.getResources().size() > 1 ? plusFour : ZERO);
        boolean first = true;
        for (Tree resource : node.getResources()) {
            if (!first) {
                builder.forcedBreak();
            }
            VariableTree variableTree = (VariableTree) resource;
            declareOne(
                    DeclarationKind.PARAMETER,
                    fieldAnnotationDirection(variableTree.getModifiers()),
                    Optional.of(variableTree.getModifiers()),
                    variableTree.getType(),
                    VarArgsOrNot.NO,
                    ImmutableList.<AnnotationTree>of(),
                    variableTree.getName(),
                    "",
                    "=",
                    Optional.fromNullable(variableTree.getInitializer()),
                    Optional.<String>absent(),
                    Optional.<ExpressionTree>absent(),
                    Optional.<TypeWithDims>absent());
            if (builder.peekToken().equals(Optional.of(";"))) {
                token(";");
                builder.space();
            }
            first = false;
        }
        if (builder.peekToken().equals(Optional.of(";"))) {
            token(";");
            builder.space();
        }
        token(")");
        builder.close();
        builder.space();
    }
    // An empty try-with-resources body can collapse to "{}" if there are no trailing catch or
    // finally blocks.
    boolean trailingClauses = !node.getCatches().isEmpty() || node.getFinallyBlock() != null;
    visitBlock(
            node.getBlock(),
            CollapseEmptyOrNot.valueOf(!trailingClauses),
            AllowLeadingBlankLine.YES,
            AllowTrailingBlankLine.valueOf(trailingClauses));
    for (int i = 0; i < node.getCatches().size(); i++) {
        CatchTree catchClause = node.getCatches().get(i);
        trailingClauses = i < node.getCatches().size() - 1 || node.getFinallyBlock() != null;
        visitCatchClause(catchClause, AllowTrailingBlankLine.valueOf(trailingClauses));
    }
    if (node.getFinallyBlock() != null) {
        builder.space();
        token("finally");
        builder.space();
        visitBlock(
                node.getFinallyBlock(),
                CollapseEmptyOrNot.NO,
                AllowLeadingBlankLine.YES,
                AllowTrailingBlankLine.NO);
    }
    builder.close();
    return null;
}
 
Example #22
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 4 votes vote down vote up
@Override
public Void visitTry(TryTree node, Void unused) {
  sync(node);
  builder.open(ZERO);
  token("try");
  builder.space();
  if (!node.getResources().isEmpty()) {
    token("(");
    builder.open(node.getResources().size() > 1 ? plusFour : ZERO);
    boolean first = true;
    for (Tree resource : node.getResources()) {
      if (!first) {
        builder.forcedBreak();
      }
      if (resource instanceof VariableTree) {
        VariableTree variableTree = (VariableTree) resource;
        declareOne(
            DeclarationKind.PARAMETER,
            fieldAnnotationDirection(variableTree.getModifiers()),
            Optional.of(variableTree.getModifiers()),
            variableTree.getType(),
            /* name= */ variableTree.getName(),
            "",
            "=",
            Optional.ofNullable(variableTree.getInitializer()),
            /* trailing= */ Optional.empty(),
            /* receiverExpression= */ Optional.empty(),
            /* typeWithDims= */ Optional.empty());
      } else {
        // TODO(cushon): think harder about what to do with `try (resource1; resource2) {}`
        scan(resource, null);
      }
      if (builder.peekToken().equals(Optional.of(";"))) {
        token(";");
        builder.space();
      }
      first = false;
    }
    if (builder.peekToken().equals(Optional.of(";"))) {
      token(";");
      builder.space();
    }
    token(")");
    builder.close();
    builder.space();
  }
  // An empty try-with-resources body can collapse to "{}" if there are no trailing catch or
  // finally blocks.
  boolean trailingClauses = !node.getCatches().isEmpty() || node.getFinallyBlock() != null;
  visitBlock(
      node.getBlock(),
      CollapseEmptyOrNot.valueOf(!trailingClauses),
      AllowLeadingBlankLine.YES,
      AllowTrailingBlankLine.valueOf(trailingClauses));
  for (int i = 0; i < node.getCatches().size(); i++) {
    CatchTree catchClause = node.getCatches().get(i);
    trailingClauses = i < node.getCatches().size() - 1 || node.getFinallyBlock() != null;
    visitCatchClause(catchClause, AllowTrailingBlankLine.valueOf(trailingClauses));
  }
  if (node.getFinallyBlock() != null) {
    builder.space();
    token("finally");
    builder.space();
    visitBlock(
        node.getFinallyBlock(),
        CollapseEmptyOrNot.NO,
        AllowLeadingBlankLine.YES,
        AllowTrailingBlankLine.NO);
  }
  builder.close();
  return null;
}
 
Example #23
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Void visitTry(TryTree node, Void unused) {
    sync(node);
    builder.open(ZERO);
    token("try");
    builder.space();
    if (!node.getResources().isEmpty()) {
        token("(");
        builder.open(node.getResources().size() > 1 ? plusFour : ZERO);
        boolean first = true;
        for (Tree resource : node.getResources()) {
            if (!first) {
                builder.forcedBreak();
            }
            VariableTree variableTree = (VariableTree) resource;
            declareOne(
                    DeclarationKind.PARAMETER,
                    fieldAnnotationDirection(variableTree.getModifiers()),
                    Optional.of(variableTree.getModifiers()),
                    variableTree.getType(),
                    VarArgsOrNot.NO,
                    ImmutableList.<AnnotationTree>of(),
                    variableTree.getName(),
                    "",
                    "=",
                    Optional.fromNullable(variableTree.getInitializer()),
                    Optional.<String>absent(),
                    Optional.<ExpressionTree>absent(),
                    Optional.<TypeWithDims>absent());
            if (builder.peekToken().equals(Optional.of(";"))) {
                token(";");
                builder.space();
            }
            first = false;
        }
        if (builder.peekToken().equals(Optional.of(";"))) {
            token(";");
            builder.space();
        }
        token(")");
        builder.close();
        builder.space();
    }
    // An empty try-with-resources body can collapse to "{}" if there are no trailing catch or
    // finally blocks.
    boolean trailingClauses = !node.getCatches().isEmpty() || node.getFinallyBlock() != null;
    visitBlock(
            node.getBlock(),
            CollapseEmptyOrNot.valueOf(!trailingClauses),
            AllowLeadingBlankLine.YES,
            AllowTrailingBlankLine.valueOf(trailingClauses));
    for (int i = 0; i < node.getCatches().size(); i++) {
        CatchTree catchClause = node.getCatches().get(i);
        trailingClauses = i < node.getCatches().size() - 1 || node.getFinallyBlock() != null;
        visitCatchClause(catchClause, AllowTrailingBlankLine.valueOf(trailingClauses));
    }
    if (node.getFinallyBlock() != null) {
        builder.space();
        token("finally");
        builder.space();
        visitBlock(
                node.getFinallyBlock(),
                CollapseEmptyOrNot.NO,
                AllowLeadingBlankLine.YES,
                AllowTrailingBlankLine.NO);
    }
    builder.close();
    return null;
}
 
Example #24
Source File: MethodExitDetector.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Boolean visitTry(TryTree tree, Stack<Tree> d) {
    exceptions2HighlightsStack.push(null);
    
    Boolean returnInTryBlock = scan(tree.getBlock(), d);
    
    boolean returnInCatchBlock = true;
    
    for (Tree t : tree.getCatches()) {
        Boolean b = scan(t, d);
        
        returnInCatchBlock &= b == Boolean.TRUE;
    }
    
    Boolean returnInFinallyBlock = scan(tree.getFinallyBlock(), d);
    
    doPopup();
    
    if (returnInTryBlock == Boolean.TRUE && returnInCatchBlock)
        return Boolean.TRUE;
    
    return returnInFinallyBlock;
}
 
Example #25
Source File: NullAway.java    From NullAway with MIT License 4 votes vote down vote up
/**
 * computes those fields always initialized by callee safe init methods before a read operation
 * (pathToRead) is invoked. See <a
 * href="https://github.com/uber/NullAway/wiki/Error-Messages#initializer-method-does-not-guarantee-nonnull-field-is-initialized--nonnull-field--not-initialized">the
 * docs</a> for what is considered a safe initializer method.
 */
private ImmutableSet<Element> safeInitByCalleeBefore(
    TreePath pathToRead, VisitorState state, TreePath enclosingBlockPath) {
  Set<Element> safeInitMethods = new LinkedHashSet<>();
  Tree enclosingBlockOrMethod = enclosingBlockPath.getLeaf();
  if (enclosingBlockOrMethod instanceof VariableTree) {
    return ImmutableSet.of();
  }
  ImmutableSet.Builder<Element> resultBuilder = ImmutableSet.builder();
  BlockTree blockTree =
      enclosingBlockOrMethod instanceof BlockTree
          ? (BlockTree) enclosingBlockOrMethod
          : ((MethodTree) enclosingBlockOrMethod).getBody();
  List<? extends StatementTree> statements = blockTree.getStatements();
  Tree readExprTree = pathToRead.getLeaf();
  int readStartPos = getStartPos((JCTree) readExprTree);
  TreePath classTreePath = enclosingBlockPath;
  // look for the parent ClassTree node, which represents the enclosing class / enum / interface
  while (!(classTreePath.getLeaf() instanceof ClassTree)) {
    classTreePath = classTreePath.getParentPath();
    if (classTreePath == null) {
      throw new IllegalStateException(
          "could not find enclosing class / enum / interface for "
              + state.getSourceForNode(enclosingBlockPath.getLeaf()));
    }
  }
  Symbol.ClassSymbol classSymbol = ASTHelpers.getSymbol((ClassTree) classTreePath.getLeaf());
  for (int i = 0; i < statements.size(); i++) {
    StatementTree curStmt = statements.get(i);
    if (getStartPos((JCTree) curStmt) <= readStartPos) {
      Element privMethodElem = getInvokeOfSafeInitMethod(curStmt, classSymbol, state);
      if (privMethodElem != null) {
        safeInitMethods.add(privMethodElem);
      }
      // Hack: Handling try{...}finally{...} statement, see getSafeInitMethods
      if (curStmt.getKind().equals(Tree.Kind.TRY)) {
        TryTree tryTree = (TryTree) curStmt;
        // ToDo: Should we check initialization inside tryTree.getResources ? What is the scope of
        // that initialization?
        if (tryTree.getCatches().size() == 0) {
          if (tryTree.getBlock() != null) {
            resultBuilder.addAll(
                safeInitByCalleeBefore(
                    pathToRead, state, new TreePath(enclosingBlockPath, tryTree.getBlock())));
          }
          if (tryTree.getFinallyBlock() != null) {
            resultBuilder.addAll(
                safeInitByCalleeBefore(
                    pathToRead,
                    state,
                    new TreePath(enclosingBlockPath, tryTree.getFinallyBlock())));
          }
        }
      }
    }
  }
  addGuaranteedNonNullFromInvokes(
      state, getTreesInstance(state), safeInitMethods, getNullnessAnalysis(state), resultBuilder);
  return resultBuilder.build();
}
 
Example #26
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public List<? extends TypeMirror> visitTry(TryTree node, Object p) {
    return null;
}
 
Example #27
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Computes possible types for throw expression. Throw can safely throw an exception, which is
 * either declared by method as a thrown type, or catched within method, by an upper try-catch block.
 * Unchecked exceptions are permitted (derivatives of RuntimeException or Error).
 */
@Override
public List<? extends TypeMirror> visitThrow(ThrowTree node, Object p) {
    List<TypeMirror> result = new ArrayList<TypeMirror>();
    TreePath parents = getCurrentPath();
    Tree prev = null;
    while (parents != null && parents.getLeaf().getKind() != Tree.Kind.METHOD) {
        Tree l = parents.getLeaf();
        if (l.getKind() == Tree.Kind.TRY) {
            TryTree tt = (TryTree) l;
            if (prev == tt.getBlock()) {
                for (CatchTree ct : tt.getCatches()) {
                    TypeMirror ex = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), ct.getParameter().getType()));
                    if (ex != null) {
                        switch (ex.getKind()) {
                            case DECLARED:
                                if (!result.contains(ex)) {
                                    result.add(ex);
                                }
                                break;
                            case UNION:
                                for (TypeMirror t : ((UnionType) ex).getAlternatives()) {
                                    if (!result.contains(t)) {
                                        result.add(t);
                                    }
                                }
                                break;
                        }
                    }
                }
            }
        }
        prev = l;
        parents = parents.getParentPath();
    }
    if (parents != null) {
        MethodTree mt = (MethodTree) parents.getLeaf();
        for (ExpressionTree etree : mt.getThrows()) {
            TypeMirror m = info.getTrees().getTypeMirror(new TreePath(parents, etree));
            if (m != null && !result.contains(m)) {
                result.add(m);
            }
        }
    }
    TypeMirror jlre = info.getElements().getTypeElement("java.lang.RuntimeException").asType(); // NOI18N
    TypeMirror jler = info.getElements().getTypeElement("java.lang.Error").asType(); // NOI18N
    for (TypeMirror em : result) {
        if (jlre != null && info.getTypes().isAssignable(jlre, em)) {
            jlre = null;
        }
        if (jler != null && info.getTypes().isAssignable(jler, em)) {
            jler = null;
        }
        if (jlre == null && jler == null) {
            break;
        }
    }
    if (jlre != null) {
        result.add(jlre);
    }
    if (jler != null) {
        result.add(jler);
    }
    return result;
}
 
Example #28
Source File: UnlockOutsideFinally.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerPatterns({
    @TriggerPattern(value="$lock.lock(); $otherStats$; try { $statements$; $lock.unlock(); $rest$; } catch $catches$ finally { $finstats$; } ",
                    constraints=@ConstraintVariableType(variable="$lock", type="java.util.concurrent.locks.Lock")),
    @TriggerPattern(value="$lock.lock(); $otherStats$; try { $statements$; $lock.unlock(); $rest$; } catch $catches$",
                    constraints=@ConstraintVariableType(variable="$lock", type="java.util.concurrent.locks.Lock")),
    @TriggerPattern(value="$lock.lock(); $otherStats$; try { $statements$; } catch $catches$ catch($excType $var) { $catchStats1$; $lock.unlock(); $catchStats2$; } catch $catches2$ finally { $finstmts$; }",
                    constraints=@ConstraintVariableType(variable="$lock", type="java.util.concurrent.locks.Lock")),
})
@NbBundle.Messages({
    "ERR_UnlockOutsideTryFinally=Lock.lock() not unlocked in finally",
    "FIX_UnlockOutsideTryFinally=Wrap by try-finally",
    "MSG_ExtraUnlock=Extra unlock() call; lock is already released in finally"
})
public static ErrorDescription unlockInsideTry(HintContext ctx) {
    TreePath fin = ctx.getVariables().get("$lock$1");
    if (fin == null) {
        return null;
    }
    TreePath parent = fin.getParentPath();
    if (parent.getLeaf().getKind() != Tree.Kind.MEMBER_SELECT) {
        return null;
    }
    parent = parent.getParentPath();
    if (parent == null || parent.getLeaf().getKind() != Tree.Kind.METHOD_INVOCATION) {
        return null;
    }
    TreePath tPath = parent.getParentPath();
    while (tPath != null && tPath.getLeaf().getKind() != Tree.Kind.TRY) {
        if (tPath.getLeaf().getKind() == Tree.Kind.METHOD || 
            tPath.getLeaf().getKind() == Tree.Kind.CLASS) {
            return null;
        }
        tPath = tPath.getParentPath();
    }
    if (tPath == null) {
        return null;
    }
    TryTree tt = (TryTree)tPath.getLeaf();
    Fix f = null;
    
    String displayName = null;
    
    if (tt.getFinallyBlock() != null) {
        
        TreePath finBlockPath = new TreePath(tPath, tt.getFinallyBlock());
        Collection<? extends Occurrence> occ = Matcher.create(ctx.getInfo()).
            setSearchRoot(finBlockPath).
            match(
                Pattern.createSimplePattern(parent)
            );
        if (!occ.isEmpty()) {
            f = new MoveUnlockFix(
                    TreePathHandle.create(parent, ctx.getInfo()),
                    null).toEditorFix();
            displayName = Bundle.MSG_ExtraUnlock();
        }
    }
    if (f == null) {
        displayName = Bundle.ERR_UnlockOutsideTryFinally();
        f = new MoveUnlockFix(
                TreePathHandle.create(parent, ctx.getInfo()),
                TreePathHandle.create(tPath, ctx.getInfo())).toEditorFix();
    }
    
    return ErrorDescriptionFactory.forName(ctx, parent, displayName, f);
}
 
Example #29
Source File: LocalVarScanner.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Boolean visitTry(TryTree node, Element p) {
    return null;
}
 
Example #30
Source File: UncaughtException.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private List<? extends TypeMirror> findUncaughtExceptions(CompilationInfo info, TreePath path, List<? extends TypeMirror> exceptions) {
    List<TypeMirror> result = new ArrayList<TypeMirror>();
    
    result.addAll(exceptions);
    
    Tree lastTree = null;
    
    while (path != null) {
        Tree currentTree = path.getLeaf();

        if (currentTree.getKind() == Tree.Kind.METHOD) {
            TypeMirror tm = info.getTrees().getTypeMirror(path);
            if (tm != null && tm.getKind() == TypeKind.EXECUTABLE) {
                for (TypeMirror mirr : ((ExecutableType) tm).getThrownTypes()) {
                    for (Iterator<TypeMirror> it = result.iterator(); it.hasNext();)
                        if (info.getTypes().isSameType(it.next(), mirr))
                            it.remove();
                }
                break;
            }
        }            
        
        if (currentTree.getKind() == Tree.Kind.LAMBDA_EXPRESSION) {
            // no checked exceptions can be thrown out of Lambda, #243106
            break;
        }
        
        if (currentTree.getKind() == Kind.TRY) {
            TryTree tt = (TryTree) currentTree;
            
            if (tt.getBlock() == lastTree) {
                for (CatchTree c : tt.getCatches()) {
                    TreePath catchPath = new TreePath(new TreePath(path, c), c.getParameter());
                    VariableElement variable = (VariableElement) info.getTrees().getElement(catchPath);
                    if (variable == null) {
                        continue;
                    }
                    TypeMirror variableType = variable.asType();
                    if (variableType.getKind() == TypeKind.UNION) {
                        result.removeAll(((UnionType)variableType).getAlternatives());
                    } else {
                        result.remove(variableType);
                    }
                }
            }
        }
        
        lastTree = path.getLeaf();
        path = path.getParentPath();
    }
    
    List<TypeMirror> filtered = new ArrayList<>();
    
    OUTER: for (Iterator<TypeMirror> sourceIt = result.iterator(); sourceIt.hasNext(); ) {
        TypeMirror sourceType = sourceIt.next();
        
        for (Iterator<TypeMirror> filteredIt = filtered.iterator(); filteredIt.hasNext(); ) {
            TypeMirror filteredType = filteredIt.next();
            
            if (info.getTypes().isSubtype(sourceType, filteredType)) {
                sourceIt.remove();
                continue OUTER;
            }
            
            if (info.getTypes().isSubtype(filteredType, sourceType)) {
                filteredIt.remove();
                break;
            }
        }
        
        filtered.add(sourceType);
    }
    
    return filtered;
}