Search in sources :

Example 36 with VisitorState

use of com.google.errorprone.VisitorState in project error-prone by google.

the class Matchers method enclosingNode.

/**
 * Matches an AST node that is enclosed by some node that matches the given matcher.
 *
 * <p>TODO(eaftan): This could be used instead of enclosingBlock and enclosingClass.
 */
public static <T extends Tree> Matcher<Tree> enclosingNode(final Matcher<T> matcher) {
    return new Matcher<Tree>() {

        // TODO(cushon): this should take a Class<T>
        @SuppressWarnings("unchecked")
        @Override
        public boolean matches(Tree t, VisitorState state) {
            TreePath path = state.getPath().getParentPath();
            while (path != null) {
                Tree node = path.getLeaf();
                state = state.withPath(path);
                if (matcher.matches((T) node, state)) {
                    return true;
                }
                path = path.getParentPath();
            }
            return false;
        }
    };
}
Also used : TreePath(com.sun.source.util.TreePath) InstanceMethodMatcher(com.google.errorprone.matchers.method.MethodMatchers.InstanceMethodMatcher) AnyMethodMatcher(com.google.errorprone.matchers.method.MethodMatchers.AnyMethodMatcher) StaticMethodMatcher(com.google.errorprone.matchers.method.MethodMatchers.StaticMethodMatcher) ConstructorMatcher(com.google.errorprone.matchers.method.MethodMatchers.ConstructorMatcher) VisitorState(com.google.errorprone.VisitorState) LiteralTree(com.sun.source.tree.LiteralTree) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) AssignmentTree(com.sun.source.tree.AssignmentTree) TypeCastTree(com.sun.source.tree.TypeCastTree) IdentifierTree(com.sun.source.tree.IdentifierTree) ContinueTree(com.sun.source.tree.ContinueTree) MemberSelectTree(com.sun.source.tree.MemberSelectTree) ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree) BlockTree(com.sun.source.tree.BlockTree) SynchronizedTree(com.sun.source.tree.SynchronizedTree) AssertTree(com.sun.source.tree.AssertTree) StatementTree(com.sun.source.tree.StatementTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) BinaryTree(com.sun.source.tree.BinaryTree) VariableTree(com.sun.source.tree.VariableTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) ExpressionTree(com.sun.source.tree.ExpressionTree) JCTree(com.sun.tools.javac.tree.JCTree)

Example 37 with VisitorState

use of com.google.errorprone.VisitorState in project error-prone by google.

the class Matchers method receiverSameAsArgument.

/**
 * Matches when the receiver of an instance method is the same reference as a particular argument
 * to the method. For example, receiverSameAsArgument(1) would match {@code obj.method("", obj)}
 *
 * @param argNum The number of the argument to compare against (zero-based.
 */
public static Matcher<? super MethodInvocationTree> receiverSameAsArgument(final int argNum) {
    return new Matcher<MethodInvocationTree>() {

        @Override
        public boolean matches(MethodInvocationTree t, VisitorState state) {
            List<? extends ExpressionTree> args = t.getArguments();
            if (args.size() <= argNum) {
                return false;
            }
            ExpressionTree arg = args.get(argNum);
            JCExpression methodSelect = (JCExpression) t.getMethodSelect();
            if (methodSelect instanceof JCFieldAccess) {
                JCFieldAccess fieldAccess = (JCFieldAccess) methodSelect;
                return ASTHelpers.sameVariable(fieldAccess.getExpression(), arg);
            } else if (methodSelect instanceof JCIdent) {
                // A bare method call: "equals(foo)".  Receiver is implicitly "this".
                return "this".equals(arg.toString());
            }
            return false;
        }
    };
}
Also used : JCIdent(com.sun.tools.javac.tree.JCTree.JCIdent) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) InstanceMethodMatcher(com.google.errorprone.matchers.method.MethodMatchers.InstanceMethodMatcher) AnyMethodMatcher(com.google.errorprone.matchers.method.MethodMatchers.AnyMethodMatcher) StaticMethodMatcher(com.google.errorprone.matchers.method.MethodMatchers.StaticMethodMatcher) ConstructorMatcher(com.google.errorprone.matchers.method.MethodMatchers.ConstructorMatcher) VisitorState(com.google.errorprone.VisitorState) JCFieldAccess(com.sun.tools.javac.tree.JCTree.JCFieldAccess) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) ExpressionTree(com.sun.source.tree.ExpressionTree)

