Search in sources :

Example 36 with Description

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

the class TruthIncompatibleType method matchMethodInvocation.

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
    MatchResult result = MATCHER.matches(tree, state);
    if (result == null) {
        return Description.NO_MATCH;
    }
    TypeCompatibilityReport compatibilityReport = EqualsIncompatibleType.compatibilityOfTypes(result.targetType(), result.sourceType(), state);
    if (compatibilityReport.compatible()) {
        return Description.NO_MATCH;
    }
    String sourceType = Signatures.prettyType(result.sourceType());
    String targetType = Signatures.prettyType(result.targetType());
    if (sourceType.equals(targetType)) {
        sourceType = result.sourceType().toString();
        targetType = result.targetType().toString();
    }
    Description.Builder description = buildDescription(tree);
    description.setMessage(String.format("Argument '%s' should not be passed to this method; its type %s is not compatible " + "with subject type %s", result.sourceTree(), sourceType, targetType));
    return description.build();
}
Also used : Description(com.google.errorprone.matchers.Description) MatchResult(com.google.errorprone.bugpatterns.collectionincompatibletype.AbstractCollectionIncompatibleTypeMatcher.MatchResult) TypeCompatibilityReport(com.google.errorprone.bugpatterns.EqualsIncompatibleType.TypeCompatibilityReport)

Example 37 with Description

use of com.google.errorprone.matchers.Description 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 38 with Description

use of com.google.errorprone.matchers.Description 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)

Example 39 with Description

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

the class UnsafeFinalization method matchMethodInvocation.

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
    MethodSymbol sym = ASTHelpers.getSymbol(tree);
    // Match invocations of static native methods.
    if (sym == null || !sym.isStatic() || !Flags.asFlagSet(sym.flags()).contains(Flag.NATIVE)) {
        return NO_MATCH;
    }
    // Find the enclosing method declaration where the invocation occurs.
    MethodTree method = enclosingMethod(state);
    if (method == null) {
        return NO_MATCH;
    }
    // Don't check native methods called from static methods and constructors:
    // static methods don't have an instance to finalize, and we shouldn't need to worry about
    // finalization during construction.
    MethodSymbol enclosing = ASTHelpers.getSymbol(method);
    if (enclosing == null || enclosing.isStatic() || enclosing.isConstructor()) {
        return NO_MATCH;
    }
    // Check if any arguments of the static native method are members (e.g. fields) of the enclosing
    // class. We're only looking for cases where the static native uses state of the enclosing class
    // that may become invalid after finalization.
    ImmutableList<Symbol> arguments = tree.getArguments().stream().map(ASTHelpers::getSymbol).filter(x -> x != null).collect(toImmutableList());
    if (arguments.stream().filter(x -> EnumSet.of(TypeKind.INT, TypeKind.LONG).contains(state.getTypes().unboxedTypeOrType(x.asType()).getKind())).noneMatch(arg -> arg.isMemberOf(enclosing.enclClass(), state.getTypes()))) {
        // no instance state is passed to the native method
        return NO_MATCH;
    }
    if (arguments.stream().anyMatch(arg -> arg.getSimpleName().contentEquals("this") && arg.isMemberOf(enclosing.enclClass(), state.getTypes()))) {
        // the instance is passed to the native method
        return NO_MATCH;
    }
    Symbol finalizeSym = getFinalizer(state, enclosing.enclClass());
    if (finalizeSym.equals(enclosing)) {
        // Don't check native methods called from within the implementation of finalize.
        return NO_MATCH;
    }
    if (finalizeSym.enclClass().equals(state.getSymtab().objectType.asElement())) {
        // Inheriting finalize from Object doesn't count.
        return NO_MATCH;
    }
    boolean[] sawFence = { false };
    new TreeScanner<Void, Void>() {

        @Override
        public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
            if (FENCE_MATCHER.matches(tree, state)) {
                sawFence[0] = true;
            }
            return null;
        }
    }.scan(state.getPath().getCompilationUnit(), null);
    if (sawFence[0]) {
        // Ignore methods that contain a use of reachabilityFence.
        return NO_MATCH;
    }
    return describeMatch(tree);
}
Also used : MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) MethodTree(com.sun.source.tree.MethodTree) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) VisitorState(com.google.errorprone.VisitorState) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) ImmutableList(com.google.common.collect.ImmutableList) BugPattern(com.google.errorprone.BugPattern) Matcher(com.google.errorprone.matchers.Matcher) Tree(com.sun.source.tree.Tree) EnumSet(java.util.EnumSet) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) MethodInvocationTreeMatcher(com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher) ElementKind(javax.lang.model.element.ElementKind) ExpressionTree(com.sun.source.tree.ExpressionTree) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Flag(com.sun.tools.javac.code.Flags.Flag) Symbol(com.sun.tools.javac.code.Symbol) NO_MATCH(com.google.errorprone.matchers.Description.NO_MATCH) Streams(com.google.common.collect.Streams) TypeKind(javax.lang.model.type.TypeKind) TreeScanner(com.sun.source.util.TreeScanner) MethodMatchers.staticMethod(com.google.errorprone.matchers.method.MethodMatchers.staticMethod) Stream(java.util.stream.Stream) Description(com.google.errorprone.matchers.Description) Optional(java.util.Optional) WARNING(com.google.errorprone.BugPattern.SeverityLevel.WARNING) Flags(com.sun.tools.javac.code.Flags) ASTHelpers(com.google.errorprone.util.ASTHelpers) Type(com.sun.tools.javac.code.Type) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) MethodTree(com.sun.source.tree.MethodTree) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) Symbol(com.sun.tools.javac.code.Symbol) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) ASTHelpers(com.google.errorprone.util.ASTHelpers)

