Refine search
@Override public UTry visitTry(TryTree tree, Void v) { @SuppressWarnings({"unchecked", "rawtypes"}) List<UTree<?>> resources = cast(templateTrees(tree.getResources()), (Class<UTree<?>>) (Class) UTree.class); UBlock block = visitBlock(tree.getBlock(), null); ImmutableList.Builder<UCatch> catchesBuilder = ImmutableList.builder(); for (CatchTree catchTree : tree.getCatches()) { catchesBuilder.add(visitCatch(catchTree, null)); } UBlock finallyBlock = (tree.getFinallyBlock() == null) ? null : visitBlock(tree.getFinallyBlock(), null); return UTry.create(resources, block, catchesBuilder.build(), finallyBlock); }
@Override public Result visitTry(TryTree node, BreakContext cxt) { Result result = node.getBlock().accept(this, cxt); for (CatchTree catchTree : node.getCatches()) { result = result.or(catchTree.accept(this, cxt)); } if (node.getFinallyBlock() != null) { result = result.then(node.getFinallyBlock().accept(this, cxt)); } return result; }
@Override protected MatchResult matchAncestor(Tree tree, Tree prevTree) { if (tree instanceof TryTree) { TryTree tryTree = (TryTree) tree; if (tryTree.getBlock().equals(prevTree) && !tryTree.getCatches().isEmpty()) { // The current ancestor is a try block with associated catch blocks. return MatchResult.NO_MATCH; } } return super.matchAncestor(tree, prevTree); } }
@Override public Boolean visitTry(TryTree that, Void unused) { boolean completes = scan(that.getBlock()); // assume all catch blocks are reachable; javac has already rejected unreachable // checked exception handlers for (CatchTree catchTree : that.getCatches()) { completes |= scan(catchTree.getBlock()); } if (that.getFinallyBlock() != null && !scan(that.getFinallyBlock())) { completes = false; } return completes; } }
private boolean fixExceptions(final VisitorState state, SuggestedFix.Builder fix) { TryTree tryTree = null; OUTER: for (TreePath path = state.getPath(); path != null; path = path.getParentPath()) { if (path.getLeaf() instanceof CatchTree) { } else if (path.getLeaf() instanceof TryTree && !((TryTree) path.getLeaf()).getCatches().isEmpty()) { tryTree = (TryTree) path.getLeaf(); break; for (CatchTree c : tryTree.getCatches()) { catches.put(ASTHelpers.getType(c.getParameter().getType()), c); CatchTree last = Iterables.getLast(tryTree.getCatches()); Tree lastType = last.getParameter().getType(); if (lastType.getKind() == Tree.Kind.UNION_TYPE) { Type roe = state.getTypeFromString(ReflectiveOperationException.class.getName()); Set<String> exceptions = new LinkedHashSet<>(); uniq.add(state.getSourceForNode(ct.getBlock())); CatchTree last = Iterables.getLast(tryTree.getCatches()); String name = last.getParameter().getName().toString(); fix.postfixWith( last,
@Override public Description matchTry(TryTree tree, VisitorState state) { List<? extends StatementTree> body = tree.getBlock().getStatements(); if (body.isEmpty() || tree.getFinallyBlock() != null || tree.getCatches().size() != 1) { // TODO(cushon): support finally // TODO(cushon): support multiple catch blocks return NO_MATCH; } CatchTree catchTree = getOnlyElement(tree.getCatches()); if (catchTree.getParameter().getType().getKind() == UNION_TYPE) { // TODO(cushon): handle multi-catch return NO_MATCH; } if (!FAIL_METHOD.matches(getLast(body), state)) { return NO_MATCH; } // try body statements, excluding the trailing `fail()` List<? extends StatementTree> throwingStatements = tree.getBlock().getStatements().subList(0, tree.getBlock().getStatements().size() - 1); Optional<Fix> fix = AssertThrowsUtils.tryFailToAssertThrows(tree, throwingStatements, state); return fix.isPresent() ? describeMatch(tree, fix) : NO_MATCH; } }
result.add(ASTHelpers.getSymbol(((CatchTree) curr).getParameter())); break; case CLASS: TryTree tryTree = (TryTree) curr; boolean inResources = false; for (Tree resource : tryTree.getResources()) { if (resource.equals(prev)) { inResources = true; for (Tree resource : tryTree.getResources()) { if (resource.equals(prev)) { break; } else if (tryTree.getBlock().equals(prev)) { addAllIfVariable(tryTree.getResources(), result); for (ImportTree importTree : ((CompilationUnitTree) curr).getImports()) { if (importTree.isStatic() && importTree.getQualifiedIdentifier().getKind() == Kind.MEMBER_SELECT) { MemberSelectTree memberSelectTree = (MemberSelectTree) importTree.getQualifiedIdentifier();
if (pathToLoop != null) { Tree statements = pathToLoop.getStatement(); if (statements instanceof BlockTree && ((BlockTree) statements).getStatements().size() == 1) { hasWhileLoopOneStatement = true; TryTree tryTree = (TryTree) tryTreePath.getLeaf(); if (hasOtherInvocationsOrAssignments(methodInvocationTree, tryTree, state)) { return Description.NO_MATCH; if (tryTree.getFinallyBlock() != null) { return Description.NO_MATCH; for (CatchTree tree : tryTree.getCatches()) { Type typeSym = getType(tree.getParameter().getType()); if (ASTHelpers.isCastable(typeSym, interruptedType, state)) { if (tree.getBlock().getStatements().stream() .allMatch(s -> s instanceof EmptyStatementTree)) { SuggestedFix.Builder fix = SuggestedFix.builder();
return false; Tree parent = path.getParentPath().getLeaf(); if (parent.getKind() != Tree.Kind.BLOCK) { return false; int idx = block.getStatements().indexOf(path.getLeaf()); if (idx == -1 || idx == block.getStatements().size() - 1) { return false; StatementTree next = block.getStatements().get(idx + 1); if (!(next instanceof TryTree)) { return false; if (tryTree.getFinallyBlock() == null) { return false; .getFinallyBlock() .accept( new TreeScanner<Void, Void>() {
Set<Element> result = new LinkedHashSet<>(); Set<Element> safeInitMethods = new LinkedHashSet<>(); Tree enclosingBlockOrMethod = enclosingBlockPath.getLeaf(); if (enclosingBlockOrMethod instanceof VariableTree) { return Collections.emptySet(); while (!(classTreePath.getLeaf() instanceof ClassTree)) { classTreePath = classTreePath.getParentPath(); if (classTreePath == null) { if (tryTree.getCatches().size() == 0) { if (tryTree.getBlock() != null) { result.addAll( safeInitByCalleeBefore( pathToRead, state, new TreePath(enclosingBlockPath, tryTree.getBlock()))); if (tryTree.getFinallyBlock() != null) { result.addAll( safeInitByCalleeBefore( pathToRead, state, new TreePath(enclosingBlockPath, tryTree.getFinallyBlock())));
@Override public Boolean visitBlock(BlockTree node, Void p) { if (node.isStatic()) accept(STATIC); CodeStyle.BracePlacement bracePlacement; boolean spaceBeforeLeftBrace = false; switch (getCurrentPath().getParentPath().getLeaf().getKind()) { case ANNOTATION_TYPE: case CLASS: case INTERFACE: bracePlacement = cs.getOtherBracePlacement(); if (node.isStatic()) spaceBeforeLeftBrace = cs.spaceBeforeStaticInitLeftBrace(); break; case TRY: bracePlacement = cs.getOtherBracePlacement(); if (((TryTree)getCurrentPath().getParentPath().getLeaf()).getBlock() == node) spaceBeforeLeftBrace = cs.spaceBeforeTryLeftBrace(); else int lastMaxPreservedBlankLines = maxPreservedBlankLines; maxPreservedBlankLines = cs.getMaximumBlankLinesInCode(); for (StatementTree stat : node.getStatements()) { if (!isSynthetic(getCurrentPath().getCompilationUnit(), stat)) { isEmpty = false;
type = controller.getTrees().getTypeMirror(new TreePath(path, ((AssignmentTree) tree).getVariable())); if (type == null) { return null; TreePath parentPath = path.getParentPath(); if (parentPath != null && parentPath.getLeaf().getKind() == Tree.Kind.ANNOTATION && type.getKind() == TypeKind.EXECUTABLE) { type = ((ExecutableType) type).getReturnType(); while (dim-- > 0) { return null; if (methodOrLambdaPath.getLeaf().getKind() == Tree.Kind.METHOD) { Tree retTree = ((MethodTree) methodOrLambdaPath.getLeaf()).getReturnType(); if (retTree == null) { case TRY: TryTree tt = (TryTree) tree; BlockTree tryBlock = tt.getBlock(); SourcePositions sourcePositions = env.getSourcePositions(); if (tryBlock != null && sourcePositions.getStartPosition(env.getRoot(), tryBlock) <= offset) { final Trees trs = controller.getTrees(); final TypeElement enclClass = scope.getEnclosingClass(); final boolean isStatic = enclClass != null ? (tu.isStaticContext(scope) || (env.getPath().getLeaf().getKind() == Tree.Kind.BLOCK && ((BlockTree) env.getPath().getLeaf()).isStatic())) : false; if (SUPER_KEYWORD.equals(name) && enclClass != null) { ElementUtilities.ElementAcceptor acceptor = new ElementUtilities.ElementAcceptor() {
Types types = info.getTypes(); Elements elements = info.getElements(); for (Tree res : node.getResources()) { TypeMirror resType = trees.getTypeMirror(new TreePath(getCurrentPath(), res)); if (resType != null && resType.getKind() == TypeKind.DECLARED) { for (ExecutableElement method : ElementFilter.methodsIn(elements.getAllMembers((TypeElement)((DeclaredType)resType).asElement()))) { scan(node.getBlock(), s); Set<TypeMirror> c = new LinkedHashSet<TypeMirror>(); for (CatchTree ct : node.getCatches()) { TypeMirror t = trees.getTypeMirror(new TreePath(getCurrentPath(), ct.getParameter().getType())); if (t != null) { if (t.getKind() == TypeKind.UNION) { scan(node.getCatches(), p); scan(node.getFinallyBlock(), p); return null;
int lastPos = getStartPosition(last); int currentIndent = getCurrentIndent(last, path); switch (last.getKind()) { case COMPILATION_UNIT: break; switch (prevTokenId) { case LBRACE: if (path.get(1).getKind() == Kind.NEW_CLASS && isLeftBraceOnNewLine(lastPos, startOffset)) { switch (cs.getClassDeclBracePlacement()) { case SAME_LINE: Tree type = ((VariableTree)last).getType(); if (type != null && type.getKind() != Kind.ERRONEOUS) { ExpressionTree init = ((VariableTree)last).getInitializer(); if (init == null || init.getKind() != Kind.NEW_ARRAY || (token = findFirstNonWhitespaceToken(startOffset, lastPos)) == null last = ((VariableTree)last).getModifiers(); if (last == null) break; if (token != null && token.token().id() != JavaTokenId.RBRACE) { t = null; for (Tree res : ((TryTree)last).getResources()) { if (getEndPosition(res) > startOffset) { break;
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 (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));
TreeUtilities tu = info.getTreeUtilities(); TreePath tp = tu.pathFor(caretPosition); if (tp.getParentPath() != null && tp.getParentPath().getLeaf().getKind() == Kind.ANNOTATED_TYPE) { tp = tp.getParentPath(); if (typePath != null && typePath.getParentPath().getLeaf().getKind() == Kind.METHOD) { MethodTree decl = (MethodTree) typePath.getParentPath().getLeaf(); if (typePath != null && ((typePath.getParentPath().getLeaf().getKind() == Kind.UNION_TYPE && typePath.getParentPath().getParentPath().getLeaf().getKind() == Kind.VARIABLE && typePath.getParentPath().getParentPath().getParentPath().getLeaf().getKind() == Kind.CATCH) TreePath tryPath = tu.getPathElementOfKind(Kind.TRY, typePath); if (tryPath != null) { return med.process(info, doc, ((TryTree)tryPath.getLeaf()).getBlock(), Collections.singletonList(typePath.getLeaf()));
@Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!FENCE_MATCHER.matches(tree, state)) { return NO_MATCH; } Tree previous = null; OUTER: for (Tree enclosing : state.getPath().getParentPath()) { switch (enclosing.getKind()) { case TRY: if (((TryTree) enclosing).getFinallyBlock().equals(previous)) { return NO_MATCH; } break; case CLASS: case METHOD: case LAMBDA_EXPRESSION: break OUTER; default: // fall out } previous = enclosing; } return describeMatch(tree); } }
List<? extends CatchTree> catchTrees = tryTree.getCatches(); if (catchTrees.size() != 1) { return Optional.empty(); return Optional.empty(); List<? extends StatementTree> catchStatements = catchTree.getBlock().getStatements(); fix.addStaticImport("org.junit.Assert.assertThrows"); if (!catchStatements.isEmpty()) { fixPrefix.append(String.format("%s = ", state.getSourceForNode(catchTree.getParameter()))); state.getSourceForNode(catchTree.getParameter().getType()))); boolean useExpressionLambda = throwingStatements.size() == 1
/** * Returns a string describing the exception type caught by the given try tree's catch * statement(s), defaulting to {@code "Exception"} if more than one exception type is caught. */ private static String exceptionToString(TryTree tree, VisitorState state) { if (tree.getCatches().size() != 1) { return "Exception"; } Tree exceptionType = tree.getCatches().iterator().next().getParameter().getType(); Type type = ASTHelpers.getType(exceptionType); if (type != null && type.isUnion()) { return "Exception"; } return state.getSourceForNode(exceptionType); }
private static MatchResult tryTreeMatches(TryTree tryTree, VisitorState state) { BlockTree tryBlock = tryTree.getBlock(); List<? extends StatementTree> statements = tryBlock.getStatements(); if (statements.isEmpty()) { return doesNotMatch(); List<? extends CatchTree> catches = tryTree.getCatches(); if (catches.size() != 1) { VariableTree catchType = catchTree.getParameter(); boolean catchesThrowable = javaLangThrowable.matches(catchType, state); boolean catchesError = javaLangError.matches(catchType, state); List<? extends StatementTree> catchStatements = catchTree.getBlock().getStatements(); for (StatementTree catchStatement : catchStatements) {