Example 38 with VisitorState

use of com.google.errorprone.VisitorState in project error-prone by google.

the class TypeParameterShadowing method findDuplicatesOf.

private Description findDuplicatesOf(Tree tree, List<? extends TypeParameterTree> typeParameters, VisitorState state) {
    Symbol symbol = ASTHelpers.getSymbol(tree);
    if (symbol == null) {
        return Description.NO_MATCH;
    }
    List<TypeVariableSymbol> enclosingTypeSymbols = typeVariablesEnclosing(symbol);
    if (enclosingTypeSymbols.isEmpty()) {
        return Description.NO_MATCH;
    }
    List<TypeVariableSymbol> conflictingTypeSymbols = new ArrayList<>();
    typeParameters.forEach(param -> enclosingTypeSymbols.stream().filter(tvs -> tvs.name.contentEquals(param.getName())).findFirst().ifPresent(conflictingTypeSymbols::add));
    if (conflictingTypeSymbols.isEmpty()) {
        return Description.NO_MATCH;
    }
    Description.Builder descriptionBuilder = buildDescription(tree);
    String message = "Found aliased type parameters: " + conflictingTypeSymbols.stream().map(tvs -> tvs.name + " declared in " + tvs.owner.getSimpleName()).collect(Collectors.joining("\n"));
    descriptionBuilder.setMessage(message);
    Set<String> typeVarsInScope = Streams.concat(enclosingTypeSymbols.stream(), symbol.getTypeParameters().stream()).map(v -> v.name.toString()).collect(toImmutableSet());
    SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
    conflictingTypeSymbols.stream().map(v -> renameTypeVariable(typeParameterInList(typeParameters, v), tree, replacementTypeVarName(v.name, typeVarsInScope), state)).forEach(fixBuilder::merge);
    descriptionBuilder.addFix(fixBuilder.build());
    return descriptionBuilder.build();
}
Also used : ClassTreeMatcher(com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher) MethodTreeMatcher(com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher) MethodTree(com.sun.source.tree.MethodTree) TreeScanner(com.sun.tools.javac.tree.TreeScanner) TypeParameterTree(com.sun.source.tree.TypeParameterTree) ArrayList(java.util.ArrayList) VisitorState(com.google.errorprone.VisitorState) Matcher(java.util.regex.Matcher) StandardTags(com.google.errorprone.BugPattern.StandardTags) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) BugPattern(com.google.errorprone.BugPattern) JDK(com.google.errorprone.BugPattern.Category.JDK) Objects(com.google.common.base.Objects) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) Name(javax.lang.model.element.Name) MoreCollectors(com.google.common.collect.MoreCollectors) Symbol(com.sun.tools.javac.code.Symbol) Set(java.util.Set) Streams(com.google.common.collect.Streams) JCTree(com.sun.tools.javac.tree.JCTree) Collectors(java.util.stream.Collectors) TypeVariableSymbol(com.sun.tools.javac.code.Symbol.TypeVariableSymbol) List(java.util.List) Description(com.google.errorprone.matchers.Description) WARNING(com.google.errorprone.BugPattern.SeverityLevel.WARNING) ProvidesFix(com.google.errorprone.BugPattern.ProvidesFix) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) Pattern(java.util.regex.Pattern) ASTHelpers(com.google.errorprone.util.ASTHelpers) Description(com.google.errorprone.matchers.Description) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) Symbol(com.sun.tools.javac.code.Symbol) TypeVariableSymbol(com.sun.tools.javac.code.Symbol.TypeVariableSymbol) ArrayList(java.util.ArrayList) TypeVariableSymbol(com.sun.tools.javac.code.Symbol.TypeVariableSymbol)

Example 39 with VisitorState

use of com.google.errorprone.VisitorState in project error-prone by google.

the class UngroupedOverloads method checkOverloads.