Example 40 with Description

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

the class TruthSelfEquals method matchMethodInvocation.

@Override
public Description matchMethodInvocation(MethodInvocationTree methodInvocationTree, VisitorState state) {
    if (methodInvocationTree.getArguments().isEmpty()) {
        return Description.NO_MATCH;
    }
    Description.Builder description = buildDescription(methodInvocationTree);
    ExpressionTree toReplace = methodInvocationTree.getArguments().get(0);
    if (EQUALS_MATCHER.matches(methodInvocationTree, state)) {
        description.setMessage(generateSummary(ASTHelpers.getSymbol(methodInvocationTree).getSimpleName().toString(), "passes")).addFix(suggestEqualsTesterFix(methodInvocationTree, toReplace));
    } else if (NOT_EQUALS_MATCHER.matches(methodInvocationTree, state)) {
        description.setMessage(generateSummary(ASTHelpers.getSymbol(methodInvocationTree).getSimpleName().toString(), "fails"));
    } else {
        return Description.NO_MATCH;
    }
    Fix fix = SelfEquals.fieldFix(toReplace, state);
    if (fix != null) {
        description.addFix(fix);
    }
    return description.build();
}
Also used : Description(com.google.errorprone.matchers.Description) ProvidesFix(com.google.errorprone.BugPattern.ProvidesFix) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) Fix(com.google.errorprone.fixes.Fix) ExpressionTree(com.sun.source.tree.ExpressionTree)

Aggregations

Description (com.google.errorprone.matchers.Description)56 Tree (com.sun.source.tree.Tree)23 VisitorState (com.google.errorprone.VisitorState)22 BugPattern (com.google.errorprone.BugPattern)21 SuggestedFix (com.google.errorprone.fixes.SuggestedFix)20 ASTHelpers (com.google.errorprone.util.ASTHelpers)20 WARNING (com.google.errorprone.BugPattern.SeverityLevel.WARNING)17 ExpressionTree (com.sun.source.tree.ExpressionTree)17 MethodInvocationTree (com.sun.source.tree.MethodInvocationTree)17 JDK (com.google.errorprone.BugPattern.Category.JDK)16 Symbol (com.sun.tools.javac.code.Symbol)16 ProvidesFix (com.google.errorprone.BugPattern.ProvidesFix)14 Type (com.sun.tools.javac.code.Type)14 DescriptionBasedDiff (com.google.errorprone.apply.DescriptionBasedDiff)11 VariableTree (com.sun.source.tree.VariableTree)11 MethodSymbol (com.sun.tools.javac.code.Symbol.MethodSymbol)11 NO_MATCH (com.google.errorprone.matchers.Description.NO_MATCH)10 ClassTree (com.sun.source.tree.ClassTree)10 Optional (java.util.Optional)10 MethodTree (com.sun.source.tree.MethodTree)9