private void checkOverloads(VisitorState state, List<? extends Tree> members, Name name, Collection<MemberWithIndex> overloads) {
    if (overloads.size() <= 1) {
        return;
    }
    // check if the indices of the overloads in the member list are sequential
    MemberWithIndex first = overloads.iterator().next();
    boolean grouped = Streams.zip(Stream.iterate(first.index(), i -> i + 1), overloads.stream().map(m -> m.index()), (a, b) -> Objects.equals(a, b)).allMatch(x -> x);
    if (grouped) {
        return;
    }
    if (overloads.stream().anyMatch(m -> isSuppressed(m.tree()))) {
        return;
    }
    // build a fix that deletes all but the first overload, and adds them back immediately after
    // the first overload
    SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
    StringBuilder sb = new StringBuilder("\n");
    overloads.stream().filter(o -> o != first).forEach(o -> {
        int start = state.getEndPosition(members.get(o.index() - 1));
        int end = state.getEndPosition(o.tree());
        sb.append(state.getSourceCode(), start, end).append('\n');
        fixBuilder.replace(start, end, "");
    });
    fixBuilder.postfixWith(first.tree(), sb.toString());
    SuggestedFix fix = fixBuilder.build();
    String message = String.format("Overloads of '%s' are not grouped together.", name);
    // emit findings for each overload
    overloads.stream().forEach(o -> state.reportMatch(buildDescription(o.tree()).addFix(fix).setMessage(message).build()));
}
Also used : MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) ClassTreeMatcher(com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher) MethodTree(com.sun.source.tree.MethodTree) Collection(java.util.Collection) CUSTOM(com.google.errorprone.BugPattern.LinkType.CUSTOM) NO_MATCH(com.google.errorprone.matchers.Description.NO_MATCH) Streams(com.google.common.collect.Streams) Objects(java.util.Objects) VisitorState(com.google.errorprone.VisitorState) List(java.util.List) Stream(java.util.stream.Stream) Multimaps.toMultimap(com.google.common.collect.Multimaps.toMultimap) Description(com.google.errorprone.matchers.Description) AutoValue(com.google.auto.value.AutoValue) BugPattern(com.google.errorprone.BugPattern) SUGGESTION(com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) JDK(com.google.errorprone.BugPattern.Category.JDK) Tree(com.sun.source.tree.Tree) LinkedHashMultimap(com.google.common.collect.LinkedHashMultimap) ASTHelpers(com.google.errorprone.util.ASTHelpers) ClassTree(com.sun.source.tree.ClassTree) Name(javax.lang.model.element.Name) SuggestedFix(com.google.errorprone.fixes.SuggestedFix)

Example 40 with VisitorState

use of com.google.errorprone.VisitorState in project error-prone by google.

the class UnnecessaryDefaultInEnumSwitch method matchSwitch.

@Override
public Description matchSwitch(SwitchTree tree, VisitorState state) {
    TypeSymbol switchType = ((JCSwitch) tree).getExpression().type.tsym;
    if (switchType.getKind() != ElementKind.ENUM) {
        return NO_MATCH;
    }
    CaseTree caseBeforeDefault = null;
    CaseTree defaultCase = null;
    for (CaseTree caseTree : tree.getCases()) {
        if (caseTree.getExpression() == null) {
            defaultCase = caseTree;
            break;
        } else {
            caseBeforeDefault = caseTree;
        }
    }
    if (defaultCase == null) {
        return NO_MATCH;
    }
    Set<String> handledCases = tree.getCases().stream().map(CaseTree::getExpression).filter(IdentifierTree.class::isInstance).map(p -> ((IdentifierTree) p).getName().toString()).collect(toImmutableSet());
    if (!ASTHelpers.enumValues(switchType).equals(handledCases)) {
        return NO_MATCH;
    }
    Fix fix;
    List<? extends StatementTree> defaultStatements = defaultCase.getStatements();
    if (trivialDefault(defaultStatements)) {
        // deleting `default:` or `default: break;` is a no-op
        fix = SuggestedFix.delete(defaultCase);
    } else {
        String defaultSource = state.getSourceCode().subSequence(((JCTree) defaultStatements.get(0)).getStartPosition(), state.getEndPosition(getLast(defaultStatements))).toString();
        String initialComments = comments(state, defaultCase, defaultStatements);
        if (!canCompleteNormally(tree)) {
            // if the switch statement cannot complete normally, then deleting the default
            // and moving its statements to after the switch statement is a no-op
            fix = SuggestedFix.builder().delete(defaultCase).postfixWith(tree, initialComments + defaultSource).build();
        } else {
            // and the code is unreachable -- so use (2) as the strategy.  Otherwise, use (1).
            if (!SuggestedFixes.compilesWithFix(SuggestedFix.delete(defaultCase), state)) {
                // case (3)
                return NO_MATCH;
            }
            if (!canCompleteNormally(caseBeforeDefault)) {
                // case (2) -- If the case before the default can't complete normally,
                // it's OK to to delete the default.
                fix = SuggestedFix.delete(defaultCase);
            } else {
                // case (1) -- If it can complete, we need to merge the default into it.
                fix = SuggestedFix.builder().delete(defaultCase).postfixWith(caseBeforeDefault, initialComments + defaultSource).build();
            }
        }
    }
    return describeMatch(defaultCase, fix);
}
Also used : SuggestedFixes(com.google.errorprone.fixes.SuggestedFixes) SwitchTreeMatcher(com.google.errorprone.bugpatterns.BugChecker.SwitchTreeMatcher) VisitorState(com.google.errorprone.VisitorState) JCSwitch(com.sun.tools.javac.tree.JCTree.JCSwitch) IdentifierTree(com.sun.source.tree.IdentifierTree) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) BugPattern(com.google.errorprone.BugPattern) JDK(com.google.errorprone.BugPattern.Category.JDK) Fix(com.google.errorprone.fixes.Fix) Tree(com.sun.source.tree.Tree) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) ElementKind(javax.lang.model.element.ElementKind) Set(java.util.Set) Iterables.getLast(com.google.common.collect.Iterables.getLast) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) NO_MATCH(com.google.errorprone.matchers.Description.NO_MATCH) CaseTree(com.sun.source.tree.CaseTree) JCTree(com.sun.tools.javac.tree.JCTree) SwitchTree(com.sun.source.tree.SwitchTree) List(java.util.List) Description(com.google.errorprone.matchers.Description) StatementTree(com.sun.source.tree.StatementTree) WARNING(com.google.errorprone.BugPattern.SeverityLevel.WARNING) ProvidesFix(com.google.errorprone.BugPattern.ProvidesFix) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) Reachability.canCompleteNormally(com.google.errorprone.util.Reachability.canCompleteNormally) ASTHelpers(com.google.errorprone.util.ASTHelpers) CaseTree(com.sun.source.tree.CaseTree) JCSwitch(com.sun.tools.javac.tree.JCTree.JCSwitch) Fix(com.google.errorprone.fixes.Fix) ProvidesFix(com.google.errorprone.BugPattern.ProvidesFix) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) IdentifierTree(com.sun.source.tree.IdentifierTree) JCTree(com.sun.tools.javac.tree.JCTree) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol)

Aggregations

VisitorState (com.google.errorprone.VisitorState)52 Tree (com.sun.source.tree.Tree)31 ASTHelpers (com.google.errorprone.util.ASTHelpers)29 Description (com.google.errorprone.matchers.Description)28 BugPattern (com.google.errorprone.BugPattern)27 MethodInvocationTree (com.sun.source.tree.MethodInvocationTree)23 Symbol (com.sun.tools.javac.code.Symbol)23 ClassTree (com.sun.source.tree.ClassTree)22 Type (com.sun.tools.javac.code.Type)22 WARNING (com.google.errorprone.BugPattern.SeverityLevel.WARNING)21 ExpressionTree (com.sun.source.tree.ExpressionTree)21 MethodTree (com.sun.source.tree.MethodTree)21 JDK (com.google.errorprone.BugPattern.Category.JDK)19 SuggestedFix (com.google.errorprone.fixes.SuggestedFix)18 MethodSymbol (com.sun.tools.javac.code.Symbol.MethodSymbol)16 List (java.util.List)16 NO_MATCH (com.google.errorprone.matchers.Description.NO_MATCH)14 Optional (java.util.Optional)14 VariableTree (com.sun.source.tree.VariableTree)13 ArrayList (java.util.ArrayList)13