repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SystemOut.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.FieldMatchers.staticField;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Printing to standard output should only be used for debugging, not in production code",
severity = WARNING,
tags = StandardTags.LIKELY_ERROR)
public class SystemOut extends BugChecker
implements MethodInvocationTreeMatcher, MemberSelectTreeMatcher {
private static final Matcher<ExpressionTree> SYSTEM_OUT =
anyOf(
staticField(System.class.getName(), "out"), //
staticField(System.class.getName(), "err"));
private static final Matcher<ExpressionTree> PRINT_STACK_TRACE =
anyOf(
staticMethod().onClass(Thread.class.getName()).named("dumpStack").withNoParameters(),
instanceMethod()
.onDescendantOf(Throwable.class.getName())
.named("printStackTrace")
.withNoParameters());
@Override
public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) {
if (SYSTEM_OUT.matches(tree, state)) {
return describeMatch(tree);
}
return NO_MATCH;
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (PRINT_STACK_TRACE.matches(tree, state)) {
return describeMatch(tree);
}
return NO_MATCH;
}
}
| 2,933
| 38.12
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BugPatternNaming.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static com.google.errorprone.util.MoreAnnotations.getValue;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.MoreAnnotations;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.IdentifierTree;
import java.util.Optional;
/** See the {@code summary}. */
@BugPattern(
summary = "Giving BugPatterns a name different to the enclosing class can be confusing",
severity = WARNING)
public final class BugPatternNaming extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (!isSubtype(getType(tree), state.getTypeFromString(BugChecker.class.getName()), state)) {
return NO_MATCH;
}
var classSymbol = getSymbol(tree);
var attribute = classSymbol.attribute(state.getSymbolFromString(BugPattern.class.getName()));
if (attribute == null) {
// e.g. abstract subtypes of BugChecker
return NO_MATCH;
}
return getValue(attribute, "name")
.flatMap(MoreAnnotations::asStringValue)
.filter(name -> !name.isEmpty())
.flatMap(
name -> {
if (!classSymbol.name.contentEquals(name)) {
return Optional.of(describeMatch(tree));
}
return removeName(tree, state);
})
.orElse(NO_MATCH);
}
private Optional<Description> removeName(ClassTree tree, VisitorState state) {
return tree.getModifiers().getAnnotations().stream()
.filter(
anno ->
isSameType(
getType(anno.getAnnotationType()),
state.getTypeFromString(BugPattern.class.getName()),
state))
.findFirst()
.flatMap(
anno ->
anno.getArguments().stream()
.filter(
t ->
t instanceof AssignmentTree
&& ((IdentifierTree) ((AssignmentTree) t).getVariable())
.getName()
.contentEquals("name"))
.findFirst()
.map(
ele ->
buildDescription(anno)
.setMessage(
"Setting @BugPattern.name to the class name of the check is"
+ " redundant")
.addFix(
SuggestedFixes.removeElement(ele, anno.getArguments(), state))
.build()));
}
}
| 3,960
| 39.835052
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UndefinedEquals.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.assertEqualsInvocation;
import static com.google.errorprone.matchers.Matchers.assertNotEqualsInvocation;
import static com.google.errorprone.matchers.Matchers.instanceEqualsInvocation;
import static com.google.errorprone.matchers.Matchers.receiverOfInvocation;
import static com.google.errorprone.matchers.Matchers.staticEqualsInvocation;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Type;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
/**
* Flags types which do not have well-defined equals behavior.
*
* @author eleanorh@google.com (Eleanor Harris)
*/
@BugPattern(
summary = "This type is not guaranteed to implement a useful #equals method.",
severity = WARNING)
public final class UndefinedEquals extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> IS_EQUAL_TO =
instanceMethod().onDescendantOf("com.google.common.truth.Subject").named("isEqualTo");
private static final Matcher<MethodInvocationTree> ASSERT_THAT_EQUALS =
allOf(
instanceMethod()
.onDescendantOf("com.google.common.truth.Subject")
.namedAnyOf("isEqualTo", "isNotEqualTo"),
receiverOfInvocation(
anyOf(
staticMethod().onClass("com.google.common.truth.Truth").named("assertThat"),
instanceMethod()
.onDescendantOf("com.google.common.truth.StandardSubjectBuilder")
.named("that"))));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
Tree receiver;
Tree argument;
List<? extends ExpressionTree> arguments = tree.getArguments();
if (staticEqualsInvocation().matches(tree, state)
|| assertEqualsInvocation().matches(tree, state)
|| assertNotEqualsInvocation().matches(tree, state)) {
receiver = arguments.get(arguments.size() - 2);
argument = getLast(arguments);
} else if (instanceEqualsInvocation().matches(tree, state)) {
receiver = getReceiver(tree);
argument = arguments.get(0);
} else if (ASSERT_THAT_EQUALS.matches(tree, state)) {
receiver = getOnlyElement(arguments);
argument = getOnlyElement(((MethodInvocationTree) getReceiver(tree)).getArguments());
} else {
return Description.NO_MATCH;
}
return Arrays.stream(TypesWithUndefinedEquality.values())
.filter(
b -> b.matchesType(getType(receiver), state) || b.matchesType(getType(argument), state))
.findFirst()
.map(
b ->
buildDescription(tree)
.setMessage(
"Subtypes of "
+ b.shortName()
+ " are not guaranteed to implement a useful #equals method.")
.addFix(
generateFix(tree, state, receiver, argument)
.orElse(SuggestedFix.emptyFix()))
.build())
.orElse(Description.NO_MATCH);
}
private static Optional<SuggestedFix> generateFix(
MethodInvocationTree tree, VisitorState state, Tree receiver, Tree argument) {
// Generate fix for certain Truth `isEqualTo` calls
if (IS_EQUAL_TO.matches(tree, state)) {
String methodText =
state.getSourceForNode(tree.getMethodSelect()); // e.g. "assertThat(foo).isEqualTo"
String assertThatWithArg = methodText.substring(0, methodText.lastIndexOf('.'));
// If both the argument and receiver are subtypes of the given type, rewrites the isEqualTo
// method invocation to use the replacement comparison method instead.
BiFunction<Type, String, Optional<SuggestedFix>> generateTruthFix =
(type, replacementMethod) -> {
if (type != null
&& isSubtype(getType(argument), type, state)
&& isSubtype(getType(receiver), type, state)) {
return Optional.of(
SuggestedFix.replace(
tree,
String.format(
"%s.%s(%s)",
assertThatWithArg, replacementMethod, state.getSourceForNode(receiver))));
}
return Optional.empty();
};
// If both are subtypes of Iterable, rewrite
Type iterableType = state.getSymtab().iterableType;
Type multimapType = COM_GOOGLE_COMMON_COLLECT_MULTIMAP.get(state);
Optional<SuggestedFix> fix =
firstPresent(
generateTruthFix.apply(iterableType, "containsExactlyElementsIn"),
generateTruthFix.apply(multimapType, "containsExactlyEntriesIn"));
if (fix.isPresent()) {
return fix;
}
}
// Generate fix for CharSequence
Type charSequenceType = JAVA_LANG_CHARSEQUENCE.get(state);
BiFunction<Tree, Tree, Optional<SuggestedFix>> generateCharSequenceFix =
(maybeCharSequence, maybeString) -> {
if (charSequenceType != null
&& isSameType(getType(maybeCharSequence), charSequenceType, state)
&& isSameType(getType(maybeString), state.getSymtab().stringType, state)) {
return Optional.of(SuggestedFix.postfixWith(maybeCharSequence, ".toString()"));
}
return Optional.empty();
};
return firstPresent(
generateCharSequenceFix.apply(receiver, argument),
generateCharSequenceFix.apply(argument, receiver));
}
private static <T> Optional<T> firstPresent(Optional<T>... optionals) {
for (Optional<T> optional : optionals) {
if (optional.isPresent()) {
return optional;
}
}
return Optional.empty();
}
private static final Supplier<Type> COM_GOOGLE_COMMON_COLLECT_MULTIMAP =
VisitorState.memoize(state -> state.getTypeFromString("com.google.common.collect.Multimap"));
private static final Supplier<Type> JAVA_LANG_CHARSEQUENCE =
VisitorState.memoize(state -> state.getTypeFromString("java.lang.CharSequence"));
}
| 8,009
| 42.532609
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/PreferredInterfaceType.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Multimaps.asMap;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFixes.qualifyType;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.InjectMatchers.hasProvidesAnnotation;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.isType;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import static com.google.errorprone.matchers.Matchers.variableType;
import static com.google.errorprone.predicates.TypePredicates.isDescendantOf;
import static com.google.errorprone.suppliers.Suppliers.typeFromString;
import static com.google.errorprone.util.ASTHelpers.canBeRemoved;
import static com.google.errorprone.util.ASTHelpers.findSuperMethods;
import static com.google.errorprone.util.ASTHelpers.getErasedTypeTree;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.getUpperBound;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static com.google.errorprone.util.ASTHelpers.methodCanBeOverridden;
import static com.google.errorprone.util.ASTHelpers.shouldKeep;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ListMultimap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.predicates.TypePredicate;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.lang.model.element.ElementKind;
import javax.lang.model.type.TypeKind;
/** Tightens types which refer to an Iterable, Map, Multimap, etc. */
@BugPattern(
altNames = {"MutableConstantField", "MutableMethodReturnType"},
summary = "This type can be more specific.",
severity = WARNING)
public final class PreferredInterfaceType extends BugChecker implements CompilationUnitTreeMatcher {
private static final ImmutableList<BetterTypes> BETTER_TYPES =
ImmutableList.of(
BetterTypes.of(
isDescendantOf("java.lang.Iterable"),
"com.google.common.collect.ImmutableSortedSet",
"com.google.common.collect.ImmutableSortedMap",
"com.google.common.collect.ImmutableSortedMultiset",
"com.google.common.collect.ImmutableList",
"com.google.common.collect.ImmutableSet",
"com.google.common.collect.ImmutableCollection",
"java.util.List",
"java.util.Set"),
BetterTypes.of(isDescendantOf("java.util.Map"), "com.google.common.collect.ImmutableMap"),
BetterTypes.of(
isDescendantOf("com.google.common.collect.Table"),
"com.google.common.collect.ImmutableTable"),
BetterTypes.of(
isDescendantOf("com.google.common.collect.RangeSet"),
"com.google.common.collect.ImmutableRangeSet"),
BetterTypes.of(
isDescendantOf("com.google.common.collect.RangeMap"),
"com.google.common.collect.ImmutableRangeMap"),
BetterTypes.of(
isDescendantOf("com.google.common.collect.Multimap"),
"com.google.common.collect.ImmutableListMultimap",
"com.google.common.collect.ImmutableSetMultimap",
"com.google.common.collect.ImmutableMultimap",
"com.google.common.collect.ListMultimap",
"com.google.common.collect.SetMultimap"),
BetterTypes.of(isDescendantOf("java.lang.CharSequence"), "java.lang.String"));
private static final Matcher<Tree> INTERESTING_TYPE =
anyOf(
BETTER_TYPES.stream()
.map(bt -> Matchers.typePredicateMatcher(bt.predicate()))
.collect(toImmutableList()));
public static final Matcher<Tree> SHOULD_IGNORE =
anyOf(
hasProvidesAnnotation(),
annotations(AT_LEAST_ONE, anyOf(isType("com.google.inject.testing.fieldbinder.Bind"))));
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
ImmutableMap<Symbol, Tree> fixableTypes = getFixableTypes(state);
ListMultimap<Symbol, Type> symbolsToType = ArrayListMultimap.create();
new TreePathScanner<Void, Void>() {
private final Deque<Symbol> currentMethod = new LinkedList<>();
@Override
public Void visitMethod(MethodTree node, Void unused) {
MethodSymbol methodSymbol = getSymbol(node);
currentMethod.addLast(methodSymbol);
super.visitMethod(node, null);
currentMethod.removeLast();
return null;
}
@Override
public Void visitVariable(VariableTree node, Void unused) {
if (node.getInitializer() != null) {
symbolsToType.put(getSymbol(node), getType(node.getInitializer()));
}
return super.visitVariable(node, null);
}
@Override
public Void visitAssignment(AssignmentTree node, Void unused) {
Symbol symbol = getSymbol(node.getVariable());
if (fixableTypes.containsKey(symbol)) {
symbolsToType.put(symbol, getType(node.getExpression()));
}
return super.visitAssignment(node, null);
}
@Override
public Void visitReturn(ReturnTree node, Void unused) {
var method = currentMethod.peekLast();
if (method != null) {
symbolsToType.put(method, getType(node.getExpression()));
}
return super.visitReturn(node, unused);
}
@Override
public Void visitLambdaExpression(LambdaExpressionTree node, Void unused) {
currentMethod.addLast(null);
super.visitLambdaExpression(node, unused);
currentMethod.removeLast();
return null;
}
}.scan(state.getPath(), null);
reportFixes(fixableTypes, symbolsToType, state);
return NO_MATCH;
}
private ImmutableMap<Symbol, Tree> getFixableTypes(VisitorState state) {
ImmutableMap.Builder<Symbol, Tree> fixableTypes = ImmutableMap.builder();
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitVariable(VariableTree tree, Void unused) {
VarSymbol symbol = getSymbol(tree);
if (variableIsFixable(tree, symbol)) {
fixableTypes.put(symbol, tree.getType());
}
return super.visitVariable(tree, null);
}
private boolean variableIsFixable(VariableTree tree, VarSymbol symbol) {
if (symbol == null) {
return false;
}
if (symbol.getKind() == ElementKind.PARAMETER) {
return false;
}
if (shouldKeep(tree)) {
return false;
}
// TODO(ghm): Open source @Keep on the elements in SHOULD_IGNORE, and remove this.
if (SHOULD_IGNORE.matches(tree, state)) {
return false;
}
if (symbol.getKind() == ElementKind.FIELD
&& !isConsideredFinal(symbol)
&& !canBeRemoved(symbol)) {
return false;
}
return variableType(INTERESTING_TYPE).matches(tree, state);
}
@Override
public Void visitMethod(MethodTree node, Void unused) {
MethodSymbol methodSymbol = getSymbol(node);
if (methodReturns(INTERESTING_TYPE).matches(node, state)
&& !methodCanBeOverridden(methodSymbol)
&& !SHOULD_IGNORE.matches(node, state)) {
fixableTypes.put(methodSymbol, node.getReturnType());
}
return super.visitMethod(node, null);
}
}.scan(state.getPath(), null);
return fixableTypes.buildOrThrow();
}
private void reportFixes(
Map<Symbol, Tree> fixableTypes,
ListMultimap<Symbol, Type> symbolsToType,
VisitorState state) {
Types types = state.getTypes();
for (Map.Entry<Symbol, List<Type>> entry : asMap(symbolsToType).entrySet()) {
Symbol symbol = entry.getKey();
List<Type> assignedTypes = entry.getValue();
Tree tree = fixableTypes.get(symbol);
if (tree == null) {
continue;
}
assignedTypes.stream()
.filter(type -> !type.getKind().equals(TypeKind.NULL))
.map(type -> getUpperBound(type, types))
.reduce(types::lub)
.flatMap(type -> toGoodReplacement(type, state))
.filter(replacement -> !isSubtype(getType(tree), replacement, state))
.filter(replacement -> isSubtype(replacement, getType(tree), state))
.ifPresent(
type -> {
SuggestedFix.Builder builder = SuggestedFix.builder();
SuggestedFix fix =
builder
.replace(
getErasedTypeTree(tree), qualifyType(state, builder, type.asElement()))
.addImport(types.erasure(type).toString())
.build();
state.reportMatch(
buildDescription(tree)
.setMessage(getMessage(symbol, type, state))
.addFix(fix)
.build());
});
}
}
private static String getMessage(Symbol symbol, Type newType, VisitorState state) {
String messageBase =
!isImmutable(targetType(symbol)) && isImmutable(newType)
? IMMUTABLE_MESSAGE
: NON_IMMUTABLE_MESSAGE;
if (symbol instanceof MethodSymbol) {
if (!findSuperMethods((MethodSymbol) symbol, state.getTypes()).isEmpty()) {
return "Method return" + messageBase + OVERRIDE_NOTE;
} else {
return "Method return" + messageBase;
}
} else {
return "Variable" + messageBase;
}
}
private static Type targetType(Symbol symbol) {
return symbol instanceof MethodSymbol ? ((MethodSymbol) symbol).getReturnType() : symbol.type;
}
private static boolean isImmutable(Type type) {
return type.tsym
.getQualifiedName()
.toString()
.startsWith("com.google.common.collect.Immutable");
}
private static final String IMMUTABLE_MESSAGE =
" type should use the immutable type (such as ImmutableList) instead of the general"
+ " collection interface type (such as List).";
private static final String NON_IMMUTABLE_MESSAGE =
" type can use a more specific type to convey more information to callers.";
private static final String OVERRIDE_NOTE =
" Note that it is possible to return a more specific type even when overriding a method.";
private static Optional<Type> toGoodReplacement(Type type, VisitorState state) {
return BETTER_TYPES.stream()
.filter(bt -> bt.predicate().apply(type, state))
.map(BetterTypes::betterTypes)
.findFirst()
.flatMap(
betterTypes ->
betterTypes.stream()
.map(typeName -> typeFromString(typeName).get(state))
.filter(
sensibleType ->
sensibleType != null && isSubtype(type, sensibleType, state))
.findFirst());
}
@AutoValue
abstract static class BetterTypes {
abstract TypePredicate predicate();
abstract ImmutableSet<String> betterTypes();
private static BetterTypes of(TypePredicate predicate, String... betterTypes) {
return new AutoValue_PreferredInterfaceType_BetterTypes(
predicate, ImmutableSet.copyOf(betterTypes));
}
}
}
| 13,613
| 39.760479
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ParametersButNotParameterized.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.JUnitMatchers.hasJUnit4TestRunner;
import static com.google.errorprone.util.ASTHelpers.getAnnotationWithSimpleName;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
/** Flags uses of parameters in non-parameterized tests. */
@BugPattern(
summary =
"This test has @Parameters but is using the default JUnit4 runner. The parameters will"
+ " have no effect.",
severity = ERROR)
public final class ParametersButNotParameterized extends BugChecker implements ClassTreeMatcher {
private static final String PARAMETERIZED = "org.junit.runners.Parameterized";
private static final String PARAMETER = "org.junit.runners.Parameterized.Parameter";
private static final String PARAMETERS = "org.junit.runners.Parameterized.Parameters";
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (!hasJUnit4TestRunner.matches(tree, state)) {
return NO_MATCH;
}
if (tree.getMembers().stream()
.noneMatch(
m -> hasAnnotation(m, PARAMETER, state) || hasAnnotation(m, PARAMETERS, state))) {
return NO_MATCH;
}
AnnotationTree annotation =
getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "RunWith");
SuggestedFix.Builder fix = SuggestedFix.builder();
fix.replace(
annotation,
String.format("@RunWith(%s.class)", SuggestedFixes.qualifyType(state, fix, PARAMETERIZED)));
return describeMatch(tree, fix.build());
}
}
| 2,704
| 41.265625
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryOptionalGet.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.sameVariable;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreeScanner;
/**
* A refactoring to replace Optional.get() with lambda arg in expressions passed as arg to member
* functions of Optionals.
*/
@BugPattern(
summary =
"This code can be simplified by directly using the lambda parameters instead of calling"
+ " get..() on optional.",
severity = WARNING)
public final class UnnecessaryOptionalGet extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> OPTIONAL_FUNCTIONS_WITH_FUNCTIONAL_ARG =
anyOf(
instanceMethod()
.onExactClass("java.util.Optional")
.namedAnyOf("map", "filter", "ifPresent", "flatMap"),
instanceMethod().onExactClass("java.util.OptionalLong").named("ifPresent"),
instanceMethod().onExactClass("java.util.OptionalInt").named("ifPresent"),
instanceMethod().onExactClass("java.util.OptionalDouble").named("ifPresent"),
instanceMethod().onExactClass("com.google.common.base.Optional").named("transform"));
private static final Matcher<ExpressionTree> OPTIONAL_GET =
anyOf(
instanceMethod()
.onExactClass("java.util.Optional")
.namedAnyOf("get", "orElseThrow", "orElse", "orElseGet", "orElseThrow"),
instanceMethod()
.onExactClass("java.util.OptionalLong")
.namedAnyOf("getAsLong", "orElse", "orElseGet", "orElseThrow"),
instanceMethod()
.onExactClass("java.util.OptionalInt")
.namedAnyOf("getAsInt", "orElse", "orElseGet", "orElseThrow"),
instanceMethod()
.onExactClass("java.util.OptionalDouble")
.namedAnyOf("getAsDouble", "orElse", "orElseGet", "orElseThrow"),
instanceMethod()
.onExactClass("com.google.common.base.Optional")
.namedAnyOf("get", "or", "orNull"));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!OPTIONAL_FUNCTIONS_WITH_FUNCTIONAL_ARG.matches(tree, state)) {
return Description.NO_MATCH;
}
ExpressionTree onlyArg = getOnlyElement(tree.getArguments());
if (!onlyArg.getKind().equals(Kind.LAMBDA_EXPRESSION)) {
return Description.NO_MATCH;
}
VariableTree arg = getOnlyElement(((LambdaExpressionTree) onlyArg).getParameters());
SuggestedFix.Builder fix = SuggestedFix.builder();
new TreeScanner<Void, VisitorState>() {
@Override
public Void visitMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState visitorState) {
if (OPTIONAL_GET.matches(methodInvocationTree, visitorState)
&& sameVariable(getReceiver(tree), getReceiver(methodInvocationTree))) {
fix.replace(methodInvocationTree, state.getSourceForNode(arg));
}
return super.visitMethodInvocation(methodInvocationTree, visitorState);
}
}.scan(onlyArg, state);
if (fix.isEmpty()) {
return Description.NO_MATCH;
}
return describeMatch(tree, fix.build());
}
}
| 4,700
| 43.771429
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryBoxedAssignment.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.AssignmentTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTag;
/**
* Finds and fixes unnecessarily boxed return expressions.
*
* @author awturner@google.com (Andy Turner)
*/
@BugPattern(
summary = "This expression can be implicitly boxed.",
severity = SeverityLevel.SUGGESTION)
public class UnnecessaryBoxedAssignment extends BugChecker
implements AssignmentTreeMatcher, ReturnTreeMatcher, VariableTreeMatcher {
private static final Matcher<ExpressionTree> VALUE_OF_MATCHER =
staticMethod().onClass(UnnecessaryBoxedAssignment::isBoxableType).named("valueOf");
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return matchCommon(tree.getExpression(), state);
}
@Override
public Description matchAssignment(AssignmentTree tree, VisitorState state) {
return matchCommon(tree.getExpression(), state);
}
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
return matchCommon(tree.getInitializer(), state);
}
private Description matchCommon(ExpressionTree expression, VisitorState state) {
if (expression == null || !VALUE_OF_MATCHER.matches(expression, state)) {
return Description.NO_MATCH;
}
MethodInvocationTree methodInvocationTree = (MethodInvocationTree) expression;
if (methodInvocationTree.getArguments().size() != 1) {
return Description.NO_MATCH;
}
ExpressionTree arg = methodInvocationTree.getArguments().get(0);
Type argType = ASTHelpers.getType(arg);
if (ASTHelpers.isSameType(argType, state.getSymtab().stringType, state)) {
return Description.NO_MATCH;
}
// Don't fix if there is an implicit primitive widening. This would need a cast, and that's not
// clearly better than using valueOf.
if (!ASTHelpers.isSameType(
state.getTypes().unboxedTypeOrType(argType),
state.getTypes().unboxedType(ASTHelpers.getType(expression)),
state)) {
return Description.NO_MATCH;
}
return describeMatch(expression, SuggestedFix.replace(expression, state.getSourceForNode(arg)));
}
private static boolean isBoxableType(Type type, VisitorState state) {
Type unboxedType = state.getTypes().unboxedType(type);
return unboxedType != null && unboxedType.getTag() != TypeTag.NONE;
}
}
| 3,831
| 38.916667
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MissingBraces.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.DoWhileLoopTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.EnhancedForLoopTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.ForLoopTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.IfTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.WhileLoopTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.DoWhileLoopTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.WhileLoopTree;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"The Google Java Style Guide requires braces to be used with if, else, for, do and while"
+ " statements, even when the body is empty or contains only a single statement.",
severity = SeverityLevel.SUGGESTION,
tags = StandardTags.STYLE,
linkType = LinkType.CUSTOM,
link = "https://google.github.io/styleguide/javaguide.html#s4.1.1-braces-always-used")
public class MissingBraces extends BugChecker
implements IfTreeMatcher,
ForLoopTreeMatcher,
DoWhileLoopTreeMatcher,
WhileLoopTreeMatcher,
EnhancedForLoopTreeMatcher {
@Override
public Description matchIf(IfTree tree, VisitorState state) {
check(tree.getThenStatement(), state);
if (tree.getElseStatement() != null
&& !tree.getElseStatement().getKind().equals(Tree.Kind.IF)) {
check(tree.getElseStatement(), state);
}
return NO_MATCH;
}
@Override
public Description matchDoWhileLoop(DoWhileLoopTree tree, VisitorState state) {
check(tree.getStatement(), state);
return NO_MATCH;
}
@Override
public Description matchForLoop(ForLoopTree tree, VisitorState state) {
check(tree.getStatement(), state);
return NO_MATCH;
}
@Override
public Description matchEnhancedForLoop(EnhancedForLoopTree tree, VisitorState state) {
check(tree.getStatement(), state);
return NO_MATCH;
}
@Override
public Description matchWhileLoop(WhileLoopTree tree, VisitorState state) {
check(tree.getStatement(), state);
return NO_MATCH;
}
void check(StatementTree tree, VisitorState state) {
if (tree != null && !(tree instanceof BlockTree)) {
state.reportMatch(
describeMatch(
tree, SuggestedFix.builder().prefixWith(tree, "{").postfixWith(tree, "}").build()));
}
}
}
| 3,676
| 35.77
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryFinal.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ErrorProneToken;
import com.google.errorprone.util.ErrorProneTokens;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.parser.Tokens.TokenKind;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
/** Removes {@code final} from non-field variables. */
@BugPattern(
summary =
"Since Java 8, it's been unnecessary to make local variables and parameters `final` for use"
+ " in lambdas or anonymous classes. Marking them as `final` is weakly discouraged, as"
+ " it adds a fair amount of noise for minimal benefit.",
severity = WARNING)
public final class UnnecessaryFinal extends BugChecker implements VariableTreeMatcher {
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
Symbol symbol = getSymbol(tree);
if (symbol.getKind() == ElementKind.FIELD) {
return NO_MATCH;
}
if (!tree.getModifiers().getFlags().contains(Modifier.FINAL)) {
return NO_MATCH;
}
ImmutableList<ErrorProneToken> tokens =
ErrorProneTokens.getTokens(state.getSourceForNode(tree.getModifiers()), state.context);
for (ErrorProneToken token : tokens) {
if (token.kind() == TokenKind.FINAL) {
int startPos = getStartPosition(tree);
return describeMatch(
tree, SuggestedFix.replace(startPos + token.pos(), startPos + token.endPos(), ""));
}
}
return NO_MATCH;
}
}
| 2,760
| 40.208955
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LossyPrimitiveCompare.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import java.util.function.Predicate;
/**
* Checker to prevent usages of comparison methods where both the operands undergo lossy widening.
*
* @author awturner@google.com (Andy Turner)
*/
@BugPattern(
summary = "Using an unnecessarily-wide comparison method can lead to lossy comparison",
explanation =
"Implicit widening conversions when comparing two primitives with methods like"
+ " Float.compare can lead to lossy comparison. For example,"
+ " `Float.compare(Integer.MAX_VALUE, Integer.MAX_VALUE - 1) == 0`. Use a compare"
+ " method with non-lossy conversion, or ideally no conversion if possible.",
severity = ERROR)
public class LossyPrimitiveCompare extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> COMPARE_MATCHER =
staticMethod().onClassAny("java.lang.Float", "java.lang.Double").named("compare");
private static final Matcher<ExpressionTree> FLOAT_COMPARE_MATCHER =
staticMethod().onClass("java.lang.Float").named("compare");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!COMPARE_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
Types types = state.getTypes();
Symtab symtab = state.getSymtab();
ImmutableList<Type> argTypes =
tree.getArguments().stream().map(ASTHelpers::getType).collect(toImmutableList());
Predicate<Type> argsAreConvertible =
type -> argTypes.stream().allMatch(t -> types.isConvertible(t, type));
if (argsAreConvertible.test(symtab.byteType)
|| argsAreConvertible.test(symtab.charType)
|| argsAreConvertible.test(symtab.shortType)) {
// These types can be converted to float and double without loss.
} else if (argsAreConvertible.test(symtab.intType)) {
// Only need to fix in the case of Float.compare, because int can be converted to double
// without loss.
if (FLOAT_COMPARE_MATCHER.matches(tree, state)) {
return describeMatch(tree, SuggestedFix.replace(tree.getMethodSelect(), "Integer.compare"));
}
} else if (argsAreConvertible.test(symtab.longType)) {
return describeMatch(tree, SuggestedFix.replace(tree.getMethodSelect(), "Long.compare"));
}
return Description.NO_MATCH;
}
}
| 3,849
| 42.75
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Streams.stream;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.findSuperMethods;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static com.sun.source.tree.Tree.Kind.IDENTIFIER;
import static com.sun.source.tree.Tree.Kind.MEMBER_SELECT;
import static com.sun.source.tree.Tree.Kind.METHOD_INVOCATION;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.MoreAnnotations;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import javax.lang.model.element.Modifier;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(name = "DoNotCall", summary = "This method should not be called.", severity = ERROR)
public class DoNotCallChecker extends BugChecker
implements MethodTreeMatcher, CompilationUnitTreeMatcher {
private static final Matcher<ExpressionTree> THREAD_RUN =
instanceMethod().onDescendantOf("java.lang.Thread").named("run").withNoParameters();
private static final Matcher<ExpressionTree> CALL_ON_SUPER =
(invocation, state) -> {
if (invocation.getKind() != METHOD_INVOCATION) {
return false;
}
ExpressionTree select = ((MethodInvocationTree) invocation).getMethodSelect();
if (select.getKind() != MEMBER_SELECT) {
return false;
}
ExpressionTree receiver = ((MemberSelectTree) select).getExpression();
if (receiver.getKind() != IDENTIFIER) {
return false;
}
return ((IdentifierTree) receiver).getName().contentEquals("super");
};
// If your method cannot be annotated with @DoNotCall (e.g., it's a JDK or thirdparty method),
// then add it to this Map with an explanation.
private static final ImmutableMap<Matcher<ExpressionTree>, String> THIRD_PARTY_METHODS =
ImmutableMap.<Matcher<ExpressionTree>, String>builder()
.put(
staticMethod()
.onClass("org.junit.Assert")
.named("assertEquals")
.withParameters("double", "double"),
"This method always throws java.lang.AssertionError. Use assertEquals("
+ "expected, actual, delta) to compare floating-point numbers")
.put(
staticMethod()
.onClass("org.junit.Assert")
.named("assertEquals")
.withParameters("java.lang.String", "double", "double"),
"This method always throws java.lang.AssertionError. Use assertEquals("
+ "String, expected, actual, delta) to compare floating-point numbers")
.put(
instanceMethod()
.onExactClass("java.lang.Thread")
.named("stop")
.withParameters("java.lang.Throwable"),
"Thread.stop(Throwable) always throws an UnsupportedOperationException")
.put(
instanceMethod()
.onExactClass("java.sql.Date")
.namedAnyOf(
"getHours",
"getMinutes",
"getSeconds",
"setHours",
"setMinutes",
"setSeconds"),
"The hour/minute/second getters and setters on java.sql.Date are guaranteed to throw"
+ " IllegalArgumentException because java.sql.Date does not have a time"
+ " component.")
.put(
instanceMethod().onExactClass("java.sql.Date").named("toInstant"),
"sqlDate.toInstant() is not supported. Did you mean to call toLocalDate() instead?")
.put(
instanceMethod()
.onExactClass("java.sql.Time")
.namedAnyOf(
"getYear", "getMonth", "getDay", "getDate", "setYear", "setMonth", "setDate"),
"The year/month/day getters and setters on java.sql.Time are guaranteed to throw"
+ " IllegalArgumentException because java.sql.Time does not have a date"
+ " component.")
.put(
instanceMethod().onExactClass("java.sql.Time").named("toInstant"),
"sqlTime.toInstant() is not supported. Did you mean to call toLocalTime() instead?")
.put(
instanceMethod()
.onExactClass("java.util.concurrent.ThreadLocalRandom")
.named("setSeed"),
"ThreadLocalRandom does not support setting a seed.")
.put(
instanceMethod()
.onExactClass("java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock")
.named("newCondition"),
"ReadLocks do not support conditions.")
.put(
instanceMethod().onExactClass("java.lang.StackTraceElement").named("getClass"),
"Calling getClass on StackTraceElement returns the Class object for"
+ " StackTraceElement, you probably meant to retrieve the class containing the"
+ " execution point represented by this stack trace element using getClassName")
.put(
instanceMethod().onExactClass("java.lang.StackWalker").named("getClass"),
"Calling getClass on StackWalker returns the Class object for StackWalker, you"
+ " probably meant to retrieve the class containing the execution point"
+ " represented by this StackWalker using getCallerClass")
.put(
instanceMethod().onExactClass("java.lang.StackWalker$StackFrame").named("getClass"),
"Calling getClass on StackFrame returns the Class object for StackFrame, you probably"
+ " meant to retrieve the class containing the execution point represented by"
+ " this StackFrame using getClassName")
.put(
instanceMethod().onExactClass("java.lang.reflect.Constructor").named("getClass"),
"Calling getClass on Constructor returns the Class object for Constructor, you"
+ " probably meant to retrieve the class containing the constructor represented"
+ " by this Constructor using getDeclaringClass")
.put(
instanceMethod().onExactClass("java.lang.reflect.Field").named("getClass"),
"Calling getClass on Field returns the Class object for Field, you probably meant to"
+ " retrieve the class containing the field represented by this Field using"
+ " getDeclaringClass")
.put(
instanceMethod().onExactClass("java.lang.reflect.Method").named("getClass"),
"Calling getClass on Method returns the Class object for Method, you probably meant"
+ " to retrieve the class containing the method represented by this Method using"
+ " getDeclaringClass")
.put(
instanceMethod()
.onExactClass("java.lang.reflect.ParameterizedType")
.named("getClass"),
"Calling getClass on ParameterizedType returns the Class object for"
+ " ParameterizedType, you probably meant to retrieve the class containing the"
+ " method represented by this ParameterizedType using getRawType")
.put(
instanceMethod().onExactClass("java.beans.BeanDescriptor").named("getClass"),
"Calling getClass on BeanDescriptor returns the Class object for BeanDescriptor, you"
+ " probably meant to retrieve the class described by this BeanDescriptor using"
+ " getBeanClass")
.put(
/*
* LockInfo has a publicly visible subclass, MonitorInfo. It seems unlikely that
* anyone is using getClass() in an attempt to distinguish the two. (If anyone is,
* then it would make more sense to use instanceof, anyway.)
*/
instanceMethod().onDescendantOf("java.lang.management.LockInfo").named("getClass"),
"Calling getClass on LockInfo returns the Class object for LockInfo, you probably"
+ " meant to retrieve the class of the object that is being locked using"
+ " getClassName")
/*
* These methods are part of Guava, but we have to list them in this "thirdparty" section:
* We can't annotate them with @DoNotCall because we can't override getClass.
*/
.put(
instanceMethod()
.onExactClass("com.google.common.reflect.ClassPath$ClassInfo")
.named("getClass"),
"Calling getClass on ClassInfo returns the Class object for ClassInfo, you probably"
+ " meant to retrieve the class described by this ClassInfo using getName or"
+ " load")
/*
* Users of TypeToken have to create a subclass. The static type of their instance is
* probably often still "TypeToken," but that may change as we see more usage of `var`. So
* let's check subclasses, too. If anyone defines an overload of getClass on such a
* subclass, this check will give that person a bad time in one additional way.
*/
.put(
instanceMethod()
.onDescendantOf("com.google.common.reflect.TypeToken")
.named("getClass"),
"Calling getClass on TypeToken returns the Class object for TypeToken, you probably"
+ " meant to retrieve the class described by this TypeToken using getRawType")
.put(
/*
* A call to super.run() from a direct subclass of Thread is a no-op. That could be
* worth telling the user about, but it's not as big a deal as "You meant to call
* start()," so we ignore it here.
*
* (And if someone defines a MyThread class with a run() method that does something,
* then a call to super.run() from a subclass of *MyThread* would *not* be a no-op,
* and we wouldn't want to flag it. Still, *usually* it's likely to be useful to
* report a warning even on subclasses of Thread, such as anonymous classes.)
*/
allOf(THREAD_RUN, not(CALL_ON_SUPER)),
"Calling run on Thread runs work on this thread, rather than the given thread, you"
+ " probably meant to call start")
.buildOrThrow();
static final String DO_NOT_CALL = "com.google.errorprone.annotations.DoNotCall";
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
MethodSymbol symbol = getSymbol(tree);
if (hasAnnotation(tree, DO_NOT_CALL, state)) {
if (symbol.getModifiers().contains(Modifier.PRIVATE)) {
return buildDescription(tree)
.setMessage("A private method that should not be called should simply be removed.")
.build();
}
if (symbol.getModifiers().contains(Modifier.ABSTRACT)) {
return NO_MATCH;
}
if (!ASTHelpers.methodCanBeOverridden(symbol)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage("Methods annotated with @DoNotCall should be final or static.")
.addFix(
SuggestedFixes.addModifiers(tree, state, Modifier.FINAL)
.orElse(SuggestedFix.emptyFix()))
.build();
}
return findSuperMethods(symbol, state.getTypes()).stream()
.filter(s -> hasAnnotation(s, DO_NOT_CALL, state))
.findAny()
.map(
s -> {
String message =
String.format(
"Method overrides %s in %s which is annotated @DoNotCall,"
+ " it should also be annotated.",
s.getSimpleName(), s.owner.getSimpleName());
return buildDescription(tree)
.setMessage(message)
.addFix(
SuggestedFix.builder()
.addImport(DO_NOT_CALL)
.prefixWith(tree, "@DoNotCall ")
.build())
.build();
})
.orElse(NO_MATCH);
}
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
ImmutableListMultimap<VarSymbol, Type> assignedTypes = getAssignedTypes(state);
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
handleTree(tree, getSymbol(tree));
return super.visitMethodInvocation(tree, null);
}
@Override
public Void visitMemberReference(MemberReferenceTree tree, Void unused) {
handleTree(tree, getSymbol(tree));
return super.visitMemberReference(tree, null);
}
private void handleTree(ExpressionTree tree, MethodSymbol symbol) {
for (Map.Entry<Matcher<ExpressionTree>, String> matcher : THIRD_PARTY_METHODS.entrySet()) {
if (matcher.getKey().matches(tree, state)) {
state.reportMatch(buildDescription(tree).setMessage(matcher.getValue()).build());
return;
}
}
checkTree(tree, symbol, state);
}
private void checkTree(ExpressionTree tree, MethodSymbol sym, VisitorState state) {
mustNotCall(tree, sym, state).ifPresent(symbol -> handleDoNotCall(tree, symbol, state));
}
private void handleDoNotCall(ExpressionTree tree, Symbol symbol, VisitorState state) {
String doNotCall = getDoNotCallValue(symbol);
StringBuilder message = new StringBuilder("This method should not be called");
if (doNotCall.isEmpty()) {
message.append(", see its documentation for details.");
} else {
message.append(": ").append(doNotCall);
}
state.reportMatch(buildDescription(tree).setMessage(message.toString()).build());
}
private Optional<Symbol> mustNotCall(
ExpressionTree tree, MethodSymbol sym, VisitorState state) {
if (hasAnnotation(sym, DO_NOT_CALL, state)) {
return Optional.of(sym);
}
ExpressionTree receiver = getReceiver(tree);
Symbol receiverSymbol = getSymbol(receiver);
if (!(receiverSymbol instanceof VarSymbol)) {
return Optional.empty();
}
ImmutableList<Type> assigned = assignedTypes.get((VarSymbol) receiverSymbol);
if (!assigned.stream().allMatch(t -> isSameType(t, assigned.get(0), state))) {
return Optional.empty();
}
Types types = state.getTypes();
return assigned.stream()
.flatMap(
typeSeen ->
types.closure(typeSeen).stream()
.flatMap(
t ->
t.tsym.members() == null
? Stream.empty()
: stream(t.tsym.members().getSymbolsByName(sym.name)))
.filter(
symbol ->
!sym.isStatic()
&& (sym.flags() & Flags.SYNTHETIC) == 0
&& hasAnnotation(symbol, DO_NOT_CALL, state)
&& symbol.overrides(
sym,
types.erasure(typeSeen).tsym,
types,
/* checkResult= */ true)))
.findFirst();
}
}.scan(state.getPath(), null);
return NO_MATCH;
}
private ImmutableListMultimap<VarSymbol, Type> getAssignedTypes(VisitorState state) {
ImmutableListMultimap.Builder<VarSymbol, Type> assignedTypes = ImmutableListMultimap.builder();
new TreePathScanner<Void, Void>() {
@Override
public Void visitVariable(VariableTree node, Void unused) {
VarSymbol symbol = getSymbol(node);
if (node.getInitializer() != null && isConsideredFinal(symbol)) {
Type type = getType(node.getInitializer());
if (type != null) {
assignedTypes.put(symbol, type);
}
}
return super.visitVariable(node, null);
}
@Override
public Void visitAssignment(AssignmentTree node, Void unused) {
Symbol assignee = getSymbol(node.getVariable());
if (assignee instanceof VarSymbol && isConsideredFinal(assignee)) {
Type type = getType(node.getExpression());
if (type != null) {
assignedTypes.put((VarSymbol) assignee, type);
}
}
return super.visitAssignment(node, null);
}
}.scan(state.getPath(), null);
return assignedTypes.build();
}
private static String getDoNotCallValue(Symbol symbol) {
for (Attribute.Compound a : symbol.getRawAttributes()) {
if (!a.type.tsym.getQualifiedName().contentEquals(DO_NOT_CALL)) {
continue;
}
return MoreAnnotations.getAnnotationValue(a, "value")
.flatMap(MoreAnnotations::asStringValue)
.orElse("");
}
throw new IllegalStateException();
}
}
| 20,307
| 47.70024
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/EqualsHashCode.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.equalsMethodDeclaration;
import static com.google.errorprone.matchers.Matchers.instanceEqualsInvocation;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.Matchers.singleStatementReturnMatcher;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Type;
import javax.annotation.Nullable;
import javax.lang.model.element.ElementKind;
/**
* Classes that override {@link Object#equals} should also override {@link Object#hashCode}.
*
* @author cushon@google.com (Liam Miller-Cushon)
*/
@BugPattern(
summary = "Classes that override equals should also override hashCode.",
severity = ERROR,
tags = StandardTags.FRAGILE_CODE)
public class EqualsHashCode extends BugChecker implements ClassTreeMatcher {
private static final Matcher<MethodTree> NON_TRIVIAL_EQUALS =
allOf(
equalsMethodDeclaration(), not(singleStatementReturnMatcher(instanceEqualsInvocation())));
@Override
public Description matchClass(ClassTree classTree, VisitorState state) {
MethodTree methodTree = checkMethodPresence(classTree, state/* expectedNoArgMethod= */ );
if (methodTree == null || isSuppressed(methodTree, state)) {
return NO_MATCH;
}
return describeMatch(methodTree);
}
/**
* Returns the {@link MethodTree} node in the {@code classTree} if both :
*
* <ol>
* <li>there is a method matched by {@code requiredMethodPresenceMatcher}
* <li>there is no additional method with name matching {@code expectedNoArgMethod}
* </ol>
*/
@Nullable
private static MethodTree checkMethodPresence(ClassTree classTree, VisitorState state) {
TypeSymbol symbol = ASTHelpers.getSymbol(classTree);
if (symbol.getKind() != ElementKind.CLASS) {
return null;
}
// don't flag java.lang.Object
if (symbol == state.getSymtab().objectType.tsym) {
return null;
}
MethodTree requiredMethod = null;
for (Tree member : classTree.getMembers()) {
if (!(member instanceof MethodTree)) {
continue;
}
MethodTree methodTree = (MethodTree) member;
if (EqualsHashCode.NON_TRIVIAL_EQUALS.matches(methodTree, state)) {
requiredMethod = methodTree;
}
}
if (requiredMethod == null) {
return null;
}
MethodSymbol expectedMethodSym =
ASTHelpers.resolveExistingMethod(
state,
symbol,
state.getName("hashCode"),
ImmutableList.<Type>of(),
ImmutableList.<Type>of());
if (!expectedMethodSym.owner.equals(state.getSymtab().objectType.tsym)) {
return null;
}
return requiredMethod;
}
}
| 4,156
| 35.787611
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditions.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.contains;
import static com.google.errorprone.util.ASTHelpers.stripParentheses;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.IfTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.InstanceOfTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Types;
/**
* @author sulku@google.com (Marsela Sulku)
* @author mariasam@google.com (Maria Sam)
*/
@BugPattern(
summary =
"Nested instanceOf conditions of disjoint types create blocks of code that never execute",
severity = WARNING)
public class NestedInstanceOfConditions extends BugChecker implements IfTreeMatcher {
@Override
public Description matchIf(IfTree ifTree, VisitorState visitorState) {
ExpressionTree expressionTree = stripParentheses(ifTree.getCondition());
if (expressionTree instanceof InstanceOfTree) {
InstanceOfTree instanceOfTree = (InstanceOfTree) expressionTree;
if (!(instanceOfTree.getExpression() instanceof IdentifierTree)) {
return Description.NO_MATCH;
}
Matcher<Tree> assignmentTreeMatcher =
new AssignmentTreeMatcher(instanceOfTree.getExpression());
Matcher<Tree> containsAssignmentTreeMatcher = contains(assignmentTreeMatcher);
if (containsAssignmentTreeMatcher.matches(ifTree, visitorState)) {
return Description.NO_MATCH;
}
// set expression and type to look for in matcher
Matcher<Tree> nestedInstanceOfMatcher =
new NestedInstanceOfMatcher(instanceOfTree.getExpression(), instanceOfTree.getType());
Matcher<Tree> containsNestedInstanceOfMatcher = contains(nestedInstanceOfMatcher);
if (containsNestedInstanceOfMatcher.matches(ifTree.getThenStatement(), visitorState)) {
return describeMatch(ifTree);
}
}
return Description.NO_MATCH;
}
private static class AssignmentTreeMatcher implements Matcher<Tree> {
private final ExpressionTree variableExpressionTree;
public AssignmentTreeMatcher(ExpressionTree e) {
variableExpressionTree = e;
}
@Override
public boolean matches(Tree tree, VisitorState visitorState) {
if (tree instanceof AssignmentTree) {
return visitorState
.getSourceForNode(variableExpressionTree)
.equals(visitorState.getSourceForNode(((AssignmentTree) tree).getVariable()));
}
return false;
}
}
/**
* Matches if current tree is an if tree with an instanceof statement as a condition that checks
* if an expression is an instanceof a type that is disjoint from the matcher's type that is set
* beforehand.
*/
private static class NestedInstanceOfMatcher implements Matcher<Tree> {
private final ExpressionTree expressionTree;
private final Tree typeTree;
public NestedInstanceOfMatcher(ExpressionTree e, Tree t) {
expressionTree = e;
typeTree = t;
}
@Override
public boolean matches(Tree tree, VisitorState state) {
if (tree instanceof IfTree) {
ExpressionTree conditionTree = ASTHelpers.stripParentheses(((IfTree) tree).getCondition());
if (conditionTree instanceof InstanceOfTree) {
InstanceOfTree instanceOfTree = (InstanceOfTree) conditionTree;
Types types = state.getTypes();
boolean isCastable =
types.isCastable(
types.erasure(ASTHelpers.getType(instanceOfTree.getType())),
types.erasure(ASTHelpers.getType(typeTree)));
boolean isSameExpression =
state
.getSourceForNode(instanceOfTree.getExpression())
.equals(state.getSourceForNode(expressionTree));
return isSameExpression && !isCastable;
}
}
return false;
}
}
}
| 4,910
| 34.078571
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ErroneousThreadPoolConstructorChecker.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.constructor;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.NewClassTree;
import java.util.List;
/**
* ErrorProne checker to generate warning whenever {@link java.util.concurrent.ThreadPoolExecutor}
* is constructed with different {@code corePoolSize} and {@code maximumPoolSize} using an unbounded
* {@code workQueue}
*/
@BugPattern(
summary = "Thread pool size will never go beyond corePoolSize if an unbounded queue is used",
severity = WARNING)
public final class ErroneousThreadPoolConstructorChecker extends BugChecker
implements NewClassTreeMatcher {
private static final Matcher<ExpressionTree> THREAD_POOL_CONSTRUCTOR_MATCHER =
constructor().forClass("java.util.concurrent.ThreadPoolExecutor");
private static final Matcher<ExpressionTree> UNBOUNDED_WORK_QUEUE_CONSTRUCTOR_MATCHER =
anyOf(
constructor().forClass("java.util.concurrent.LinkedBlockingDeque").withNoParameters(),
constructor()
.forClass("java.util.concurrent.LinkedBlockingDeque")
.withParameters("java.util.Collection"),
constructor().forClass("java.util.concurrent.LinkedBlockingQueue").withNoParameters(),
constructor()
.forClass("java.util.concurrent.LinkedBlockingQueue")
.withParameters("java.util.Collection"),
constructor().forClass("java.util.concurrent.LinkedTransferQueue"),
constructor().forClass("java.util.concurrent.PriorityBlockingQueue"));
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (!THREAD_POOL_CONSTRUCTOR_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
List<? extends ExpressionTree> arguments = tree.getArguments();
if (arguments.size() < 2) {
return Description.NO_MATCH;
}
Integer corePoolSize = ASTHelpers.constValue(arguments.get(0), Integer.class);
Integer maximumPoolSize = ASTHelpers.constValue(arguments.get(1), Integer.class);
if (corePoolSize == null || maximumPoolSize == null || corePoolSize.equals(maximumPoolSize)) {
return Description.NO_MATCH;
}
// This is a special case, as ThreadPoolExecutor ensures starting the first thread in the pool
if (corePoolSize == 0 && maximumPoolSize == 1) {
return Description.NO_MATCH;
}
ExpressionTree workQueueExpressionTree = arguments.get(4);
if (!UNBOUNDED_WORK_QUEUE_CONSTRUCTOR_MATCHER.matches(workQueueExpressionTree, state)) {
return Description.NO_MATCH;
}
String maximumPoolSizeReplacement;
// maximumPoolSize cannot be 0, so when corePoolSize is 0 set maximumPoolSize to 1 explicitly
if (corePoolSize == 0) {
maximumPoolSizeReplacement = "1";
} else {
maximumPoolSizeReplacement = state.getSourceForNode(arguments.get(0));
}
Fix maximumPoolSizeReplacementFix =
SuggestedFix.builder().replace(arguments.get(1), maximumPoolSizeReplacement).build();
Fix corePoolSizeReplacementFix =
SuggestedFix.builder()
.replace(arguments.get(0), state.getSourceForNode(arguments.get(1)))
.build();
return buildDescription(tree)
.addFix(maximumPoolSizeReplacementFix)
.addFix(corePoolSizeReplacementFix)
.build();
}
}
| 4,524
| 42.932039
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MathAbsoluteNegative.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.argument;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.MethodInvocationTree;
/**
* @author kayco@google.com (Kayla Walker)
*/
@BugPattern(
summary =
"Math.abs does not always give a non-negative result. Please consider other "
+ "methods for positive numbers.",
severity = WARNING,
altNames = "MathAbsoluteRandom")
public final class MathAbsoluteNegative extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<MethodInvocationTree> POSSIBLY_NEGATIVE_ABS_VAL =
allOf(
staticMethod().onClass("java.lang.Math").named("abs"),
argument(
0,
anyOf(
instanceMethod()
.onDescendantOf("java.util.Random")
.namedAnyOf("nextInt", "nextLong")
.withNoParameters(),
instanceMethod()
.onDescendantOf("java.util.UUID")
.namedAnyOf("getLeastSignificantBits", "getMostSignificantBits")
.withNoParameters(),
instanceMethod()
.onDescendantOf("java.lang.Object")
.named("hashCode")
.withNoParameters(),
staticMethod().onClass("java.lang.System").named("identityHashCode"),
instanceMethod()
.onDescendantOf("com.google.common.hash.HashCode")
.namedAnyOf("asInt", "asLong", "padToLong")
.withNoParameters())));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (POSSIBLY_NEGATIVE_ABS_VAL.matches(tree, state)) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
}
| 3,091
| 40.226667
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/RxReturnValueIgnored.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import static com.google.errorprone.util.ASTHelpers.streamSuperMethods;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import javax.inject.Inject;
/** A {@link BugChecker}; see the associated {@link BugPattern} for details. */
@BugPattern(
summary =
"Returned Rx objects must be checked. Ignoring a returned Rx value means it is never "
+ "scheduled for execution",
explanation =
"Methods that return an ignored [Observable | Single | Flowable | Maybe ] generally "
+ "indicate errors.\n\nIf you don’t check the return value of these methods, the "
+ "observables may never execute. It also means the error case is not being handled",
severity = WARNING)
public final class RxReturnValueIgnored extends AbstractReturnValueIgnored {
private static boolean hasCirvAnnotation(ExpressionTree tree, VisitorState state) {
Symbol untypedSymbol = getSymbol(tree);
if (!(untypedSymbol instanceof MethodSymbol)) {
return false;
}
MethodSymbol sym = (MethodSymbol) untypedSymbol;
// Directly has @CanIgnoreReturnValue
if (ASTHelpers.hasAnnotation(sym, CanIgnoreReturnValue.class, state)) {
return true;
}
// If a super-class's method is annotated with @CanIgnoreReturnValue, we only honor that
// if the super-type returned the exact same type. This lets us catch issues where a
// superclass was annotated with @CanIgnoreReturnValue but the parent did not intend to
// return an Rx type
return streamSuperMethods(sym, state.getTypes())
.anyMatch(
superSym ->
hasAnnotation(superSym, CanIgnoreReturnValue.class, state)
&& superSym.getReturnType().tsym.equals(sym.getReturnType().tsym));
}
private static boolean isExemptedMethod(ExpressionTree tree, VisitorState state) {
Symbol sym = getSymbol(tree);
if (!(sym instanceof MethodSymbol)) {
return false;
}
// Currently the only exempted method is Map.put().
return ASTHelpers.isSubtype(sym.owner.type, JAVA_UTIL_MAP.get(state), state)
&& sym.name.contentEquals("put");
}
private static final Matcher<ExpressionTree> MATCHER =
allOf(
Matchers.kindIs(Kind.METHOD_INVOCATION),
anyOf(
// RxJava2
isSubtypeOf("io.reactivex.Observable"),
isSubtypeOf("io.reactivex.Flowable"),
isSubtypeOf("io.reactivex.Single"),
isSubtypeOf("io.reactivex.Maybe"),
isSubtypeOf("io.reactivex.Completable"),
// RxJava1
isSubtypeOf("rx.Observable"),
isSubtypeOf("rx.Single"),
isSubtypeOf("rx.Completable")),
not(
anyOf(
RxReturnValueIgnored::hasCirvAnnotation,
RxReturnValueIgnored::isExemptedMethod)));
@Inject
RxReturnValueIgnored(ConstantExpressions constantExpressions) {
super(constantExpressions);
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
Description description = super.matchMethodInvocation(tree, state);
return description.equals(Description.NO_MATCH) ? Description.NO_MATCH : describeMatch(tree);
}
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
Description description = super.matchMemberReference(tree, state);
return description.equals(Description.NO_MATCH) ? Description.NO_MATCH : describeMatch(tree);
}
@Override
public Matcher<? super ExpressionTree> specializedMatcher() {
return MATCHER;
}
private static final Supplier<Type> JAVA_UTIL_MAP =
VisitorState.memoize(state -> state.getTypeFromString("java.util.Map"));
}
| 5,603
| 40.820896
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/FloatingPointLiteralPrecision.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.constValue;
import com.google.common.base.CharMatcher;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.LiteralTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.LiteralTree;
import com.sun.tools.javac.code.Type;
import java.math.BigDecimal;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Floating point literal loses precision",
severity = WARNING,
tags = StandardTags.STYLE)
public class FloatingPointLiteralPrecision extends BugChecker implements LiteralTreeMatcher {
/*
* Don't emit a fix if the suggested fix is too much longer than the original literal, as defined
* by this constant multiplied by the original length.
*/
private static final int REPLACEMENT_MAX_MULTIPLIER = 3;
@Override
public Description matchLiteral(LiteralTree tree, VisitorState state) {
Type type = ASTHelpers.getType(tree);
if (type == null) {
return NO_MATCH;
}
String suffix;
BigDecimal value;
switch (type.getKind()) {
case DOUBLE:
value = new BigDecimal(Double.toString(constValue(tree, Double.class)));
suffix = "";
break;
case FLOAT:
value = new BigDecimal(Float.toString(constValue(tree, Float.class)));
suffix = "f";
break;
default:
return NO_MATCH;
}
String source = state.getSourceForNode(tree);
switch (source.charAt(source.length() - 1)) {
case 'f':
case 'F':
case 'd':
case 'D':
source = source.substring(0, source.length() - 1);
break;
default: // fall out
}
source = CharMatcher.is('_').removeFrom(source);
BigDecimal exact;
try {
exact = new BigDecimal(source);
} catch (NumberFormatException e) {
// BigDecimal doesn't support e.g. hex floats
return NO_MATCH;
}
// Compare the actual and exact value, ignoring scale.
// BigDecimal#equals returns false for e.g. `1.0` and `1.00`.
if (exact.compareTo(value) == 0) {
return NO_MATCH;
}
String replacement = value + suffix;
// Don't emit a fix with the warning if the replacement is too long.
if (replacement.length() > (REPLACEMENT_MAX_MULTIPLIER * source.length())) {
return describeMatch(tree);
}
return describeMatch(tree, SuggestedFix.replace(tree, replacement));
}
}
| 3,490
| 34.262626
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/FunctionalInterfaceClash.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Streams.zip;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static java.util.stream.Collectors.joining;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.SetMultimap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.Signatures;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.CompletionFailure;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.comp.Check;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Overloads will be ambiguous when passing lambda arguments.",
severity = WARNING)
public class FunctionalInterfaceClash extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
ClassSymbol origin = getSymbol(tree);
Types types = state.getTypes();
// collect declared and inherited methods whose signature contains a functional interface
SetMultimap<String, MethodSymbol> methodsByName = HashMultimap.create();
for (Symbol sym :
types.membersClosure(getType(tree), /* skipInterface= */ false).getSymbols()) {
if (!(sym instanceof MethodSymbol)) {
continue;
}
MethodSymbol msym = (MethodSymbol) sym;
if (msym.getParameters().stream()
.noneMatch(p -> maybeFunctionalInterface(p.type, types, state))) {
continue;
}
if (msym.isConstructor() && !msym.owner.equals(origin)) {
continue;
}
methodsByName.put(msym.getSimpleName().toString(), msym);
}
// Only consider methods which don't have strictly more specific overloads; these won't actually
// clash.
SetMultimap<String, MethodSymbol> methodsBySignature = HashMultimap.create();
for (MethodSymbol msym : methodsByName.values()) {
if (methodsByName.get(msym.getSimpleName().toString()).stream()
.anyMatch(
o ->
!msym.overrides(o, (TypeSymbol) msym.owner, types, /* checkResult= */ true)
&& !o.equals(msym)
&& o.getParameters().length() == msym.getParameters().length()
&& zip(
msym.getParameters().stream(),
o.getParameters().stream(),
(a, b) -> isSubtype(a.type, b.type, state))
.allMatch(x -> x))) {
continue;
}
methodsBySignature.put(functionalInterfaceSignature(state, msym), msym);
}
// check if any declared members clash with another declared or inherited member
// (don't report clashes between inherited members)
for (Tree member : tree.getMembers()) {
if (!(member instanceof MethodTree)) {
continue;
}
MethodSymbol msym = getSymbol((MethodTree) member);
if (msym.getParameters().stream()
.noneMatch(p -> maybeFunctionalInterface(p.type, types, state))) {
continue;
}
List<MethodSymbol> clash =
new ArrayList<>(methodsBySignature.removeAll(functionalInterfaceSignature(state, msym)));
// Ignore inherited methodsBySignature that are overridden in the original class. Note that we
// have to
// handle transitive inheritance explicitly to handle cases where the visibility of an
// overridden method is expanded somewhere in the type hierarchy.
Deque<MethodSymbol> worklist = new ArrayDeque<>();
worklist.push(msym);
clash.remove(msym);
while (!worklist.isEmpty()) {
MethodSymbol msym2 = worklist.removeFirst();
ImmutableList<MethodSymbol> overrides =
clash.stream()
.filter(m -> msym2.overrides(m, origin, types, /* checkResult= */ false))
.collect(toImmutableList());
worklist.addAll(overrides);
clash.removeAll(overrides);
}
if (!clash.isEmpty()) {
// ignore if there are overridden clashing methodsBySignature in class
if (ASTHelpers.findSuperMethod(msym, types).isPresent()
&& clash.stream()
.anyMatch(
methodSymbol -> ASTHelpers.findSuperMethod(methodSymbol, types).isPresent())) {
continue;
}
if (isSuppressed(member, state)) {
continue;
}
String message =
"When passing lambda arguments to this function, callers will need a cast to"
+ " disambiguate with: "
+ clash.stream()
.map(m -> "\n " + Signatures.prettyMethodSignature(origin, m))
.sorted()
.collect(joining(""));
state.reportMatch(buildDescription(member).setMessage(message).build());
}
}
return NO_MATCH;
}
/**
* A string representation of a method descriptor, where all parameters whose type is a functional
* interface are "erased" to the interface's function type. For example, `foo(Supplier<String>)`
* is represented as `foo(()->Ljava/lang/String;)`.
*/
private static String functionalInterfaceSignature(VisitorState state, MethodSymbol msym) {
return String.format(
"%s(%s)",
msym.getSimpleName(),
msym.getParameters().stream()
.map(p -> functionalInterfaceSignature(state, p.type))
.collect(joining(",")));
}
private static String functionalInterfaceSignature(VisitorState state, Type type) {
Types types = state.getTypes();
if (!maybeFunctionalInterface(type, types, state)) {
return Signatures.descriptor(type, types);
}
Type descriptorType = types.findDescriptorType(type);
List<Type> fiparams = descriptorType.getParameterTypes();
// Implicitly typed block-statement-bodied lambdas are potentially compatible with
// void-returning and value-returning functional interface types, so we don't consider return
// types in general. The except is nullary functional interfaces, since the lambda parameters
// will never be implicitly typed.
String result =
fiparams.isEmpty() ? Signatures.descriptor(descriptorType.getReturnType(), types) : "_";
return String.format(
"(%s)->%s",
fiparams.stream().map(t -> Signatures.descriptor(t, types)).collect(joining(",")), result);
}
private static boolean maybeFunctionalInterface(Type type, Types types, VisitorState state) {
try {
return types.isFunctionalInterface(type);
} catch (CompletionFailure e) {
// Report completion errors to avoid e.g. https://github.com/bazelbuild/bazel/issues/4105
Check.instance(state.context)
.completionError((DiagnosticPosition) state.getPath().getLeaf(), e);
return false;
}
}
}
| 8,583
| 41.92
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryMethodReference.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.fixes.SuggestedFix.replace;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.findSuperMethodInType;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static com.google.errorprone.util.ASTHelpers.targetType;
import static javax.lang.model.element.Modifier.ABSTRACT;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.ASTHelpers.TargetType;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
/** Matches unnecessary uses of method references. */
@BugPattern(
severity = SeverityLevel.WARNING,
summary = "This method reference is unnecessary, and can be replaced with the variable itself.")
public final class UnnecessaryMethodReference extends BugChecker
implements MemberReferenceTreeMatcher {
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
if (!tree.getMode().equals(ReferenceMode.INVOKE)) {
return NO_MATCH;
}
if (!(state.getPath().getParentPath().getLeaf() instanceof MethodInvocationTree)) {
return NO_MATCH;
}
TargetType targetType = targetType(state);
if (targetType == null) {
return NO_MATCH;
}
ExpressionTree receiver = getReceiver(tree);
if (receiver == null) {
return NO_MATCH;
}
if (receiver instanceof IdentifierTree
&& ((IdentifierTree) receiver).getName().contentEquals("super")) {
return NO_MATCH;
}
if (!state.getTypes().isSubtype(getType(receiver), targetType.type())) {
return NO_MATCH;
}
MethodSymbol symbol = getSymbol(tree);
Scope members = targetType.type().tsym.members();
if (!ASTHelpers.scope(members)
.anyMatch(sym -> isFunctionalInterfaceInvocation(symbol, targetType.type(), sym, state))
&& !isKnownAlias(tree, targetType.type(), state)) {
return NO_MATCH;
}
return describeMatch(
tree, replace(state.getEndPosition(receiver), state.getEndPosition(tree), ""));
}
private static boolean isFunctionalInterfaceInvocation(
MethodSymbol memberReferenceTarget, Type type, Symbol symbol, VisitorState state) {
return (memberReferenceTarget.equals(symbol)
|| findSuperMethodInType(memberReferenceTarget, type, state.getTypes()) != null)
&& symbol.getModifiers().contains(ABSTRACT);
}
private static boolean isKnownAlias(MemberReferenceTree tree, Type type, VisitorState state) {
return KNOWN_ALIASES.stream()
.anyMatch(
k ->
k.matcher().matches(tree, state)
&& isSubtype(k.targetType().get(state), type, state));
}
/**
* Methods that we know delegate directly to the abstract method on a functional interface that
* they implement.
*
* <p>That is: the method matched by {@code matcher} delegates to the abstract method on any
* supertype of {@code targetType}.
*/
private static final ImmutableList<KnownAlias> KNOWN_ALIASES =
ImmutableList.of(
KnownAlias.create(
instanceMethod().onDescendantOf("com.google.common.base.Predicate").named("apply"),
Suppliers.typeFromString("java.util.function.Predicate")),
KnownAlias.create(
instanceMethod().onDescendantOf("com.google.common.base.Converter").named("convert"),
Suppliers.typeFromString("com.google.common.base.Function")),
KnownAlias.create(
instanceMethod().onDescendantOf("com.google.common.collect.Range").named("contains"),
Suppliers.typeFromString("com.google.common.base.Predicate")));
@AutoValue
abstract static class KnownAlias {
public static KnownAlias create(Matcher<ExpressionTree> matcher, Supplier<Type> targetType) {
return new AutoValue_UnnecessaryMethodReference_KnownAlias(matcher, targetType);
}
abstract Matcher<ExpressionTree> matcher();
abstract Supplier<Type> targetType();
}
}
| 5,797
| 41.632353
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ModifyingCollectionWithItself.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.bugpatterns.ReplacementVariableFinder.fixesByReplacingExpressionWithLocallyDeclaredField;
import static com.google.errorprone.bugpatterns.ReplacementVariableFinder.fixesByReplacingExpressionWithMethodParameter;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.receiverSameAsArgument;
import static com.google.errorprone.matchers.Matchers.variableType;
import static com.sun.source.tree.Tree.Kind.IDENTIFIER;
import static com.sun.source.tree.Tree.Kind.MEMBER_SELECT;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import java.util.List;
import java.util.function.Predicate;
import javax.lang.model.element.ElementKind;
/**
* @author scottjohnson@google.com (Scott Johnson)
*/
@BugPattern(summary = "Using a collection function with itself as the argument.", severity = ERROR)
public class ModifyingCollectionWithItself extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Matcher<MethodInvocationTree> IS_COLLECTION_MODIFIED_WITH_ITSELF =
buildMatcher();
private static Matcher<MethodInvocationTree> buildMatcher() {
return anyOf(
allOf(
anyOf(
instanceMethod().onDescendantOf("java.util.Collection").named("addAll"),
instanceMethod().onDescendantOf("java.util.Collection").named("removeAll"),
instanceMethod().onDescendantOf("java.util.Collection").named("containsAll"),
instanceMethod().onDescendantOf("java.util.Collection").named("retainAll")),
receiverSameAsArgument(0)),
allOf(
instanceMethod().onDescendantOf("java.util.Collection").named("addAll"),
receiverSameAsArgument(1)));
}
/** Matches calls to addAll, containsAll, removeAll, and retainAll on itself */
@Override
public Description matchMethodInvocation(MethodInvocationTree t, VisitorState state) {
if (IS_COLLECTION_MODIFIED_WITH_ITSELF.matches(t, state)) {
return describe(t, state);
}
return Description.NO_MATCH;
}
/**
* We expect that the lhs is a field and the rhs is an identifier, specifically a parameter to the
* method. We base our suggested fixes on this expectation.
*
* <p>Case 1: If lhs is a field and rhs is an identifier, find a method parameter of the same type
* and similar name and suggest it as the rhs. (Guess that they have misspelled the identifier.)
*
* <p>Case 2: If lhs is a field and rhs is not an identifier, find a method parameter of the same
* type and similar name and suggest it as the rhs.
*
* <p>Case 3: If lhs is not a field and rhs is an identifier, find a class field of the same type
* and similar name and suggest it as the lhs.
*
* <p>Case 4: Otherwise replace with literal meaning of functionality
*/
private Description describe(MethodInvocationTree methodInvocationTree, VisitorState state) {
ExpressionTree receiver = ASTHelpers.getReceiver(methodInvocationTree);
List<? extends ExpressionTree> arguments = methodInvocationTree.getArguments();
ExpressionTree argument;
// .addAll(int, Collection); for the true case
argument = arguments.size() == 2 ? arguments.get(1) : arguments.get(0);
Description.Builder builder = buildDescription(methodInvocationTree);
for (Fix fix : buildFixes(methodInvocationTree, state, receiver, argument)) {
builder.addFix(fix);
}
return builder.build();
}
private static List<Fix> buildFixes(
MethodInvocationTree methodInvocationTree,
VisitorState state,
ExpressionTree receiver,
ExpressionTree argument) {
List<Fix> fixes;
// this.a.addAll(...);
if (receiver.getKind() == MEMBER_SELECT) {
// Only inspect method parameters, unlikely to want to this.a.addAll(b), where b is another
// field.
fixes =
fixesByReplacingExpressionWithMethodParameter(
argument, isCollectionVariable(state), state);
} else {
// a.addAll(...)
Preconditions.checkState(receiver.getKind() == IDENTIFIER, "receiver.getKind is identifier");
boolean lhsIsField = ASTHelpers.getSymbol(receiver).getKind() == ElementKind.FIELD;
fixes =
lhsIsField
? fixesByReplacingExpressionWithMethodParameter(
argument, isCollectionVariable(state), state)
: fixesByReplacingExpressionWithLocallyDeclaredField(
receiver, isCollectionVariable(state), state);
}
if (fixes.isEmpty()) {
fixes = literalReplacement(methodInvocationTree, state, receiver);
}
return fixes;
}
private static Predicate<JCVariableDecl> isCollectionVariable(VisitorState state) {
return var -> variableType(isSubtypeOf("java.util.Collection")).matches(var, state);
}
private static ImmutableList<Fix> literalReplacement(
MethodInvocationTree methodInvocationTree, VisitorState state, ExpressionTree lhs) {
Tree parent = state.getPath().getParentPath().getLeaf();
// If the parent is an ExpressionStatement, the expression value is ignored, so we can delete
// the call entirely (or replace removeAll with .clear()). Otherwise, we can't provide a good
// replacement.
if (parent instanceof ExpressionStatementTree) {
Fix fix;
if (instanceMethod().anyClass().named("removeAll").matches(methodInvocationTree, state)) {
fix = SuggestedFix.replace(methodInvocationTree, state.getSourceForNode(lhs) + ".clear()");
} else {
fix = SuggestedFix.delete(parent);
}
return ImmutableList.of(fix);
}
return ImmutableList.of();
}
}
| 7,292
| 41.9
| 125
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/PublicApiNamedStreamShouldReturnStream.java
|
/*
* Copyright 2021 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.methodHasVisibility;
import static com.google.errorprone.matchers.Matchers.methodIsNamed;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.MethodVisibility;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodTree;
import com.sun.tools.javac.code.Type;
/**
* Checks if public APIs named "stream" returns a type whose name ends with Stream.
*
* @author sauravtiwary@google.com (Saurav Tiwary)
*/
@BugPattern(
summary =
"Public methods named stream() are generally expected to return a type whose name ends with"
+ " Stream. Consider choosing a different method name instead.",
severity = SUGGESTION)
public class PublicApiNamedStreamShouldReturnStream extends BugChecker
implements MethodTreeMatcher {
private static final String STREAM = "stream";
private static final Matcher<MethodTree> CONFUSING_PUBLIC_API_STREAM_MATCHER =
allOf(
methodIsNamed(STREAM),
methodHasVisibility(MethodVisibility.Visibility.PUBLIC),
PublicApiNamedStreamShouldReturnStream::returnTypeDoesNotEndsWithStream);
private static boolean returnTypeDoesNotEndsWithStream(
MethodTree methodTree, VisitorState state) {
Type returnType = ASTHelpers.getSymbol(methodTree).getReturnType();
// Constructors have no return type.
return returnType != null && !returnType.tsym.getSimpleName().toString().endsWith("Stream");
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!CONFUSING_PUBLIC_API_STREAM_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
return describeMatch(tree);
}
}
| 2,744
| 37.661972
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/package-info.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** Checks added to the java compiler which detect common bug patterns. */
package com.google.errorprone.bugpatterns;
| 727
| 37.315789
| 75
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/FieldCanBeStatic.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.base.CaseFormat.LOWER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.fixes.SuggestedFixes.addModifiers;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.annotationsAmong;
import static com.google.errorprone.util.ASTHelpers.canBeRemoved;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static javax.lang.model.element.ElementKind.FIELD;
import static javax.lang.model.element.Modifier.FINAL;
import static javax.lang.model.element.Modifier.STATIC;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.Immutable;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions.ConstantExpression;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions.ConstantExpressionVisitor;
import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety;
import com.google.errorprone.bugpatterns.threadsafety.WellKnownMutability;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.Name;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.lang.model.element.NestingKind;
/** Finds fields which can be safely made static. */
@BugPattern(
summary =
"A final field initialized at compile-time with an instance of an immutable type can be"
+ " static.",
severity = SUGGESTION)
public final class FieldCanBeStatic extends BugChecker implements VariableTreeMatcher {
private static final Supplier<ImmutableSet<Name>> EXEMPTING_VARIABLE_ANNOTATIONS =
VisitorState.memoize(
s ->
Stream.of("com.google.inject.testing.fieldbinder.Bind")
.map(s::getName)
.collect(toImmutableSet()));
private final WellKnownMutability wellKnownMutability;
private final ConstantExpressions constantExpressions;
@Inject
FieldCanBeStatic(
WellKnownMutability wellKnownMutability, ConstantExpressions constantExpressions) {
this.wellKnownMutability = wellKnownMutability;
this.constantExpressions = constantExpressions;
}
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
VarSymbol symbol = getSymbol(tree);
if (!canBeRemoved(symbol)
|| !tree.getModifiers().getFlags().contains(FINAL)
|| symbol.isStatic()
|| !symbol.getKind().equals(FIELD)
|| (symbol.flags() & RECORD_FLAG) == RECORD_FLAG) {
return NO_MATCH;
}
ClassSymbol enclClass = symbol.owner.enclClass();
if (enclClass == null) {
return NO_MATCH;
}
if (!enclClass.getNestingKind().equals(NestingKind.TOP_LEVEL)
&& !enclClass.isStatic()
&& symbol.getConstantValue() == null) {
// JLS 8.1.3: inner classes cannot declare static members, unless the member is a constant
// variable
return NO_MATCH;
}
if (!isTypeKnownImmutable(getType(tree), state)) {
return NO_MATCH;
}
if (tree.getInitializer() == null || !isPure(tree.getInitializer(), state)) {
return NO_MATCH;
}
if (!annotationsAmong(symbol, EXEMPTING_VARIABLE_ANNOTATIONS.get(state), state).isEmpty()) {
return NO_MATCH;
}
SuggestedFix fix =
SuggestedFix.builder()
.merge(renameVariable(tree, state))
.merge(addModifiers(tree, state, STATIC).orElse(SuggestedFix.emptyFix()))
.build();
return describeMatch(tree, fix);
}
private static final long RECORD_FLAG = 1L << 61;
/**
* Renames the variable, clobbering any qualifying (like {@code this.}). This is a tad unsafe, but
* we need to somehow remove any qualification with an instance.
*/
private SuggestedFix renameVariable(VariableTree variableTree, VisitorState state) {
String name = variableTree.getName().toString();
if (!LOWER_CAMEL_PATTERN.matcher(name).matches()) {
return SuggestedFix.emptyFix();
}
String replacement = LOWER_CAMEL.to(UPPER_UNDERSCORE, variableTree.getName().toString());
int typeEndPos = state.getEndPosition(variableTree.getType());
int searchOffset = typeEndPos - ((JCTree) variableTree).getStartPosition();
int pos =
((JCTree) variableTree).getStartPosition()
+ state.getSourceForNode(variableTree).indexOf(name, searchOffset);
SuggestedFix.Builder fix =
SuggestedFix.builder().replace(pos, pos + name.length(), replacement);
VarSymbol sym = getSymbol(variableTree);
new TreeScanner<Void, Void>() {
@Override
public Void visitIdentifier(IdentifierTree tree, Void unused) {
handle(tree);
return super.visitIdentifier(tree, null);
}
@Override
public Void visitMemberSelect(MemberSelectTree tree, Void unused) {
handle(tree);
return super.visitMemberSelect(tree, null);
}
private void handle(Tree tree) {
if (sym.equals(getSymbol(tree))) {
fix.replace(tree, replacement);
}
}
}.scan(state.getPath().getCompilationUnit(), null);
return fix.build();
}
private static final Pattern LOWER_CAMEL_PATTERN = Pattern.compile("[a-z][a-zA-Z0-9]+");
/**
* Tries to establish whether an expression is pure. For example, literals and invocations of
* known-pure functions are pure.
*/
private boolean isPure(ExpressionTree initializer, VisitorState state) {
return constantExpressions
.constantExpression(initializer, state)
.map(FieldCanBeStatic::isStatic)
.orElse(false);
}
private static boolean isStatic(ConstantExpression expression) {
AtomicBoolean staticable = new AtomicBoolean(true);
expression.accept(
new ConstantExpressionVisitor() {
@Override
public void visitIdentifier(Symbol identifier) {
if (!(identifier instanceof ClassSymbol) && !ASTHelpers.isStatic(identifier)) {
staticable.set(false);
}
}
});
return staticable.get();
}
private boolean isTypeKnownImmutable(Type type, VisitorState state) {
ThreadSafety threadSafety =
ThreadSafety.builder()
.setPurpose(ThreadSafety.Purpose.FOR_IMMUTABLE_CHECKER)
.knownTypes(wellKnownMutability)
.acceptedAnnotations(
ImmutableSet.of(Immutable.class.getName(), AutoValue.class.getName()))
.markerAnnotations(ImmutableSet.of())
.build(state);
return !threadSafety
.isThreadSafeType(
/* allowContainerTypeParameters= */ true,
threadSafety.threadSafeTypeParametersInScope(type.tsym),
type)
.isPresent();
}
}
| 8,595
| 38.981395
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/OutlineNone.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.constValue;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.AnnotationMatcherUtils;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
/** Check for the a11y antipattern of setting CSS outline attributes to none or 0. */
@BugPattern(
summary =
"Setting CSS outline style to none or 0 (while not otherwise providing visual focus "
+ "indicators) is inaccessible for users navigating a web page without a mouse.",
severity = WARNING)
public class OutlineNone extends BugChecker
implements MethodInvocationTreeMatcher, AnnotationTreeMatcher {
// TODO(b/119196262): Expand to more methods of setting CSS properties.
private static final Matcher<AnnotationTree> TEMPLATE_ANNOTATION =
Matchers.isType("com.google.gwt.safehtml.client.SafeHtmlTemplates.Template");
private static final Matcher<ExpressionTree> GWT_SET_PROPERTY =
Matchers.instanceMethod()
.onDescendantOf("com.google.gwt.dom.client.Style")
.withNameMatching(Pattern.compile("setProperty(Px)?"));
private static final Pattern OUTLINE_NONE_REGEX =
Pattern.compile("outline\\s*:\\s*(none|0px)\\s*;?");
private static final ImmutableSet<String> NONE_STRINGS = ImmutableSet.of("none", "0px");
/**
* Matches on {@code @Template} annotations whose value contains "outline:none" or equivalent
* outline style.
*/
@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
if (!TEMPLATE_ANNOTATION.matches(tree, state)) {
return NO_MATCH;
}
ExpressionTree arg = AnnotationMatcherUtils.getArgument(tree, "value");
String template = constValue(arg, String.class);
if (template == null) {
return NO_MATCH;
}
java.util.regex.Matcher matcher = OUTLINE_NONE_REGEX.matcher(template);
if (!matcher.find()) {
return NO_MATCH;
}
return describeMatch(tree);
}
/** Matches on {@code setProperty("outline", "none")} and equivalent method calls. */
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
List<? extends ExpressionTree> args = tree.getArguments();
/*
* Matches the following methods from com.google.gwt.dom.client.Style:
* setProperty(String name, String value)
* setProperty(String name, double value, Unit unit)
* setPropertyPx(String name, int value)
* The first argument is always `name`; we only care about these when `name` is "outline".
* The second argument is always `value`, but of variable type. We care about the strings
* "none" and "0px", and any numeric `0`.
* We don't care about the `unit` parameter, as zero of anything is bad.
*/
if (GWT_SET_PROPERTY.matches(tree, state)
&& args.size() >= 2
&& Objects.equals(constValue(args.get(0), String.class), "outline")
&& constantNoneOrZero(args.get(1))) {
return describeMatch(tree);
}
return NO_MATCH;
}
/**
* Matches if the expression is a numeric 0, or either of the strings "none" or "0px". These are
* the values which will cause the outline to be invisible and therefore impede accessibility.
*/
private static boolean constantNoneOrZero(ExpressionTree arg) {
Object value = constValue(arg);
if (value instanceof String && NONE_STRINGS.contains(value)) {
return true;
}
return value instanceof Number && ((Number) value).doubleValue() == 0.0;
}
}
| 4,877
| 41.417391
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BanJNDI.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.matchers.Matchers.anyMethod;
import static com.google.errorprone.matchers.Matchers.anyOf;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
/** A {@link BugChecker} that detects use of the unsafe JNDI API system. */
@BugPattern(
summary =
"Using JNDI may deserialize user input via the `Serializable` API which is extremely"
+ " dangerous",
severity = SeverityLevel.ERROR)
public final class BanJNDI extends BugChecker implements MethodInvocationTreeMatcher {
/** Checks for direct or indirect calls to context.lookup() via the JDK */
private static final Matcher<ExpressionTree> MATCHER =
anyOf(
anyMethod()
.onDescendantOf("javax.naming.directory.DirContext")
.namedAnyOf(
"modifyAttributes",
"getAttributes",
"search",
"getSchema",
"getSchemaClassDefinition"),
anyMethod()
.onDescendantOf("javax.naming.Context")
.namedAnyOf("lookup", "bind", "rebind", "createSubcontext"),
anyMethod()
.onDescendantOf("javax.jdo.JDOHelperTest")
.namedAnyOf(
"testGetPMFBadJNDI",
"testGetPMFBadJNDIGoodClassLoader",
"testGetPMFNullJNDI",
"testGetPMFNullJNDIGoodClassLoader"),
anyMethod().onDescendantOf("javax.jdo.JDOHelper").named("getPersistenceManagerFactory"),
anyMethod()
.onDescendantOf("javax.management.remote.JMXConnectorFactory")
.named("connect"),
anyMethod().onDescendantOf("javax.sql.rowset.spi.SyncFactory").named("getInstance"),
anyMethod()
.onDescendantOf("javax.management.remote.rmi.RMIConnector.RMIClientCommunicatorAdmin")
.named("doStart"),
anyMethod().onDescendantOf("javax.management.remote.rmi.RMIConnector").named("connect"),
anyMethod().onDescendantOf("javax.naming.InitialContext").named("doLookup"));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (state.errorProneOptions().isTestOnlyTarget() || !MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
Description.Builder description = buildDescription(tree);
return description.build();
}
}
| 3,434
| 40.890244
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BigDecimalLiteralDouble.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.UnaryTree;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Optional;
/**
* Matches usages of {@code new BigDecimal(double)} which lose precision.
*
* @author endobson@google.com (Eric Dobson)
*/
@BugPattern(summary = "new BigDecimal(double) loses precision in this case.", severity = WARNING)
public class BigDecimalLiteralDouble extends BugChecker implements NewClassTreeMatcher {
private static final BigInteger LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE);
private static final BigInteger LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE);
private static final String BIG_DECIMAL = BigDecimal.class.getName();
private static final Matcher<ExpressionTree> BIGDECIMAL_DOUBLE_CONSTRUCTOR =
Matchers.constructor().forClass(BIG_DECIMAL).withParameters("double");
// Matches literals and unary +/- followed by a literal, since most people conceptually think of
// -1.0 as a literal. Doesn't handle nested unary operators as new BigDecimal(String) doesn't
// accept multiple unary prefixes.
private static boolean floatingPointArgument(ExpressionTree tree) {
if (tree.getKind() == Kind.UNARY_PLUS || tree.getKind() == Kind.UNARY_MINUS) {
tree = ((UnaryTree) tree).getExpression();
}
return tree.getKind() == Kind.DOUBLE_LITERAL || tree.getKind() == Kind.FLOAT_LITERAL;
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (!BIGDECIMAL_DOUBLE_CONSTRUCTOR.matches(tree, state)) {
return Description.NO_MATCH;
}
ExpressionTree arg = getOnlyElement(tree.getArguments());
if (!floatingPointArgument(arg)) {
return Description.NO_MATCH;
}
return createDescription(arg, state);
}
private Description createDescription(ExpressionTree arg, VisitorState state) {
Number literalNumber = ASTHelpers.constValue(arg, Number.class);
if (literalNumber == null) {
return Description.NO_MATCH;
}
double literal = literalNumber.doubleValue();
// Strip off 'd', 'f' suffixes and _ separators from the source.
String literalString = state.getSourceForNode(arg).replaceAll("[_dDfF]", "");
// We assume that the expected value of `new BigDecimal(double)` is precisely the BigDecimal
// which stringifies to the same String as `double`'s literal.
BigDecimal intendedValue;
try {
intendedValue = new BigDecimal(literalString);
} catch (ArithmeticException e) {
return Description.NO_MATCH;
}
// Compute the actual BigDecimal produced by the expression, and bail if they're equivalent.
BigDecimal actualValue = new BigDecimal(literal);
if (actualValue.compareTo(intendedValue) == 0) {
return Description.NO_MATCH;
}
Optional<BigInteger> integralValue = asBigInteger(intendedValue);
if (integralValue.map(BigDecimalLiteralDouble::isWithinLongRange).orElse(false)) {
long longValue = integralValue.get().longValue();
return suggestReplacement(arg, actualValue, String.format("%sL", longValue));
}
return suggestReplacement(arg, actualValue, String.format("\"%s\"", literalString));
}
private Description suggestReplacement(
ExpressionTree tree, BigDecimal actualValue, String replacement) {
return buildDescription(tree)
.setMessage(
message()
+ String.format(" The exact value here is `new BigDecimal(\"%s\")`.", actualValue))
.addFix(SuggestedFix.replace(tree, replacement))
.build();
}
private static Optional<BigInteger> asBigInteger(BigDecimal v) {
try {
return Optional.of(v.toBigIntegerExact());
} catch (ArithmeticException e) {
return Optional.empty();
}
}
private static boolean isWithinLongRange(BigInteger v) {
return LONG_MIN.compareTo(v) <= 0 && v.compareTo(LONG_MAX) <= 0;
}
}
| 5,185
| 37.414815
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SuppressWarningsDeprecated.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.hasArgumentWithValue;
import static com.google.errorprone.matchers.Matchers.isType;
import static com.google.errorprone.matchers.Matchers.stringLiteral;
import static java.util.stream.Collectors.toList;
import com.google.auto.common.AnnotationMirrors;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.MoreAnnotations;
import com.sun.source.tree.AnnotationTree;
import java.util.List;
import javax.lang.model.element.AnnotationMirror;
/**
* Find uses of SuppressWarnings with "deprecated".
*
* @author sjnickerson@google.com (Simon Nickerson)
*/
@BugPattern(
summary = "Suppressing \"deprecated\" is probably a typo for \"deprecation\"",
severity = ERROR)
public class SuppressWarningsDeprecated extends BugChecker implements AnnotationTreeMatcher {
private static final Matcher<AnnotationTree> matcher =
allOf(
isType("java.lang.SuppressWarnings"),
hasArgumentWithValue("value", stringLiteral("deprecated")));
@Override
public final Description matchAnnotation(AnnotationTree annotationTree, VisitorState state) {
if (!matcher.matches(annotationTree, state)) {
return Description.NO_MATCH;
}
AnnotationMirror mirror = ASTHelpers.getAnnotationMirror(annotationTree);
List<String> values =
MoreAnnotations.asStrings(AnnotationMirrors.getAnnotationValue(mirror, "value"))
.map(v -> v.equals("deprecated") ? "deprecation" : v)
.map(state::getConstantExpression)
.collect(toList());
return describeMatch(
annotationTree,
SuggestedFixes.updateAnnotationArgumentValues(annotationTree, state, "value", values)
.build());
}
}
| 2,842
| 37.945205
| 95
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TypeCompatibilityUtils.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.isEmpty;
import static com.google.errorprone.util.ASTHelpers.enclosingPackage;
import static com.google.errorprone.util.ASTHelpers.findMatchingMethods;
import static com.google.errorprone.util.ASTHelpers.getUpperBound;
import static com.google.errorprone.util.ASTHelpers.isCastable;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static com.google.errorprone.util.ASTHelpers.scope;
import com.google.auto.value.AutoValue;
import com.google.common.collect.Streams;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.suppliers.Supplier;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Names;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.Nullable;
import javax.lang.model.type.TypeKind;
/**
* Logical utility methods to answer the question: Are these two types "compatible" with each other,
* in the context of an equality check.
*
* <p>i.e.: It is possible that an object of one type could be equal to an object of the other type.
*/
public final class TypeCompatibilityUtils {
private static final String WITHOUT_EQUALS_REASON =
". Though these types are the same, the type doesn't implement equals.";
private final boolean treatBuildersAsIncomparable;
public static TypeCompatibilityUtils fromFlags(ErrorProneFlags flags) {
return new TypeCompatibilityUtils(
flags.getBoolean("TypeCompatibility:TreatBuildersAsIncomparable").orElse(true));
}
public static TypeCompatibilityUtils allOn() {
return new TypeCompatibilityUtils(/* treatBuildersAsIncomparable= */ true);
}
private TypeCompatibilityUtils(boolean treatBuildersAsIncomparable) {
this.treatBuildersAsIncomparable = treatBuildersAsIncomparable;
}
public TypeCompatibilityReport compatibilityOfTypes(
Type receiverType, Type argumentType, VisitorState state) {
return compatibilityOfTypes(receiverType, argumentType, typeSet(state), typeSet(state), state);
}
private TypeCompatibilityReport compatibilityOfTypes(
Type leftType,
Type rightType,
Set<Type> previouslySeenComponentsOfLeftType,
Set<Type> previouslySeenComponentsOfRightType,
VisitorState state) {
if (leftType == null
|| rightType == null
|| leftType.getKind() == TypeKind.NULL
|| rightType.getKind() == TypeKind.NULL) {
return TypeCompatibilityReport.compatible();
}
Types types = state.getTypes();
Type leftUpperBound = getUpperBound(leftType, types);
Type rightUpperBound = getUpperBound(rightType, types);
if (types.isSameType(leftUpperBound, rightUpperBound)) {
// As a special case, consider Builder classes without an equals implementation to not be
// comparable to themselves. It would be reasonable to mistake Builders as having value
// semantics, which may be misleading.
if (treatBuildersAsIncomparable
&& !leftUpperBound.tsym.isEnum()
&& leftUpperBound.isFinal()
&& leftUpperBound.tsym.name.toString().endsWith("Builder")) {
Names names = state.getNames();
MethodSymbol equals =
(MethodSymbol)
state.getSymtab().objectType.tsym.members().findFirst(state.getNames().equals);
return isEmpty(
scope(types.membersClosure(leftUpperBound, /* skipInterface= */ false))
.getSymbolsByName(
names.toString,
m ->
m != equals
&& m.overrides(
equals, leftUpperBound.tsym, types, /* checkResult= */ false)))
? TypeCompatibilityReport.incompatible(leftType, rightType, WITHOUT_EQUALS_REASON)
: TypeCompatibilityReport.compatible();
}
return TypeCompatibilityReport.compatible();
}
if (leftType.isPrimitive()
&& rightType.isPrimitive()
&& !isSameType(leftType, rightType, state)) {
return TypeCompatibilityReport.incompatible(leftType, rightType);
}
if (!isFeasiblyCompatible(leftType, rightType, state)) {
return TypeCompatibilityReport.incompatible(leftType, rightType);
}
// Now, see if we can find a generic superclass between the two types, and if so, check the
// generic parameters for cast-compatibility:
// class Super<T> (with an equals() override)
// class Bar extends Super<String>
// class Foo extends Super<Integer>
// Bar and Foo would least-upper-bound to Super, and we compare String and Integer to each-other
Type erasedLeftType = types.erasure(leftType);
Type erasedRightType = types.erasure(rightType);
Type commonSupertype = types.lub(erasedRightType, erasedLeftType);
// primitives, etc. can't have a common superclass.
if (commonSupertype.getTag().equals(TypeTag.BOT)
|| commonSupertype.getTag().equals(TypeTag.ERROR)) {
return TypeCompatibilityReport.compatible();
}
// Detect a potential generics mismatch - if there are no generics, this will return a
// compatible report.
TypeCompatibilityReport compatibilityReport =
checkForGenericsMismatch(
leftType,
rightType,
commonSupertype,
previouslySeenComponentsOfLeftType,
previouslySeenComponentsOfRightType,
state);
if (!compatibilityReport.isCompatible()) {
return compatibilityReport;
}
// At this point, we're pretty sure these types are compatible with each other. However, there
// are certain scenarios where the normal processing believes that these two types are
// compatible, but due to the way that certain classes' equals methods are constructed, they
// deceive the normal processing into thinking they're compatible, but they are not.
return areTypesIncompatibleCollections(leftType, rightType, commonSupertype, state)
|| areIncompatibleProtoTypes(erasedLeftType, erasedRightType, commonSupertype, state)
? TypeCompatibilityReport.incompatible(leftType, rightType)
: TypeCompatibilityReport.compatible();
}
private static boolean isFeasiblyCompatible(Type leftType, Type rightType, VisitorState state) {
// If one type can be cast into the other, they are potentially equal to each other.
// Note: we do this precisely in this order to allow primitive values to be checked pre-1.7:
// 1.6: java.lang.Object can't be cast to primitives
// 1.7: java.lang.Object can be cast to primitives (implicitly through the boxed primitive type)
if (isCastable(rightType, leftType, state)) {
return true;
}
// Otherwise, we collect all overrides of java.lang.Object.equals() that the left type has.
// If one of those overrides is inherited by the right type, then they share a common supertype
// that defines its own equals method.
Types types = state.getTypes();
Symbol rightClass = getUpperBound(rightType, state.getTypes()).tsym;
return findMatchingMethods(
EQUALS.get(state), m -> customEqualsMethod(m, state), leftType, types)
.stream()
.anyMatch(method -> rightClass.isSubClass(method.enclClass(), types));
}
/**
* Returns if the method represents an override of equals(Object) that is not on `Object` or
* `Enum`.
*
* <p>This would represent an equals method that could specify equality semantics aside from
* object identity.
*/
private static boolean customEqualsMethod(MethodSymbol methodSymbol, VisitorState state) {
ClassSymbol owningClass = methodSymbol.enclClass();
return !methodSymbol.isStatic()
&& ((methodSymbol.flags() & Flags.SYNTHETIC) == 0)
&& state.getTypes().isSameType(methodSymbol.getReturnType(), state.getSymtab().booleanType)
&& methodSymbol.getParameters().size() == 1
&& state
.getTypes()
.isSameType(methodSymbol.getParameters().get(0).type, state.getSymtab().objectType)
&& !owningClass.equals(state.getSymtab().objectType.tsym)
&& !owningClass.equals(state.getSymtab().enumSym);
}
/**
* Detects the situation where two distinct subtypes of Collection (e.g.: List or Set) are
* compared.
*
* <p>Since they share a common interface with an equals() declaration ({@code Collection<T>}),
* normal processing will consider them compatible with each other, but each subtype of Collection
* overrides equals() in such a way as to be incompatible with each other.
*/
private static boolean areTypesIncompatibleCollections(
Type leftType, Type rightType, Type nearestCommonSupertype, VisitorState state) {
// We want to disallow equality between these collection sub-interfaces, but *do* want to
// allow compatibility between Collection and List.
Type collectionType = JAVA_UTIL_COLLECTION.get(state);
return isSameType(nearestCommonSupertype, collectionType, state)
&& !isSameType(leftType, collectionType, state)
&& !isSameType(rightType, collectionType, state);
}
private boolean areIncompatibleProtoTypes(
Type leftType, Type rightType, Type nearestCommonSupertype, VisitorState state) {
// See discussion in b/152428396 - Proto equality is defined as having the "same message type",
// with the same corresponding field values. However - there are 3 flavors of Java Proto API
// that could represent the same message (proto1, mutable proto2, and immutable proto2 [as well
// as immutable proto3, but those look like proto2 classes without "hazzer" method]).
//
// Protos share a common super-interface that defines an equals() method, but since every proto
// message shares that supertype, we shouldn't let that shared equals() definition override our
// attempts to find mismatched equals() between "really" unrelated objects.
//
// We do our best here to identify circumstances where the programmer likely got protos that are
// unrelated (requiring special treatment above and beyond the normal logic in
// compatibilityOfTypes), but ignore cases where the protos are *actually* equal to each other
// according to its definition.
// proto1: io.ProtocolMessage < p.AbstractMutableMessage < p.MutableMessage < p.Message
// proto2-mutable: p.GeneratedMutableMessage < p.AbstractMutableMessage < ... as proto1
// proto2-immutable: p.GeneratedMessage < p.AbstractMessage < p.Message
// DynamicMessage is comparable to all other proto types.
Type dynamicMessage = COM_GOOGLE_PROTOBUF_DYNAMICMESSAGE.get(state);
if (isSameType(leftType, dynamicMessage, state)
|| isSameType(rightType, dynamicMessage, state)) {
return false;
}
Type protoBase = COM_GOOGLE_PROTOBUF_MESSAGE.get(state);
if (isSameType(nearestCommonSupertype, protoBase, state)
&& !isSameType(leftType, protoBase, state)
&& !isSameType(rightType, protoBase, state)) {
// In this situation, there's a mix of (immutable proto2, others) messages. Here, we want to
// figure out if the other is a proto2-mutable representing the same message/type as the
// immutable proto.
// While proto2 can be compared to proto1, this is somewhat of a historical accident. We don't
// want to endorse this, and want to ban it. Protos of the same version and same descriptor
// should be comparable, hence proto2-immutable and proto2-mutable can be.
// See b/152428396#comment10, but basically, we inspect the names of the classes to guess
// whether or not those types are actually representing the same type.
String leftClassPart = classNamePart(leftType);
String rightClassPart = classNamePart(rightType);
return !classesAreMutableAndImmutableOfSameType(leftClassPart, rightClassPart)
&& !classesAreMutableAndImmutableOfSameType(rightClassPart, leftClassPart);
}
// Otherwise, if these two types are *concrete* proto classes, but not the same message, then
// consider them incompatible with each other.
Type messageLite = COM_GOOGLE_PROTOBUF_MESSAGELITE.get(state);
return isSubtype(nearestCommonSupertype, messageLite, state)
&& isConcrete(leftType, state.getTypes())
&& isConcrete(rightType, state.getTypes());
}
private static boolean isConcrete(Type type, Types types) {
Type toEvaluate = getUpperBound(type, types);
return (toEvaluate.tsym.flags() & (Flags.ABSTRACT | Flags.INTERFACE)) == 0;
}
private static boolean classesAreMutableAndImmutableOfSameType(String l, String r) {
return l.startsWith("Mutable") && l.substring("Mutable".length()).equals(r);
}
private static String classNamePart(Type type) {
String fullClassname = type.asElement().getQualifiedName().toString();
String packageName = enclosingPackage(type.asElement()).fullname.toString();
String prefix = fullClassname.substring(packageName.length());
return prefix.startsWith(".") ? prefix.substring(1) : prefix;
}
/**
* Given a {@code leftType} and {@code rightType} (of the shared supertype {@code superType}),
* compare the generic types of those two types (as projected against the {@code superType})
* against each other.
*
* <p>If there are no generic types, or the generic types are compatible with each other, returns
* a {@link TypeCompatibilityReport#isCompatible} report. Otherwise, returns a compatibility
* report showing that a specific generic type in the projection of {@code leftType} is
* incompatible with the specific generic type in the projection of {@code rightType}.
*/
private TypeCompatibilityReport checkForGenericsMismatch(
Type leftType,
Type rightType,
Type superType,
Set<Type> previousLeftTypes,
Set<Type> previousRightTypes,
VisitorState state) {
List<Type> leftGenericTypes = typeArgsAsSuper(leftType, superType, state);
List<Type> rightGenericTypes = typeArgsAsSuper(rightType, superType, state);
return Streams.zip(leftGenericTypes.stream(), rightGenericTypes.stream(), TypePair::new)
// If we encounter an f-bound, skip that index's type when comparing the compatibility of
// types to avoid infinite recursion:
// interface Super<A extends Super<A, B>, B>
// class Foo extends Super<Foo, String>
// class Bar extends Super<Bar, Integer>
.filter(
tp ->
!(previousLeftTypes.contains(tp.left)
|| isSameType(tp.left, leftType, state)
|| previousRightTypes.contains(tp.right)
|| isSameType(tp.right, rightType, state)))
.map(
types -> {
Set<Type> nextLeftTypes = typeSet(state);
nextLeftTypes.addAll(previousLeftTypes);
nextLeftTypes.add(leftType);
Set<Type> nextRightTypes = typeSet(state);
nextRightTypes.addAll(previousRightTypes);
nextRightTypes.add(rightType);
return compatibilityOfTypes(
types.left, types.right, nextLeftTypes, nextRightTypes, state);
})
.filter(tcr -> !tcr.isCompatible())
.findFirst()
.orElse(TypeCompatibilityReport.compatible());
}
private static List<Type> typeArgsAsSuper(Type baseType, Type superType, VisitorState state) {
Type projectedType = state.getTypes().asSuper(baseType, superType.tsym);
if (projectedType != null) {
return projectedType.getTypeArguments();
}
return new ArrayList<>();
}
private static TreeSet<Type> typeSet(VisitorState state) {
return new TreeSet<>(
(t1, t2) ->
state.getTypes().isSameType(t1, t2) ? 0 : t1.toString().compareTo(t2.toString()));
}
@AutoValue
public abstract static class TypeCompatibilityReport {
private static final TypeCompatibilityReport COMPATIBLE =
new AutoValue_TypeCompatibilityUtils_TypeCompatibilityReport(true, null, null, null);
public abstract boolean isCompatible();
@Nullable
public abstract Type lhs();
@Nullable
public abstract Type rhs();
@Nullable
public abstract String extraReason();
static TypeCompatibilityReport compatible() {
return COMPATIBLE;
}
static TypeCompatibilityReport incompatible(Type lhs, Type rhs) {
return incompatible(lhs, rhs, "");
}
static TypeCompatibilityReport incompatible(Type lhs, Type rhs, String extraReason) {
return new AutoValue_TypeCompatibilityUtils_TypeCompatibilityReport(
false, lhs, rhs, extraReason);
}
}
private static final class TypePair {
final Type left;
final Type right;
TypePair(Type left, Type right) {
this.left = left;
this.right = right;
}
}
private static final Supplier<Name> EQUALS =
VisitorState.memoize(state -> state.getName("equals"));
private static final Supplier<Type> COM_GOOGLE_PROTOBUF_DYNAMICMESSAGE =
VisitorState.memoize(state -> state.getTypeFromString("com.google.protobuf.DynamicMessage"));
private static final Supplier<Type> COM_GOOGLE_PROTOBUF_MESSAGE =
VisitorState.memoize(state -> state.getTypeFromString("com.google.protobuf.Message"));
private static final Supplier<Type> COM_GOOGLE_PROTOBUF_MESSAGELITE =
VisitorState.memoize(state -> state.getTypeFromString("com.google.protobuf.MessageLite"));
private static final Supplier<Type> JAVA_UTIL_COLLECTION =
VisitorState.memoize(state -> state.getTypeFromString("java.util.Collection"));
}
| 18,779
| 43.821002
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/PreconditionsCheckNotNullRepeated.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import java.util.List;
/**
* Checks that Precondition.checkNotNull is not invoked with same arg twice.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary =
"Including the first argument of checkNotNull in the failure message is not useful, "
+ "as it will always be `null`.",
severity = WARNING)
public class PreconditionsCheckNotNullRepeated extends BugChecker
implements MethodInvocationTreeMatcher {
private static final String MESSAGE =
"Including `%s` in the failure message isn't helpful,"
+ " since its value will always be `null`.";
private static final Matcher<MethodInvocationTree> MATCHER =
allOf(staticMethod().onClass("com.google.common.base.Preconditions").named("checkNotNull"));
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState state) {
if (!MATCHER.matches(methodInvocationTree, state)) {
return Description.NO_MATCH;
}
if (methodInvocationTree.getArguments().size() < 2) {
return Description.NO_MATCH;
}
List<? extends ExpressionTree> args = methodInvocationTree.getArguments();
int numArgs = args.size();
for (int i = 1; i < numArgs; i++) {
if (!ASTHelpers.sameVariable(args.get(0), args.get(i))) {
continue;
}
String nullArgSource = state.getSourceForNode(args.get(0));
// Special case in case there are only two args and they're same.
// checkNotNull(T reference, Object errorMessage)
if (numArgs == 2) {
return buildDescription(args.get(1))
.setMessage(String.format(MESSAGE, nullArgSource))
.addFix(
SuggestedFix.replace(
args.get(1), String.format("\"%s must not be null\"", nullArgSource)))
.build();
}
return buildDescription(args.get(i))
.setMessage(String.format(MESSAGE, nullArgSource))
.build();
}
return Description.NO_MATCH;
}
}
| 3,326
| 37.686047
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AnnotationPosition.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Streams.stream;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getAnnotationType;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static java.util.Comparator.naturalOrder;
import static java.util.stream.Collectors.joining;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Streams;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.ErrorProneToken;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.TypeAnnotations.AnnotationType;
import com.sun.tools.javac.parser.Tokens.Comment;
import com.sun.tools.javac.parser.Tokens.TokenKind;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
/**
* Checks annotation positioning, and orphaned Javadocs.
*
* @author ghm@google.com (Graeme Morgan)
*/
@BugPattern(
summary = "Annotations should be positioned after Javadocs, but before modifiers.",
severity = WARNING,
// TODO(b/218854220): Put a tag back once patcher is fixed.
linkType = CUSTOM,
link = "https://google.github.io/styleguide/javaguide.html#s4.8.5-annotations")
public final class AnnotationPosition extends BugChecker
implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher {
private static final ImmutableMap<String, TokenKind> TOKEN_KIND_BY_NAME =
Arrays.stream(TokenKind.values()).collect(toImmutableMap(tk -> tk.name(), tk -> tk));
private static final ImmutableSet<TokenKind> MODIFIERS =
Streams.concat(
Arrays.stream(Modifier.values())
.map(m -> TOKEN_KIND_BY_NAME.get(m.name()))
// TODO(b/168625474): sealed doesn't have a token kind in Java 15
.filter(Objects::nonNull),
// Pretend that "<" and ">" are modifiers, so that type arguments wind up grouped with
// modifiers.
Stream.of(TokenKind.LT, TokenKind.GT, TokenKind.GTGT))
.collect(toImmutableSet());
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
return handle(tree, tree.getSimpleName(), tree.getModifiers(), state);
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
return handle(tree, tree.getName(), tree.getModifiers(), state);
}
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
return handle(tree, tree.getName(), tree.getModifiers(), state);
}
private Description handle(Tree tree, Name name, ModifiersTree modifiers, VisitorState state) {
List<? extends AnnotationTree> annotations = modifiers.getAnnotations();
if (annotations.isEmpty()) {
return NO_MATCH;
}
int treePos = getStartPosition(tree);
List<ErrorProneToken> tokens = annotationTokens(tree, state, treePos);
Comment danglingJavadoc = findOrphanedJavadoc(name, tokens);
ImmutableList<ErrorProneToken> modifierTokens =
tokens.stream().filter(t -> MODIFIERS.contains(t.kind())).collect(toImmutableList());
int firstModifierPos =
modifierTokens.stream().findFirst().map(x -> x.pos()).orElse(Integer.MAX_VALUE);
int lastModifierPos = Streams.findLast(modifierTokens.stream()).map(x -> x.endPos()).orElse(0);
Description description =
checkAnnotations(
tree, annotations, danglingJavadoc, firstModifierPos, lastModifierPos, state);
if (!description.equals(NO_MATCH)) {
return description;
}
if (danglingJavadoc == null) {
return NO_MATCH;
}
// If the tree already has Javadoc, don't suggest double-Javadoccing it. It has dangling Javadoc
// but the suggestion will be rubbish.
if (JavacTrees.instance(state.context).getDocCommentTree(state.getPath()) != null) {
return NO_MATCH;
}
SuggestedFix.Builder builder = SuggestedFix.builder();
String javadoc = removeJavadoc(state, danglingJavadoc, builder);
String message = "Javadocs should appear before any modifiers or annotations.";
return buildDescription(tree)
.setMessage(message)
.addFix(builder.prefixWith(tree, javadoc).build())
.build();
}
/** Tokenizes as little of the {@code tree} as possible to ensure we grab all the annotations. */
private static List<ErrorProneToken> annotationTokens(
Tree tree, VisitorState state, int annotationEnd) {
int endPos;
if (tree instanceof JCMethodDecl) {
JCMethodDecl methodTree = (JCMethodDecl) tree;
if (methodTree.getReturnType() != null) {
endPos = getStartPosition(methodTree.getReturnType());
} else if (!methodTree.getParameters().isEmpty()) {
endPos = getStartPosition(methodTree.getParameters().get(0));
if (endPos < annotationEnd) {
endPos = state.getEndPosition(methodTree);
}
} else if (methodTree.getBody() != null && !methodTree.getBody().getStatements().isEmpty()) {
endPos = getStartPosition(methodTree.getBody().getStatements().get(0));
} else {
endPos = state.getEndPosition(methodTree);
}
} else if (tree instanceof JCVariableDecl) {
JCVariableDecl variableTree = (JCVariableDecl) tree;
endPos = getStartPosition(variableTree.getType());
if (endPos == -1) {
// handle 'var'
endPos = state.getEndPosition(variableTree.getModifiers());
}
} else if (tree instanceof JCClassDecl) {
JCClassDecl classTree = (JCClassDecl) tree;
endPos =
classTree.getMembers().isEmpty()
? state.getEndPosition(classTree)
: classTree.getMembers().get(0).getStartPosition();
} else {
throw new AssertionError();
}
return state.getOffsetTokens(annotationEnd, endPos);
}
/** Checks that annotations are on the right side of the modifiers. */
private Description checkAnnotations(
Tree tree,
List<? extends AnnotationTree> annotations,
Comment danglingJavadoc,
int firstModifierPos,
int lastModifierPos,
VisitorState state) {
Symbol symbol = getSymbol(tree);
ImmutableList<AnnotationTree> shouldBeBefore =
annotations.stream()
.filter(
a -> {
Position position = annotationPosition(tree, getAnnotationType(a, symbol, state));
return position == Position.BEFORE
|| (position == Position.EITHER && getStartPosition(a) < firstModifierPos);
})
.collect(toImmutableList());
ImmutableList<AnnotationTree> shouldBeAfter =
annotations.stream()
.filter(
a -> {
Position position = annotationPosition(tree, getAnnotationType(a, symbol, state));
return position == Position.AFTER
|| (position == Position.EITHER && getStartPosition(a) > firstModifierPos);
})
.collect(toImmutableList());
boolean annotationsInCorrectPlace =
shouldBeBefore.stream().allMatch(a -> getStartPosition(a) < firstModifierPos)
&& shouldBeAfter.stream().allMatch(a -> getStartPosition(a) > lastModifierPos);
if (annotationsInCorrectPlace && isOrderingIsCorrect(shouldBeBefore, shouldBeAfter)) {
return NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
for (AnnotationTree annotation : concat(shouldBeBefore, shouldBeAfter)) {
fix.delete(annotation);
}
String javadoc = danglingJavadoc == null ? "" : removeJavadoc(state, danglingJavadoc, fix);
if (lastModifierPos == 0) {
fix.replace(
getStartPosition(tree),
getStartPosition(tree),
String.format(
"%s%s ", javadoc, joinSource(state, concat(shouldBeBefore, shouldBeAfter))));
} else {
fix.replace(
firstModifierPos,
firstModifierPos,
String.format("%s%s ", javadoc, joinSource(state, shouldBeBefore)))
.replace(
lastModifierPos,
lastModifierPos,
String.format(" %s ", joinSource(state, shouldBeAfter)));
}
Stream.Builder<String> messages = Stream.builder();
if (!shouldBeBefore.isEmpty()) {
ImmutableList<String> names = annotationNames(shouldBeBefore);
String flattened = String.join(", ", names);
String isAre =
names.size() > 1 ? "are not TYPE_USE annotations" : "is not a TYPE_USE annotation";
messages.add(
String.format(
"%s %s, so should appear before any modifiers and after Javadocs.",
flattened, isAre));
}
if (!shouldBeAfter.isEmpty()) {
ImmutableList<String> names = annotationNames(shouldBeAfter);
String flattened = String.join(", ", names);
String isAre = names.size() > 1 ? "are TYPE_USE annotations" : "is a TYPE_USE annotation";
messages.add(
String.format(
"%s %s, so should appear after modifiers and directly before the type.",
flattened, isAre));
}
return buildDescription(tree)
.setMessage(messages.build().collect(joining(" ")))
.addFix(fix.build())
.build();
}
private static boolean isOrderingIsCorrect(
List<AnnotationTree> shouldBeBefore, List<AnnotationTree> shouldBeAfter) {
if (shouldBeBefore.isEmpty() || shouldBeAfter.isEmpty()) {
return true;
}
int largestNonTypeAnnotationPosition =
shouldBeBefore.stream().map(ASTHelpers::getStartPosition).max(naturalOrder()).get();
int smallestTypeAnnotationPosition =
shouldBeAfter.stream().map(ASTHelpers::getStartPosition).min(naturalOrder()).get();
return largestNonTypeAnnotationPosition < smallestTypeAnnotationPosition;
}
private static Position annotationPosition(Tree tree, AnnotationType annotationType) {
if (tree instanceof ClassTree || annotationType == null) {
return Position.BEFORE;
}
switch (annotationType) {
case DECLARATION:
return Position.BEFORE;
case TYPE:
return Position.AFTER;
case NONE:
case BOTH:
return Position.EITHER;
}
throw new AssertionError();
}
private static ImmutableList<String> annotationNames(List<AnnotationTree> annotations) {
return annotations.stream()
.map(ASTHelpers::getSymbol)
.filter(Objects::nonNull)
.map(Symbol::getSimpleName)
.map(a -> "@" + a)
.collect(toImmutableList());
}
private static String joinSource(VisitorState state, Iterable<AnnotationTree> moveBefore) {
return stream(moveBefore).map(state::getSourceForNode).collect(joining(" "));
}
private static String removeJavadoc(
VisitorState state, Comment danglingJavadoc, SuggestedFix.Builder builder) {
int javadocStart = danglingJavadoc.getSourcePos(0);
int javadocEnd = javadocStart + danglingJavadoc.getText().length();
// Capturing an extra newline helps the formatter.
if (state.getSourceCode().charAt(javadocEnd) == '\n') {
javadocEnd++;
}
builder.replace(javadocStart, javadocEnd, "");
return danglingJavadoc.getText();
}
@Nullable
private static Comment findOrphanedJavadoc(Name name, List<ErrorProneToken> tokens) {
for (ErrorProneToken token : tokens) {
for (Comment comment : token.comments()) {
if (comment.getText().startsWith("/**")) {
return comment;
}
}
if (token.kind() == TokenKind.IDENTIFIER && token.name().equals(name)) {
return null;
}
}
return null;
}
private enum Position {
BEFORE,
AFTER,
EITHER
}
}
| 13,949
| 39.434783
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ImplementAssertionWithChaining.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.fixes.SuggestedFix.replace;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static com.google.errorprone.util.ASTHelpers.stripParentheses;
import static com.sun.source.tree.Tree.Kind.BLOCK;
import static com.sun.source.tree.Tree.Kind.EXPRESSION_STATEMENT;
import static com.sun.source.tree.Tree.Kind.IDENTIFIER;
import static com.sun.source.tree.Tree.Kind.MEMBER_SELECT;
import static com.sun.source.tree.Tree.Kind.METHOD_INVOCATION;
import static java.lang.String.format;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.IfTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.UnaryTree;
import com.sun.tools.javac.code.Symbol;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* Migrates Truth subjects from a manual "test and fail" approach to one using {@code
* Subject.check(...)}. For example:
*
* <pre>{@code
* // Before:
* if (actual().foo() != expected) {
* failWithActual("expected to have foo", expected);
* }
*
* // After:
* check("foo()").that(actual().foo()).isEqualTo(expected);
* }</pre>
*/
@BugPattern(
summary = "Prefer check(...), which usually generates more readable failure messages.",
severity = SUGGESTION)
public final class ImplementAssertionWithChaining extends BugChecker implements IfTreeMatcher {
@Override
public Description matchIf(IfTree ifTree, VisitorState state) {
if (ifTree.getElseStatement() != null) {
return NO_MATCH;
}
if (!isCallToFail(ifTree.getThenStatement(), state)) {
return NO_MATCH;
}
/*
* TODO(cpovirk): Also look for assertions that could use isTrue, isFalse, isNull, isEmpty, etc.
* (But isTrue and isFalse in particular often benefit from custom messages.)
*/
ImmutableList<ExpressionTree> actualAndExpected =
findActualAndExpected(stripParentheses(ifTree.getCondition()), state);
if (actualAndExpected == null) {
return NO_MATCH;
}
String checkDescription = makeCheckDescription(actualAndExpected.get(0), state);
if (checkDescription == null) {
return NO_MATCH;
}
/*
* TODO(cpovirk): Write "this.check(...)" if the code uses "this.actual()" or "this.fail*(...)."
* Similarly for "otherObject.check(...)."
*/
return describeMatch(
ifTree,
replace(
ifTree,
format(
"check(%s).that(%s).isEqualTo(%s);",
checkDescription,
state.getSourceForNode(actualAndExpected.get(0)),
state.getSourceForNode(actualAndExpected.get(1)))));
}
@Nullable
private static ImmutableList<ExpressionTree> findActualAndExpected(
ExpressionTree condition, VisitorState state) {
/*
* Note that all these look "backward": If the code is "if (foo == bar) { fail }," then the
* assertion is checking that the values are *not* equal.
*/
switch (condition.getKind()) {
case LOGICAL_COMPLEMENT:
return findActualAndExpectedForPossibleEqualsCall(
stripParentheses(((UnaryTree) condition).getExpression()), state);
case NOT_EQUAL_TO:
return findActualAndExpectedForBinaryOp((BinaryTree) condition, state);
default:
return null;
}
}
@Nullable
private static ImmutableList<ExpressionTree> findActualAndExpectedForPossibleEqualsCall(
ExpressionTree possiblyEqualsCall, VisitorState state) {
if (!EQUALS_LIKE_METHOD.matches(possiblyEqualsCall, state)) {
return null;
}
MethodInvocationTree equalsCheck = (MethodInvocationTree) possiblyEqualsCall;
List<? extends ExpressionTree> args = equalsCheck.getArguments();
return (args.size() == 2)
? ImmutableList.copyOf(args)
: ImmutableList.of(
((MemberSelectTree) equalsCheck.getMethodSelect()).getExpression(),
getOnlyElement(args));
}
@Nullable
private static ImmutableList<ExpressionTree> findActualAndExpectedForBinaryOp(
BinaryTree binaryTree, VisitorState state) {
/*
* It's actually enough for *either* to be a primitive, thanks to autounboxing (and enough for
* *either* to be an enum, since equals() is symmetric). However, it turns out that handling
* those cases catches almost nothing new in practice, and I'm seeing some evidence that "null"
* is considered to be a primitive? or something? That seems wrong, but given the low payoff,
* I'm not going to investigate further.
*/
boolean bothPrimitives =
getType(binaryTree.getLeftOperand()).isPrimitive()
&& getType(binaryTree.getRightOperand()).isPrimitive();
boolean bothEnums =
isEnum(binaryTree.getLeftOperand(), state) && isEnum(binaryTree.getRightOperand(), state);
if (!bothPrimitives && !bothEnums) {
// TODO(cpovirk): Generate an isSameAs() check (if that is what users really want).
return null;
}
return ImmutableList.of(binaryTree.getLeftOperand(), binaryTree.getRightOperand());
}
private static boolean isEnum(ExpressionTree tree, VisitorState state) {
return isSubtype(getType(tree), state.getSymtab().enumSym.type, state);
}
/**
* Checks that the statement, after unwrapping any braces, consists of a single call to a {@code
* fail*} method.
*/
private static boolean isCallToFail(StatementTree then, VisitorState state) {
while (then.getKind() == BLOCK) {
List<? extends StatementTree> statements = ((BlockTree) then).getStatements();
if (statements.size() != 1) {
return false;
}
then = getOnlyElement(statements);
}
if (then.getKind() != EXPRESSION_STATEMENT) {
return false;
}
ExpressionTree thenExpr = ((ExpressionStatementTree) then).getExpression();
if (thenExpr.getKind() != METHOD_INVOCATION) {
return false;
}
MethodInvocationTree thenCall = (MethodInvocationTree) thenExpr;
ExpressionTree methodSelect = thenCall.getMethodSelect();
if (methodSelect.getKind() != IDENTIFIER) {
return false;
// TODO(cpovirk): Handle "this.fail*(...)," etc.
}
return FAIL_METHOD.matches(methodSelect, state);
}
/**
* Converts the tree for the actual value under test (like {@code actual().foo()}) to a string
* suitable for passing to {@code Subject.check(...)} (like {@code "foo()"}, which Truth appends
* to the name is has for the actual value, producing something like {@code "bar.foo()"}).
*
* <p>Sometimes the tree contains multiple method calls, like {@code actual().foo().bar()}. In
* that case, they appear "backward" as we walk the tree (i.e., bar, foo), so we add each one to
* the beginning of the list as we go.
*/
@Nullable
static String makeCheckDescription(ExpressionTree actual, VisitorState state) {
/*
* This conveniently also acts as a check that the actual and expected values aren't backward,
* since the actual value is almost always an invocation on actual() and the expected value is
* almost always a parameter.
*/
if (actual.getKind() != METHOD_INVOCATION) {
return null;
}
Deque<String> parts = new ArrayDeque<>();
MethodInvocationTree invocation = (MethodInvocationTree) actual;
while (true) {
ExpressionTree methodSelect = invocation.getMethodSelect();
if (methodSelect.getKind() != MEMBER_SELECT) {
return null;
}
MemberSelectTree memberSelect = (MemberSelectTree) methodSelect;
if (!invocation.getArguments().isEmpty()) {
// TODO(cpovirk): Handle invocations with arguments.
return null;
}
parts.addFirst(memberSelect.getIdentifier() + "()");
ExpressionTree expression = memberSelect.getExpression();
if (ACTUAL_METHOD.matches(expression, state) || refersToFieldNamedActual(expression)) {
return '"' + Joiner.on('.').join(parts) + '"';
}
if (expression.getKind() != METHOD_INVOCATION) {
return null;
}
invocation = (MethodInvocationTree) expression;
}
}
private static boolean refersToFieldNamedActual(ExpressionTree tree) {
Symbol symbol = getSymbol(tree);
// Using the name "actual" for this field is just a convention, but that's good enough here.
return symbol != null
&& symbol.getKind().isField()
&& symbol.getSimpleName().contentEquals("actual");
}
private static final Matcher<ExpressionTree> FAIL_METHOD =
instanceMethod()
.onDescendantOf("com.google.common.truth.Subject")
.withNameMatching(Pattern.compile("fail.*"));
private static final Matcher<ExpressionTree> EQUALS_LIKE_METHOD =
anyOf(
instanceMethod().anyClass().named("equals").withParameters("java.lang.Object"),
staticMethod().onClass("com.google.common.base.Objects").named("equal"),
staticMethod().onClass("java.util.Objects").named("equals"));
private static final Matcher<ExpressionTree> ACTUAL_METHOD =
anyOf(
instanceMethod()
.onDescendantOf("com.google.common.truth.Subject")
.named("actual")
.withNoParameters(),
instanceMethod()
.onDescendantOf("com.google.common.truth.Subject")
.named("getSubject")
.withNoParameters());
}
| 11,186
| 38.390845
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DifferentNameButSame.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Iterables.getLast;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.FindIdentifiers.findIdent;
import com.google.common.base.Ascii;
import com.google.common.base.Splitter;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Table;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.MultiMatcher;
import com.sun.source.tree.AnnotatedTypeTree;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Kinds.KindSelector;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.util.Position;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Discourages using multiple names to refer to the same type within a file (e.g. both {@code
* OuterClass.InnerClass} and {@code InnerClass}).
*/
@BugPattern(
severity = SeverityLevel.WARNING,
summary =
"This type is referred to in different ways within this file, which may be confusing.",
tags = StandardTags.STYLE)
public final class DifferentNameButSame extends BugChecker implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
Table<Symbol, String, List<TreePath>> names = HashBasedTable.create();
new TreePathScanner<Void, Void>() {
@Override
public Void visitImport(ImportTree importTree, Void unused) {
return null;
}
@Override
public Void visitCase(CaseTree caseTree, Void unused) {
return null;
}
@Override
public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void unused) {
if (getCurrentPath().getParentPath().getLeaf() instanceof MemberSelectTree) {
MemberSelectTree tree = (MemberSelectTree) getCurrentPath().getParentPath().getLeaf();
Symbol superSymbol = getSymbol(tree);
if (superSymbol instanceof ClassSymbol) {
return super.visitMemberSelect(memberSelectTree, null);
}
}
handle(memberSelectTree);
return super.visitMemberSelect(memberSelectTree, null);
}
@Override
public Void visitIdentifier(IdentifierTree identifierTree, Void unused) {
Tree parent = getCurrentPath().getParentPath().getLeaf();
if (parent instanceof NewClassTree) {
NewClassTree newClassTree = (NewClassTree) parent;
if (newClassTree.getIdentifier().equals(identifierTree)
&& newClassTree.getEnclosingExpression() != null) {
// don't try to fix instantiations with explicit enclosing instances, e.g. `a.new B();`
return null;
}
}
handle(identifierTree);
return super.visitIdentifier(identifierTree, null);
}
private void handle(Tree tree) {
if (state.getEndPosition(tree) == Position.NOPOS) {
return;
}
Symbol symbol = getSymbol(tree);
if (!(symbol instanceof ClassSymbol)) {
return;
}
@SuppressWarnings("TreeToString") // TODO(ghm): fix
String name = tree.toString();
List<TreePath> treePaths = names.get(symbol, name);
if (treePaths == null) {
treePaths = new ArrayList<>();
names.put(symbol, name, treePaths);
}
treePaths.add(getCurrentPath());
}
}.scan(tree, null);
for (Map.Entry<Symbol, Map<String, List<TreePath>>> entry : names.rowMap().entrySet()) {
Symbol symbol = entry.getKey();
// Skip generic symbols; we need to do a lot more work to check the type parameters match at
// each level.
if (isGeneric(symbol)) {
continue;
}
if (isDefinedInThisFile(symbol, tree)) {
continue;
}
Map<String, List<TreePath>> references = entry.getValue();
if (references.size() == 1) {
continue;
}
// Skip if any look to be fully qualified: this will be mentioned by a different check.
if (references.keySet().stream().anyMatch(n -> Ascii.isLowerCase(n.charAt(0)))) {
continue;
}
ImmutableList<String> namesByPreference =
references.entrySet().stream()
.sorted(REPLACEMENT_PREFERENCE)
.map(Map.Entry::getKey)
.collect(toImmutableList());
for (String name : namesByPreference) {
ImmutableList<TreePath> sites =
references.entrySet().stream()
.filter(e -> !e.getKey().equals(name))
.map(Map.Entry::getValue)
.flatMap(Collection::stream)
.collect(toImmutableList());
if (!(symbol instanceof MethodSymbol) && !visibleAndReferToSameThing(name, sites, state)) {
continue;
}
if (BadImport.BAD_NESTED_CLASSES.contains(name)) {
continue;
}
List<String> components = DOT_SPLITTER.splitToList(name);
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
for (TreePath site : sites) {
fixBuilder.merge(createFix(site, components, state));
}
SuggestedFix fix = fixBuilder.build();
for (TreePath path : sites) {
state.reportMatch(describeMatch(path.getLeaf(), fix));
}
break;
}
}
return NO_MATCH;
}
private boolean isDefinedInThisFile(Symbol symbol, CompilationUnitTree tree) {
return tree.getTypeDecls().stream()
.anyMatch(
t -> {
Symbol topLevelClass = getSymbol(t);
return topLevelClass instanceof ClassSymbol
&& symbol.isEnclosedBy((ClassSymbol) topLevelClass);
});
}
private static boolean isGeneric(Symbol symbol) {
for (Symbol s = symbol; s != null; s = s.owner) {
if (!s.getTypeParameters().isEmpty()) {
return true;
}
}
return false;
}
private static SuggestedFix createFix(
TreePath path, List<String> components, VisitorState state) {
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
StringBuilder stringBuilder = new StringBuilder();
components.stream()
.limit(components.size() - 1)
.forEachOrdered(c -> stringBuilder.append(c).append("."));
Tree site = path.getLeaf();
Tree parent = path.getParentPath().getLeaf();
if (canHaveTypeUseAnnotations(parent)) {
for (AnnotationTree annotation :
HAS_TYPE_USE_ANNOTATION.multiMatchResult(parent, state).matchingNodes()) {
if (state.getEndPosition(annotation) < getStartPosition(site)) {
fixBuilder.delete(annotation);
}
stringBuilder.append(state.getSourceForNode(annotation)).append(" ");
}
}
stringBuilder.append(getLast(components));
return fixBuilder.replace(site, stringBuilder.toString()).build();
}
private static boolean canHaveTypeUseAnnotations(Tree tree) {
return tree instanceof AnnotatedTypeTree
|| tree instanceof MethodTree
|| tree instanceof VariableTree;
}
/**
* Checks whether the symbol with {@code name} is visible from the position encoded in {@code
* state}.
*
* <p>This is not fool-proof by any means: it doesn't check that the symbol actually has the same
* meaning.
*/
private static boolean visibleAndReferToSameThing(
String name, ImmutableList<TreePath> locations, VisitorState state) {
String firstComponent = name.contains(".") ? name.substring(0, name.indexOf(".")) : name;
Set<Symbol> idents = new HashSet<>();
for (TreePath path : locations) {
VisitorState stateWithPath = state.withPath(path);
if (findIdent(firstComponent, stateWithPath, KindSelector.VAR) != null) {
return false;
}
Symbol symbol = findIdent(firstComponent, stateWithPath, KindSelector.VAL_TYP_PCK);
if (symbol == null) {
return false;
}
idents.add(symbol);
}
return idents.size() == 1;
}
private static final Comparator<Map.Entry<String, List<TreePath>>> REPLACEMENT_PREFERENCE =
Comparator.<Map.Entry<String, List<TreePath>>>comparingInt(e -> e.getKey().length())
.thenComparing(Map.Entry::getKey);
private static final Splitter DOT_SPLITTER = Splitter.on('.');
private static final MultiMatcher<Tree, AnnotationTree> HAS_TYPE_USE_ANNOTATION =
annotations(AT_LEAST_ONE, (t, state) -> isTypeAnnotation(t));
private static boolean isTypeAnnotation(AnnotationTree t) {
Symbol annotationSymbol = getSymbol(t.getAnnotationType());
if (annotationSymbol == null) {
return false;
}
Target target = annotationSymbol.getAnnotation(Target.class);
if (target == null) {
return false;
}
List<ElementType> value = Arrays.asList(target.value());
return value.contains(ElementType.TYPE_USE) || value.contains(ElementType.TYPE_PARAMETER);
}
}
| 11,102
| 37.686411
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/RobolectricShadowDirectlyOn.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getLast;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFixes.qualifyType;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static java.util.stream.Collectors.joining;
import com.google.common.collect.Streams;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.stream.Stream;
/** A {@link BugChecker}; see the summary. */
@BugPattern(
summary = "Migrate off a deprecated overload of org.robolectric.shadow.api.Shadow#directlyOn",
severity = WARNING)
public class RobolectricShadowDirectlyOn extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
MethodMatchers.staticMethod()
.onClass("org.robolectric.shadow.api.Shadow")
.withSignature("<T>directlyOn(T,java.lang.Class<T>)");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
TreePath path = state.getPath().getParentPath();
if (!(path.getLeaf() instanceof MemberSelectTree)) {
return NO_MATCH;
}
path = path.getParentPath();
Tree parentTree = path.getLeaf();
if (!(parentTree instanceof MethodInvocationTree)) {
return NO_MATCH;
}
MethodInvocationTree parent = (MethodInvocationTree) parentTree;
if (!tree.equals(getReceiver(parent))) {
return NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
MethodSymbol symbol = getSymbol(parent);
String argReplacement =
Streams.concat(
Stream.of(state.getConstantExpression(symbol.getSimpleName().toString())),
Streams.zip(
symbol.getParameters().stream(),
parent.getArguments().stream(),
(p, a) ->
String.format(
"ClassParameter.from(%s.class, %s)",
qualifyType(state, fix, state.getTypes().erasure(p.asType())),
state.getSourceForNode(a))))
.collect(joining(", ", ", ", ""));
fix.replace(state.getEndPosition(tree), state.getEndPosition(parent), "")
.postfixWith(getLast(tree.getArguments()), argReplacement)
.addImport("org.robolectric.util.ReflectionHelpers.ClassParameter");
return describeMatch(tree, fix.build());
}
}
| 3,898
| 41.380435
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NullableVoid.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.MethodTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import javax.lang.model.type.TypeKind;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"void-returning methods should not be annotated with @Nullable,"
+ " since they cannot return null",
severity = WARNING,
tags = StandardTags.STYLE)
public class NullableVoid extends BugChecker implements MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
MethodSymbol sym = ASTHelpers.getSymbol(tree);
if (sym.getReturnType().getKind() != TypeKind.VOID) {
return NO_MATCH;
}
AnnotationTree annotation =
ASTHelpers.getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "Nullable");
if (annotation == null) {
return NO_MATCH;
}
return describeMatch(annotation, SuggestedFix.delete(annotation));
}
}
| 2,180
| 37.263158
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ClassNewInstance.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TryTree;
import com.sun.source.tree.UnionTypeTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeScanner;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Class.newInstance() bypasses exception checking; prefer"
+ " getDeclaredConstructor().newInstance()",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public class ClassNewInstance extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> NEW_INSTANCE =
instanceMethod().onExactClass(Class.class.getName()).named("newInstance");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!NEW_INSTANCE.matches(tree, state)) {
return Description.NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
fix.replace(
state.getEndPosition(ASTHelpers.getReceiver(tree)),
state.getEndPosition(tree),
".getDeclaredConstructor().newInstance()");
boolean fixedExceptions = fixExceptions(state, fix);
if (!fixedExceptions) {
fixThrows(state, fix);
}
return describeMatch(tree, fix.build());
}
// if the match occurrs inside the body of a try statement with existing catch clauses
// update or add a catch block to handle the new exceptions
private static boolean fixExceptions(VisitorState state, SuggestedFix.Builder fix) {
TryTree tryTree = null;
for (TreePath path = state.getPath(); path != null; path = path.getParentPath()) {
if (path.getLeaf() instanceof CatchTree) {
// don't add more catch blocks if newInstance() was called in a catch block
return false;
} else if (path.getLeaf() instanceof TryTree
&& !((TryTree) path.getLeaf()).getCatches().isEmpty()) {
tryTree = (TryTree) path.getLeaf();
break;
}
}
if (tryTree == null) {
return false;
}
ImmutableMap.Builder<Type, CatchTree> catches = ImmutableMap.builder();
for (CatchTree c : tryTree.getCatches()) {
catches.put(ASTHelpers.getType(c.getParameter().getType()), c);
}
UnhandledResult<CatchTree> result = unhandled(catches.buildOrThrow(), state);
if (result.unhandled.isEmpty()) {
// no fix needed
return true;
}
{
// if there's an existing multi-catch at the end that handles reflective exceptions,
// replace all of them with ROE and leave any non-reflective exceptions.
// earlier catch blocks are left unchanged.
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<>();
boolean foundReflective = false;
for (Tree alternate : ((UnionTypeTree) lastType).getTypeAlternatives()) {
if (ASTHelpers.isSubtype(ASTHelpers.getType(alternate), roe, state)) {
foundReflective = true;
exceptions.add("ReflectiveOperationException");
} else {
exceptions.add(state.getSourceForNode(alternate));
}
}
if (foundReflective) {
fix.replace(lastType, Joiner.on(" | ").join(exceptions));
return true;
}
}
}
// check for duplicated catch blocks that handle reflective exceptions exactly the same way,
// and merge them into a single block that catches ROE
Set<String> uniq = new HashSet<>();
for (CatchTree ct : result.handles.values()) {
uniq.add(state.getSourceForNode(ct.getBlock()));
}
// the catch blocks are all unique, append a new fresh one
if (uniq.size() != 1) {
CatchTree last = Iterables.getLast(tryTree.getCatches());
// borrow the variable name of the previous catch variable, in case the naive 'e' conflicts
// with something in the current scope
String name = last.getParameter().getName().toString();
fix.postfixWith(
last,
String.format(
"catch (ReflectiveOperationException %s) {"
+ " throw new LinkageError(%s.getMessage(), %s); }",
name, name, name));
return true;
}
// if the catch blocks contain calls to newInstance, don't delete any of them to avoid
// overlapping fixes
AtomicBoolean newInstanceInCatch = new AtomicBoolean(false);
((JCTree) result.handles.values().iterator().next())
.accept(
new TreeScanner() {
@Override
public void visitApply(JCTree.JCMethodInvocation tree) {
if (NEW_INSTANCE.matches(tree, state)) {
newInstanceInCatch.set(true);
}
}
});
if (newInstanceInCatch.get()) {
fix.replace(
Iterables.getLast(result.handles.values()).getParameter().getType(),
"ReflectiveOperationException");
return true;
}
// otherwise, merge the duplicated catch blocks into a single block that
// handles ROE
boolean first = true;
for (CatchTree ct : result.handles.values()) {
if (first) {
fix.replace(ct.getParameter().getType(), "ReflectiveOperationException");
first = false;
} else {
fix.delete(ct);
}
}
return true;
}
// if there wasn't a try/catch to add new catch clauses to, update the enclosing
// method declaration's throws clause to declare the new checked exceptions
private static void fixThrows(VisitorState state, SuggestedFix.Builder fix) {
MethodTree methodTree = state.findEnclosing(MethodTree.class);
if (methodTree == null || methodTree.getThrows().isEmpty()) {
return;
}
ImmutableMap.Builder<Type, ExpressionTree> thrown = ImmutableMap.builder();
for (ExpressionTree e : methodTree.getThrows()) {
thrown.put(ASTHelpers.getType(e), e);
}
UnhandledResult<ExpressionTree> result = unhandled(thrown.buildOrThrow(), state);
if (result.unhandled.isEmpty()) {
return;
}
List<String> newThrows = new ArrayList<>();
for (Type handle : result.unhandled) {
newThrows.add(handle.tsym.getSimpleName().toString());
}
Collections.sort(newThrows);
fix.postfixWith(
Iterables.getLast(methodTree.getThrows()), ", " + Joiner.on(", ").join(newThrows));
// the other exceptions are in java.lang
fix.addImport("java.lang.reflect.InvocationTargetException");
}
static class UnhandledResult<T> {
/** Exceptions thrown by {@link Constructor#newInstance} that were unhandled. */
final ImmutableSet<Type> unhandled;
/** Handlers for reflective exceptions (e.g. a throws declaration or catch clause). */
final ImmutableMap<Type, T> handles;
UnhandledResult(ImmutableSet<Type> unhandled, ImmutableMap<Type, T> handles) {
this.unhandled = unhandled;
this.handles = handles;
}
}
/**
* Given a map of handled exception types and the trees of those handlers (i.e. catch clauses or
* method throws clauses), determine which handlers are for reflective exceptions, and whether all
* exceptions thrown by {#link Constructor#newInstance} are handled.
*/
private static <T> UnhandledResult<T> unhandled(
ImmutableMap<Type, T> handles, VisitorState state) {
LinkedHashSet<Type> toHandle = new LinkedHashSet<>();
for (Class<?> e :
Arrays.asList(
InstantiationException.class,
IllegalAccessException.class,
InvocationTargetException.class,
NoSuchMethodException.class)) {
Type type = state.getTypeFromString(e.getName());
if (type != null) {
toHandle.add(type);
}
}
Type roe = state.getTypeFromString(ReflectiveOperationException.class.getName());
ImmutableMap.Builder<Type, T> newHandles = ImmutableMap.builder();
for (Map.Entry<Type, T> entry : handles.entrySet()) {
Type type = entry.getKey();
if (ASTHelpers.isSubtype(type, roe, state)) {
newHandles.put(type, entry.getValue());
}
for (Type precise :
type.isUnion()
? ((Type.UnionClassType) type).getAlternativeTypes()
: Collections.singleton(type)) {
toHandle.removeIf((Type elem) -> ASTHelpers.isSubtype(elem, precise, state));
}
}
return new UnhandledResult<>(ImmutableSet.copyOf(toHandle), newHandles.buildOrThrow());
}
}
| 10,656
| 39.367424
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AutoValueSubclassLeaked.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Type;
/** Matches {@code AutoValue_} uses outside the containing file. */
@BugPattern(
severity = WARNING,
summary =
"Do not refer to the autogenerated AutoValue_ class outside the file containing the"
+ " corresponding @AutoValue base class.",
explanation =
"@AutoValue-annotated classes may form part of your API, but the AutoValue_ generated"
+ " classes should not. The fact that the generated classes are visible to other"
+ " classes within the same package is an implementation detail, and is best avoided."
+ " Ideally, any reference to the AutoValue_-prefixed class should be confined to a"
+ " single factory method, with other factories delegating to it if necessary.")
public final class AutoValueSubclassLeaked extends BugChecker
implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
ImmutableSet<Type> autoValueClassesFromThisFile = findAutoValueClasses(tree, state);
scanAndReportAutoValueReferences(tree, autoValueClassesFromThisFile, state);
return NO_MATCH;
}
private void scanAndReportAutoValueReferences(
CompilationUnitTree tree,
ImmutableSet<Type> autoValueClassesFromThisFile,
VisitorState state) {
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitClass(ClassTree classTree, Void unused) {
if (!ASTHelpers.getGeneratedBy(getSymbol(classTree), state).isEmpty()) {
return null;
}
return super.visitClass(classTree, null);
}
@Override
public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void unused) {
handle(memberSelectTree);
return super.visitMemberSelect(memberSelectTree, null);
}
@Override
public Void visitIdentifier(IdentifierTree identifierTree, Void unused) {
handle(identifierTree);
return super.visitIdentifier(identifierTree, null);
}
private void handle(Tree tree) {
Symbol symbol = getSymbol(tree);
if (symbol instanceof ClassSymbol
&& symbol.getSimpleName().toString().startsWith("AutoValue_")
&& autoValueClassesFromThisFile.stream()
.noneMatch(av -> isSubtype(symbol.type, av, state))) {
state.reportMatch(describeMatch(tree));
}
}
}.scan(tree, null);
}
private static ImmutableSet<Type> findAutoValueClasses(
CompilationUnitTree tree, VisitorState state) {
ImmutableSet.Builder<Type> types = ImmutableSet.builder();
tree.accept(
new TreeScanner<Void, Void>() {
@Override
public Void visitClass(ClassTree classTree, Void unused) {
if (hasAnnotation(classTree, AutoValue.class, state)) {
types.add(getType(classTree));
}
return super.visitClass(classTree, null);
}
},
null);
return types.build();
}
}
| 4,810
| 39.091667
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SelfAlwaysReturnsThis.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.enclosingClass;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static com.google.errorprone.util.ASTHelpers.isVoidType;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Non-abstract instance methods named 'self()' or 'getThis()' that return the enclosing"
+ " class must always 'return this'",
severity = WARNING)
public final class SelfAlwaysReturnsThis extends BugChecker implements MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
MethodSymbol methodSymbol = getSymbol(methodTree);
// The method must:
// * not be a constructor
// * be named `self` or `getThis`
// * have no params
// * be an instance method (not static)
// * have a body (not abstract)
if (methodSymbol.isConstructor()
|| (!methodSymbol.getSimpleName().contentEquals("self")
&& !methodSymbol.getSimpleName().contentEquals("getThis"))
|| !methodSymbol.getParameters().isEmpty()
|| methodSymbol.isStatic()
|| methodTree.getBody() == null) {
return NO_MATCH;
}
// * not have a void (or Void) return type
Tree returnType = methodTree.getReturnType();
if (isVoidType(getType(returnType), state)) {
return NO_MATCH;
}
// * have the same return type as the enclosing type
if (!isSameType(getType(returnType), enclosingClass(methodSymbol).type, state)) {
return NO_MATCH;
}
// TODO(kak): we should probably re-used the TreePathScanner from CanIgnoreReturnValueSuggester
// This TreePathScanner is mostly copied from CanIgnoreReturnValueSuggester
AtomicBoolean allReturnThis = new AtomicBoolean(true);
AtomicBoolean atLeastOneReturn = new AtomicBoolean(false);
new TreePathScanner<Void, Void>() {
private final Set<VarSymbol> thises = new HashSet<>();
@Override
public Void visitVariable(VariableTree variableTree, Void unused) {
VarSymbol symbol = getSymbol(variableTree);
if (isConsideredFinal(symbol) && maybeCastThis(variableTree.getInitializer())) {
thises.add(symbol);
}
return super.visitVariable(variableTree, null);
}
@Override
public Void visitReturn(ReturnTree returnTree, Void unused) {
atLeastOneReturn.set(true);
if (!isThis(returnTree.getExpression())) {
allReturnThis.set(false);
// once we've set allReturnThis to false, no need to descend further
return null;
}
return super.visitReturn(returnTree, null);
}
/** Returns whether the given {@link ExpressionTree} is {@code this}. */
private boolean isThis(ExpressionTree returnExpression) {
return maybeCastThis(returnExpression) || thises.contains(getSymbol(returnExpression));
}
@Override
public Void visitLambdaExpression(LambdaExpressionTree node, Void unused) {
// don't descend into lambdas
return null;
}
@Override
public Void visitNewClass(NewClassTree node, Void unused) {
// don't descend into declarations of anonymous classes
return null;
}
}.scan(state.getPath(), null);
if (atLeastOneReturn.get() && allReturnThis.get()) {
return NO_MATCH;
}
return describeMatch(
methodTree, SuggestedFix.replace(methodTree.getBody(), "{ return this; }"));
}
private static boolean maybeCastThis(Tree tree) {
return firstNonNull(
new SimpleTreeVisitor<Boolean, Void>() {
@Override
public Boolean visitParenthesized(ParenthesizedTree tree, Void unused) {
return visit(tree.getExpression(), null);
}
@Override
public Boolean visitTypeCast(TypeCastTree tree, Void unused) {
return visit(tree.getExpression(), null);
}
@Override
public Boolean visitIdentifier(IdentifierTree tree, Void unused) {
return tree.getName().contentEquals("this");
}
}.visit(tree, null),
false);
}
}
| 6,232
| 36.775758
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ProtocolBufferOrdinal.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
/**
* Points out if #ordinal() is called on a Protocol Buffer Enum.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary = "To get the tag number of a protocol buffer enum, use getNumber() instead.",
severity = ERROR)
public class ProtocolBufferOrdinal extends BugChecker implements MethodInvocationTreeMatcher {
private static final String PROTO_SUPER_CLASS = "com.google.protobuf.Internal.EnumLite";
private static final Matcher<ExpressionTree> PROTO_MSG_ORDINAL_MATCHER =
instanceMethod().onDescendantOf(PROTO_SUPER_CLASS).named("ordinal").withNoParameters();
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState state) {
return PROTO_MSG_ORDINAL_MATCHER.matches(methodInvocationTree, state)
? describeMatch(methodInvocationTree)
: Description.NO_MATCH;
}
}
| 2,041
| 37.528302
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StronglyType.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.canBeRemoved;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import com.google.auto.value.AutoValue;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.SetMultimap;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import javax.lang.model.element.ElementKind;
/**
* Helper for strongly typing fields. Fields that are declared as a weaker type but only used when
* wrapped in a stronger type will be refactored to the stronger type.
*
* @see com.google.errorprone.bugpatterns.time.StronglyTypeTime
*/
@AutoValue
public abstract class StronglyType {
abstract Function<String, String> renameFunction();
abstract ImmutableSet<Type> primitiveTypesToReplace();
abstract Matcher<ExpressionTree> factoryMatcher();
abstract BugChecker bugChecker();
public static Builder forCheck(BugChecker bugChecker) {
return new AutoValue_StronglyType.Builder()
.setBugChecker(bugChecker)
.setRenameFunction(name -> name);
}
/** Builder for {@link StronglyType} */
@AutoValue.Builder
public abstract static class Builder {
/**
* Set a mapping function that maps from the original name to a new name more befitting the
* strong type.
*/
public abstract Builder setRenameFunction(Function<String, String> renameFn);
/** Set the matcher used to check if an expression is a factory creating a stronger type. */
public abstract Builder setFactoryMatcher(Matcher<ExpressionTree> matcher);
abstract Builder setBugChecker(BugChecker bugChecker);
abstract ImmutableSet.Builder<Type> primitiveTypesToReplaceBuilder();
/** Add a type that can be replaced with a stronger type. */
@CanIgnoreReturnValue
public final Builder addType(Type type) {
primitiveTypesToReplaceBuilder().add(type);
return this;
}
public abstract StronglyType build();
}
public final Description match(CompilationUnitTree tree, VisitorState state) {
Map<VarSymbol, TreePath> fields =
new HashMap<>(findPathToPotentialFields(state, primitiveTypesToReplace()));
SetMultimap<VarSymbol, ExpressionTree> usages = HashMultimap.create();
new TreePathScanner<Void, Void>() {
@Override
public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void unused) {
handle(memberSelectTree);
return super.visitMemberSelect(memberSelectTree, null);
}
@Override
public Void visitIdentifier(IdentifierTree identifierTree, Void unused) {
handle(identifierTree);
return null;
}
private void handle(Tree tree) {
Symbol symbol = getSymbol(tree);
if (!fields.containsKey(symbol)) {
return;
}
Tree parent = getCurrentPath().getParentPath().getLeaf();
if (!(parent instanceof ExpressionTree)
|| !factoryMatcher().matches((ExpressionTree) parent, state)) {
fields.remove(symbol);
return;
}
usages.put((VarSymbol) symbol, (ExpressionTree) parent);
}
}.scan(tree, null);
for (Map.Entry<VarSymbol, TreePath> entry : fields.entrySet()) {
state.reportMatch(match(entry.getValue(), entry.getKey(), usages.get(entry.getKey()), state));
}
return NO_MATCH;
}
private Description match(
TreePath variableTreePath,
VarSymbol replacedSymbol,
Set<ExpressionTree> invocationTrees,
VisitorState state) {
if (invocationTrees.stream().map(ASTHelpers::getSymbol).distinct().count() != 1) {
return NO_MATCH;
}
VariableTree variableTree = (VariableTree) variableTreePath.getLeaf();
ExpressionTree factory = invocationTrees.iterator().next();
String newName = renameFunction().apply(variableTree.getName().toString());
SuggestedFix.Builder fix = SuggestedFix.builder();
Type targetType = getType(factory);
String typeName = SuggestedFixes.qualifyType(state.withPath(variableTreePath), fix, targetType);
fix.replace(
variableTree,
String.format(
"%s %s %s = %s(%s);",
state.getSourceForNode(variableTree.getModifiers()),
typeName,
newName,
getMethodSelectOrNewClass(factory, state),
getWeakTypeIntitializerCode(variableTree, state)));
for (ExpressionTree expressionTree : invocationTrees) {
fix.replace(expressionTree, newName);
}
Type replacedType = state.getTypes().unboxedTypeOrType(replacedSymbol.type);
return bugChecker()
.buildDescription(variableTree)
.setMessage(
String.format(
"This %s is only used to construct %s instances. It would be"
+ " clearer to strongly type the field instead.",
buildStringForType(replacedType, state), targetType.tsym.getSimpleName()))
.addFix(fix.build())
.build();
}
private static String buildStringForType(Type type, VisitorState state) {
return SuggestedFixes.prettyType(type, state);
}
/**
* Get the source code for the initializer. If the initializer is an array literal without a type,
* prefix with new <type>.
*/
private static String getWeakTypeIntitializerCode(VariableTree weakType, VisitorState state) {
// If the new array type is missing, we need to add it.
String prefix =
(weakType.getInitializer().getKind() == Kind.NEW_ARRAY
&& ((NewArrayTree) weakType.getInitializer()).getType() == null)
? String.format("new %s ", state.getSourceForNode(weakType.getType()))
: "";
return prefix + state.getSourceForNode(weakType.getInitializer());
}
private static String getMethodSelectOrNewClass(ExpressionTree tree, VisitorState state) {
switch (tree.getKind()) {
case METHOD_INVOCATION:
return state.getSourceForNode(((MethodInvocationTree) tree).getMethodSelect());
case NEW_CLASS:
return "new " + state.getSourceForNode(((NewClassTree) tree).getIdentifier());
default:
throw new AssertionError();
}
}
/** Finds the path to potential fields that we might want to strongly type. */
// TODO(b/147006492): Consider extracting a helper to find all fields that match a Matcher.
private ImmutableMap<VarSymbol, TreePath> findPathToPotentialFields(
VisitorState state, Set<Type> potentialTypes) {
ImmutableMap.Builder<VarSymbol, TreePath> fields = ImmutableMap.builder();
bugChecker().new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitVariable(VariableTree variableTree, Void unused) {
VarSymbol symbol = getSymbol(variableTree);
Type type = state.getTypes().unboxedTypeOrType(symbol.type);
if (symbol.getKind() == ElementKind.FIELD
&& canBeRemoved(symbol)
&& isConsideredFinal(symbol)
&& variableTree.getInitializer() != null
&& potentialTypes.stream()
.anyMatch(potentialType -> isSameType(type, potentialType, state))
&& !bugChecker().isSuppressed(variableTree, state)) {
fields.put(symbol, getCurrentPath());
}
return super.visitVariable(variableTree, null);
}
}.scan(state.getPath().getCompilationUnit(), null);
return fields.buildOrThrow();
}
}
| 9,418
| 37.921488
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ChainingConstructorIgnoresParameter.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.fixes.SuggestedFix.replace;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.hasIdentifier;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.sun.source.tree.Tree.Kind.IDENTIFIER;
import static java.util.Collections.unmodifiableList;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import java.util.List;
import java.util.Map;
/**
* Checks, if two constructors in a class both accept {@code Foo foo} and one calls the other, that
* the caller passes {@code foo} as a parameter. The goal is to catch copy-paste errors:
*
* <pre>
* MissileLauncher(Location target, boolean askForConfirmation) {
* ...
* }
* MissileLauncher(Location target) {
* this(target, false);
* }
* MissileLauncher(boolean askForConfirmation) {
* this(TEST_TARGET, <b>false</b>); // should be askForConfirmation
* }</pre>
*
* @author cpovirk@google.com (Chris Povirk)
*/
@BugPattern(
severity = ERROR,
summary =
"The called constructor accepts a parameter with the same name and type as one of "
+ "its caller's parameters, but its caller doesn't pass that parameter to it. It's "
+ "likely that it was intended to.")
public final class ChainingConstructorIgnoresParameter extends BugChecker
implements CompilationUnitTreeMatcher, MethodInvocationTreeMatcher, MethodTreeMatcher {
private final Map<MethodSymbol, List<VariableTree>> paramTypesForMethod = newHashMap();
private final ListMultimap<MethodSymbol, Caller> callersToEvaluate = ArrayListMultimap.create();
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
/*
* Clear the collections to save memory. (I wonder if it also helps to handle weird cases when a
* class has multiple definitions. But I would expect for multiple definitions within the same
* compiler invocation to cause deeper problems.)
*/
paramTypesForMethod.clear();
callersToEvaluate.clear(); // should have already been cleared
return NO_MATCH;
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
MethodSymbol symbol = getSymbol(tree);
// TODO(cpovirk): determine whether anyone might be calling Foo.this()
if (!isIdentifierWithName(tree.getMethodSelect(), "this")) {
return NO_MATCH;
}
callersToEvaluate.put(symbol, new Caller(tree, state));
return evaluateCallers(symbol);
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
MethodSymbol symbol = getSymbol(tree);
if (!symbol.isConstructor()) {
return NO_MATCH;
}
paramTypesForMethod.put(symbol, unmodifiableList(tree.getParameters()));
return evaluateCallers(symbol);
}
private Description evaluateCallers(MethodSymbol symbol) {
List<VariableTree> paramTypes = paramTypesForMethod.get(symbol);
if (paramTypes == null) {
// We haven't seen the declaration yet. We'll evaluate the call when we do.
return NO_MATCH;
}
for (Caller caller : callersToEvaluate.removeAll(symbol)) {
VisitorState state = caller.state;
MethodInvocationTree invocation = caller.tree;
MethodTree callerConstructor = state.findEnclosing(MethodTree.class);
if (callerConstructor == null) {
continue; // impossible, at least in compilable code?
}
Map<String, Type> availableParams = indexTypeByName(callerConstructor.getParameters());
/*
* TODO(cpovirk): Better handling of varargs: If the last parameter type is varargs and it is
* called as varargs (rather than by passing an array), then rewrite the parameter types to
* (p0, p1, ..., p[n-2], p[n-1] = element type of varargs parameter if an argument is
* supplied, p[n] = ditto, etc.). For now, we settle for not crashing in the face of a
* mismatch between the number of parameters declared and the number supplied.
*
* (Use MethodSymbol.isVarArgs.)
*/
for (int i = 0; i < paramTypes.size() && i < invocation.getArguments().size(); i++) {
VariableTree formalParam = paramTypes.get(i);
String formalParamName = formalParam.getName().toString();
Type formalParamType = getType(formalParam.getType());
Type availableParamType = availableParams.get(formalParamName);
ExpressionTree actualParam = invocation.getArguments().get(i);
if (
/*
* The caller has no param of this type. (Or if it did, we couldn't determine the type.
* Does that ever happen?) If the param doesn't exist, the caller can't be failing to
* pass it.
*/
availableParamType == null
/*
* We couldn't determine the type of the formal parameter. (Does this ever happen?)
*/
|| formalParamType == null
/*
* The caller is passing the expected parameter (or "ImmutableList.copyOf(parameter),"
* "new File(parameter)," etc.).
*/
|| referencesIdentifierWithName(formalParamName, actualParam, state)) {
continue;
}
if (state.getTypes().isAssignable(availableParamType, formalParamType)) {
reportMatch(invocation, state, actualParam, formalParamName);
}
/*
* If formal parameter is of an incompatible type, the caller might in theory still intend
* to pass a derived expression. For example, "Foo(String file)" might intend to call
* "Foo(File file)" by passing "new File(file)." If this comes up in practice, we could
* provide the dummy suggested fix "someExpression(formalParamName)." However, my research
* suggests that this will rarely if ever be what the user wants.
*/
}
}
// All matches are reported through reportMatch calls instead of return values.
return NO_MATCH;
}
private static Map<String, Type> indexTypeByName(List<? extends VariableTree> parameters) {
Map<String, Type> result = newHashMap();
for (VariableTree parameter : parameters) {
result.put(parameter.getName().toString(), getType(parameter.getType()));
}
return result;
}
private void reportMatch(
Tree diagnosticPosition, VisitorState state, Tree toReplace, String replaceWith) {
state.reportMatch(describeMatch(diagnosticPosition, replace(toReplace, replaceWith)));
}
private static boolean referencesIdentifierWithName(
String name, ExpressionTree tree, VisitorState state) {
Matcher<IdentifierTree> identifierMatcher =
new Matcher<IdentifierTree>() {
@Override
public boolean matches(IdentifierTree tree, VisitorState state) {
return isIdentifierWithName(tree, name);
}
};
return hasIdentifier(identifierMatcher).matches(tree, state);
}
private static boolean isIdentifierWithName(ExpressionTree tree, String name) {
return tree.getKind() == IDENTIFIER && ((IdentifierTree) tree).getName().contentEquals(name);
}
private static final class Caller {
final MethodInvocationTree tree;
final VisitorState state;
Caller(MethodInvocationTree tree, VisitorState state) {
this.tree = tree;
this.state = state;
}
}
}
| 9,132
| 39.955157
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TryFailRefactoring.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.REFACTORING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.expressionStatement;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.sun.source.tree.Tree.Kind.UNION_TYPE;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.TryTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.JUnitMatchers;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TryTree;
import java.util.List;
import java.util.Optional;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "Prefer assertThrows to try/fail", severity = SUGGESTION, tags = REFACTORING)
public class TryFailRefactoring extends BugChecker implements TryTreeMatcher {
private static final Matcher<StatementTree> FAIL_METHOD =
expressionStatement(staticMethod().anyClass().named("fail"));
@Override
public Description matchTry(TryTree tree, VisitorState state) {
MethodTree enclosingMethod = state.findEnclosing(MethodTree.class);
if (enclosingMethod == null || !JUnitMatchers.TEST_CASE.matches(enclosingMethod, state)) {
return NO_MATCH;
}
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 = body.subList(0, body.size() - 1);
List<? extends ExpressionTree> failArgs =
((MethodInvocationTree) ((ExpressionStatementTree) getLast(body)).getExpression())
.getArguments();
Optional<Tree> message = Optional.ofNullable(Iterables.get(failArgs, 0, null));
Optional<Fix> fix =
AssertThrowsUtils.tryFailToAssertThrows(tree, throwingStatements, message, state);
return fix.map(f -> describeMatch(tree, f)).orElse(NO_MATCH);
}
}
| 3,807
| 43.8
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ThreadLocalUsage.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.method.MethodMatchers.constructor;
import static com.google.errorprone.predicates.TypePredicates.isDescendantOf;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.hasDirectAnnotationWithSimpleName;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Streams;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "ThreadLocals should be stored in static fields", severity = WARNING)
public class ThreadLocalUsage extends BugChecker implements NewClassTreeMatcher {
private static final Matcher<ExpressionTree> NEW_THREAD_LOCAL =
constructor().forClass(isDescendantOf("java.lang.ThreadLocal"));
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (!NEW_THREAD_LOCAL.matches(tree, state)) {
return NO_MATCH;
}
if (wellKnownTypeArgument(tree, state)) {
return NO_MATCH;
}
Tree parent = state.getPath().getParentPath().getLeaf();
if (!(parent instanceof VariableTree)) {
// If the ThreadLocal is created outside of a field we can't easily make assumptions about its
// scope.
return NO_MATCH;
}
VarSymbol sym = getSymbol((VariableTree) parent);
if (sym.isStatic()) {
return NO_MATCH;
}
if (Streams.stream(state.getPath())
.filter(ClassTree.class::isInstance)
.map(ClassTree.class::cast)
.anyMatch(
c -> {
if (hasDirectAnnotationWithSimpleName(getSymbol(c), "Singleton")) {
return true;
}
Type scopeType = COM_GOOGLE_INJECT_SCOPE.get(state);
if (isSubtype(getType(c), scopeType, state)) {
return true;
}
return false;
})) {
// The instance X thread issue doesn't apply if there's only one instance.
return NO_MATCH;
}
return describeMatch(tree);
}
private static final ImmutableSet<String> WELL_KNOWN_TYPES =
ImmutableSet.of(
"java.lang.String",
"java.lang.Boolean",
"java.lang.Long",
"java.lang.Integer",
"java.lang.Short",
"java.lang.Character",
"java.lang.Float",
"java.lang.Double");
/** Ignore some common ThreadLocal type arguments that are fine to have per-instance copies of. */
private static boolean wellKnownTypeArgument(NewClassTree tree, VisitorState state) {
Type type = getType(tree);
if (type == null) {
return false;
}
type = state.getTypes().asSuper(type, JAVA_LANG_THREADLOCAL.get(state));
if (type == null) {
return false;
}
if (type.getTypeArguments().isEmpty()) {
return false;
}
Type argType = getOnlyElement(type.getTypeArguments());
if (WELL_KNOWN_TYPES.contains(argType.asElement().getQualifiedName().toString())) {
return true;
}
if (isSubtype(argType, JAVA_TEXT_DATEFORMAT.get(state), state)) {
return true;
}
return false;
}
private static final Supplier<Symbol> JAVA_LANG_THREADLOCAL =
VisitorState.memoize(state -> state.getSymbolFromString("java.lang.ThreadLocal"));
private static final Supplier<Type> COM_GOOGLE_INJECT_SCOPE =
VisitorState.memoize(state -> state.getTypeFromString("com.google.inject.Scope"));
private static final Supplier<Type> JAVA_TEXT_DATEFORMAT =
VisitorState.memoize(state -> state.getTypeFromString("java.text.DateFormat"));
}
| 5,211
| 37.895522
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LiteEnumValueOf.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.predicates.TypePredicates.allOf;
import static com.google.errorprone.predicates.TypePredicates.isDescendantOf;
import static com.google.errorprone.predicates.TypePredicates.not;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
/**
* Points out if #valueOf() is called on a Protocol Buffer Enum.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary =
"Instead of converting enums to string and back, its numeric value should be used instead"
+ " as it is the stable part of the protocol defined by the enum.",
severity = WARNING)
public class LiteEnumValueOf extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> PROTO_MSG_VALUE_OF_MATCHER =
staticMethod()
.onClass(
allOf(
isDescendantOf("com.google.protobuf.Internal.EnumLite"),
not(isDescendantOf("com.google.protobuf.ProtocolMessageEnum")),
not(isDescendantOf("com.google.protobuf.AbstractMessageLite.InternalOneOfEnum"))))
.named("valueOf")
.withParameters("java.lang.String");
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState state) {
if (!PROTO_MSG_VALUE_OF_MATCHER.matches(methodInvocationTree, state)) {
return Description.NO_MATCH;
}
// AutoValue Parcelable generated code uses the API in #createForParcel implementation.
// We explicitly suppress the matches.
if (ASTHelpers.getGeneratedBy(state)
.contains("com.ryanharter.auto.value.parcel.AutoValueParcelExtension")) {
return Description.NO_MATCH;
}
return describeMatch(methodInvocationTree);
}
}
| 2,921
| 40.15493
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LenientFormatStringValidation.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static java.lang.String.format;
import static java.util.Collections.nCopies;
import static java.util.stream.Collectors.joining;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MethodInvocationTree;
import java.util.regex.Pattern;
/** A BugPattern; see the summary. */
@BugPattern(
severity = ERROR,
summary =
"The number of arguments provided to lenient format methods should match the positional"
+ " specifiers.")
public final class LenientFormatStringValidation extends BugChecker
implements MethodInvocationTreeMatcher {
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
for (LenientFormatMethod method : METHODS) {
if (!method.matcher().matches(tree, state)) {
continue;
}
var args = tree.getArguments();
if (args.size() <= method.formatStringPosition()) {
continue;
}
ExpressionTree formatStringArgument = args.get(method.formatStringPosition());
Object formatString = ASTHelpers.constValue(formatStringArgument);
if (!(formatString instanceof String)) {
continue;
}
int expected = occurrences((String) formatString, "%s");
int actual = args.size() - method.formatStringPosition() - 1;
if (expected == actual) {
continue;
}
var builder =
buildDescription(tree)
.setMessage(format("Expected %s positional arguments, but saw %s", expected, actual));
if (expected < actual) {
String extraArgs =
nCopies(actual - expected, "%s").stream().collect(joining(", ", " (", ")"));
int endPos = state.getEndPosition(formatStringArgument);
builder.addFix(
formatStringArgument instanceof LiteralTree
? SuggestedFix.replace(endPos - 1, endPos, extraArgs + "\"")
: SuggestedFix.postfixWith(formatStringArgument, format("+ \"%s\"", extraArgs)));
}
return builder.build();
}
return NO_MATCH;
}
private static int occurrences(String haystack, String needle) {
int count = 0;
int start = 0;
while (true) {
start = haystack.indexOf(needle, start);
if (start == -1) {
return count;
}
count++;
start += needle.length();
}
}
// TODO(ghm): Consider replacing this with an annotation-based approach (@LenientFormatString?)
private static final ImmutableList<LenientFormatMethod> METHODS =
ImmutableList.of(
LenientFormatMethod.create(
staticMethod()
.onClass("com.google.common.base.Preconditions")
.withNameMatching(Pattern.compile("^check.*")),
1),
LenientFormatMethod.create(
staticMethod()
.onClass("com.google.common.base.Verify")
.withNameMatching(Pattern.compile("^verify.*")),
1),
LenientFormatMethod.create(
staticMethod().onClass("com.google.common.base.Strings").named("lenientFormat"), 0),
LenientFormatMethod.create(
staticMethod().onClass("com.google.common.truth.Truth").named("assertWithMessage"),
0),
LenientFormatMethod.create(
instanceMethod().onDescendantOf("com.google.common.truth.Subject").named("check"), 0),
LenientFormatMethod.create(
instanceMethod()
.onDescendantOf("com.google.common.truth.StandardSubjectBuilder")
.named("withMessage"),
0));
@AutoValue
abstract static class LenientFormatMethod {
abstract Matcher<ExpressionTree> matcher();
/** Position of the format string; we assume every argument afterwards is a format argument. */
abstract int formatStringPosition();
public static LenientFormatMethod create(
Matcher<ExpressionTree> matcher, int formatStringPosition) {
return new AutoValue_LenientFormatStringValidation_LenientFormatMethod(
matcher, formatStringPosition);
}
}
}
| 5,510
| 38.364286
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryTestMethodPrefix.java
|
/*
* Copyright 2023 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.base.Ascii.toLowerCase;
import static com.google.errorprone.fixes.SuggestedFixes.renameMethod;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.JUnitMatchers.JUNIT4_TEST_ANNOTATION;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import java.util.HashSet;
/** See the summary. */
@BugPattern(
severity = SeverityLevel.WARNING,
summary =
"A `test` prefix for a JUnit4 test is redundant, and a holdover from JUnit3. The `@Test`"
+ " annotation makes it clear it's a test.")
public final class UnnecessaryTestMethodPrefix extends BugChecker
implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
var fixBuilder = SuggestedFix.builder();
var sites = new HashSet<Tree>();
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitMethod(MethodTree tree, Void unused) {
if (!TEST.matches(tree, state)) {
return super.visitMethod(tree, unused);
}
String name = tree.getName().toString();
if (!name.startsWith("test") || name.equals("test")) {
return super.visitMethod(tree, unused);
}
var newName = toLowerCase(name.charAt(4)) + name.substring(5);
fixBuilder.merge(renameMethod(tree, newName, state));
sites.add(tree);
return super.visitMethod(tree, unused);
}
}.scan(state.getPath(), null);
var fix = fixBuilder.build();
for (Tree site : sites) {
state.reportMatch(describeMatch(site, fix));
}
return NO_MATCH;
}
private static final Matcher<Tree> TEST = hasAnnotation(JUNIT4_TEST_ANNOTATION);
}
| 2,944
| 37.246753
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AnnotateFormatMethod.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.MoreCollectors.toOptional;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.FRAGILE_CODE;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.FormatMethod;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
/**
* Detects occurrences of pairs of parameters being passed straight through to {@link String#format}
* from a method not annotated with {@link FormatMethod}.
*
* @author ghm@google.com (Graeme Morgan)
*/
@BugPattern(
summary =
"This method passes a pair of parameters through to String.format, but the enclosing"
+ " method wasn't annotated @FormatMethod. Doing so gives compile-time rather than"
+ " run-time protection against malformed format strings.",
tags = FRAGILE_CODE,
severity = WARNING)
public final class AnnotateFormatMethod extends BugChecker implements MethodInvocationTreeMatcher {
private static final String REORDER =
" (The parameters of this method would need to be reordered to make the format string and "
+ "arguments the final parameters before the @FormatMethod annotation can be used.)";
private static final Matcher<ExpressionTree> STRING_FORMAT =
staticMethod().onClass("java.lang.String").named("format");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!STRING_FORMAT.matches(tree, state)) {
return Description.NO_MATCH;
}
if (tree.getArguments().size() != 2) {
return Description.NO_MATCH;
}
VarSymbol formatString = asSymbol(tree.getArguments().get(0));
VarSymbol formatArgs = asSymbol(tree.getArguments().get(1));
if (formatString == null || formatArgs == null) {
return Description.NO_MATCH;
}
MethodTree enclosingMethod = ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class);
if (enclosingMethod == null
|| !ASTHelpers.getSymbol(enclosingMethod).isVarArgs()
|| ASTHelpers.hasAnnotation(enclosingMethod, FormatMethod.class, state)) {
return Description.NO_MATCH;
}
List<? extends VariableTree> enclosingParameters = enclosingMethod.getParameters();
Optional<? extends VariableTree> formatParameter =
findParameterWithSymbol(enclosingParameters, formatString);
Optional<? extends VariableTree> argumentsParameter =
findParameterWithSymbol(enclosingParameters, formatArgs);
if (!formatParameter.isPresent() || !argumentsParameter.isPresent()) {
return Description.NO_MATCH;
}
if (!argumentsParameter.get().equals(getLast(enclosingParameters))) {
return Description.NO_MATCH;
}
// We can only generate a fix if the format string is the penultimate parameter.
boolean fixable =
formatParameter.get().equals(enclosingParameters.get(enclosingParameters.size() - 2));
return buildDescription(enclosingMethod)
.setMessage(fixable ? message() : (message() + REORDER))
.build();
}
private static Optional<? extends VariableTree> findParameterWithSymbol(
List<? extends VariableTree> parameters, Symbol symbol) {
return parameters.stream()
.filter(parameter -> symbol.equals(ASTHelpers.getSymbol(parameter)))
.collect(toOptional());
}
@Nullable
private static VarSymbol asSymbol(ExpressionTree tree) {
Symbol symbol = ASTHelpers.getSymbol(tree);
return symbol instanceof VarSymbol ? (VarSymbol) symbol : null;
}
}
| 4,929
| 41.869565
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AbstractJUnit4InitMethodNotRun.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.matchers.JUnitMatchers.isJUnit4TestClass;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.enclosingClass;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.hasAnnotationOnAnyOverriddenMethod;
import static com.google.errorprone.matchers.Matchers.not;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.tools.javac.code.Symbol;
import java.io.Serializable;
import java.util.List;
import javax.lang.model.element.Modifier;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Base class for JUnit4SetUp/TearDown not run. This will take care of the nitty-gritty about
* replacing @After with @Before, adding @Before on unannotated methods, making them public if
* necessary, fixing the imports of other @Before, etc.
*
* @author glorioso@google.com
*/
abstract class AbstractJUnit4InitMethodNotRun extends BugChecker implements MethodTreeMatcher {
private static final String JUNIT_TEST = "org.junit.Test";
/**
* Returns a matcher that selects which methods this matcher applies to (e.g. public void setUp()
* without @Before/@BeforeClass annotation)
*/
protected abstract Matcher<MethodTree> methodMatcher();
/**
* Returns the fully qualified class name of the annotation this bugpattern should apply to
* matched methods.
*
* <p>If another annotation is on the method that has the same name, the import will be replaced
* with the appropriate one (e.g.: com.example.Before becomes org.junit.Before)
*/
protected abstract String correctAnnotation();
/**
* Returns a collection of 'before-and-after' pairs of annotations that should be replaced on
* these methods.
*
* <p>If this method matcher finds a method annotated with {@link
* AnnotationReplacements#badAnnotation}, instead of applying {@link #correctAnnotation()},
* instead replace it with {@link AnnotationReplacements#goodAnnotation}
*/
protected abstract List<AnnotationReplacements> annotationReplacements();
/**
* Matches if all of the following conditions are true: 1) The method matches {@link
* #methodMatcher()}, (looks like setUp() or tearDown(), and none of the overrides in the
* hierarchy of the method have the appropriate @Before or @After annotations) 2) The method is
* not annotated with @Test 3) The enclosing class has an @RunWith annotation and does not extend
* TestCase. This marks that the test is intended to run with JUnit 4.
*/
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
boolean matches =
allOf(
methodMatcher(),
not(hasAnnotationOnAnyOverriddenMethod(JUNIT_TEST)),
enclosingClass(isJUnit4TestClass))
.matches(methodTree, state);
if (!matches) {
return Description.NO_MATCH;
}
// For each annotationReplacement, replace the first annotation that matches. If any of them
// matches, don't try and do the rest of the work.
Description description;
for (AnnotationReplacements replacement : annotationReplacements()) {
description =
tryToReplaceAnnotation(
methodTree, state, replacement.badAnnotation, replacement.goodAnnotation);
if (description != null) {
return description;
}
}
// Search for another @Before annotation on the method and replace the import
// if we find one
String correctAnnotation = correctAnnotation();
String unqualifiedClassName = getUnqualifiedClassName(correctAnnotation);
for (AnnotationTree annotationNode : methodTree.getModifiers().getAnnotations()) {
Symbol annoSymbol = ASTHelpers.getSymbol(annotationNode);
if (annoSymbol.getSimpleName().contentEquals(unqualifiedClassName)) {
SuggestedFix.Builder suggestedFix =
SuggestedFix.builder()
.removeImport(annoSymbol.getQualifiedName().toString())
.addImport(correctAnnotation);
makeProtectedPublic(methodTree, state, suggestedFix);
return describeMatch(annotationNode, suggestedFix.build());
}
}
// Add correctAnnotation() to the unannotated method
// (and convert protected to public if it is)
SuggestedFix.Builder suggestedFix = SuggestedFix.builder().addImport(correctAnnotation);
makeProtectedPublic(methodTree, state, suggestedFix);
suggestedFix.prefixWith(methodTree, "@" + unqualifiedClassName + "\n");
return describeMatch(methodTree, suggestedFix.build());
}
private static void makeProtectedPublic(
MethodTree methodTree, VisitorState state, SuggestedFix.Builder suggestedFix) {
if (Matchers.<MethodTree>hasModifier(Modifier.PROTECTED).matches(methodTree, state)) {
ModifiersTree modifiers = methodTree.getModifiers();
CharSequence modifiersSource = state.getSourceForNode(modifiers);
suggestedFix.replace(
modifiers, modifiersSource.toString().replaceFirst("protected", "public"));
}
}
private @Nullable Description tryToReplaceAnnotation(
MethodTree methodTree, VisitorState state, String badAnnotation, String goodAnnotation) {
String finalName = getUnqualifiedClassName(goodAnnotation);
if (hasAnnotation(badAnnotation).matches(methodTree, state)) {
AnnotationTree annotationTree = findAnnotation(methodTree, state, badAnnotation);
return describeMatch(
annotationTree,
SuggestedFix.builder()
.addImport(goodAnnotation)
.replace(annotationTree, "@" + finalName)
.build());
} else {
return null;
}
}
private static String getUnqualifiedClassName(String goodAnnotation) {
return goodAnnotation.substring(goodAnnotation.lastIndexOf(".") + 1);
}
private static AnnotationTree findAnnotation(
MethodTree methodTree, VisitorState state, String annotationName) {
AnnotationTree annotationNode = null;
for (AnnotationTree annotation : methodTree.getModifiers().getAnnotations()) {
if (ASTHelpers.getSymbol(annotation).equals(state.getSymbolFromString(annotationName))) {
annotationNode = annotation;
}
}
return annotationNode;
}
protected static class AnnotationReplacements implements Serializable {
private final String goodAnnotation;
private final String badAnnotation;
protected AnnotationReplacements(String badAnnotation, String goodAnnotation) {
this.goodAnnotation = goodAnnotation;
this.badAnnotation = badAnnotation;
}
}
}
| 7,766
| 41.211957
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JdkObsolete.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.util.Position;
import java.util.Optional;
import javax.annotation.Nullable;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "Suggests alternatives to obsolete JDK classes.", severity = WARNING)
public class JdkObsolete extends BugChecker
implements NewClassTreeMatcher, ClassTreeMatcher, MemberReferenceTreeMatcher {
static class Obsolete {
final String qualifiedName;
final String message;
Obsolete(String qualifiedName, String message) {
this.qualifiedName = qualifiedName;
this.message = message;
}
String qualifiedName() {
return qualifiedName;
}
String message() {
return message;
}
Optional<Fix> fix(Tree tree, VisitorState state) {
return Optional.empty();
}
}
static final ImmutableMap<String, Obsolete> OBSOLETE =
ImmutableList.of(
new Obsolete(
"java.util.LinkedList",
"It is very rare for LinkedList to out-perform ArrayList or ArrayDeque. Avoid it"
+ " unless you're willing to invest a lot of time into benchmarking. Caveat:"
+ " LinkedList supports null elements, but ArrayDeque does not.") {
@Override
Optional<Fix> fix(Tree tree, VisitorState state) {
return linkedListFix(tree, state);
}
},
new Obsolete(
"java.util.Vector",
"Vector performs synchronization that is usually unnecessary; prefer ArrayList."),
new Obsolete(
"java.util.Hashtable",
"Hashtable performs synchronization this is usually unnecessary; prefer"
+ " LinkedHashMap."),
new Obsolete(
"java.util.Stack",
"Stack is a nonstandard class that predates the Java Collections Framework;"
+ " prefer ArrayDeque. Note that the Stack methods push/pop/peek correspond"
+ " to the Deque methods addFirst/removeFirst/peekFirst."),
new Obsolete(
"java.lang.StringBuffer",
"StringBuffer performs synchronization that is usually unnecessary;"
+ " prefer StringBuilder.") {
@Override
Optional<Fix> fix(Tree tree, VisitorState state) {
return stringBufferFix(state);
}
},
new Obsolete(
"java.util.SortedSet", "SortedSet was replaced by NavigableSet in Java 6."),
new Obsolete(
"java.util.SortedMap", "SortedMap was replaced by NavigableMap in Java 6."),
new Obsolete(
"java.util.Dictionary",
"Dictionary is a nonstandard class that predates the Java Collections Framework;"
+ " use LinkedHashMap."),
new Obsolete(
"java.util.Enumeration", "Enumeration is an ancient precursor to Iterator."))
.stream()
.collect(toImmutableMap(Obsolete::qualifiedName, x -> x));
static final Matcher<ExpressionTree> MATCHER_STRINGBUFFER =
anyOf(
// a pre-JDK-8039124 concession
instanceMethod()
.onExactClass("java.util.regex.Matcher")
.named("appendTail")
.withParameters("java.lang.StringBuffer"),
instanceMethod()
.onExactClass("java.util.regex.Matcher")
.named("appendReplacement")
.withParameters("java.lang.StringBuffer", "java.lang.String"),
// TODO(cushon): back this out if https://github.com/google/re2j/pull/44 happens
instanceMethod()
.onExactClass("com.google.re2j.Matcher")
.named("appendTail")
.withParameters("java.lang.StringBuffer"),
instanceMethod()
.onExactClass("com.google.re2j.Matcher")
.named("appendReplacement")
.withParameters("java.lang.StringBuffer", "java.lang.String"));
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
MethodSymbol constructor = ASTHelpers.getSymbol(tree);
Symbol owner = constructor.owner;
Description description =
describeIfObsolete(
// don't refactor anonymous implementations of LinkedList
tree.getClassBody() == null ? tree.getIdentifier() : null,
owner.name.isEmpty()
? state.getTypes().directSupertypes(owner.asType())
: ImmutableList.of(owner.asType()),
state);
if (description == NO_MATCH) {
return NO_MATCH;
}
if (owner.getQualifiedName().contentEquals("java.lang.StringBuffer")) {
boolean[] found = {false};
new TreeScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
if (MATCHER_STRINGBUFFER.matches(tree, state)) {
found[0] = true;
}
return null;
}
}.scan(state.getPath().getCompilationUnit(), null);
if (found[0]) {
return NO_MATCH;
}
}
return description;
}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
Tree parent = state.getPath().getParentPath().getLeaf();
if (parent instanceof NewClassTree && tree.equals(((NewClassTree) parent).getClassBody())) {
// don't double-report anonymous implementations of obsolete interfaces
return NO_MATCH;
}
ClassSymbol symbol = ASTHelpers.getSymbol(tree);
return describeIfObsolete(null, state.getTypes().directSupertypes(symbol.asType()), state);
}
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
Type type = ASTHelpers.getType(tree.getQualifierExpression());
if (type == null) {
return NO_MATCH;
}
return describeIfObsolete(tree.getQualifierExpression(), ImmutableList.of(type), state);
}
private Description describeIfObsolete(
@Nullable Tree tree, Iterable<Type> types, VisitorState state) {
for (Type type : types) {
Obsolete obsolete = OBSOLETE.get(type.asElement().getQualifiedName().toString());
if (obsolete == null) {
continue;
}
if (shouldSkip(state, type)) {
continue;
}
Description.Builder description =
buildDescription(state.getPath().getLeaf()).setMessage(obsolete.message());
if (tree != null) {
obsolete.fix(tree, state).ifPresent(description::addFix);
}
return description.build();
}
return NO_MATCH;
}
@Nullable
private static Type getMethodOrLambdaReturnType(VisitorState state) {
for (Tree tree : state.getPath()) {
switch (tree.getKind()) {
case LAMBDA_EXPRESSION:
return state.getTypes().findDescriptorType(ASTHelpers.getType(tree)).getReturnType();
case METHOD:
return ASTHelpers.getType(tree).getReturnType();
case CLASS:
return null;
default: // fall out
}
}
return null;
}
@Nullable
static Type getTargetType(VisitorState state) {
Tree parent = state.getPath().getParentPath().getLeaf();
Type type;
if (parent instanceof VariableTree || parent instanceof AssignmentTree) {
type = ASTHelpers.getType(parent);
} else if (parent instanceof ReturnTree || parent instanceof LambdaExpressionTree) {
type = getMethodOrLambdaReturnType(state);
} else if (parent instanceof MethodInvocationTree) {
MethodInvocationTree tree = (MethodInvocationTree) parent;
int idx = tree.getArguments().indexOf(state.getPath().getLeaf());
if (idx == -1) {
return null;
}
Type methodType = ASTHelpers.getType(tree.getMethodSelect());
if (idx >= methodType.getParameterTypes().size()) {
return null;
}
return methodType.getParameterTypes().get(idx);
} else {
return null;
}
Tree tree = state.getPath().getLeaf();
if (tree instanceof MemberReferenceTree) {
type = state.getTypes().findDescriptorType(ASTHelpers.getType(tree)).getReturnType();
}
return type;
}
// rewrite e.g. `List<Object> xs = new LinkedList<>()` -> `... = new ArrayList<>()`
private static Optional<Fix> linkedListFix(Tree tree, VisitorState state) {
Type type = getTargetType(state);
if (type == null) {
return Optional.empty();
}
Types types = state.getTypes();
for (String replacement : ImmutableList.of("java.util.ArrayList", "java.util.ArrayDeque")) {
Symbol sym = state.getSymbolFromString(replacement);
if (sym == null) {
continue;
}
if (types.isAssignable(types.erasure(sym.asType()), types.erasure(type))) {
SuggestedFix.Builder fix = SuggestedFix.builder();
while (tree instanceof ParameterizedTypeTree) {
tree = ((ParameterizedTypeTree) tree).getType();
}
fix.replace(tree, SuggestedFixes.qualifyType(state, fix, sym));
return Optional.of(fix.build());
}
}
return Optional.empty();
}
// Rewrite StringBuffers that are immediately assigned to a variable which does not escape the
// current method.
private static Optional<Fix> stringBufferFix(VisitorState state) {
Tree tree = state.getPath().getLeaf();
// expect `new StringBuffer()`
if (!(tree instanceof NewClassTree)) {
return Optional.empty();
}
// expect e.g. `StringBuffer sb = new StringBuffer();`
NewClassTree newClassTree = (NewClassTree) tree;
Tree parent = state.getPath().getParentPath().getLeaf();
if (!(parent instanceof VariableTree)) {
return Optional.empty();
}
VariableTree varTree = (VariableTree) parent;
VarSymbol varSym = ASTHelpers.getSymbol(varTree);
TreePath methodPath = findEnclosingMethod(state);
if (methodPath == null) {
return Optional.empty();
}
// Expect all uses to be of the form `sb.<method>` (append, toString, etc.)
// We don't want to refactor StringBuffers that escape the current method.
// Use an array to get a boxed boolean that we can update in the anonymous class.
boolean[] escape = {false};
new TreePathScanner<Void, Void>() {
@Override
public Void visitIdentifier(IdentifierTree tree, Void unused) {
if (varSym.equals(ASTHelpers.getSymbol(tree))) {
Tree parent = getCurrentPath().getParentPath().getLeaf();
if (parent == varTree) {
// the use of the variable in its declaration gets a pass
return null;
}
// the LHS of a select (e.g. in `sb.append(...)`) does not escape
if (!(parent instanceof MemberSelectTree)
|| ((MemberSelectTree) parent).getExpression() != tree) {
escape[0] = true;
}
}
return null;
}
}.scan(methodPath, null);
if (escape[0]) {
return Optional.empty();
}
SuggestedFix.Builder fix =
SuggestedFix.builder().replace(newClassTree.getIdentifier(), "StringBuilder");
if (ASTHelpers.getStartPosition(varTree.getType()) != Position.NOPOS) {
// If the variable is declared with `var`, there's no declaration type to change
fix = fix.replace(varTree.getType(), "StringBuilder");
}
return Optional.of(fix.build());
}
@Nullable
private static TreePath findEnclosingMethod(VisitorState state) {
TreePath path = state.getPath();
while (path != null) {
switch (path.getLeaf().getKind()) {
case METHOD:
return path;
case CLASS:
case LAMBDA_EXPRESSION:
return null;
default: // fall out
}
path = path.getParentPath();
}
return null;
}
private boolean shouldSkip(VisitorState state, Type type) {
TreePath path = findEnclosingMethod(state);
if (path == null) {
return false;
}
MethodTree enclosingMethod = (MethodTree) path.getLeaf();
if (enclosingMethod == null) {
return false;
}
return implementingObsoleteMethod(enclosingMethod, state, type)
|| mockingObsoleteMethod(enclosingMethod, state, type);
}
private static final Matcher<ExpressionTree> MOCKITO_MATCHER =
staticMethod().onClass("org.mockito.Mockito").named("when");
/** Allow mocking APIs that return obsolete types. */
private boolean mockingObsoleteMethod(MethodTree enclosingMethod, VisitorState state, Type type) {
// mutable boolean to return result from visitor
boolean[] found = {false};
enclosingMethod.accept(
new TreeScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void unused) {
if (found[0]) {
return null;
}
if (MOCKITO_MATCHER.matches(node, state)) {
Type stubber = ASTHelpers.getReturnType(node);
if (!stubber.getTypeArguments().isEmpty()
&& ASTHelpers.isSameType(
getOnlyElement(stubber.getTypeArguments()), type, state)) {
found[0] = true;
}
}
return super.visitMethodInvocation(node, null);
}
},
null);
return found[0];
}
/** Allow creating obsolete types when overriding a method with an obsolete return type. */
private static boolean implementingObsoleteMethod(
MethodTree enclosingMethod, VisitorState state, Type type) {
MethodSymbol method = ASTHelpers.getSymbol(enclosingMethod);
if (ASTHelpers.findSuperMethods(method, state.getTypes()).isEmpty()) {
// not an override
return false;
}
if (!ASTHelpers.isSameType(method.getReturnType(), type, state)) {
return false;
}
return true;
}
}
| 16,860
| 38.211628
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InvalidTimeZoneID.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import java.util.TimeZone;
import java.util.regex.Pattern;
/**
* @author awturner@google.com (Andy Turner)
*/
@BugPattern(
summary =
"Invalid time zone identifier. TimeZone.getTimeZone(String) will silently return GMT"
+ " instead of the time zone you intended.",
severity = ERROR)
public class InvalidTimeZoneID extends BugChecker implements MethodInvocationTreeMatcher {
private static final ImmutableSet<String> AVAILABLE_IDS =
ImmutableSet.copyOf(TimeZone.getAvailableIDs());
private static final Matcher<ExpressionTree> METHOD_MATCHER =
MethodMatchers.staticMethod()
.onClass("java.util.TimeZone")
.named("getTimeZone")
.withParameters("java.lang.String");
// https://docs.oracle.com/javase/8/docs/api/java/util/TimeZone.html
// "a custom time zone ID can be specified to produce a TimeZone".
// 0-23, with optional leading zero.
private static final String HOURS_PATTERN = "([0-9]|[0-1][0-9]|2[0-3])";
// 00-59, optional.
private static final String MINUTES_PATTERN = "(?:[0-5][0-9])?";
private static final Pattern CUSTOM_ID_PATTERN =
Pattern.compile("GMT[+\\-]" + HOURS_PATTERN + ":?" + MINUTES_PATTERN);
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!METHOD_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
String value = (String) ASTHelpers.constValue(tree.getArguments().get(0));
if (value == null) {
// Value isn't a compile-time constant, so we can't know if it's unsafe.
return Description.NO_MATCH;
}
if (isValidId(value)) {
// Value is supported on this JVM.
return Description.NO_MATCH;
}
// Value is invalid, so let's suggest some alternatives.
Description.Builder builder = buildDescription(tree);
// Try to see if it's just been mistyped with spaces instead of underscores - if so, offer this
// as a potential fix.
String spacesToUnderscores = value.replace(' ', '_');
if (isValidId(spacesToUnderscores)) {
builder.addFix(
SuggestedFix.replace(
tree.getArguments().get(0), String.format("\"%s\"", spacesToUnderscores)));
}
return builder.build();
}
private static boolean isValidId(String value) {
if (AVAILABLE_IDS.contains(value)) {
// Value is in TimeZone.getAvailableIDs(), so it's supported on this JVM.
return true;
}
if (CUSTOM_ID_PATTERN.matcher(value).matches()) {
// Value is a custom ID, so it's supported.
return true;
}
return false;
}
}
| 3,902
| 36.528846
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MustBeClosedChecker.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.enclosingClass;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.methodIsConstructor;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import static com.google.errorprone.matchers.Matchers.not;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.MustBeClosed;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.List;
/**
* Checks if a constructor or method annotated with {@link MustBeClosed} is called within the
* resource variable initializer of a try-with-resources statement.
*/
@BugPattern(
altNames = "MustBeClosed",
summary =
"This method returns a resource which must be managed carefully, not just left for garbage"
+ " collection. If it is a constant that will persist for the lifetime of your"
+ " program, move it to a private static final field. Otherwise, you should use it in"
+ " a try-with-resources.",
severity = ERROR)
public class MustBeClosedChecker extends AbstractMustBeClosedChecker
implements MethodTreeMatcher, ClassTreeMatcher {
private static final Matcher<Tree> IS_AUTOCLOSEABLE = isSubtypeOf(AutoCloseable.class);
private static final Matcher<MethodTree> METHOD_RETURNS_AUTO_CLOSEABLE_MATCHER =
allOf(not(methodIsConstructor()), methodReturns(IS_AUTOCLOSEABLE));
private static final Matcher<MethodTree> AUTO_CLOSEABLE_CONSTRUCTOR_MATCHER =
allOf(methodIsConstructor(), enclosingClass(isSubtypeOf(AutoCloseable.class)));
/**
* Check that the {@link MustBeClosed} annotation is only used for constructors of AutoCloseables
* and methods that return an AutoCloseable.
*/
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
// Scan the whole method at once, to avoid name clashes for resource variables.
state.reportMatch(
scanEntireMethodFor(
(t, s) -> {
if (!HAS_MUST_BE_CLOSED_ANNOTATION.matches(t, s)) {
return false;
}
if (t instanceof MethodInvocationTree && ASTHelpers.getSymbol(t).isConstructor()) {
// Invocations of constructors, like `this()` and `super()`, act kinda weird.
// they're handled specially in matchClass, and should be ignored here.
return false;
}
return true;
},
tree,
state));
if (!HAS_MUST_BE_CLOSED_ANNOTATION.matches(tree, state)) {
// But otherwise ignore methods and constructors that are not annotated with {@link
// MustBeClosed}.
return NO_MATCH;
}
// If the method/constructor is annotated @MBC, make sure it's a valid annotation.
boolean isAConstructor = methodIsConstructor().matches(tree, state);
if (isAConstructor && !AUTO_CLOSEABLE_CONSTRUCTOR_MATCHER.matches(tree, state)) {
return buildDescription(tree)
.setMessage("MustBeClosed should only annotate constructors of AutoCloseables.")
.build();
}
if (!isAConstructor && !METHOD_RETURNS_AUTO_CLOSEABLE_MATCHER.matches(tree, state)) {
return buildDescription(tree)
.setMessage("MustBeClosed should only annotate methods that return an AutoCloseable.")
.build();
}
return NO_MATCH;
}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (!IS_AUTOCLOSEABLE.matches(tree, state)) {
return NO_MATCH;
}
// Find all of the constructors in the class without the {@code @MustBeClosed} annotation, which
// invoke a constructor with {@code MustBeClosed}.
for (Tree member : tree.getMembers()) {
if (!(member instanceof MethodTree)) {
continue;
}
MethodTree methodTree = (MethodTree) member;
if (!ASTHelpers.getSymbol(methodTree).isConstructor()
|| ASTHelpers.hasAnnotation(methodTree, MustBeClosed.class, state)
|| !invokedConstructorMustBeClosed(state, methodTree)) {
continue;
}
if (ASTHelpers.isGeneratedConstructor(methodTree)) {
state.reportMatch(
buildDescription(tree)
.setMessage(
"Implicitly invoked constructor is marked @MustBeClosed, so this class must "
+ "have an explicit constructor with @MustBeClosed also.")
.build());
} else {
SuggestedFix.Builder builder = SuggestedFix.builder();
String suggestedFixName =
SuggestedFixes.qualifyType(
state, builder, state.getTypeFromString(MustBeClosed.class.getCanonicalName()));
SuggestedFix fix = builder.prefixWith(methodTree, "@" + suggestedFixName + " ").build();
state.reportMatch(
buildDescription(methodTree)
.addFix(fix)
.setMessage(
"Invoked constructor is marked @MustBeClosed, so this constructor must be "
+ "marked @MustBeClosed too.")
.build());
}
}
return NO_MATCH;
}
private static boolean invokedConstructorMustBeClosed(VisitorState state, MethodTree methodTree) {
// The first statement in a constructor should be an invocation of the super/this constructor.
List<? extends StatementTree> statements = methodTree.getBody().getStatements();
if (statements.isEmpty()) {
// Not sure how the body would be empty, but just filter it out in case.
return false;
}
ExpressionStatementTree est = (ExpressionStatementTree) statements.get(0);
MethodInvocationTree mit = (MethodInvocationTree) est.getExpression();
MethodSymbol invokedConstructorSymbol = ASTHelpers.getSymbol(mit);
return ASTHelpers.hasAnnotation(invokedConstructorSymbol, MustBeClosed.class, state);
}
}
| 7,476
| 42.219653
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JUnit4TestNotRun.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.JUnitMatchers.containsTestMethod;
import static com.google.errorprone.matchers.JUnitMatchers.isJUnit4TestClass;
import static com.google.errorprone.matchers.JUnitMatchers.isJunit3TestCase;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.hasModifier;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.suppliers.Suppliers.VOID_TYPE;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static javax.lang.model.element.Modifier.PUBLIC;
import static javax.lang.model.element.Modifier.STATIC;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.JUnitMatchers;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.lang.model.element.Modifier;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@BugPattern(
summary =
"This looks like a test method but is not run; please add @Test and @Ignore, or, if this"
+ " is a helper method, reduce its visibility.",
severity = ERROR)
public class JUnit4TestNotRun extends BugChecker implements ClassTreeMatcher {
private static final String TEST_CLASS = "org.junit.Test";
private static final String IGNORE_CLASS = "org.junit.Ignore";
private static final String TEST_ANNOTATION = "@Test ";
private static final String IGNORE_ANNOTATION = "@Ignore ";
private final Matcher<MethodTree> possibleTestMethod =
allOf(
hasModifier(PUBLIC),
methodReturns(VOID_TYPE),
(t, s) ->
t.getParameters().stream()
.allMatch(
v ->
v.getModifiers().getAnnotations().stream()
.anyMatch(a -> isParameterAnnotation(a, s))),
not(JUnitMatchers::hasJUnitAnnotation));
private boolean isParameterAnnotation(AnnotationTree annotation, VisitorState state) {
Type annotationType = getType(annotation);
if (isSameType(annotationType, FROM_DATA_POINTS.get(state), state)) {
return true;
}
return false;
}
private static final Supplier<Type> FROM_DATA_POINTS =
Suppliers.typeFromString("org.junit.experimental.theories.FromDataPoints");
private static final Matcher<Tree> NOT_STATIC = not(hasModifier(STATIC));
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (!isJUnit4TestClass.matches(tree, state)) {
return NO_MATCH;
}
Map<MethodSymbol, MethodTree> suspiciousMethods = new HashMap<>();
for (Tree member : tree.getMembers()) {
if (!(member instanceof MethodTree) || isSuppressed(member, state)) {
continue;
}
MethodTree methodTree = (MethodTree) member;
if (possibleTestMethod.matches(methodTree, state) && !isSuppressed(tree, state)) {
suspiciousMethods.put(getSymbol(methodTree), methodTree);
}
}
if (suspiciousMethods.isEmpty()) {
return NO_MATCH;
}
tree.accept(
new TreeScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(
MethodInvocationTree methodInvocationTree, Void unused) {
suspiciousMethods.remove(getSymbol(methodInvocationTree));
return super.visitMethodInvocation(methodInvocationTree, null);
}
},
null);
for (MethodTree methodTree : suspiciousMethods.values()) {
handleMethod(methodTree, state).ifPresent(state::reportMatch);
}
return NO_MATCH;
}
/**
* Matches if:
*
* <ol>
* <li>The method is public, void, and has no parameters;
* <li>the method is not already annotated with {@code @Test}, {@code @Before}, {@code @After},
* {@code @BeforeClass}, or {@code @AfterClass};
* <li>and, the method appears to be a test method, that is:
* <ol type="a">
* <li>The method is named like a JUnit 3 test case,
* <li>or, the method body contains a method call with a name that contains "assert",
* "verify", "check", "fail", or "expect".
* </ol>
* </ol>
*
* Assumes that we have reason to believe we're in a test class (i.e. has a {@code RunWith}
* annotation; has other {@code @Test} methods, etc).
*/
private Optional<Description> handleMethod(MethodTree methodTree, VisitorState state) {
// Method appears to be a JUnit 3 test case (name prefixed with "test"), probably a test.
if (isJunit3TestCase.matches(methodTree, state)) {
return Optional.of(describeFixes(methodTree, state));
}
// Method is annotated, probably not a test.
List<? extends AnnotationTree> annotations = methodTree.getModifiers().getAnnotations();
if (annotations != null && !annotations.isEmpty()) {
return Optional.empty();
}
// Method non-static and contains call(s) to testing method, probably a test,
// unless it is called elsewhere in the class, in which case it is a helper method.
if (NOT_STATIC.matches(methodTree, state) && containsTestMethod(methodTree)) {
return Optional.of(describeFixes(methodTree, state));
}
return Optional.empty();
}
/**
* Returns a finding for the given method tree containing fixes:
*
* <ol>
* <li>Add @Test, remove static modifier if present.
* <li>Add @Test and @Ignore, remove static modifier if present.
* <li>Change visibility to private (for local helper methods).
* </ol>
*/
private Description describeFixes(MethodTree methodTree, VisitorState state) {
Optional<SuggestedFix> removeStatic =
SuggestedFixes.removeModifiers(methodTree, state, Modifier.STATIC);
SuggestedFix testFix =
SuggestedFix.builder()
.merge(removeStatic.orElse(null))
.addImport(TEST_CLASS)
.prefixWith(methodTree, TEST_ANNOTATION)
.build();
SuggestedFix ignoreFix =
SuggestedFix.builder()
.merge(testFix)
.addImport(IGNORE_CLASS)
.prefixWith(methodTree, IGNORE_ANNOTATION)
.build();
SuggestedFix visibilityFix =
SuggestedFix.builder()
.merge(SuggestedFixes.removeModifiers(methodTree, state, Modifier.PUBLIC).orElse(null))
.merge(SuggestedFixes.addModifiers(methodTree, state, Modifier.PRIVATE).orElse(null))
.build();
// Suggest @Ignore first if test method is named like a purposely disabled test.
String methodName = methodTree.getName().toString();
if (methodName.startsWith("disabl") || methodName.startsWith("ignor")) {
return buildDescription(methodTree)
.addFix(ignoreFix)
.addFix(testFix)
.addFix(visibilityFix)
.build();
}
return buildDescription(methodTree)
.addFix(testFix)
.addFix(ignoreFix)
.addFix(visibilityFix)
.build();
}
}
| 8,724
| 38.840183
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NamedLikeContextualKeyword.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFixes.qualifyType;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.methodIsConstructor;
import static com.google.errorprone.matchers.Matchers.methodIsNamed;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.util.ASTHelpers.findPathFromEnclosingNodeToTopLevel;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.streamSuperMethods;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import javax.inject.Inject;
/**
* Warns on classes or methods being named similarly to contextual keywords, or invoking such
* methods.
*/
@BugPattern(
severity = WARNING,
summary =
"Avoid naming of classes and methods that is similar to contextual keywords. When invoking"
+ " such a method, qualify it.")
public final class NamedLikeContextualKeyword extends BugChecker
implements ClassTreeMatcher, MethodTreeMatcher, MethodInvocationTreeMatcher {
// Refer to JLS 19 §3.9.
// Note that "non-sealed" is not a valid class name
private static final ImmutableSet<String> DISALLOWED_CLASS_NAMES =
ImmutableSet.of(
"exports",
"opens",
"requires",
"uses",
"module",
"permits",
"sealed",
"var",
"provides",
"to",
"with",
"open",
"record",
"transitive",
"yield");
private static final Matcher<MethodTree> DISALLOWED_METHOD_NAME_MATCHER =
allOf(not(methodIsConstructor()), methodIsNamed("yield"));
private final boolean enableMethodNames;
private final boolean enableClassNames;
@Inject
NamedLikeContextualKeyword(ErrorProneFlags flags) {
this.enableMethodNames =
flags.getBoolean("NamedLikeContextualKeyword:EnableMethodNames").orElse(false);
this.enableClassNames =
flags.getBoolean("NamedLikeContextualKeyword:EnableClassNames").orElse(false);
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!this.enableMethodNames) {
return NO_MATCH;
}
MethodSymbol methodSymbol = ASTHelpers.getSymbol(tree);
// Don't alert if method is an override (this includes interfaces)
if (!streamSuperMethods(methodSymbol, state.getTypes()).findAny().isPresent()
&& DISALLOWED_METHOD_NAME_MATCHER.matches(tree, state)) {
return describeMatch(tree);
}
return NO_MATCH;
}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (!this.enableClassNames) {
return NO_MATCH;
}
if (DISALLOWED_CLASS_NAMES.contains(tree.getSimpleName().toString())) {
return describeMatch(tree);
}
return NO_MATCH;
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
ExpressionTree select = tree.getMethodSelect();
if (!(select instanceof IdentifierTree)) {
return NO_MATCH;
}
if (!((IdentifierTree) select).getName().contentEquals("yield")) {
return NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
String qualifier = getQualifier(state, getSymbol(tree), fix);
return describeMatch(tree, fix.prefixWith(select, qualifier + ".").build());
}
private static String getQualifier(
VisitorState state, MethodSymbol sym, SuggestedFix.Builder fix) {
if (sym.isStatic()) {
return qualifyType(state, fix, sym.owner.enclClass());
}
TreePath path = findPathFromEnclosingNodeToTopLevel(state.getPath(), ClassTree.class);
if (sym.isMemberOf(getSymbol((ClassTree) path.getLeaf()), state.getTypes())) {
return "this";
}
while (true) {
path = findPathFromEnclosingNodeToTopLevel(path, ClassTree.class);
ClassSymbol enclosingClass = getSymbol((ClassTree) path.getLeaf());
if (sym.isMemberOf(enclosingClass, state.getTypes())) {
return qualifyType(state, fix, enclosingClass) + ".this";
}
}
}
}
| 5,822
| 36.089172
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TooManyParameters.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import static com.google.errorprone.util.ASTHelpers.methodIsPublicAndNotAnOverride;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.MethodTree;
import javax.inject.Inject;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "A large number of parameters on public APIs should be avoided.",
severity = WARNING)
public class TooManyParameters extends BugChecker implements MethodTreeMatcher {
// In 'Detecting Argument Selection Defects' by Rice et. al., the authors argue that methods
// should have 5 of fewer parameters (see section 7.1):
// https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/46317.pdf
// However, we have chosen a very conservative starting number, with hopes to decrease this in the
// future.
private static final int DEFAULT_LIMIT = 9;
static final String TOO_MANY_PARAMETERS_FLAG_NAME = "TooManyParameters:ParameterLimit";
private static final ImmutableSet<String> ANNOTATIONS_TO_IGNORE =
ImmutableSet.of(
"java.lang.Deprecated",
"java.lang.Override",
// dependency injection annotations
"javax.inject.Inject",
"com.google.inject.Inject",
"com.google.inject.Provides",
// dagger provider / producers
"dagger.Provides",
"dagger.producers.Produces",
"com.google.auto.factory.AutoFactory");
private final int limit;
@Inject
TooManyParameters(ErrorProneFlags flags) {
this.limit = flags.getInteger(TOO_MANY_PARAMETERS_FLAG_NAME).orElse(DEFAULT_LIMIT);
checkArgument(limit > 0, "%s (%s) must be > 0", TOO_MANY_PARAMETERS_FLAG_NAME, limit);
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
int paramCount = tree.getParameters().size();
if (paramCount <= limit) {
return NO_MATCH;
}
if (!shouldApplyApiChecks(tree, state)) {
return NO_MATCH;
}
String message =
String.format(
"Consider using a builder pattern instead of a method with %s parameters. Data shows"
+ " that defining methods with > 5 parameters often leads to bugs. See also"
+ " Effective Java, Item 2.",
paramCount);
return buildDescription(tree).setMessage(message).build();
}
private static boolean shouldApplyApiChecks(MethodTree tree, VisitorState state) {
for (String annotation : ANNOTATIONS_TO_IGNORE) {
if (hasAnnotation(tree, annotation, state)) {
return false;
}
}
return methodIsPublicAndNotAnOverride(getSymbol(tree), state);
}
}
| 3,912
| 38.928571
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AvoidObjectArrays.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFixes.prettyType;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.MAIN_METHOD;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import static com.google.errorprone.util.ASTHelpers.hasOverloadWithOnlyOneParameter;
import static com.google.errorprone.util.ASTHelpers.methodIsPublicAndNotAnOverride;
import static java.util.function.Predicate.isEqual;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ArrayType;
import javax.lang.model.element.ElementKind;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Object arrays are inferior to collections in almost every way. Prefer immutable"
+ " collections (e.g., ImmutableSet, ImmutableList, etc.) over an object array whenever"
+ " possible.",
severity = WARNING)
public class AvoidObjectArrays extends BugChecker implements MethodTreeMatcher {
private static final ImmutableSet<String> ANNOTATIONS_TO_IGNORE =
ImmutableSet.of(
"com.tngtech.java.junit.dataprovider.DataProvider",
"org.junit.runners.Parameterized.Parameters",
"org.junit.experimental.theories.DataPoints",
"junitparams.Parameters");
@Override
public Description matchMethod(MethodTree method, VisitorState state) {
if (shouldApplyApiChecks(method, state)) {
// check the return type
if (isObjectArray(method.getReturnType())) {
state.reportMatch(
createDescription(method.getReturnType(), state, "returning", "ImmutableList"));
}
MethodSymbol methodSymbol = getSymbol(method);
// check each method parameter
for (int i = 0; i < method.getParameters().size(); i++) {
VariableTree varTree = method.getParameters().get(i);
if (isObjectArray(varTree)) {
// we allow an Object[] param if it's the last parameter and it's var args
if (methodSymbol.isVarArgs() && i == method.getParameters().size() - 1) {
continue;
}
// we allow an Object[] param if there's also an overload with an Iterable param
if (hasOverloadWithOnlyOneParameter(
methodSymbol, methodSymbol.name, state.getSymtab().iterableType, state)) {
continue;
}
// we _may_ want to eventually allow `String[] args` as a method param, since folks
// sometimes pass around command-line arguments to other methods
state.reportMatch(createDescription(varTree.getType(), state, "accepting", "Iterable"));
}
}
}
return NO_MATCH;
}
private Description createDescription(
Tree tree, VisitorState state, String verb, String newType) {
Type type = getType(tree);
String message = String.format("Avoid %s a %s", verb, prettyType(type, state));
if (type instanceof ArrayType) {
type = ((ArrayType) type).getComponentType();
boolean isMultiDimensional = (type instanceof ArrayType);
if (!isMultiDimensional) {
message += String.format("; consider an %s<%s> instead", newType, prettyType(type, state));
}
}
return buildDescription(tree).setMessage(message).build();
}
/** Returns whether the tree represents an object array or not. */
private static boolean isObjectArray(Tree tree) {
Type type = getType(tree);
return (type instanceof ArrayType) && !((ArrayType) type).getComponentType().isPrimitive();
}
private static boolean shouldApplyApiChecks(MethodTree methodTree, VisitorState state) {
// don't match main methods
if (MAIN_METHOD.matches(methodTree, state)) {
return false;
}
// don't match certain framework-y APIs like parameterized test data providers
for (String annotationName : ANNOTATIONS_TO_IGNORE) {
if (hasAnnotation(methodTree, annotationName, state)) {
return false;
}
}
MethodSymbol method = getSymbol(methodTree);
// don't match methods inside an annotation type
if (state.getTypes().closure(method.owner.type).stream()
.map(superType -> superType.tsym.getKind())
.anyMatch(isEqual(ElementKind.ANNOTATION_TYPE))) {
return false;
}
return methodIsPublicAndNotAnOverride(method, state);
}
}
| 5,672
| 39.234043
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NonRuntimeAnnotation.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.getUpperBound;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Attribute.RetentionPolicy;
import com.sun.tools.javac.code.Type;
/**
* @author scottjohnson@google.com (Scott Johnson)
*/
@BugPattern(
summary = "Calling getAnnotation on an annotation that is not retained at runtime",
severity = ERROR)
public class NonRuntimeAnnotation extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
instanceMethod()
.onExactClass("java.lang.Class")
.named("getAnnotation")
.withParameters("java.lang.Class");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
Type classType = getType(getOnlyElement(tree.getArguments()));
if (classType == null || classType.getTypeArguments().isEmpty()) {
return NO_MATCH;
}
Type type = getUpperBound(getOnlyElement(classType.getTypeArguments()), state.getTypes());
if (isSameType(type, state.getSymtab().annotationType, state)) {
return NO_MATCH;
}
RetentionPolicy retention = state.getTypes().getRetention(type.asElement());
switch (retention) {
case RUNTIME:
break;
case SOURCE:
case CLASS:
return buildDescription(tree)
.setMessage(
String.format(
"%s; %s has %s retention",
message(), type.asElement().getSimpleName(), retention))
.build();
}
return NO_MATCH;
}
}
| 3,049
| 37.125
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NarrowCalculation.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFix.replace;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.constValue;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static com.google.errorprone.util.ASTHelpers.targetType;
import static java.lang.String.format;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
/** A BugPattern; see the summary. */
@BugPattern(
summary = "This calculation may lose precision compared to its target type.",
severity = WARNING)
public final class NarrowCalculation extends BugChecker implements BinaryTreeMatcher {
@Override
public Description matchBinary(BinaryTree tree, VisitorState state) {
var leftType = getType(tree.getLeftOperand());
var rightType = getType(tree.getRightOperand());
var targetType = targetType(state);
if (leftType == null || rightType == null || targetType == null) {
return NO_MATCH;
}
if (tree.getKind().equals(Kind.DIVIDE)
&& leftType.isIntegral()
&& rightType.isIntegral()
&& isFloatingPoint(targetType.type())) {
Object leftConst = constValue(tree.getLeftOperand());
Object rightConst = constValue(tree.getRightOperand());
if (leftConst != null && rightConst != null) {
long left = ((Number) leftConst).longValue();
long right = ((Number) rightConst).longValue();
long divided = left / right;
if (divided * right == left) {
return NO_MATCH;
}
}
return buildDescription(tree)
.setMessage(
"This division will discard the fractional part of the result, despite being assigned"
+ " to a float.")
.addFix(
SuggestedFix.builder()
.setShortDescription("Perform the division using floating point arithmetic")
.merge(forceExpressionType(tree, targetType.type(), state))
.build())
.build();
}
if (tree.getKind().equals(Kind.MULTIPLY)
&& isInt(leftType, state)
&& isInt(rightType, state)
&& isLong(targetType.type(), state)) {
// Heuristic: test data often gets generated with stuff like `i * 1000`, and is known not to
// overflow.
if (state.errorProneOptions().isTestOnlyTarget()) {
return NO_MATCH;
}
var leftConst = constValue(tree.getLeftOperand());
var rightConst = constValue(tree.getRightOperand());
if (leftConst != null && rightConst != null) {
int leftInt = (int) leftConst;
int rightInt = (int) rightConst;
long product = ((long) leftInt) * ((long) rightInt);
if (product == (int) product) {
return NO_MATCH;
}
}
return buildDescription(tree)
.setMessage(
"This product of integers could overflow before being implicitly cast to a long.")
.addFix(
SuggestedFix.builder()
.setShortDescription("Perform the multiplication as long * long")
.merge(forceExpressionType(tree, targetType.type(), state))
.build())
.build();
}
return NO_MATCH;
}
private static SuggestedFix forceExpressionType(
BinaryTree tree, Type targetType, VisitorState state) {
if (tree.getRightOperand() instanceof LiteralTree) {
return SuggestedFix.replace(
tree.getRightOperand(), forceLiteralType(tree.getRightOperand(), targetType, state));
}
if (tree.getLeftOperand() instanceof LiteralTree) {
return SuggestedFix.replace(
tree.getLeftOperand(), forceLiteralType(tree.getLeftOperand(), targetType, state));
}
return replace(
tree.getRightOperand(),
format("((%s) %s)", targetType, state.getSourceForNode(tree.getRightOperand())));
}
private static String forceLiteralType(ExpressionTree tree, Type targetType, VisitorState state) {
return state.getSourceForNode(tree).replaceAll("[LlFfDd]$", "")
+ suffixForType(targetType, state);
}
private static String suffixForType(Type type, VisitorState state) {
Symtab symtab = state.getSymtab();
if (isSameType(type, symtab.longType, state)) {
return "L";
}
if (isSameType(type, symtab.floatType, state)) {
return "f";
}
if (isSameType(type, symtab.doubleType, state)) {
return ".0";
}
throw new AssertionError();
}
private static boolean isFloatingPoint(Type type) {
return type.isNumeric() && !type.isIntegral();
}
private static boolean isInt(Type type, VisitorState state) {
return isSameType(type, state.getSymtab().intType, state);
}
private static boolean isLong(Type type, VisitorState state) {
return isSameType(type, state.getSymtab().longType, state);
}
}
| 6,096
| 37.834395
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/PrivateSecurityContractProtoAccess.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.NONE;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.Matchers.packageStartsWith;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.MethodInvocationTree;
import java.util.regex.Pattern;
/** Check for disallowed access to private_do_not_access_or_else proto fields. */
@BugPattern(
summary =
"Access to a private protocol buffer field is forbidden. This protocol buffer carries"
+ " a security contract, and can only be created using an approved library."
+ " Direct access to the fields is forbidden.",
severity = ERROR,
linkType = NONE)
public class PrivateSecurityContractProtoAccess extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Pattern PRIVATE_DO_NOT_ACCESS_OR_ELSE =
Pattern.compile(".*PrivateDoNotAccessOrElse.*");
private static final Matcher<MethodInvocationTree> SAFEHTML_PRIVATE_FIELD_ACCESS =
allOf(
anyOf(
createFieldMatcher("com.google.common.html.types.SafeHtmlProto"),
createFieldMatcher("com.google.common.html.types.SafeUrlProto"),
createFieldMatcher("com.google.common.html.types.TrustedResourceUrlProto"),
createFieldMatcher("com.google.common.html.types.SafeScriptProto"),
createFieldMatcher("com.google.common.html.types.SafeStyleProto"),
createFieldMatcher("com.google.common.html.types.SafeStyleSheetProto")),
not(packageStartsWith("com.google.common.html.types")));
private static final String MESSAGE = "Forbidden access to a private proto field. See ";
private static final String SAFEHTML_LINK =
"https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md#protocol-buffer-conversion";
// Matches instance methods with PrivateDoNotAccessOrElse in their names.
private static Matcher<MethodInvocationTree> createFieldMatcher(String className) {
String builderName = className + ".Builder";
return anyOf(
instanceMethod().onExactClass(className).withNameMatching(PRIVATE_DO_NOT_ACCESS_OR_ELSE),
instanceMethod().onExactClass(builderName).withNameMatching(PRIVATE_DO_NOT_ACCESS_OR_ELSE));
}
private Description buildErrorMessage(MethodInvocationTree tree, String link) {
Description.Builder description = buildDescription(tree);
String message = MESSAGE + link + ".";
description.setMessage(message);
return description.build();
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (SAFEHTML_PRIVATE_FIELD_ACCESS.matches(tree, state)) {
return buildErrorMessage(tree, SAFEHTML_LINK);
}
return Description.NO_MATCH;
}
}
| 3,971
| 44.655172
| 111
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ComparingThisWithNull.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.Tree.Kind;
/** Check for expressions containing {@code this != null} or {@code this == null} */
@BugPattern(
summary = "this == null is always false, this != null is always true",
explanation =
"The boolean expression this != null always returns true"
+ " and similarly this == null always returns false.",
severity = ERROR)
public class ComparingThisWithNull extends BugChecker implements BinaryTreeMatcher {
private static final Matcher<BinaryTree> EQUAL_OR_NOT_EQUAL =
Matchers.allOf(
Matchers.anyOf(Matchers.kindIs(Kind.EQUAL_TO), Matchers.kindIs(Kind.NOT_EQUAL_TO)),
Matchers.binaryTree(Matchers.kindIs(Kind.NULL_LITERAL), new ThisMatcher()));
@Override
public Description matchBinary(BinaryTree tree, VisitorState state) {
if (EQUAL_OR_NOT_EQUAL.matches(tree, state)) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
private static class ThisMatcher implements Matcher<ExpressionTree> {
@Override
public boolean matches(ExpressionTree thisExpression, VisitorState state) {
if (thisExpression.getKind().equals(Kind.IDENTIFIER)) {
IdentifierTree identifier = (IdentifierTree) thisExpression;
if (identifier.getName().contentEquals("this")) {
return true;
}
}
return false;
}
}
}
| 2,528
| 36.746269
| 93
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/EqualsReference.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.util.Objects;
/**
* @author mariasam@google.com (Maria Sam)
*/
@BugPattern(
summary =
"== must be used in equals method to check equality to itself"
+ " or an infinite loop will occur.",
severity = ERROR)
public class EqualsReference extends BugChecker implements MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree methodTree, VisitorState visitorState) {
if (Matchers.equalsMethodDeclaration().matches(methodTree, visitorState)) {
VariableTree variableTree = methodTree.getParameters().get(0);
VarSymbol varSymbol = ASTHelpers.getSymbol(variableTree);
TreeScannerEquals treeScannerEquals = new TreeScannerEquals(methodTree);
treeScannerEquals.scan(methodTree.getBody(), varSymbol);
if (treeScannerEquals.hasIllegalEquals) {
return describeMatch(methodTree);
}
}
return Description.NO_MATCH;
}
private static class TreeScannerEquals extends TreeScanner<Void, VarSymbol> {
private boolean hasIllegalEquals = false;
private final MethodTree methodTree;
public TreeScannerEquals(MethodTree currMethodTree) {
methodTree = currMethodTree;
}
@Override
public Void visitMethodInvocation(
MethodInvocationTree methodInvocationTree, VarSymbol varSymbol) {
ExpressionTree methodSelectTree = methodInvocationTree.getMethodSelect();
MemberSelectTree memberSelectTree;
boolean hasParameterAndSameSymbol =
methodInvocationTree.getArguments().size() == 1
&& Objects.equals(
ASTHelpers.getSymbol(methodInvocationTree.getArguments().get(0)), varSymbol);
if (methodSelectTree instanceof MemberSelectTree) {
memberSelectTree = (MemberSelectTree) methodSelectTree;
ExpressionTree e = memberSelectTree.getExpression();
// this.equals(o)
// not using o.equals(this) because all instances of this were false positives
// (people checked to see if o was an instance of this class)
if (e instanceof IdentifierTree
&& ((IdentifierTree) e).getName().contentEquals("this")
&& Objects.equals(
ASTHelpers.getSymbol(methodTree), ASTHelpers.getSymbol(memberSelectTree))
&& hasParameterAndSameSymbol) {
hasIllegalEquals = true;
}
} else if (methodInvocationTree.getMethodSelect() instanceof IdentifierTree) {
IdentifierTree methodSelect = (IdentifierTree) methodInvocationTree.getMethodSelect();
if (Objects.equals(ASTHelpers.getSymbol(methodTree), ASTHelpers.getSymbol(methodSelect))
&& hasParameterAndSameSymbol) {
hasIllegalEquals = true;
}
}
return super.visitMethodInvocation(methodInvocationTree, varSymbol);
}
}
}
| 4,185
| 39.640777
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/Overrides.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Matches the behaviour of javac's overrides Xlint warning.
*
* @author cushon@google.com (Liam Miller-Cushon)
*/
@BugPattern(
altNames = "overrides",
summary = "Varargs doesn't agree for overridden method",
severity = WARNING)
public class Overrides extends BugChecker implements MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
MethodSymbol methodSymbol = ASTHelpers.getSymbol(methodTree);
boolean isVarargs = methodSymbol.isVarArgs();
Set<MethodSymbol> superMethods = ASTHelpers.findSuperMethods(methodSymbol, state.getTypes());
// If there are no super methods, we're fine:
if (superMethods.isEmpty()) {
return Description.NO_MATCH;
}
Iterator<MethodSymbol> superMethodsIterator = superMethods.iterator();
boolean areSupersVarargs = superMethodsIterator.next().isVarArgs();
while (superMethodsIterator.hasNext()) {
if (areSupersVarargs != superMethodsIterator.next().isVarArgs()) {
// The super methods are inconsistent (some are varargs, some are not varargs). Then the
// current method is inconsistent with some of its supermethods, so report a match.
return describeMatch(methodTree);
}
}
// The current method is consistent with all of its supermethods:
if (isVarargs == areSupersVarargs) {
return Description.NO_MATCH;
}
// The current method is inconsistent with all of its supermethods, so flip the varargs-ness
// of the current method.
List<? extends VariableTree> parameterTree = methodTree.getParameters();
Tree paramType = parameterTree.get(parameterTree.size() - 1).getType();
CharSequence paramTypeSource = state.getSourceForNode(paramType);
if (paramTypeSource == null) {
// No fix if we don't have tree end positions.
return describeMatch(methodTree);
}
Description.Builder descriptionBuilder = buildDescription(methodTree);
if (isVarargs) {
descriptionBuilder.addFix(
SuggestedFix.replace(paramType, "[]", paramTypeSource.length() - 3, 0));
} else {
// There may be a comment that includes a '[' character between the open and closed
// brackets of the array type. If so, we don't return a fix.
int arrayOpenIndex = paramTypeSource.length() - 2;
while (paramTypeSource.charAt(arrayOpenIndex) == ' ') {
arrayOpenIndex--;
}
if (paramTypeSource.charAt(arrayOpenIndex) == '[') {
descriptionBuilder.addFix(SuggestedFix.replace(paramType, "...", arrayOpenIndex, 0));
}
}
return descriptionBuilder.build();
}
}
| 3,917
| 37.038835
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessarilyFullyQualified.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getGeneratedBy;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isGeneratedConstructor;
import static com.google.errorprone.util.FindIdentifiers.findIdent;
import static com.sun.tools.javac.code.Kinds.KindSelector.VAL_TYP;
import static java.util.stream.Collectors.toCollection;
import com.google.common.base.Ascii;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Table;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.util.Position;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.lang.model.element.Name;
/** Flags uses of fully qualified names which are not ambiguous if imported. */
@BugPattern(
severity = SeverityLevel.WARNING,
summary = "This fully qualified name is unambiguous to the compiler if imported.")
public final class UnnecessarilyFullyQualified extends BugChecker
implements CompilationUnitTreeMatcher {
private static final ImmutableSet<String> EXEMPTED_NAMES = ImmutableSet.of("Annotation");
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
if (tree.getTypeDecls().stream()
.anyMatch(
t -> getSymbol(tree) != null && !getGeneratedBy(getSymbol(tree), state).isEmpty())) {
return NO_MATCH;
}
if (isPackageInfo(tree)) {
return NO_MATCH;
}
Table<Name, TypeSymbol, List<TreePath>> table = HashBasedTable.create();
SetMultimap<Name, TypeSymbol> identifiersSeen = HashMultimap.create();
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitImport(ImportTree importTree, Void unused) {
return null;
}
@Override
public Void visitClass(ClassTree tree, Void unused) {
scan(tree.getModifiers(), null);
scan(tree.getTypeParameters(), null);
// Some anonymous classes have an extends clause which is fully qualified. Just ignore it.
if (!getSymbol(tree).isAnonymous()) {
scan(tree.getExtendsClause(), null);
scan(tree.getImplementsClause(), null);
}
scan(tree.getMembers(), null);
return null;
}
@Override
public Void visitMethod(MethodTree tree, Void unused) {
// Some generated constructors sneak in a fully qualified argument.
return isGeneratedConstructor(tree) ? null : super.visitMethod(tree, null);
}
@Override
public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void unused) {
if (!shouldIgnore()) {
handle(getCurrentPath());
}
return super.visitMemberSelect(memberSelectTree, null);
}
@Override
public Void visitIdentifier(IdentifierTree identifierTree, Void unused) {
Type type = getType(identifierTree);
if (type != null) {
identifiersSeen.put(identifierTree.getName(), type.tsym);
}
return null;
}
private boolean shouldIgnore() {
// Don't report duplicate hits if we're not at the tail of a series of member selects on
// classes.
Tree parentTree = getCurrentPath().getParentPath().getLeaf();
return parentTree instanceof MemberSelectTree
&& getSymbol(parentTree) instanceof ClassSymbol;
}
private void handle(TreePath path) {
MemberSelectTree tree = (MemberSelectTree) path.getLeaf();
if (!isFullyQualified(tree)) {
return;
}
if (BadImport.BAD_NESTED_CLASSES.contains(tree.getIdentifier().toString())) {
if (tree.getExpression() instanceof MemberSelectTree
&& getSymbol(tree.getExpression()) instanceof ClassSymbol) {
handle(new TreePath(path, tree.getExpression()));
}
return;
}
Symbol symbol = getSymbol(tree);
if (!(symbol instanceof ClassSymbol)) {
return;
}
if (state.getEndPosition(tree) == Position.NOPOS) {
return;
}
List<TreePath> treePaths = table.get(tree.getIdentifier(), symbol.type.tsym);
if (treePaths == null) {
treePaths = new ArrayList<>();
table.put(tree.getIdentifier(), symbol.type.tsym, treePaths);
}
treePaths.add(path);
}
private boolean isFullyQualified(MemberSelectTree tree) {
AtomicBoolean isFullyQualified = new AtomicBoolean();
new SimpleTreeVisitor<Void, Void>() {
@Override
public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void unused) {
return visit(memberSelectTree.getExpression(), null);
}
@Override
public Void visitIdentifier(IdentifierTree identifierTree, Void aVoid) {
if (getSymbol(identifierTree) instanceof PackageSymbol) {
isFullyQualified.set(true);
}
return null;
}
}.visit(tree, null);
return isFullyQualified.get();
}
}.scan(state.getPath(), null);
for (Map.Entry<Name, Map<TypeSymbol, List<TreePath>>> rows : table.rowMap().entrySet()) {
Name name = rows.getKey();
Map<TypeSymbol, List<TreePath>> types = rows.getValue();
// Skip places where the same simple name refers to multiple types.
if (types.size() > 1) {
continue;
}
TypeSymbol type = getOnlyElement(types.keySet());
// Skip weird Android classes which don't look like classes.
if (Ascii.isLowerCase(name.charAt(0))) {
continue;
}
// Don't replace if this name is already used in the file to refer to a _different_ type.
if (identifiersSeen.get(name).stream().anyMatch(s -> !s.equals(type))) {
continue;
}
String nameString = name.toString();
if (EXEMPTED_NAMES.contains(nameString)) {
continue;
}
List<TreePath> pathsToFix = getOnlyElement(types.values());
Set<Symbol> meaningAtUsageSites =
pathsToFix.stream()
.map(path -> findIdent(nameString, state.withPath(path), VAL_TYP))
.collect(toCollection(HashSet::new));
// Don't report a finding if the simple name has a different meaning elsewhere.
if (meaningAtUsageSites.stream().anyMatch(s -> s != null && !s.equals(type))) {
continue;
}
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
// Only add the import if any of the usage sites don't already resolve to this type.
if (meaningAtUsageSites.stream().anyMatch(Objects::isNull)) {
fixBuilder.addImport(getOnlyElement(types.keySet()).getQualifiedName().toString());
}
for (TreePath path : pathsToFix) {
fixBuilder.replace(path.getLeaf(), nameString);
}
SuggestedFix fix = fixBuilder.build();
for (TreePath path : pathsToFix) {
state.reportMatch(describeMatch(path.getLeaf(), fix));
}
}
return NO_MATCH;
}
private static boolean isPackageInfo(CompilationUnitTree tree) {
String name = ASTHelpers.getFileName(tree);
int idx = name.lastIndexOf('/');
if (idx != -1) {
name = name.substring(idx + 1);
}
return name.equals("package-info.java");
}
}
| 9,371
| 38.544304
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryParentheses.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ParenthesizedTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.Tree;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"These grouping parentheses are unnecessary; it is unlikely the code will"
+ " be misinterpreted without them",
severity = WARNING)
public class UnnecessaryParentheses extends BugChecker implements ParenthesizedTreeMatcher {
@Override
public Description matchParenthesized(ParenthesizedTree tree, VisitorState state) {
ExpressionTree expression = tree.getExpression();
Tree parent = state.getPath().getParentPath().getLeaf();
switch (parent.getKind()) {
case IF:
case WHILE_LOOP:
case DO_WHILE_LOOP:
case FOR_LOOP:
case SWITCH:
case SYNCHRONIZED:
return NO_MATCH;
default: // fall out
}
switch (parent.getKind().name()) {
case "SWITCH_EXPRESSION":
return NO_MATCH;
default: // fall out
}
if (ASTHelpers.requiresParentheses(expression, state)) {
return NO_MATCH;
}
return describeMatch(
tree,
SuggestedFix.builder()
// add an extra leading space to handle e.g. `return(x)`
.replace(getStartPosition(tree), getStartPosition(expression), " ")
.replace(state.getEndPosition(expression), state.getEndPosition(tree), "")
.build());
}
}
| 2,647
| 35.777778
| 92
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ArrayFillIncompatibleType.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.Signatures;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.code.Type;
/**
* Checks when Arrays.fill(Object[], Object) is called with object types that are guaranteed to
* result in an ArrayStoreException.
*/
@BugPattern(
summary = "Arrays.fill(Object[], Object) called with incompatible types.",
severity = ERROR)
public class ArrayFillIncompatibleType extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> ARRAY_FILL_MATCHER =
anyOf(
staticMethod()
.onClass("java.util.Arrays")
.withSignature("fill(java.lang.Object[],java.lang.Object)"),
staticMethod()
.onClass("java.util.Arrays")
.withSignature("fill(java.lang.Object[],int,int,java.lang.Object)"));
@Override
public Description matchMethodInvocation(
MethodInvocationTree invocationTree, VisitorState state) {
if (!ARRAY_FILL_MATCHER.matches(invocationTree, state)) {
return Description.NO_MATCH;
}
Type arrayComponentType =
state.getTypes().elemtype(ASTHelpers.getType(invocationTree.getArguments().get(0)));
Tree fillingArgument = Iterables.getLast(invocationTree.getArguments());
Type fillingObjectType = ASTHelpers.getType(fillingArgument);
// You can put an Integer or an int into a Number[], but you can't put a Number into an
// Integer[].
// (Note that you can assign Integer[] to Number[] and then try to put the Number into it, but
// that's a hole provided by array covariance we can't plug here)
if (isValidArrayFill(state, arrayComponentType, fillingObjectType)) {
return Description.NO_MATCH;
}
// Due to some funky behavior, javac doesn't appear to fully expand the type of a ternary
// when passed into an "Object" context. Let's explore both sides
if (fillingArgument.getKind() == Kind.CONDITIONAL_EXPRESSION) {
ConditionalExpressionTree cet = (ConditionalExpressionTree) fillingArgument;
Type trueExpressionType = ASTHelpers.getType(cet.getTrueExpression());
if (!isValidArrayFill(state, arrayComponentType, trueExpressionType)) {
return reportMismatch(invocationTree, arrayComponentType, trueExpressionType);
}
Type falseExpressionType = ASTHelpers.getType(cet.getFalseExpression());
if (!isValidArrayFill(state, arrayComponentType, falseExpressionType)) {
return reportMismatch(invocationTree, arrayComponentType, falseExpressionType);
}
// Looks like we were able to find a ternary that would actually work
return Description.NO_MATCH;
}
return reportMismatch(invocationTree, arrayComponentType, fillingObjectType);
}
private Description reportMismatch(
MethodInvocationTree invocationTree, Type arrayComponentType, Type fillingObjectType) {
return buildDescription(invocationTree)
.setMessage(getMessage(fillingObjectType, arrayComponentType))
.build();
}
private static boolean isValidArrayFill(
VisitorState state, Type arrayComponentType, Type fillingObjectType) {
if (arrayComponentType == null || fillingObjectType == null) {
return true; // shrug
}
return ASTHelpers.isSubtype(
state.getTypes().boxedTypeOrType(fillingObjectType), arrayComponentType, state);
}
private static String getMessage(Type fillingObjectType, Type arrayComponentType) {
String fillingTypeString = Signatures.prettyType(fillingObjectType);
String arrayComponentTypeString = Signatures.prettyType(arrayComponentType);
if (arrayComponentTypeString.equals(fillingTypeString)) {
fillingTypeString = fillingObjectType.toString();
arrayComponentTypeString = arrayComponentType.toString();
}
return "Calling Arrays.fill trying to put a "
+ fillingTypeString
+ " into an array of type "
+ arrayComponentTypeString;
}
}
| 5,352
| 41.824
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DoNotMockAutoValue.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import com.google.auto.value.AutoValue;
import com.google.errorprone.BugPattern;
import com.sun.source.tree.VariableTree;
import java.util.stream.Stream;
/** Suggests not mocking AutoValue classes. */
@BugPattern(
summary =
"AutoValue classes represent pure data classes, so mocking them should not be necessary."
+ " Construct a real instance of the class instead.",
severity = WARNING)
public final class DoNotMockAutoValue extends AbstractMockChecker<AutoValue> {
private static final TypeExtractor<VariableTree> MOCKED_VAR =
fieldAnnotatedWithOneOf(Stream.of("org.mockito.Mock", "org.mockito.Spy"));
public DoNotMockAutoValue() {
super(
MOCKED_VAR,
MOCKING_METHOD,
AutoValue.class,
unused ->
"AutoValue classes represent pure value classes, so mocking them should not be"
+ " necessary");
}
}
| 1,627
| 34.391304
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InlineTrivialConstant.java
|
/*
* Copyright 2023 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MultimapBuilder;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "Consider inlining this constant", severity = WARNING)
public class InlineTrivialConstant extends BugChecker implements CompilationUnitTreeMatcher {
@AutoValue
abstract static class TrivialConstant {
abstract VariableTree tree();
abstract String replacement();
static TrivialConstant create(VariableTree tree, String replacement) {
return new AutoValue_InlineTrivialConstant_TrivialConstant(tree, replacement);
}
}
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
Map<VarSymbol, TrivialConstant> fields = new HashMap<>();
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitVariable(VariableTree tree, Void unused) {
VarSymbol sym = getSymbol(tree);
isTrivialConstant(tree, sym, state)
.ifPresent(r -> fields.put(sym, TrivialConstant.create(tree, r)));
return super.visitVariable(tree, null);
}
}.scan(state.getPath(), null);
ListMultimap<Symbol, Tree> uses = MultimapBuilder.hashKeys().arrayListValues().build();
new TreePathScanner<Void, Void>() {
@Override
public Void visitMemberSelect(MemberSelectTree tree, Void unused) {
handle(tree);
return super.visitMemberSelect(tree, null);
}
@Override
public Void visitIdentifier(IdentifierTree tree, Void unused) {
handle(tree);
return super.visitIdentifier(tree, null);
}
private void handle(Tree tree) {
Symbol sym = getSymbol(tree);
if (sym == null) {
return;
}
if (fields.containsKey(sym)) {
uses.put(sym, tree);
}
}
}.scan(state.getPath(), null);
for (Map.Entry<VarSymbol, TrivialConstant> e : fields.entrySet()) {
SuggestedFix.Builder fix = SuggestedFix.builder();
TrivialConstant value = e.getValue();
fix.delete(value.tree());
uses.get(e.getKey()).forEach(x -> fix.replace(x, value.replacement()));
state.reportMatch(describeMatch(value.tree(), fix.build()));
}
return NO_MATCH;
}
private static final ImmutableSet<String> EMPTY_STRING_VARIABLE_NAMES =
ImmutableSet.of("EMPTY", "EMPTY_STR", "EMPTY_STRING");
private static Optional<String> isTrivialConstant(
VariableTree tree, VarSymbol sym, VisitorState state) {
if (!(sym.getKind().equals(ElementKind.FIELD)
&& sym.getModifiers().contains(Modifier.PRIVATE)
&& sym.isStatic()
&& sym.getModifiers().contains(Modifier.FINAL))) {
return Optional.empty();
}
if (!EMPTY_STRING_VARIABLE_NAMES.contains(tree.getName().toString())) {
return Optional.empty();
}
if (!isSameType(sym.asType(), state.getSymtab().stringType, state)) {
return Optional.empty();
}
ExpressionTree initializer = tree.getInitializer();
if (initializer.getKind().equals(Tree.Kind.STRING_LITERAL)) {
String value = (String) ((LiteralTree) initializer).getValue();
if (Objects.equals(value, "")) {
return Optional.of("\"\"");
}
}
return Optional.empty();
}
}
| 5,229
| 36.898551
| 93
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CollectorShouldNotUseState.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.contains;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import javax.lang.model.element.Modifier;
/**
* @author sulku@google.com (Marsela Sulku)
*/
@BugPattern(summary = "Collector.of() should not use state", severity = WARNING)
public class CollectorShouldNotUseState extends BugChecker implements MethodInvocationTreeMatcher {
public static final Matcher<ExpressionTree> COLLECTOR_OF_CALL =
staticMethod().onClass("java.util.stream.Collector").named("of");
public final Matcher<Tree> containsAnonymousClassUsingState =
contains(new AnonymousClassUsingStateMatcher());
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState visitorState) {
if (COLLECTOR_OF_CALL.matches(methodInvocationTree, visitorState)
&& containsAnonymousClassUsingState.matches(methodInvocationTree, visitorState)) {
return describeMatch(methodInvocationTree);
}
return Description.NO_MATCH;
}
/*
Matches an anonymous inner class that contains one or more members that are not final
*/
private class AnonymousClassUsingStateMatcher implements Matcher<Tree> {
@Override
public boolean matches(Tree tree, VisitorState visitorState) {
if (!(tree instanceof NewClassTree)) {
return false;
}
NewClassTree newClassTree = (NewClassTree) tree;
if (newClassTree.getClassBody() == null) {
return false;
}
return newClassTree.getClassBody().getMembers().stream()
.filter(mem -> mem instanceof VariableTree)
.anyMatch(mem -> !isFinal(mem));
}
private boolean isFinal(Tree tree) {
return ASTHelpers.getSymbol((VariableTree) tree).getModifiers().contains(Modifier.FINAL);
}
}
}
| 3,084
| 34.872093
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ArrayToString.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.predicates.TypePredicate;
import com.google.errorprone.predicates.TypePredicates;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import java.util.Optional;
/**
* @author adgar@google.com (Mike Edgar)
* @author cushon@google.com (Liam Miller-Cushon)
*/
@BugPattern(
summary = "Calling toString on an array does not provide useful information",
severity = ERROR)
public class ArrayToString extends AbstractToString {
private static final Matcher<ExpressionTree> GET_STACK_TRACE =
instanceMethod().onDescendantOf("java.lang.Throwable").named("getStackTrace");
private static final TypePredicate IS_ARRAY = TypePredicates.isArray();
@Override
protected TypePredicate typePredicate() {
return IS_ARRAY;
}
@Override
protected Optional<Fix> implicitToStringFix(ExpressionTree tree, VisitorState state) {
// e.g. println(theArray) -> println(Arrays.toString(theArray))
// or: "" + theArray -> "" + Arrays.toString(theArray)
return toStringFix(tree, tree, state);
}
@Override
protected boolean allowableToStringKind(ToStringKind toStringKind) {
return toStringKind == ToStringKind.FLOGGER || toStringKind == ToStringKind.FORMAT_METHOD;
}
@Override
protected Optional<Fix> toStringFix(Tree parent, ExpressionTree tree, VisitorState state) {
// If the array is the result of calling e.getStackTrace(), replace
// e.getStackTrace().toString() with Guava's Throwables.getStackTraceAsString(e).
if (GET_STACK_TRACE.matches(tree, state)) {
return Optional.of(
SuggestedFix.builder()
.addImport("com.google.common.base.Throwables")
.replace(
parent,
String.format(
"Throwables.getStackTraceAsString(%s)",
state.getSourceForNode(ASTHelpers.getReceiver(tree))))
.build());
}
// e.g. String.valueOf(theArray) -> Arrays.toString(theArray)
// or: theArray.toString() -> Arrays.toString(theArray)
// or: theArrayOfArrays.toString() -> Arrays.deepToString(theArrayOfArrays)
return fix(parent, tree, state);
}
private static Optional<Fix> fix(Tree replace, Tree with, VisitorState state) {
String method = isNestedArray(with, state) ? "deepToString" : "toString";
return Optional.of(
SuggestedFix.builder()
.addImport("java.util.Arrays")
.replace(replace, String.format("Arrays.%s(%s)", method, state.getSourceForNode(with)))
.build());
}
private static boolean isNestedArray(Tree with, VisitorState state) {
Types types = state.getTypes();
Type withType = ASTHelpers.getType(with);
return withType != null && types.isArray(withType) && types.isArray(types.elemtype(withType));
}
}
| 3,984
| 37.317308
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ParameterComment.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Streams.forEachPair;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.Comments.findCommentsForArguments;
import static com.google.errorprone.util.Comments.getTextFromComment;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.Commented;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.parser.Tokens.Comment;
import java.util.stream.Stream;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Non-standard parameter comment; prefer `/* paramName= */ arg`",
severity = SUGGESTION)
public class ParameterComment extends BugChecker
implements MethodInvocationTreeMatcher, NewClassTreeMatcher {
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return matchNewClassOrMethodInvocation(
getSymbol(tree), findCommentsForArguments(tree, state), tree);
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
return matchNewClassOrMethodInvocation(
getSymbol(tree), findCommentsForArguments(tree, state), tree);
}
private Description matchNewClassOrMethodInvocation(
MethodSymbol symbol, ImmutableList<Commented<ExpressionTree>> arguments, Tree tree) {
if (symbol.getParameters().isEmpty()) {
return NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
forEachPair(
arguments.stream(),
Stream.concat(
symbol.getParameters().stream(),
Stream.iterate(getLast(symbol.getParameters()), x -> x)),
(commented, param) -> {
if (commented.beforeComments().stream()
.anyMatch(
c ->
getTextFromComment(c).replace(" ", "").equals(param.getSimpleName() + "="))) {
return;
}
ImmutableList<Comment> comments =
commented.afterComments().isEmpty()
? commented.beforeComments()
: commented.afterComments();
comments.stream()
.filter(c -> matchingParamComment(c, param))
.findFirst()
.ifPresent(c -> fixParamComment(fix, commented, param, c));
});
return fix.isEmpty() ? NO_MATCH : describeMatch(tree, fix.build());
}
private static boolean matchingParamComment(Comment c, VarSymbol param) {
return param.getSimpleName().contentEquals(getTextFromComment(c).replaceAll("\\s*=\\s*$", ""));
}
private static void fixParamComment(
SuggestedFix.Builder fix, Commented<ExpressionTree> commented, VarSymbol param, Comment c) {
fix.prefixWith(commented.tree(), String.format("/* %s= */ ", param.getSimpleName()))
.replace(c.getSourcePos(0), c.getSourcePos(0) + c.getText().length(), "");
}
}
| 4,347
| 41.213592
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ParameterName.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import com.google.auto.value.AutoValue;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Range;
import com.google.errorprone.BugPattern;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.bugpatterns.argumentselectiondefects.NamedParameterComment;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.Comments;
import com.google.errorprone.util.ErrorProneToken;
import com.google.errorprone.util.ErrorProneTokens;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.parser.Tokens.Comment;
import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle;
import com.sun.tools.javac.util.Position;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import javax.inject.Inject;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Detects `/* name= */`-style comments on actual parameters where the name doesn't match the"
+ " formal parameter",
severity = WARNING)
public class ParameterName extends BugChecker
implements MethodInvocationTreeMatcher, NewClassTreeMatcher {
private final ImmutableList<String> exemptPackages;
@Inject
ParameterName(ErrorProneFlags errorProneFlags) {
this.exemptPackages =
errorProneFlags
.getList("ParameterName:exemptPackagePrefixes")
.orElse(ImmutableList.of())
.stream()
// add a trailing '.' so that e.g. com.foo matches as a prefix of com.foo.bar, but not
// com.foobar
.map(p -> p.endsWith(".") ? p : p + ".")
.collect(toImmutableList());
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
checkArguments(tree, tree.getArguments(), state.getEndPosition(tree.getMethodSelect()), state);
return NO_MATCH;
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
checkArguments(tree, tree.getArguments(), state.getEndPosition(tree.getIdentifier()), state);
return NO_MATCH;
}
private void checkArguments(
Tree tree,
List<? extends ExpressionTree> arguments,
int argListStartPosition,
VisitorState state) {
if (arguments.isEmpty()) {
return;
}
MethodSymbol sym = (MethodSymbol) ASTHelpers.getSymbol(tree);
if (NamedParameterComment.containsSyntheticParameterName(sym)) {
return;
}
int start = argListStartPosition;
if (start == Position.NOPOS) {
// best effort work-around for https://github.com/google/error-prone/issues/780
return;
}
String enclosingClass = ASTHelpers.enclosingClass(sym).toString();
if (exemptPackages.stream().anyMatch(enclosingClass::startsWith)) {
return;
}
Iterator<? extends ExpressionTree> argumentIterator = arguments.iterator();
// For each parameter/argument pair, we tokenize the characters between the end of the
// previous argument (or the start of the argument list, in the case of the first argument)
// and the start of the current argument. The `start` variable is advanced each time, stepping
// over each argument when we finish processing it.
for (VarSymbol param : sym.getParameters()) {
if (!argumentIterator.hasNext()) {
return; // A vararg parameter has zero corresponding arguments passed
}
ExpressionTree argument = argumentIterator.next();
Optional<Range<Integer>> positions = positions(argument, state);
if (positions.isEmpty()) {
return;
}
start =
processArgument(
positions.get(), start, state, tok -> checkArgument(param, argument, tok, state));
}
// handle any varargs arguments after the first
while (argumentIterator.hasNext()) {
ExpressionTree argument = argumentIterator.next();
Optional<Range<Integer>> positions = positions(argument, state);
if (positions.isEmpty()) {
return;
}
start =
processArgument(positions.get(), start, state, tok -> checkComment(argument, tok, state));
}
}
/** Returns the source span for a tree, or empty if the position information is not available. */
Optional<Range<Integer>> positions(Tree tree, VisitorState state) {
int endPosition = state.getEndPosition(tree);
if (endPosition == Position.NOPOS) {
return Optional.empty();
}
return Optional.of(Range.closedOpen(getStartPosition(tree), endPosition));
}
private static int processArgument(
Range<Integer> positions,
int offset,
VisitorState state,
Consumer<ErrorProneToken> consumer) {
String source = state.getSourceCode().subSequence(offset, positions.upperEndpoint()).toString();
Deque<ErrorProneToken> tokens =
new ArrayDeque<>(ErrorProneTokens.getTokens(source, offset, state.context));
if (advanceTokens(tokens, positions)) {
consumer.accept(tokens.removeFirst());
}
return positions.upperEndpoint();
}
private static boolean advanceTokens(Deque<ErrorProneToken> tokens, Range<Integer> actual) {
while (!tokens.isEmpty() && tokens.getFirst().pos() < actual.lowerEndpoint()) {
tokens.removeFirst();
}
if (tokens.isEmpty()) {
return false;
}
if (!actual.contains(tokens.getFirst().pos())) {
return false;
}
return true;
}
@AutoValue
abstract static class FixInfo {
abstract boolean isFormatCorrect();
abstract boolean isNameCorrect();
abstract Comment comment();
abstract String name();
static FixInfo create(
boolean isFormatCorrect, boolean isNameCorrect, Comment comment, String name) {
return new AutoValue_ParameterName_FixInfo(isFormatCorrect, isNameCorrect, comment, name);
}
}
private void checkArgument(
VarSymbol formal, ExpressionTree actual, ErrorProneToken token, VisitorState state) {
List<FixInfo> matches = new ArrayList<>();
for (Comment comment : token.comments()) {
if (comment.getStyle().equals(CommentStyle.LINE)) {
// These are usually not intended as a parameter comment, and we don't want to flag if they
// happen to match the parameter comment format.
continue;
}
Matcher m =
NamedParameterComment.PARAMETER_COMMENT_PATTERN.matcher(
Comments.getTextFromComment(comment));
if (!m.matches()) {
continue;
}
boolean isFormatCorrect = isVarargs(formal) ^ Strings.isNullOrEmpty(m.group(2));
String name = m.group(1);
boolean isNameCorrect = formal.getSimpleName().contentEquals(name);
// If there are multiple parameter name comments, bail if any one of them is an exact match.
if (isNameCorrect && isFormatCorrect) {
matches.clear();
break;
}
matches.add(FixInfo.create(isFormatCorrect, isNameCorrect, comment, name));
}
String fixTemplate = isVarargs(formal) ? "/* %s...= */" : "/* %s= */";
for (FixInfo match : matches) {
SuggestedFix rewriteCommentFix =
rewriteComment(match.comment(), String.format(fixTemplate, formal.getSimpleName()));
SuggestedFix rewriteToRegularCommentFix =
rewriteComment(match.comment(), String.format("/* %s */", match.name()));
Description description;
if (match.isFormatCorrect() && !match.isNameCorrect()) {
description =
buildDescription(actual)
.setMessage(
String.format(
"`%s` does not match formal parameter name `%s`; either fix the name or"
+ " use a regular comment",
match.comment().getText(), formal.getSimpleName()))
.addFix(rewriteCommentFix)
.addFix(rewriteToRegularCommentFix)
.build();
} else if (!match.isFormatCorrect() && match.isNameCorrect()) {
description =
buildDescription(actual)
.setMessage(
String.format(
"parameter name comment `%s` uses incorrect format",
match.comment().getText()))
.addFix(rewriteCommentFix)
.build();
} else if (!match.isFormatCorrect() && !match.isNameCorrect()) {
description =
buildDescription(actual)
.setMessage(
String.format(
"`%s` does not match formal parameter name `%s` and uses incorrect "
+ "format; either fix the format or use a regular comment",
match.comment().getText(), formal.getSimpleName()))
.addFix(rewriteCommentFix)
.addFix(rewriteToRegularCommentFix)
.build();
} else {
throw new AssertionError(
"Unexpected match with both isNameCorrect and isFormatCorrect true: " + match);
}
state.reportMatch(description);
}
}
private static SuggestedFix rewriteComment(Comment comment, String format) {
int replacementStartPos = comment.getSourcePos(0);
int replacementEndPos = comment.getSourcePos(comment.getText().length() - 1) + 1;
return SuggestedFix.replace(replacementStartPos, replacementEndPos, format);
}
// complains on parameter name comments on varargs past the first one
private void checkComment(ExpressionTree arg, ErrorProneToken token, VisitorState state) {
for (Comment comment : token.comments()) {
Matcher m =
NamedParameterComment.PARAMETER_COMMENT_PATTERN.matcher(
Comments.getTextFromComment(comment));
if (m.matches()) {
SuggestedFix rewriteCommentFix =
rewriteComment(
comment, String.format("/* %s%s */", m.group(1), firstNonNull(m.group(2), "")));
state.reportMatch(
buildDescription(arg)
.addFix(rewriteCommentFix)
.setMessage("parameter name comment only allowed on first varargs argument")
.build());
}
}
}
private static boolean isVarargs(VarSymbol sym) {
Preconditions.checkArgument(
sym.owner instanceof MethodSymbol, "sym must be a parameter to a method");
MethodSymbol method = (MethodSymbol) sym.owner;
return method.isVarArgs() && (method.getParameters().last() == sym);
}
}
| 12,234
| 38.595469
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/OptionalMapToOptional.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.predicates.TypePredicate;
import com.google.errorprone.predicates.TypePredicates;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.ASTHelpers.TargetType;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Type;
import java.util.List;
/** Matches {@code Optional#map} mapping to another {@code Optional}. */
@BugPattern(
summary = "Mapping to another Optional will yield a nested Optional. Did you mean flatMap?",
severity = WARNING)
public final class OptionalMapToOptional extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MAP =
anyOf(
instanceMethod().onExactClass("java.util.Optional").named("map"),
instanceMethod().onExactClass("com.google.common.base.Optional").named("transform"));
private static final Matcher<ExpressionTree> ANYTHING_BUT_ISPRESENT =
anyOf(
allOf(
instanceMethod().onExactClass("java.util.Optional"),
not(instanceMethod().onExactClass("java.util.Optional").named("isPresent"))),
allOf(
instanceMethod().onExactClass("com.google.common.base.Optional"),
not(
instanceMethod()
.onExactClass("com.google.common.base.Optional")
.named("isPresent"))));
private static final TypePredicate OPTIONAL =
TypePredicates.isDescendantOfAny(
ImmutableList.of("java.util.Optional", "com.google.common.base.Optional"));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MAP.matches(tree, state)) {
return NO_MATCH;
}
TreePath path = state.getPath();
// Heuristic: if another Optional instance method is invoked on this, it's usually clear what's
// going on, unless that method is `isPresent()`.
if (path.getParentPath().getLeaf() instanceof MemberSelectTree
&& path.getParentPath().getParentPath().getLeaf() instanceof MethodInvocationTree
&& ANYTHING_BUT_ISPRESENT.matches(
(MethodInvocationTree) path.getParentPath().getParentPath().getLeaf(), state)) {
return NO_MATCH;
}
TargetType targetType =
ASTHelpers.targetType(
state.withPath(new TreePath(state.getPath(), tree.getArguments().get(0))));
if (targetType == null) {
return NO_MATCH;
}
List<Type> typeArguments = targetType.type().getTypeArguments();
// If the receiving Optional is raw, so will the target type of Function.
if (typeArguments.isEmpty()) {
return NO_MATCH;
}
Type typeMappedTo = typeArguments.get(1);
if (!OPTIONAL.apply(typeMappedTo, state)) {
return NO_MATCH;
}
return describeMatch(tree);
}
}
| 4,320
| 42.21
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TruthAssertExpected.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.streamReceivers;
import com.google.common.base.Ascii;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.suppliers.Suppliers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import java.util.List;
import javax.annotation.Nullable;
/**
* Detects usages of Truth assertions with the expected and actual values reversed.
*
* @author ghm@google.com (Graeme Morgan)
*/
@BugPattern(
summary =
"The actual and expected values appear to be swapped, which results in poor assertion "
+ "failure messages. The actual value should come first.",
severity = WARNING,
tags = StandardTags.STYLE)
public final class TruthAssertExpected extends BugChecker implements MethodInvocationTreeMatcher {
private static final String TRUTH = "com.google.common.truth.Truth";
private static final String PROTOTRUTH = "com.google.common.truth.extensions.proto.ProtoTruth";
private static final Matcher<ExpressionTree> TRUTH_ASSERTTHAT =
staticMethod().onClassAny(TRUTH, PROTOTRUTH).named("assertThat");
private static final Matcher<ExpressionTree> TRUTH_VERB =
instanceMethod()
.onDescendantOf("com.google.common.truth.StandardSubjectBuilder")
.named("that");
private static final Matcher<ExpressionTree> ASSERTION = anyOf(TRUTH_ASSERTTHAT, TRUTH_VERB);
/**
* A heuristic for whether a method may have been invoked with an expected value.
*
* <p>We match cases such as {@code assertThat(expectedFoo)}, {@code
* assertThat(expectedBar.id())}, but not if the identifier extends {@link Throwable} (as this is
* often named {@code expectedException} or similar).
*/
private static boolean expectedValue(ExpressionTree tree, VisitorState state) {
if (!(tree instanceof MethodInvocationTree)) {
return false;
}
MethodInvocationTree methodTree = (MethodInvocationTree) tree;
IdentifierTree identifier = getRootIdentifier(getOnlyElement(methodTree.getArguments()));
if (identifier == null) {
return false;
}
Type throwable = Suppliers.typeFromClass(Throwable.class).get(state);
String identifierName = Ascii.toLowerCase(identifier.getName().toString());
return identifierName.contains("expected")
&& !identifierName.contains("actual")
&& !ASTHelpers.isSubtype(ASTHelpers.getType(identifier), throwable, state);
}
private static final Matcher<ExpressionTree> ASSERT_ON_EXPECTED =
allOf(ASSERTION, TruthAssertExpected::expectedValue);
/** Truth assertion chains which are commutative. Many are not, such as {@code containsAny}. */
private static final Matcher<ExpressionTree> REVERSIBLE_TERMINATORS =
anyOf(
instanceMethod()
.onDescendantOf("com.google.common.truth.Subject")
.namedAnyOf(
"isEqualTo",
"isNotEqualTo",
"isSameAs",
"isNotSameAs",
"containsExactlyElementsIn"),
instanceMethod()
.onDescendantOf("com.google.common.truth.MapSubject")
.named("containsExactlyEntriesIn"),
instanceMethod()
.onDescendantOf("com.google.common.truth.FloatSubject.TolerantFloatComparison")
.named("of"),
instanceMethod()
.onDescendantOf("com.google.common.truth.DoubleSubject.TolerantDoubleComparison")
.named("of"));
/**
* Matches expressions that look like they should be considered constant, i.e. {@code
* ImmutableList.of(1, 2)}, {@code Long.valueOf(10L)}.
*/
private static boolean isConstantCreator(ExpressionTree tree) {
List<? extends ExpressionTree> arguments =
tree.accept(
new SimpleTreeVisitor<List<? extends ExpressionTree>, Void>() {
@Override
public List<? extends ExpressionTree> visitNewClass(NewClassTree node, Void unused) {
return node.getArguments();
}
@Nullable
@Override
public List<? extends ExpressionTree> visitMethodInvocation(
MethodInvocationTree node, Void unused) {
MethodSymbol symbol = ASTHelpers.getSymbol(node);
if (!symbol.isStatic()) {
return null;
}
return node.getArguments();
}
},
null);
return arguments != null
&& arguments.stream().allMatch(argument -> ASTHelpers.constValue(argument) != null);
}
/** Matcher for a reversible assertion that appears to be the wrong way around. */
private static final Matcher<ExpressionTree> MATCH =
allOf(REVERSIBLE_TERMINATORS, hasReceiverMatching(ASSERT_ON_EXPECTED));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MATCH.matches(tree, state)) {
return Description.NO_MATCH;
}
if (expectedValue(tree, state)) {
return Description.NO_MATCH;
}
ExpressionTree assertion = findReceiverMatching(tree, state, ASSERT_ON_EXPECTED);
if (!(assertion instanceof MethodInvocationTree)) {
return Description.NO_MATCH;
}
ExpressionTree assertedArgument =
getOnlyElement(((MethodInvocationTree) assertion).getArguments());
ExpressionTree terminatingArgument = getOnlyElement(tree.getArguments());
// To avoid some false positives, skip anything where the terminating value is already a
// compile-time constant.
if (ASTHelpers.constValue(terminatingArgument) != null
|| Matchers.staticFieldAccess().matches(terminatingArgument, state)
|| isConstantCreator(terminatingArgument)) {
return Description.NO_MATCH;
}
SuggestedFix fix = SuggestedFix.swap(assertedArgument, terminatingArgument);
if (SuggestedFixes.compilesWithFix(fix, state)) {
return describeMatch(tree, fix);
}
return describeMatch(tree);
}
private static Matcher<ExpressionTree> hasReceiverMatching(Matcher<ExpressionTree> matcher) {
return (tree, state) -> findReceiverMatching(tree, state, matcher) != null;
}
/**
* Walks up the receivers for an expression chain until one matching {@code matcher} is found, and
* returns the matched {@link ExpressionTree}, or {@code null} if none match.
*/
@Nullable
private static ExpressionTree findReceiverMatching(
ExpressionTree tree, VisitorState state, Matcher<ExpressionTree> matcher) {
return streamReceivers(tree).filter(t -> matcher.matches(t, state)).findFirst().orElse(null);
}
/**
* Walks up the provided {@link ExpressionTree} to find the {@link IdentifierTree identifier} that
* it stems from. Returns {@code null} if the tree doesn't terminate in an identifier.
*/
@Nullable
private static IdentifierTree getRootIdentifier(ExpressionTree tree) {
if (tree == null) {
return null;
}
switch (tree.getKind()) {
case IDENTIFIER:
return (IdentifierTree) tree;
case MEMBER_SELECT:
case METHOD_INVOCATION:
return getRootIdentifier(ASTHelpers.getReceiver(tree));
default:
return null;
}
}
}
| 9,044
| 40.490826
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ClassCanBeStatic.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
/**
* @author alexloh@google.com (Alex Loh)
* @author cushon@google.com (Liam Miller-Cushon)
*/
@BugPattern(
summary = "Inner class is non-static but does not reference enclosing class",
severity = WARNING,
tags = {StandardTags.STYLE, StandardTags.PERFORMANCE})
public class ClassCanBeStatic extends BugChecker implements ClassTreeMatcher {
private static final String REFASTER_ANNOTATION =
"com.google.errorprone.refaster.annotation.BeforeTemplate";
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
ClassSymbol currentClass = ASTHelpers.getSymbol(tree);
if (!currentClass.hasOuterInstance()) {
return NO_MATCH;
}
if (currentClass.getNestingKind() != NestingKind.MEMBER) {
// local or anonymous classes can't be static
return NO_MATCH;
}
switch (currentClass.owner.enclClass().getNestingKind()) {
case TOP_LEVEL:
break;
case MEMBER:
// class is nested inside an inner class, so it can't be static
if (currentClass.owner.enclClass().hasOuterInstance()) {
return NO_MATCH;
}
break;
case LOCAL:
case ANONYMOUS:
// members of local and anonymous classes can't be static
return NO_MATCH;
}
if (tree.getExtendsClause() != null
&& ASTHelpers.getType(tree.getExtendsClause()).tsym.hasOuterInstance()) {
return NO_MATCH;
}
if (CanBeStaticAnalyzer.referencesOuter(tree, currentClass, state)) {
return NO_MATCH;
}
if (ASTHelpers.shouldKeep(tree)) {
return NO_MATCH;
}
if (tree.getMembers().stream().anyMatch(m -> hasAnnotation(m, REFASTER_ANNOTATION, state))) {
return NO_MATCH;
}
return describeMatch(
tree,
SuggestedFixes.addModifiers(tree, state, Modifier.STATIC).orElse(SuggestedFix.emptyFix()));
}
}
| 3,315
| 35.43956
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ObjectEqualsForPrimitives.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.argument;
import static com.google.errorprone.matchers.Matchers.isPrimitiveType;
import static com.google.errorprone.matchers.Matchers.staticEqualsInvocation;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.MethodInvocationTree;
/**
* Check for usage of {@code Objects.equal} on primitive types.
*
* @author vlk@google.com (Volodymyr Kachurovskyi)
*/
@BugPattern(
summary = "Avoid unnecessary boxing by using plain == for primitive types.",
tags = StandardTags.PERFORMANCE,
severity = WARNING)
public class ObjectEqualsForPrimitives extends BugChecker implements MethodInvocationTreeMatcher {
/** Matches when {@link java.util.Objects#equals}-like methods compare two primitive types. */
private static final Matcher<MethodInvocationTree> MATCHER =
allOf(
staticEqualsInvocation(), argument(0, isPrimitiveType()), argument(1, isPrimitiveType()));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
String arg1 = state.getSourceForNode(tree.getArguments().get(0));
String arg2 = state.getSourceForNode(tree.getArguments().get(1));
// TODO: Rewrite to a != b if the original code has a negation (e.g. !Object.equals)
Fix fix = SuggestedFix.builder().replace(tree, "(" + arg1 + " == " + arg2 + ")").build();
return describeMatch(tree, fix);
}
}
| 2,709
| 41.34375
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ComparableAndComparator.java
|
/* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import com.google.common.collect.Lists;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import java.util.Comparator;
import java.util.List;
/**
* @author sulku@google.com (Marsela Sulku)
* @author mariasam@google.com (Maria Sam)
*/
@BugPattern(
summary = "Class should not implement both `Comparable` and `Comparator`",
severity = WARNING)
public class ComparableAndComparator extends BugChecker implements ClassTreeMatcher {
private static final String COMPARABLE = Comparable.class.getCanonicalName();
private static final String COMPARATOR = Comparator.class.getCanonicalName();
/** Matches if a class/interface is subtype of Comparable */
private static final Matcher<Tree> COMPARABLE_MATCHER = isSubtypeOf(COMPARABLE);
/** Matches if a class/interface is subtype of Comparator */
private static final Matcher<Tree> COMPARATOR_MATCHER = isSubtypeOf(COMPARATOR);
/** Matches if a class/interface is subtype of Comparable _and_ Comparator */
private static final Matcher<Tree> COMPARABLE_AND_COMPARATOR_MATCHER =
allOf(COMPARABLE_MATCHER, COMPARATOR_MATCHER);
private static boolean matchAnySuperType(ClassTree tree, VisitorState state) {
List<Tree> superTypes = Lists.<Tree>newArrayList(tree.getImplementsClause());
Tree superClass = tree.getExtendsClause();
if (superClass != null) {
superTypes.add(superClass);
}
return superTypes.stream()
.anyMatch(superType -> COMPARABLE_AND_COMPARATOR_MATCHER.matches(superType, state));
}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (COMPARABLE_AND_COMPARATOR_MATCHER.matches(tree, state)) {
// Filter out inherited case to not warn again
if (matchAnySuperType(tree, state)) {
return Description.NO_MATCH;
}
// enums already implement Comparable and are simultaneously allowed to implement Comparator
ClassSymbol symbol = getSymbol(tree);
if (symbol.isEnum()) {
return Description.NO_MATCH;
}
return describeMatch(tree);
}
return Description.NO_MATCH;
}
}
| 3,336
| 38.258824
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JUnitAmbiguousTestClass.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.JUnitMatchers.isAmbiguousJUnitVersion;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.ClassTree;
/**
* @author mwacker@google.com (Mike Wacker)
*/
@BugPattern(
summary =
"Test class inherits from JUnit 3's TestCase but has JUnit 4 @Test or @RunWith"
+ " annotations.",
severity = WARNING)
public class JUnitAmbiguousTestClass extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree classTree, VisitorState state) {
return isAmbiguousJUnitVersion.matches(classTree, state) ? describeMatch(classTree) : NO_MATCH;
}
}
| 1,621
| 35.863636
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ComparisonContractViolated.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.compareToMethodDeclaration;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.methodHasArity;
import static com.google.errorprone.matchers.Matchers.methodHasVisibility;
import static com.google.errorprone.matchers.Matchers.methodIsNamed;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import static com.google.errorprone.matchers.MethodVisibility.Visibility.PUBLIC;
import static com.google.errorprone.suppliers.Suppliers.INT_TYPE;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import java.util.EnumSet;
import java.util.Set;
/**
* @author Louis Wasserman
*/
@BugPattern(
summary = "This comparison method violates the contract",
severity = SeverityLevel.ERROR)
public class ComparisonContractViolated extends BugChecker implements MethodTreeMatcher {
private static final Matcher<ClassTree> COMPARABLE_CLASS_MATCHER =
isSubtypeOf("java.lang.Comparable");
/** Matcher for the overriding method of 'int java.util.Comparator.compare(T o1, T o2)' */
private static final Matcher<MethodTree> COMPARATOR_METHOD_MATCHER =
allOf(
methodIsNamed("compare"),
methodHasVisibility(PUBLIC),
methodReturns(INT_TYPE),
methodHasArity(2));
private static final Matcher<ClassTree> COMPARATOR_CLASS_MATCHER =
isSubtypeOf("java.util.Comparator");
private enum ComparisonResult {
NEGATIVE_CONSTANT,
ZERO,
POSITIVE_CONSTANT,
NONCONSTANT;
}
private static final TreeVisitor<ComparisonResult, VisitorState> CONSTANT_VISITOR =
new SimpleTreeVisitor<ComparisonResult, VisitorState>(ComparisonResult.NONCONSTANT) {
private ComparisonResult forInt(int x) {
if (x < 0) {
return ComparisonResult.NEGATIVE_CONSTANT;
} else if (x > 0) {
return ComparisonResult.POSITIVE_CONSTANT;
} else {
return ComparisonResult.ZERO;
}
}
@Override
public ComparisonResult visitMemberSelect(MemberSelectTree node, VisitorState state) {
Symbol sym = ASTHelpers.getSymbol(node);
if (sym instanceof VarSymbol) {
Object value = ((VarSymbol) sym).getConstantValue();
if (value instanceof Integer) {
return forInt((Integer) value);
}
}
return super.visitMemberSelect(node, state);
}
@Override
public ComparisonResult visitIdentifier(IdentifierTree node, VisitorState state) {
Symbol sym = ASTHelpers.getSymbol(node);
if (sym instanceof VarSymbol) {
Object value = ((VarSymbol) sym).getConstantValue();
if (value instanceof Integer) {
return forInt((Integer) value);
}
}
return super.visitIdentifier(node, state);
}
@Override
public ComparisonResult visitLiteral(LiteralTree node, VisitorState state) {
if (node.getValue() instanceof Integer) {
return forInt((Integer) node.getValue());
}
return super.visitLiteral(node, state);
}
};
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (tree.getBody() == null) {
return Description.NO_MATCH;
}
// Test that the match is in a Comparable.compareTo or Comparator.compare method.
ClassTree declaringClass = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class);
if (!COMPARABLE_CLASS_MATCHER.matches(declaringClass, state)
&& !COMPARATOR_CLASS_MATCHER.matches(declaringClass, state)) {
return Description.NO_MATCH;
}
if (!compareToMethodDeclaration().matches(tree, state)
&& !COMPARATOR_METHOD_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
Set<ComparisonResult> seenResults = EnumSet.noneOf(ComparisonResult.class);
TreeVisitor<Void, VisitorState> visitReturnExpression =
new SimpleTreeVisitor<Void, VisitorState>() {
@Override
protected Void defaultAction(Tree node, VisitorState state) {
seenResults.add(node.accept(CONSTANT_VISITOR, state));
return null;
}
@Override
public Void visitConditionalExpression(
ConditionalExpressionTree node, VisitorState state) {
node.getTrueExpression().accept(this, state);
node.getFalseExpression().accept(this, state);
return null;
}
};
tree.getBody()
.accept(
new TreeScanner<Void, VisitorState>() {
@Override
public Void visitReturn(ReturnTree node, VisitorState state) {
return node.getExpression().accept(visitReturnExpression, state);
}
},
state);
if (seenResults.isEmpty() || seenResults.contains(ComparisonResult.NONCONSTANT)) {
return Description.NO_MATCH;
}
if (!seenResults.contains(ComparisonResult.ZERO)) {
if (tree.getBody().getStatements().size() == 1
&& tree.getBody().getStatements().get(0).getKind() == Kind.RETURN) {
ReturnTree returnTree = (ReturnTree) tree.getBody().getStatements().get(0);
if (returnTree.getExpression().getKind() == Kind.CONDITIONAL_EXPRESSION) {
ConditionalExpressionTree condTree =
(ConditionalExpressionTree) returnTree.getExpression();
ExpressionTree conditionExpr = condTree.getCondition();
conditionExpr = ASTHelpers.stripParentheses(conditionExpr);
if (!(conditionExpr instanceof BinaryTree)) {
return describeMatch(tree);
}
ComparisonResult trueConst = condTree.getTrueExpression().accept(CONSTANT_VISITOR, state);
ComparisonResult falseConst =
condTree.getFalseExpression().accept(CONSTANT_VISITOR, state);
boolean trueFirst;
if (trueConst == ComparisonResult.NEGATIVE_CONSTANT
&& falseConst == ComparisonResult.POSITIVE_CONSTANT) {
trueFirst = true;
} else if (trueConst == ComparisonResult.POSITIVE_CONSTANT
&& falseConst == ComparisonResult.NEGATIVE_CONSTANT) {
trueFirst = false;
} else {
return describeMatch(tree);
}
switch (conditionExpr.getKind()) {
case LESS_THAN:
case LESS_THAN_EQUAL:
break;
case GREATER_THAN:
case GREATER_THAN_EQUAL:
trueFirst = !trueFirst;
break;
default:
return describeMatch(tree);
}
BinaryTree binaryExpr = (BinaryTree) conditionExpr;
Type ty = ASTHelpers.getType(binaryExpr.getLeftOperand());
Types types = state.getTypes();
Symtab symtab = state.getSymtab();
ExpressionTree first =
trueFirst ? binaryExpr.getLeftOperand() : binaryExpr.getRightOperand();
ExpressionTree second =
trueFirst ? binaryExpr.getRightOperand() : binaryExpr.getLeftOperand();
String compareType;
if (types.isSameType(ty, symtab.intType)) {
compareType = "Integer";
} else if (types.isSameType(ty, symtab.longType)) {
compareType = "Long";
} else {
return describeMatch(tree);
}
return describeMatch(
condTree,
SuggestedFix.replace(
condTree,
String.format(
"%s.compare(%s, %s)",
compareType, state.getSourceForNode(first), state.getSourceForNode(second))));
}
}
return describeMatch(tree);
}
if (COMPARATOR_METHOD_MATCHER.matches(tree, state)
&& (seenResults.contains(ComparisonResult.NEGATIVE_CONSTANT)
!= seenResults.contains(ComparisonResult.POSITIVE_CONSTANT))) {
// note that a Comparable.compareTo implementation can be asymmetric!
// See e.g. com.google.common.collect.Cut.BelowAll.
return describeMatch(tree);
} else {
return Description.NO_MATCH;
}
}
}
| 10,142
| 38.162162
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SizeGreaterThanOrEqualsZero.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static java.util.stream.Collectors.joining;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Iterables;
import com.google.common.collect.Streams;
import com.google.common.collect.Table.Cell;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.regex.Pattern;
/**
* Finds instances where one uses {@code Collection#size() >= 0} or {@code T[].length > 0}. Those
* comparisons are always true for non-null objects, where the user likely meant to compare size
* {@literal >} 0 instead.
*
* @author glorioso@google.com (Nick Glorioso)
*/
@BugPattern(
summary =
"Comparison of a size >= 0 is always true, did you intend to check for " + "non-emptiness?",
severity = ERROR)
public class SizeGreaterThanOrEqualsZero extends BugChecker implements BinaryTreeMatcher {
private enum MethodName {
LENGTH,
SIZE
}
private enum ExpressionType {
LESS_THAN_EQUAL,
GREATER_THAN_EQUAL,
MISMATCH
}
// Class name, whether it uses SIZE or LENGTH, whether or not the class has an appropriate
// isEmpty() method
private static final ImmutableTable<String, MethodName, Boolean> CLASSES =
ImmutableTable.<String, MethodName, Boolean>builder()
.put("android.util.LongSparseArray", MethodName.SIZE, false)
.put("android.util.LruCache", MethodName.SIZE, false)
.put("android.util.SparseArray", MethodName.SIZE, false)
.put("android.util.SparseBooleanArray", MethodName.SIZE, false)
.put("android.util.SparseIntArray", MethodName.SIZE, false)
.put("android.util.SparseLongArray", MethodName.SIZE, false)
.put("androidx.collection.CircularArray", MethodName.SIZE, true)
.put("androidx.collection.CircularIntArray", MethodName.SIZE, true)
.put("androidx.collection.LongSparseArray", MethodName.SIZE, false)
.put("androidx.collection.LruCache", MethodName.SIZE, false)
.put("androidx.collection.SimpleArrayMap", MethodName.SIZE, true)
.put("androidx.collection.SparseArrayCompat", MethodName.SIZE, false)
.put("com.google.common.collect.FluentIterable", MethodName.SIZE, true)
.put("com.google.common.collect.Multimap", MethodName.SIZE, true)
.put("java.io.ByteArrayOutputStream", MethodName.SIZE, false)
.put("java.util.Collection", MethodName.SIZE, true)
.put("java.util.Dictionary", MethodName.SIZE, true)
.put("java.util.Map", MethodName.SIZE, true)
.put("java.util.BitSet", MethodName.LENGTH, true)
.put("java.lang.CharSequence", MethodName.LENGTH, false)
.put("java.lang.String", MethodName.LENGTH, true)
.put("java.lang.StringBuilder", MethodName.LENGTH, false)
.put("java.lang.StringBuffer", MethodName.LENGTH, false)
.buildOrThrow();
private static final ImmutableTable<String, MethodName, Boolean> STATIC_CLASSES =
ImmutableTable.<String, MethodName, Boolean>builder()
.put("com.google.common.collect.Iterables", MethodName.SIZE, true)
.buildOrThrow();
private static final Matcher<ExpressionTree> SIZE_OR_LENGTH_INSTANCE_METHOD =
anyOf(
instanceMethod()
.onDescendantOfAny(CLASSES.column(MethodName.SIZE).keySet())
.named("size"),
instanceMethod()
.onDescendantOfAny(CLASSES.column(MethodName.LENGTH).keySet())
.named("length"));
private static final Pattern PROTO_COUNT_METHOD_PATTERN = Pattern.compile("get(.+)Count");
private static final Matcher<ExpressionTree> PROTO_METHOD_NAMED_GET_COUNT =
instanceMethod()
.onDescendantOf("com.google.protobuf.GeneratedMessage")
.withNameMatching(PROTO_COUNT_METHOD_PATTERN)
.withNoParameters();
private static final Matcher<ExpressionTree> PROTO_REPEATED_FIELD_COUNT_METHOD =
SizeGreaterThanOrEqualsZero::isProtoRepeatedFieldCountMethod;
private static final Matcher<ExpressionTree> SIZE_OR_LENGTH_STATIC_METHOD =
anyOf(
Streams.concat(
STATIC_CLASSES.column(MethodName.SIZE).keySet().stream()
.map(className -> staticMethod().onClass(className).named("size")),
STATIC_CLASSES.column(MethodName.LENGTH).keySet().stream()
.map(className -> staticMethod().onClass(className).named("length")))
.collect(toImmutableList()));
private static boolean arrayLengthMatcher(MemberSelectTree tree, VisitorState state) {
return ASTHelpers.getSymbol(tree) == state.getSymtab().lengthVar;
}
private static final Matcher<ExpressionTree> HAS_EMPTY_METHOD = classHasIsEmptyFunction();
@Override
public Description matchBinary(BinaryTree tree, VisitorState state) {
// Easy stuff: needs to be a binary expression of the form foo >= 0 or 0 <= foo
ExpressionType expressionType = isGreaterThanEqualToZero(tree);
if (expressionType == ExpressionType.MISMATCH) {
return Description.NO_MATCH;
}
ExpressionTree operand =
expressionType == ExpressionType.GREATER_THAN_EQUAL
? tree.getLeftOperand()
: tree.getRightOperand();
if (operand instanceof MethodInvocationTree) {
MethodInvocationTree callToSize = (MethodInvocationTree) operand;
if (SIZE_OR_LENGTH_INSTANCE_METHOD.matches(callToSize, state)) {
return provideReplacementForInstanceMethodInvocation(
tree, callToSize, state, expressionType);
} else if (SIZE_OR_LENGTH_STATIC_METHOD.matches(callToSize, state)) {
return provideReplacementForStaticMethodInvocation(tree, callToSize, state, expressionType);
} else if (PROTO_REPEATED_FIELD_COUNT_METHOD.matches(callToSize, state)) {
return provideReplacementForProtoMethodInvocation(tree, callToSize, state);
}
} else if (operand instanceof MemberSelectTree) {
if (arrayLengthMatcher((MemberSelectTree) operand, state)) {
return removeEqualsFromComparison(tree, state, expressionType);
}
}
return Description.NO_MATCH;
}
private static boolean isProtoRepeatedFieldCountMethod(ExpressionTree tree, VisitorState state) {
// Instance method, on proto class, named `get<Field>Count`.
if (!PROTO_METHOD_NAMED_GET_COUNT.matches(tree, state)) {
return false;
}
// Make sure it's the count method for a repeated field, not the get method for a non-repeated
// field named <something>_count, by checking for other methods on the repeated field.
MethodSymbol methodCallSym = getSymbol((MethodInvocationTree) tree);
Scope protoClassMembers = methodCallSym.owner.members();
java.util.regex.Matcher getCountRegexMatcher =
PROTO_COUNT_METHOD_PATTERN.matcher(methodCallSym.getSimpleName().toString());
if (!getCountRegexMatcher.matches()) {
return false;
}
String fieldName = getCountRegexMatcher.group(1);
return protoClassMembers.findFirst(state.getName("get" + fieldName + "List")) != null;
}
// From the defined classes above, return a matcher that will match an expression if its type
// contains a well-behaved isEmpty() method.
private static Matcher<ExpressionTree> classHasIsEmptyFunction() {
ImmutableList.Builder<String> classNames = ImmutableList.builder();
for (Cell<String, MethodName, Boolean> methodInformation :
Iterables.concat(CLASSES.cellSet(), STATIC_CLASSES.cellSet())) {
if (methodInformation.getValue()) {
classNames.add(methodInformation.getRowKey());
}
}
return anyOf(classNames.build().stream().map(Matchers::isSubtypeOf).collect(toImmutableList()));
}
private Description provideReplacementForInstanceMethodInvocation(
BinaryTree tree,
MethodInvocationTree leftOperand,
VisitorState state,
ExpressionType expressionType) {
ExpressionTree collection = getReceiver(leftOperand);
if (HAS_EMPTY_METHOD.matches(collection, state)) {
return describeMatch(
tree,
SuggestedFix.replace(tree, "!" + state.getSourceForNode(collection) + ".isEmpty()"));
} else {
return removeEqualsFromComparison(tree, state, expressionType);
}
}
private Description provideReplacementForStaticMethodInvocation(
BinaryTree tree,
MethodInvocationTree callToSize,
VisitorState state,
ExpressionType expressionType) {
ExpressionTree classToken = getReceiver(callToSize);
if (HAS_EMPTY_METHOD.matches(classToken, state)) {
String argumentString =
callToSize.getArguments().stream().map(state::getSourceForNode).collect(joining(","));
return describeMatch(
tree,
SuggestedFix.replace(
tree, "!" + state.getSourceForNode(classToken) + ".isEmpty(" + argumentString + ")"));
} else {
return removeEqualsFromComparison(tree, state, expressionType);
}
}
private Description provideReplacementForProtoMethodInvocation(
BinaryTree tree, MethodInvocationTree protoGetSize, VisitorState state) {
String expSrc = state.getSourceForNode(protoGetSize);
java.util.regex.Matcher protoGetCountMatcher = PROTO_COUNT_METHOD_PATTERN.matcher(expSrc);
if (!protoGetCountMatcher.find()) {
throw new AssertionError(
state.getSourceForNode(protoGetSize)
+ " does not contain a get<RepeatedField>Count method");
}
return describeMatch(
tree,
SuggestedFix.replace(
tree,
"!"
+ protoGetCountMatcher.replaceFirst("get" + protoGetCountMatcher.group(1) + "List")
+ ".isEmpty()"));
}
private Description removeEqualsFromComparison(
BinaryTree tree, VisitorState state, ExpressionType expressionType) {
String replacement =
expressionType == ExpressionType.GREATER_THAN_EQUAL
? state.getSourceForNode(tree.getLeftOperand()) + " > 0"
: "0 < " + state.getSourceForNode(tree.getRightOperand());
return describeMatch(tree, SuggestedFix.replace(tree, replacement));
}
private static ExpressionType isGreaterThanEqualToZero(BinaryTree tree) {
ExpressionTree literalOperand;
ExpressionType returnType;
switch (tree.getKind()) {
case GREATER_THAN_EQUAL:
literalOperand = tree.getRightOperand();
returnType = ExpressionType.GREATER_THAN_EQUAL;
break;
case LESS_THAN_EQUAL:
literalOperand = tree.getLeftOperand();
returnType = ExpressionType.LESS_THAN_EQUAL;
break;
default:
return ExpressionType.MISMATCH;
}
if (literalOperand.getKind() != Kind.INT_LITERAL) {
return ExpressionType.MISMATCH;
}
if (!((LiteralTree) literalOperand).getValue().equals(0)) {
return ExpressionType.MISMATCH;
}
return returnType;
}
}
| 12,749
| 42.814433
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AttemptedNegativeZero.java
|
/*
* Copyright 2023 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.constValue;
import static com.google.errorprone.util.ASTHelpers.targetType;
import static com.sun.source.tree.Tree.Kind.UNARY_MINUS;
import static com.sun.tools.javac.code.TypeTag.DOUBLE;
import static com.sun.tools.javac.code.TypeTag.FLOAT;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.UnaryTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.UnaryTree;
/** A BugPattern; see the summary. */
@BugPattern(
severity = WARNING,
summary = "-0 is the same as 0. For the floating-point negative zero, use -0.0.")
public class AttemptedNegativeZero extends BugChecker implements UnaryTreeMatcher {
@Override
public Description matchUnary(UnaryTree tree, VisitorState state) {
if (tree.getKind() != UNARY_MINUS) {
return NO_MATCH;
}
Object negatedConstValue = constValue(tree.getExpression());
if (negatedConstValue == null) {
return NO_MATCH;
}
if (!negatedConstValue.equals(0) && !negatedConstValue.equals(0L)) {
return NO_MATCH;
}
String replacement;
switch (targetType(state).type().getTag()) {
case DOUBLE:
replacement = "-0.0";
break;
case FLOAT:
replacement = "-0.0f";
break;
default:
return NO_MATCH;
}
return describeMatch(tree, SuggestedFix.builder().replace(tree, replacement).build());
}
}
| 2,352
| 35.2
| 90
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ImmutableCollections.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.common.collect.ImmutableMap;
import com.sun.tools.javac.code.Type;
import java.util.Optional;
/** Common utility functions for immutable collections. */
public final class ImmutableCollections {
private ImmutableCollections() {}
public static final ImmutableMap<String, String> MUTABLE_TO_IMMUTABLE_CLASS_NAME_MAP =
ImmutableMap.<String, String>builder()
.put(
com.google.common.collect.BiMap.class.getName(),
com.google.common.collect.ImmutableBiMap.class.getName())
.put(
com.google.common.collect.ListMultimap.class.getName(),
com.google.common.collect.ImmutableListMultimap.class.getName())
.put(
com.google.common.collect.Multimap.class.getName(),
com.google.common.collect.ImmutableMultimap.class.getName())
.put(
com.google.common.collect.Multiset.class.getName(),
com.google.common.collect.ImmutableMultiset.class.getName())
.put(
com.google.common.collect.RangeMap.class.getName(),
com.google.common.collect.ImmutableRangeMap.class.getName())
.put(
com.google.common.collect.RangeSet.class.getName(),
com.google.common.collect.ImmutableRangeSet.class.getName())
.put(
com.google.common.collect.SetMultimap.class.getName(),
com.google.common.collect.ImmutableSetMultimap.class.getName())
.put(
com.google.common.collect.SortedMultiset.class.getName(),
com.google.common.collect.ImmutableSortedMultiset.class.getName())
.put(
com.google.common.collect.Table.class.getName(),
com.google.common.collect.ImmutableTable.class.getName())
.put(
java.util.Collection.class.getName(),
com.google.common.collect.ImmutableCollection.class.getName())
.put(
java.util.List.class.getName(),
com.google.common.collect.ImmutableList.class.getName())
.put(
java.util.Map.class.getName(), com.google.common.collect.ImmutableMap.class.getName())
.put(
java.util.NavigableMap.class.getName(),
com.google.common.collect.ImmutableSortedMap.class.getName())
.put(
java.util.NavigableSet.class.getName(),
com.google.common.collect.ImmutableSortedSet.class.getName())
.put(
java.util.Set.class.getName(), com.google.common.collect.ImmutableSet.class.getName())
.put(
java.util.EnumSet.class.getName(),
com.google.common.collect.ImmutableSet.class.getName())
.put(
java.util.ArrayList.class.getName(),
com.google.common.collect.ImmutableList.class.getName())
.put(
java.util.HashMap.class.getName(),
com.google.common.collect.ImmutableMap.class.getName())
.put(
java.util.HashSet.class.getName(),
com.google.common.collect.ImmutableSet.class.getName())
.put(
java.util.EnumMap.class.getName(),
com.google.common.collect.ImmutableMap.class.getName())
.buildOrThrow();
public static boolean isImmutableType(Type type) {
return MUTABLE_TO_IMMUTABLE_CLASS_NAME_MAP.containsValue(getTypeQualifiedName(type));
}
static Optional<String> mutableToImmutable(String fullyQualifiedClassName) {
return Optional.ofNullable(MUTABLE_TO_IMMUTABLE_CLASS_NAME_MAP.get(fullyQualifiedClassName));
}
private static String getTypeQualifiedName(Type type) {
return type.tsym.getQualifiedName().toString();
}
}
| 4,422
| 42.362745
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AutoValueFinalMethods.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.not;
import com.google.common.base.Joiner;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.lang.model.element.Modifier;
/**
* Checks the toString(), hashCode() and equals() methods are final in AutoValue classes.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary =
"Make toString(), hashCode() and equals() final in AutoValue classes"
+ ", so it is clear to readers that AutoValue is not overriding them",
severity = WARNING)
public class AutoValueFinalMethods extends BugChecker implements ClassTreeMatcher {
private static final String MEMOIZED = "com.google.auto.value.extension.memoized.Memoized";
// public non-memoized non-final eq/ts/hs methods
private static final Matcher<MethodTree> METHOD_MATCHER =
allOf(
Matchers.<MethodTree>hasModifier(Modifier.PUBLIC),
not(Matchers.<MethodTree>hasModifier(Modifier.ABSTRACT)),
not(Matchers.<MethodTree>hasModifier(Modifier.FINAL)),
not(Matchers.<MethodTree>hasAnnotation(MEMOIZED)),
anyOf(
Matchers.equalsMethodDeclaration(),
Matchers.toStringMethodDeclaration(),
Matchers.hashCodeMethodDeclaration()));
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (!ASTHelpers.hasAnnotation(tree, "com.google.auto.value.AutoValue", state)) {
return NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
List<String> matchedMethods = new ArrayList<>();
MethodTree firstMatchedMethod = null;
for (Tree memberTree : tree.getMembers()) {
if (!(memberTree instanceof MethodTree)) {
continue;
}
MethodTree method = (MethodTree) memberTree;
if (METHOD_MATCHER.matches(method, state)) {
Optional<SuggestedFix> optionalSuggestedFix =
SuggestedFixes.addModifiers(method, state, Modifier.FINAL);
if (optionalSuggestedFix.isPresent()) {
matchedMethods.add(method.getName().toString());
fix.merge(optionalSuggestedFix.get());
if (firstMatchedMethod == null) {
firstMatchedMethod = method;
}
}
}
}
if (!fix.isEmpty()) {
String message =
String.format(
"Make %s final in AutoValue classes, "
+ "so it is clear to readers that AutoValue is not overriding them",
Joiner.on(", ").join(matchedMethods));
return buildDescription(firstMatchedMethod).setMessage(message).addFix(fix.build()).build();
}
return NO_MATCH;
}
}
| 4,155
| 38.580952
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TypeNameShadowing.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Streams;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.bugpatterns.TypeParameterNaming.TypeParameterNamingClassification;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TypeParameterTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Symbol.TypeVariableSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.tree.JCTree.Tag;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* Warns when a type parameter shadows another type name in scope.
*
* @author bennostein@google.com (Benno Stein)
*/
@BugPattern(
summary = "Type parameter declaration shadows another named type",
severity = WARNING,
tags = StandardTags.STYLE)
public class TypeNameShadowing extends BugChecker implements MethodTreeMatcher, ClassTreeMatcher {
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (tree.getTypeParameters().isEmpty()) {
return Description.NO_MATCH;
}
return findShadowedTypes(tree, tree.getTypeParameters(), state);
}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (tree.getTypeParameters().isEmpty()) {
return Description.NO_MATCH;
}
return findShadowedTypes(tree, tree.getTypeParameters(), state);
}
/**
* Returns a list of type symbols in the scope enclosing {@code env} guaranteeing that, when two
* symbols share a simple name, the shadower precedes the shadow-ee
*/
private static Iterable<Symbol> typesInEnclosingScope(
Env<AttrContext> env, PackageSymbol javaLang) {
// Collect all visible type names declared in this source file by ascending lexical scopes,
// collecting all members, filtering to keep type symbols and exclude TypeVariableSymbols
// (otherwise, every type parameter spuriously shadows itself)
ImmutableList<Symbol> localSymbolsInScope =
Streams.stream(env)
.map(
ctx ->
ctx.tree.getTag() == Tag.CLASSDEF
? ASTHelpers.getSymbol(ctx.tree).members().getSymbols()
: ctx.info.getLocalElements())
.flatMap(
symbols ->
Streams.stream(symbols)
.filter(
sym ->
sym instanceof TypeSymbol && !(sym instanceof TypeVariableSymbol)))
.collect(ImmutableList.toImmutableList());
// Concatenate with all visible type names declared in other source files:
// Ignore wildcard imports here since we don't use them and they can cause issues (b/109867096)
return Iterables.concat(
localSymbolsInScope, // Local symbols
env.toplevel.namedImportScope.getSymbols(), // Explicitly named imports
javaLang.members().getSymbols(), // implicitly imported java.lang.* symbols
env.toplevel.packge.members().getSymbols()); // Siblings in class hierarchy
}
/** Iterate through a list of type parameters, looking for type names shadowed by any of them. */
private Description findShadowedTypes(
Tree tree, List<? extends TypeParameterTree> typeParameters, VisitorState state) {
Env<AttrContext> env =
Enter.instance(state.context)
.getEnv(ASTHelpers.getSymbol(state.findEnclosing(ClassTree.class)));
Symtab symtab = state.getSymtab();
PackageSymbol javaLang = symtab.enterPackage(symtab.java_base, state.getNames().java_lang);
Iterable<Symbol> enclosingTypes = typesInEnclosingScope(env, javaLang);
ImmutableList<Symbol> shadowedTypes =
typeParameters.stream()
.map(
param ->
Iterables.tryFind(
enclosingTypes,
sym ->
sym.getSimpleName()
.equals(ASTHelpers.getType(param).tsym.getSimpleName()))
.orNull())
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
if (shadowedTypes.isEmpty()) {
return Description.NO_MATCH;
}
Description.Builder descBuilder = buildDescription(tree);
descBuilder.setMessage(buildMessage(shadowedTypes));
ImmutableSet<String> visibleNames =
Streams.stream(Iterables.concat(env.info.getLocalElements(), enclosingTypes))
.map(sym -> sym.getSimpleName().toString())
.collect(ImmutableSet.toImmutableSet());
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
shadowedTypes.stream()
.filter(tv -> TypeParameterNamingClassification.classify(tv.name.toString()).isValidName())
.map(
tv ->
SuggestedFixes.renameTypeParameter(
TypeParameterShadowing.typeParameterInList(typeParameters, tv),
tree,
TypeParameterShadowing.replacementTypeVarName(tv.name, visibleNames),
state))
.forEach(fixBuilder::merge);
descBuilder.addFix(fixBuilder.build());
return descBuilder.build();
}
private static String buildMessage(List<Symbol> shadowedTypes) {
return "Found type parameters shadowing other declared types:\n\t"
+ shadowedTypes.stream()
.map(
sym ->
"Type parameter "
+ sym.getSimpleName()
+ " shadows visible type "
+ sym.flatName())
.collect(Collectors.joining("\n\t"));
}
}
| 7,258
| 39.553073
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryStringBuilder.java
|
/*
* Copyright 2023 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.method.MethodMatchers.constructor;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static com.google.errorprone.util.ASTHelpers.requiresParentheses;
import static com.google.errorprone.util.ASTHelpers.targetType;
import static java.util.stream.Collectors.joining;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.ASTHelpers.TargetType;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.util.Position;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.element.ElementKind;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Prefer string concatenation over explicitly using `StringBuilder#append`, since `+` reads"
+ " better and has equivalent or better performance.",
severity = BugPattern.SeverityLevel.WARNING)
public class UnnecessaryStringBuilder extends BugChecker implements NewClassTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
constructor().forClass("java.lang.StringBuilder");
private static final Matcher<ExpressionTree> APPEND =
instanceMethod().onExactClass("java.lang.StringBuilder").named("append");
private static final Matcher<ExpressionTree> TO_STRING =
instanceMethod().onExactClass("java.lang.StringBuilder").named("toString");
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
List<ExpressionTree> parts = new ArrayList<>();
switch (tree.getArguments().size()) {
case 0:
break;
case 1:
ExpressionTree argument = getOnlyElement(tree.getArguments());
if (isSubtype(getType(argument), JAVA_LANG_CHARSEQUENCE.get(state), state)) {
parts.add(argument);
}
break;
default:
return NO_MATCH;
}
TreePath path = state.getPath();
while (true) {
TreePath parentPath = path.getParentPath();
if (!(parentPath.getLeaf() instanceof MemberSelectTree)) {
break;
}
TreePath grandParent = parentPath.getParentPath();
if (!(grandParent.getLeaf() instanceof MethodInvocationTree)) {
break;
}
MethodInvocationTree methodInvocationTree = (MethodInvocationTree) grandParent.getLeaf();
if (!methodInvocationTree.getMethodSelect().equals(parentPath.getLeaf())) {
break;
}
if (APPEND.matches(methodInvocationTree, state)) {
if (methodInvocationTree.getArguments().size() != 1) {
// an append method that doesn't transliterate to concat
return NO_MATCH;
}
parts.add(getOnlyElement(methodInvocationTree.getArguments()));
path = parentPath.getParentPath();
} else if (TO_STRING.matches(methodInvocationTree, state)) {
return describeMatch(
methodInvocationTree,
SuggestedFix.replace(methodInvocationTree, replacement(state, parts)));
} else {
// another instance method on StringBuilder
return NO_MATCH;
}
}
ASTHelpers.TargetType target = ASTHelpers.targetType(state.withPath(path));
if (!isUsedAsStringBuilder(state, target)) {
return describeMatch(
path.getLeaf(), SuggestedFix.replace(path.getLeaf(), replacement(state, parts)));
}
Tree leaf = target.path().getLeaf();
if (leaf instanceof VariableTree) {
VariableTree variableTree = (VariableTree) leaf;
if (isRewritableVariable(variableTree, state)) {
SuggestedFix.Builder fix = SuggestedFix.builder();
if (state.getEndPosition(variableTree.getType()) != Position.NOPOS) {
// If the variable is declared with `var`, there's no declaration type to change
fix.replace(variableTree.getType(), "String");
}
fix.replace(variableTree.getInitializer(), replacement(state, parts));
return describeMatch(variableTree, fix.build());
}
}
return NO_MATCH;
}
/**
* Returns true if the StringBuilder is assigned to a variable, and the type of the variable can
* safely be refactored to be a String.
*/
boolean isRewritableVariable(VariableTree variableTree, VisitorState state) {
Symbol sym = getSymbol(variableTree);
if (!sym.getKind().equals(ElementKind.LOCAL_VARIABLE)) {
return false;
}
boolean[] ok = {true};
new TreePathScanner<Void, Void>() {
@Override
public Void visitIdentifier(IdentifierTree tree, Void unused) {
if (sym.equals(getSymbol(tree))) {
TargetType target = targetType(state.withPath(getCurrentPath()));
if (isUsedAsStringBuilder(state, target)) {
ok[0] = false;
}
}
return super.visitIdentifier(tree, unused);
}
}.scan(state.getPath().getCompilationUnit(), null);
return ok[0];
}
private static boolean isUsedAsStringBuilder(VisitorState state, TargetType target) {
if (target.path().getLeaf().getKind().equals(Tree.Kind.MEMBER_REFERENCE)) {
// e.g. sb::append
return true;
}
return ASTHelpers.isSubtype(target.type(), JAVA_LANG_APPENDABLE.get(state), state);
}
private static String replacement(VisitorState state, List<ExpressionTree> parts) {
if (parts.isEmpty()) {
return "\"\"";
}
return parts.stream()
.map(
x -> {
String source = state.getSourceForNode(x);
if (requiresParentheses(x, state)) {
source = String.format("(%s)", source);
}
return source;
})
.collect(joining(" + "));
}
private static final Supplier<Type> JAVA_LANG_APPENDABLE =
VisitorState.memoize(state -> state.getTypeFromString("java.lang.Appendable"));
private static final Supplier<Type> JAVA_LANG_CHARSEQUENCE =
VisitorState.memoize(state -> state.getTypeFromString("java.lang.CharSequence"));
}
| 7,818
| 39.097436
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnicodeDirectionalityCharacters.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.FixedPosition;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.CompilationUnitTree;
/** Bans, without the possibility of suppression, the use of direction-changing Unicode escapes. */
@BugPattern(
severity = ERROR,
summary = "Unicode directionality modifiers can be used to conceal code in many editors.",
disableable = false)
public final class UnicodeDirectionalityCharacters extends BugChecker
implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
CharSequence source = state.getSourceCode();
for (int i = 0; i < source.length(); ++i) {
char c = source.charAt(i);
// Do not extract this switch to a method. It's ugly as-is, but profiling suggests this
// checker is expensive for large files, and also that the method-call overhead would
// double the time spent in this loop.
switch (c) {
case 0x202A: // Left-to-Right Embedding
case 0x202B: // Right-to-Left Embedding
case 0x202C: // Pop Directional Formatting
case 0x202D: // Left-to-Right Override
case 0x202E: // Right-to-Left Override
case 0x2066: // Left-to-Right Isolate
case 0x2067: // Right-to-Left Isolate
case 0x2068: // First Strong Isolate
case 0x2069: // Pop Directional Isolate
state.reportMatch(
describeMatch(
new FixedPosition(tree, i),
SuggestedFix.replace(i, i + 1, String.format("\\u%04x", (int) c))));
break;
default:
break;
}
}
return NO_MATCH;
}
}
| 2,713
| 38.911765
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BadComparable.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.compareToMethodDeclaration;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.methodHasArity;
import static com.google.errorprone.matchers.Matchers.methodHasVisibility;
import static com.google.errorprone.matchers.Matchers.methodIsNamed;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import static com.google.errorprone.matchers.MethodVisibility.Visibility.PUBLIC;
import static com.google.errorprone.suppliers.Suppliers.INT_TYPE;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.TypeCastTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TypeCastTree;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTag;
/**
* @author irogers@google.com (Ian Rogers)
*/
@BugPattern(
summary = "Possible sign flip from narrowing conversion",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public class BadComparable extends BugChecker implements TypeCastTreeMatcher {
private static final Matcher<ClassTree> COMPARABLE_CLASS_MATCHER =
isSubtypeOf("java.lang.Comparable");
/** Matcher for the overriding method of 'int java.util.Comparator.compare(T o1, T o2)' */
private static final Matcher<MethodTree> COMPARATOR_METHOD_MATCHER =
allOf(
methodIsNamed("compare"),
methodHasVisibility(PUBLIC),
methodReturns(INT_TYPE),
methodHasArity(2));
private static final Matcher<ClassTree> COMPARATOR_CLASS_MATCHER =
isSubtypeOf("java.util.Comparator");
/**
* Compute the type of the subtract BinaryTree. We use the type of the left/right operand except
* when they're not the same, in which case we prefer the type of the expression. This ensures
* that a byte/short subtracted from another byte/short isn't regarded as an int.
*/
private static Type getTypeOfSubtract(BinaryTree expression, VisitorState state) {
Type expressionType = ASTHelpers.getType(expression.getLeftOperand());
if (!ASTHelpers.isSameType(
expressionType, ASTHelpers.getType(expression.getRightOperand()), state)) {
return ASTHelpers.getType(expression);
}
return expressionType;
}
/**
* Matches if this is a narrowing integral cast between signed types where the expression is a
* subtract.
*/
private static boolean matches(TypeCastTree tree, VisitorState state) {
Type treeType = ASTHelpers.getType(tree.getType());
// If the cast isn't narrowing to an int then don't implicate it in the bug pattern.
if (treeType.getTag() != TypeTag.INT) {
return false;
}
// The expression should be a subtract but remove parentheses.
ExpressionTree expression = ASTHelpers.stripParentheses(tree.getExpression());
if (expression.getKind() != Kind.MINUS) {
return false;
}
// Ensure the expression type is wider and signed (ie a long) than the cast type ignoring
// boxing.
Type expressionType = getTypeOfSubtract((BinaryTree) expression, state);
TypeTag expressionTypeTag = state.getTypes().unboxedTypeOrType(expressionType).getTag();
return (expressionTypeTag == TypeTag.LONG);
}
@Override
public Description matchTypeCast(TypeCastTree tree, VisitorState state) {
// Check for a narrowing match first as its simplest match to test.
if (!matches(tree, state)) {
return Description.NO_MATCH;
}
// Test that the match is in a Comparable.compareTo or Comparator.compare method.
ClassTree declaringClass = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class);
if (!COMPARABLE_CLASS_MATCHER.matches(declaringClass, state)
&& !COMPARATOR_CLASS_MATCHER.matches(declaringClass, state)) {
return Description.NO_MATCH;
}
MethodTree method = ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class);
if (method == null) {
return Description.NO_MATCH;
}
if (!compareToMethodDeclaration().matches(method, state)
&& !COMPARATOR_METHOD_MATCHER.matches(method, state)) {
return Description.NO_MATCH;
}
// Get the unparenthesized expression.
BinaryTree subtract = (BinaryTree) ASTHelpers.stripParentheses(tree.getExpression());
ExpressionTree lhs = subtract.getLeftOperand();
ExpressionTree rhs = subtract.getRightOperand();
Fix fix;
if (ASTHelpers.getType(lhs).isPrimitive()) {
fix =
SuggestedFix.replace(
tree,
"Long.compare("
+ state.getSourceForNode(lhs)
+ ", "
+ state.getSourceForNode(rhs)
+ ")");
} else {
fix =
SuggestedFix.replace(
tree,
state.getSourceForNode(lhs) + ".compareTo(" + state.getSourceForNode(rhs) + ")");
}
return describeMatch(tree, fix);
}
}
| 6,238
| 39.251613
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/EmptyTopLevelDeclaration.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.Tree;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "Empty top-level type declarations should be omitted", severity = WARNING)
public final class EmptyTopLevelDeclaration extends BugChecker
implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
ImmutableList<Tree> toDelete =
tree.getTypeDecls().stream()
.filter(m -> m.getKind() == Tree.Kind.EMPTY_STATEMENT)
.collect(toImmutableList());
if (toDelete.isEmpty()) {
return NO_MATCH;
}
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
toDelete.forEach(fixBuilder::delete);
return describeMatch(toDelete.get(0), fixBuilder.build());
}
}
| 2,066
| 39.529412
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ModifiedButNotUsed.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.Streams.concat;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.kindIs;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.constructor;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;
import static com.google.errorprone.util.ASTHelpers.streamReceivers;
import static java.util.stream.Collectors.joining;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ExpressionStatementTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.IsSubtypeOf;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.predicates.type.DescendantOf;
import com.google.errorprone.predicates.type.DescendantOfAny;
import com.google.errorprone.suppliers.Suppliers;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.SideEffectAnalysis;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* Matches creation of new collections/proto builders which are modified but never used.
*
* @author ghm@google.com (Graeme Morgan)
*/
@BugPattern(
summary = "A collection or proto builder was created, but its values were never accessed.",
severity = WARNING)
public class ModifiedButNotUsed extends BugChecker
implements ExpressionStatementTreeMatcher, VariableTreeMatcher {
private static final ImmutableSet<String> GUAVA_IMMUTABLES =
ImmutableSet.of(
"com.google.common.collect.ImmutableCollection",
"com.google.common.collect.ImmutableMap",
"com.google.common.collect.ImmutableMultimap");
private static final ImmutableSet<String> COLLECTIONS =
concat(
GUAVA_IMMUTABLES.stream().map(i -> i + ".Builder"),
Stream.of(
"java.util.Collection", "java.util.Map", "com.google.common.collect.Multimap"))
.collect(toImmutableSet());
private static final Matcher<ExpressionTree> COLLECTION_SETTER =
instanceMethod()
.onDescendantOfAny(COLLECTIONS)
.namedAnyOf(
"add",
"addAll",
"clear",
"put",
"putAll",
"remove",
"removeAll",
"removeIf",
"replaceAll",
"retainAll",
"set",
"sort");
private static final String MESSAGE = "com.google.protobuf.MessageLite";
private static final String MESSAGE_BUILDER = MESSAGE + ".Builder";
static final Matcher<ExpressionTree> FLUENT_SETTER =
anyOf(
instanceMethod()
.onDescendantOf(MESSAGE_BUILDER)
.withNameMatching(Pattern.compile("(add|clear|merge|remove|set|put).*")),
instanceMethod()
.onDescendantOfAny(
GUAVA_IMMUTABLES.stream().map(c -> c + ".Builder").collect(toImmutableSet()))
.namedAnyOf("add", "addAll", "put", "putAll"));
private static final Matcher<ExpressionTree> FLUENT_CHAIN =
anyOf(
FLUENT_SETTER,
instanceMethod()
.onDescendantOf(MESSAGE_BUILDER)
.withNameMatching(Pattern.compile("get.+")));
private static final Matcher<Tree> COLLECTION_TYPE =
anyOf(COLLECTIONS.stream().map(IsSubtypeOf::new).collect(toImmutableList()));
private static final Matcher<Tree> PROTO_TYPE = new IsSubtypeOf<>(MESSAGE_BUILDER);
private static final Matcher<ExpressionTree> FLUENT_CONSTRUCTOR =
anyOf(
allOf(
kindIs(Kind.NEW_CLASS),
constructor()
.forClass(
new DescendantOfAny(
GUAVA_IMMUTABLES.stream()
.map(i -> Suppliers.typeFromString(i + ".Builder"))
.collect(toImmutableList())))),
staticMethod()
.onDescendantOfAny(GUAVA_IMMUTABLES)
.namedAnyOf("builder", "builderWithExpectedSize"),
allOf(
kindIs(Kind.NEW_CLASS),
constructor().forClass(new DescendantOf(Suppliers.typeFromString(MESSAGE_BUILDER)))),
staticMethod().onDescendantOf(MESSAGE).named("newBuilder"),
instanceMethod().onDescendantOf(MESSAGE).namedAnyOf("toBuilder", "newBuilderForType"));
private static final Matcher<ExpressionTree> NEW_COLLECTION =
anyOf(
constructor()
.forClass(
new DescendantOfAny(
COLLECTIONS.stream()
.map(Suppliers::typeFromString)
.collect(toImmutableList()))),
staticMethod()
.onClassAny(
"com.google.common.collect.Lists",
"com.google.common.collect.Maps",
"com.google.common.collect.Sets")
.withNameMatching(Pattern.compile("new.+")));
private static final Matcher<ExpressionTree> BUILD_CALL =
anyOf(
instanceMethod()
.onDescendantOf("com.google.protobuf.MessageLite.Builder")
.namedAnyOf("build", "buildPartial"),
instanceMethod()
.onDescendantOfAny(
GUAVA_IMMUTABLES.stream().map(c -> c + ".Builder").collect(toImmutableList()))
.named("build"));
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
VarSymbol symbol = getSymbol(tree);
if (!isConsideredFinal(symbol)) {
return NO_MATCH;
}
if (state.getPath().getParentPath().getLeaf() instanceof ClassTree) {
return NO_MATCH;
}
if (!COLLECTION_TYPE.matches(tree, state) && !PROTO_TYPE.matches(tree, state)) {
return NO_MATCH;
}
List<TreePath> initializers = new ArrayList<>();
if (tree.getInitializer() == null) {
new TreePathScanner<Void, Void>() {
@Override
public Void visitAssignment(AssignmentTree node, Void unused) {
if (symbol.equals(getSymbol(node.getVariable()))) {
initializers.add(new TreePath(getCurrentPath(), node.getExpression()));
}
return super.visitAssignment(node, unused);
}
}.scan(state.getPath().getParentPath(), null);
} else {
initializers.add(new TreePath(state.getPath(), tree.getInitializer()));
}
if (initializers.size() != 1) {
return NO_MATCH;
}
TreePath initializerPath = getOnlyElement(initializers);
ExpressionTree initializer = (ExpressionTree) initializerPath.getLeaf();
if (!NEW_COLLECTION.matches(initializer, state) && !newFluentChain(initializer, state)) {
return NO_MATCH;
}
UnusedScanner isUnusedScanner = new UnusedScanner(symbol, state, getMatcher(tree, state));
isUnusedScanner.scan(state.getPath().getParentPath(), null);
if (isUnusedScanner.isUsed) {
return NO_MATCH;
}
ImmutableList<TreePath> removals =
tree.getInitializer() == null
? ImmutableList.of(state.getPath(), initializerPath)
: ImmutableList.of(initializerPath);
return buildDescription(initializer).addAllFixes(isUnusedScanner.buildFixes(removals)).build();
}
private static Matcher<IdentifierTree> getMatcher(Tree tree, VisitorState state) {
return COLLECTION_TYPE.matches(tree, state)
? (t, s) -> collectionUsed(s)
: (t, s) -> fluentBuilderUsed(s);
}
private static boolean collectionUsed(VisitorState state) {
TreePath path = state.getPath();
return !(path.getParentPath().getLeaf() instanceof MemberSelectTree)
|| !(path.getParentPath().getParentPath().getLeaf() instanceof MethodInvocationTree)
|| !COLLECTION_SETTER.matches(
(MethodInvocationTree) path.getParentPath().getParentPath().getLeaf(), state)
|| ASTHelpers.targetType(state.withPath(path.getParentPath().getParentPath())) != null;
}
private static boolean fluentBuilderUsed(VisitorState state) {
for (TreePath path = state.getPath();
path != null;
path = path.getParentPath().getParentPath()) {
if (path.getParentPath().getLeaf() instanceof ExpressionStatementTree) {
return false;
}
if (!(path.getParentPath().getLeaf() instanceof MemberSelectTree
&& path.getParentPath().getParentPath().getLeaf() instanceof MethodInvocationTree
&& FLUENT_CHAIN.matches(
(MethodInvocationTree) path.getParentPath().getParentPath().getLeaf(), state))) {
return true;
}
}
return true;
}
@Override
public Description matchExpressionStatement(ExpressionStatementTree tree, VisitorState state) {
ExpressionTree expression = tree.getExpression();
if (BUILD_CALL.matches(expression, state)) {
expression = getReceiver(expression);
}
if (expression == null) {
return NO_MATCH;
}
// Make sure we actually set something.
if (!FLUENT_SETTER.matches(expression, state)) {
return NO_MATCH;
}
if (!newFluentChain(expression, state)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage("Modifying a Builder without assigning it to anything does nothing.")
.build();
}
/**
* Whether this is a chain of method invocations terminating in a new proto or collection builder.
*/
private static boolean newFluentChain(ExpressionTree tree, VisitorState state) {
return concat(Stream.of(tree), streamReceivers(tree))
.filter(t -> !FLUENT_CHAIN.matches(t, state))
.findFirst()
.map(t -> FLUENT_CONSTRUCTOR.matches(t, state))
.orElse(false);
}
private static class UnusedScanner extends TreePathScanner<Void, Void> {
private final Symbol symbol;
private final VisitorState state;
private final Matcher<IdentifierTree> matcher;
private final List<TreePath> usageSites = new ArrayList<>();
private boolean isUsed = false;
private UnusedScanner(Symbol symbol, VisitorState state, Matcher<IdentifierTree> matcher) {
this.symbol = symbol;
this.state = state;
this.matcher = matcher;
}
@Override
public Void visitIdentifier(IdentifierTree identifierTree, Void unused) {
if (!Objects.equals(getSymbol(identifierTree), symbol)) {
return null;
}
if (matcher.matches(identifierTree, state.withPath(getCurrentPath()))) {
isUsed = true;
return null;
}
usageSites.add(getCurrentPath());
return null;
}
@Override
public Void visitVariable(VariableTree variableTree, Void unused) {
// Don't count the declaration of the variable as a usage.
if (Objects.equals(getSymbol(variableTree), symbol)) {
return null;
}
return super.visitVariable(variableTree, null);
}
@Override
public Void visitAssignment(AssignmentTree assignmentTree, Void unused) {
// Don't count the LHS of the assignment to the variable as a usage.
if (Objects.equals(getSymbol(assignmentTree.getVariable()), symbol)) {
return scan(assignmentTree.getExpression(), null);
}
return super.visitAssignment(assignmentTree, null);
}
private ImmutableList<SuggestedFix> buildFixes(List<TreePath> removals) {
boolean encounteredSideEffects = false;
SuggestedFix.Builder withoutSideEffects =
SuggestedFix.builder().setShortDescription("remove unused variable and any side effects");
SuggestedFix.Builder withSideEffects =
SuggestedFix.builder().setShortDescription("remove unused variable");
for (TreePath usageSite : Iterables.concat(removals, usageSites)) {
List<String> keepingSideEffects = new ArrayList<>();
for (TreePath path = usageSite;
!(path.getLeaf() instanceof StatementTree);
path = path.getParentPath()) {
List<? extends ExpressionTree> arguments;
if (path.getLeaf() instanceof MethodInvocationTree) {
arguments = ((MethodInvocationTree) path.getLeaf()).getArguments();
} else if (path.getLeaf() instanceof NewClassTree) {
arguments = ((NewClassTree) path.getLeaf()).getArguments();
} else {
continue;
}
arguments.stream()
.filter(SideEffectAnalysis::hasSideEffect)
.map(e -> state.getSourceForNode(e) + ";")
.forEach(keepingSideEffects::add);
}
StatementTree enclosingStatement =
state.withPath(usageSite).findEnclosing(StatementTree.class);
if (!keepingSideEffects.isEmpty()) {
encounteredSideEffects = true;
withSideEffects.replace(
enclosingStatement, keepingSideEffects.stream().collect(joining("")));
} else {
withSideEffects.replace(enclosingStatement, "");
}
withoutSideEffects.replace(enclosingStatement, "");
}
return encounteredSideEffects
? ImmutableList.of(withoutSideEffects.build(), withSideEffects.build())
: ImmutableList.of(withoutSideEffects.build());
}
}
}
| 15,576
| 39.884514
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryLambda.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.base.CaseFormat.LOWER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFixes.prettyType;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.enclosingPackage;
import static com.google.errorprone.util.ASTHelpers.getModifiers;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isStatic;
import static com.sun.tools.javac.util.Position.NOPOS;
import static java.util.stream.Collectors.joining;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Streams;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
import java.util.Objects;
import java.util.function.Predicate;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import org.checkerframework.checker.nullness.qual.Nullable;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Returning a lambda from a helper method or saving it in a constant is unnecessary; prefer"
+ " to implement the functional interface method directly and use a method reference"
+ " instead.",
severity = WARNING)
public class UnnecessaryLambda extends BugChecker
implements MethodTreeMatcher, VariableTreeMatcher {
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!tree.getParameters().isEmpty() || !tree.getThrows().isEmpty()) {
return NO_MATCH;
}
LambdaExpressionTree lambda = LAMBDA_VISITOR.visit(tree.getBody(), null);
if (lambda == null) {
return NO_MATCH;
}
MethodSymbol sym = getSymbol(tree);
if (!ASTHelpers.canBeRemoved(sym, state) || ASTHelpers.shouldKeep(tree)) {
return NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
String name = tree.getName().toString();
Tree type = tree.getReturnType();
if (!canFix(type, sym, state)) {
return NO_MATCH;
}
if (state.isAndroidCompatible()) {
return NO_MATCH;
}
new TreePathScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void unused) {
if (Objects.equals(getSymbol(node), sym)) {
replaceUseWithMethodReference(fix, node, name, state.withPath(getCurrentPath()));
}
return super.visitMethodInvocation(node, null);
}
}.scan(state.getPath().getCompilationUnit(), null);
lambdaToMethod(state, lambda, fix, name, type);
return describeMatch(tree, fix.build());
}
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
if (tree.getInitializer() == null) {
return NO_MATCH;
}
LambdaExpressionTree lambda = LAMBDA_VISITOR.visit(tree.getInitializer(), null);
if (lambda == null) {
return NO_MATCH;
}
Symbol sym = getSymbol(tree);
if (sym.getKind() != ElementKind.FIELD
|| !sym.isPrivate()
|| !sym.getModifiers().contains(Modifier.FINAL)) {
return NO_MATCH;
}
if (ASTHelpers.hasAnnotation(tree, "com.google.inject.testing.fieldbinder.Bind", state)) {
return NO_MATCH;
}
Tree type = tree.getType();
if (!canFix(type, sym, state)) {
return NO_MATCH;
}
if (state.isAndroidCompatible()) {
return NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
String name =
isStatic(sym)
? UPPER_UNDERSCORE.converterTo(LOWER_CAMEL).convert(tree.getName().toString())
: tree.getName().toString();
new TreePathScanner<Void, Void>() {
@Override
public Void visitMemberSelect(MemberSelectTree node, Void unused) {
if (Objects.equals(getSymbol(node), sym)) {
replaceUseWithMethodReference(fix, node, name, state.withPath(getCurrentPath()));
}
return super.visitMemberSelect(node, null);
}
@Override
public Void visitIdentifier(IdentifierTree node, Void unused) {
if (Objects.equals(getSymbol(node), sym)) {
replaceUseWithMethodReference(fix, node, name, state.withPath(getCurrentPath()));
}
return super.visitIdentifier(node, null);
}
}.scan(state.getPath().getCompilationUnit(), null);
SuggestedFixes.removeModifiers(tree, state, Modifier.FINAL).ifPresent(fix::merge);
lambdaToMethod(state, lambda, fix, name, type);
return describeMatch(tree, fix.build());
}
// Allowlist of core packages to emit fixes for functional interfaces in. User-defined functional
// interfaces are slightly more likely to have documentation value.
private static final ImmutableSet<String> PACKAGES_TO_FIX =
ImmutableSet.of(
"com.google.common.base",
"com.google.errorprone.matchers",
"java.util.function",
"java.lang");
/**
* Check if the only methods invoked on the functional interface type are the descriptor method,
* e.g. don't rewrite uses of {@link Predicate} in compilation units that call other methods like
* {#link Predicate#add}.
*/
private boolean canFix(Tree type, Symbol sym, VisitorState state) {
Symbol descriptor;
try {
descriptor = state.getTypes().findDescriptorSymbol(getType(type).asElement());
} catch (FunctionDescriptorLookupError e) {
return false;
}
if (!PACKAGES_TO_FIX.contains(enclosingPackage(descriptor).getQualifiedName().toString())) {
return false;
}
class Scanner extends TreePathScanner<Void, Void> {
boolean fixable = true;
boolean inInitializer = false;
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void unused) {
check(node);
return super.visitMethodInvocation(node, null);
}
@Override
public Void visitVariable(VariableTree node, Void unused) {
boolean wasInInitializer = inInitializer;
if (sym.equals(getSymbol(node))) {
inInitializer = true;
}
super.visitVariable(node, null);
inInitializer = wasInInitializer;
return null;
}
@Override
public Void visitMemberSelect(MemberSelectTree node, Void unused) {
if (inInitializer && sym.equals(getSymbol(node))) {
// We're not smart enough to rewrite a recursive lambda.
fixable = false;
}
return super.visitMemberSelect(node, unused);
}
private void check(MethodInvocationTree node) {
ExpressionTree lhs = node.getMethodSelect();
if (!(lhs instanceof MemberSelectTree)) {
return;
}
ExpressionTree receiver = ((MemberSelectTree) lhs).getExpression();
if (!Objects.equals(sym, getSymbol(receiver))) {
return;
}
Symbol symbol = getSymbol(lhs);
if (Objects.equals(descriptor, symbol)) {
return;
}
fixable = false;
}
}
Scanner scanner = new Scanner();
scanner.scan(state.getPath().getCompilationUnit(), null);
return scanner.fixable;
}
private void lambdaToMethod(
VisitorState state,
LambdaExpressionTree lambda,
SuggestedFix.Builder fix,
String name,
Tree type) {
Type fi = state.getTypes().findDescriptorType(getType(type));
Tree tree = state.getPath().getLeaf();
ModifiersTree modifiers = getModifiers(tree);
int endPosition = state.getEndPosition(tree);
StringBuilder replacement = new StringBuilder();
replacement.append(String.format(" %s %s(", prettyType(state, fix, fi.getReturnType()), name));
replacement.append(
Streams.zip(
fi.getParameterTypes().stream(),
lambda.getParameters().stream(),
(t, p) -> String.format("%s %s", prettyType(state, fix, t), p.getName()))
.collect(joining(", ")));
replacement.append(")");
if (lambda.getBody().getKind() == Kind.BLOCK) {
replacement.append(state.getSourceForNode(lambda.getBody()));
} else {
replacement.append("{");
if (!fi.getReturnType().hasTag(TypeTag.VOID)) {
replacement.append("return ");
}
replacement.append(state.getSourceForNode(lambda.getBody()));
replacement.append(";");
replacement.append("}");
}
int modifiedEndPos = state.getEndPosition(modifiers);
fix.replace(
modifiedEndPos == NOPOS ? getStartPosition(tree) : modifiedEndPos + 1,
endPosition,
replacement.toString());
}
private static void replaceUseWithMethodReference(
SuggestedFix.Builder fix, ExpressionTree node, String newName, VisitorState state) {
Tree parent = state.getPath().getParentPath().getLeaf();
if (parent instanceof MemberSelectTree
&& ((MemberSelectTree) parent).getExpression().equals(node)) {
Tree receiver = node.getKind() == Tree.Kind.IDENTIFIER ? null : getReceiver(node);
fix.replace(
receiver != null ? state.getEndPosition(receiver) : getStartPosition(node),
state.getEndPosition(parent),
(receiver != null ? "." : "") + newName);
} else {
Symbol sym = getSymbol(node);
String receiverCode;
if (node instanceof MethodInvocationTree && getReceiver(node) != null) {
receiverCode = state.getSourceForNode(getReceiver(node));
} else {
receiverCode = isStatic(sym) ? sym.owner.enclClass().getSimpleName().toString() : "this";
}
fix.replace(node, String.format("%s::%s", receiverCode, newName));
}
}
private static final SimpleTreeVisitor<LambdaExpressionTree, Void> LAMBDA_VISITOR =
new SimpleTreeVisitor<LambdaExpressionTree, Void>() {
@Override
public LambdaExpressionTree visitLambdaExpression(LambdaExpressionTree node, Void unused) {
return node;
}
@Override
public @Nullable LambdaExpressionTree visitBlock(BlockTree node, Void unused) {
// when processing a method body, only consider methods with a single `return` statement
// that returns a method
return node.getStatements().size() == 1
? getOnlyElement(node.getStatements()).accept(this, null)
: null;
}
@Override
public @Nullable LambdaExpressionTree visitReturn(ReturnTree node, Void unused) {
return node.getExpression() != null ? node.getExpression().accept(this, null) : null;
}
@Override
public LambdaExpressionTree visitTypeCast(TypeCastTree node, Void unused) {
return node.getExpression().accept(this, null);
}
@Override
public LambdaExpressionTree visitParenthesized(ParenthesizedTree node, Void unused) {
return node.getExpression().accept(this, null);
}
};
}
| 13,228
| 38.372024
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NonCanonicalType.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFixes.qualifyType;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.enclosingClass;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.Visibility;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.util.Position;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/** Flags types being referred to by their non-canonical name. */
@BugPattern(
summary = "This type is referred to by a non-canonical name, which may be misleading.",
severity = WARNING)
public final class NonCanonicalType extends BugChecker implements MemberSelectTreeMatcher {
@Override
public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) {
// Only match on the outermost member select.
if (state.getPath().getParentPath().getLeaf() instanceof MemberSelectTree) {
return NO_MATCH;
}
String canonicalName = canonicalName(tree);
if (canonicalName == null) {
return NO_MATCH;
}
// Skip generated code. There are some noisy cases in AutoValue.
if (canonicalName.contains("$")) {
return NO_MATCH;
}
String nonCanonicalName = getNonCanonicalName(tree);
if (canonicalName.equals(nonCanonicalName)) {
return NO_MATCH;
}
for (Symbol symbol = getSymbol(tree); symbol != null; symbol = enclosingClass(symbol)) {
if (!Visibility.fromModifiers(symbol.getModifiers()).shouldBeVisible(tree, state)) {
return NO_MATCH;
}
}
if (getStartPosition(tree) == Position.NOPOS) {
// Can't suggest changing a synthetic type tree
return NO_MATCH;
}
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
SuggestedFix fix =
fixBuilder.replace(tree, qualifyType(state, fixBuilder, canonicalName)).build();
return buildDescription(tree)
.setMessage(createDescription(canonicalName, nonCanonicalName))
.addFix(fix)
.build();
}
@Nullable
private static String canonicalName(MemberSelectTree tree) {
Symbol sym = getSymbol(tree);
if (sym == null) {
return null;
}
if (!(sym instanceof Symbol.TypeSymbol)) {
return null;
}
Symbol owner = sym.owner;
if (owner == null) {
// module symbols don't have owners
return null;
}
return owner.getQualifiedName() + "." + sym.getSimpleName();
}
private static final Pattern PACKAGE_CLASS_NAME_SPLITTER = Pattern.compile("(.*?)\\.([A-Z].*)");
private static String createDescription(String canonicalName, String nonCanonicalName) {
Matcher canonicalNameMatcher = PACKAGE_CLASS_NAME_SPLITTER.matcher(canonicalName);
Matcher nonCanonicalNameMatcher = PACKAGE_CLASS_NAME_SPLITTER.matcher(nonCanonicalName);
if (canonicalNameMatcher.matches() && nonCanonicalNameMatcher.matches()) {
if (!canonicalNameMatcher.group(2).equals(nonCanonicalNameMatcher.group(2))) {
return String.format(
"The type `%s` was referred to by the non-canonical name `%s`. This may be"
+ " misleading.",
canonicalNameMatcher.group(2), nonCanonicalNameMatcher.group(2));
}
}
return String.format(
"The type `%s` was referred to by the non-canonical name `%s`. This may be"
+ " misleading.",
canonicalName, nonCanonicalName);
}
/**
* Find the non-canonical name which is being used to refer to this type. We can't just use {@code
* getSymbol}, given that points to the same symbol as the canonical name.
*/
private static String getNonCanonicalName(Tree tree) {
switch (tree.getKind()) {
case IDENTIFIER:
return getSymbol(tree).getQualifiedName().toString();
case MEMBER_SELECT:
MemberSelectTree memberSelectTree = (MemberSelectTree) tree;
Symbol expressionSymbol = getSymbol(memberSelectTree.getExpression());
if (!(expressionSymbol instanceof TypeSymbol)) {
return getSymbol(tree).getQualifiedName().toString();
}
return getNonCanonicalName(memberSelectTree.getExpression())
+ "."
+ memberSelectTree.getIdentifier();
case PARAMETERIZED_TYPE:
return getNonCanonicalName(((ParameterizedTypeTree) tree).getType());
default:
throw new AssertionError(tree.getKind());
}
}
}
| 5,713
| 38.680556
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ICCProfileGetInstance.java
|
/*
* Copyright 2023 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"This method searches the class path for the given file, prefer to read the file and call"
+ " getInstance(byte[]) or getInstance(InputStream)",
severity = WARNING,
tags = StandardTags.PERFORMANCE)
public class ICCProfileGetInstance extends BugChecker
implements BugChecker.MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
staticMethod()
.onClass("java.awt.color.ICC_Profile")
.named("getInstance")
.withParameters("java.lang.String");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
ExpressionTree arg = Iterables.getOnlyElement(tree.getArguments());
return describeMatch(
tree,
SuggestedFix.builder()
.prefixWith(arg, "Files.readAllBytes(Paths.get(")
.postfixWith(arg, "))")
.addImport("java.nio.file.Files")
.addImport("java.nio.file.Paths")
.build());
}
}
| 2,492
| 37.353846
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnicodeEscape.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.base.Suppliers.memoize;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import com.google.common.collect.ImmutableRangeSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.FixedPosition;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.CompilationUnitTree;
import java.util.function.Supplier;
/** Replaces printable ASCII unicode escapes with the literal version. */
@BugPattern(
summary =
"Using unicode escape sequences for printable ASCII characters is obfuscated, and"
+ " potentially dangerous.",
severity = WARNING)
public final class UnicodeEscape extends BugChecker implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
new UnicodeScanner(state.getSourceCode().toString(), state).scan();
return NO_MATCH;
}
private final class UnicodeScanner {
private final String source;
private final VisitorState state;
private final Supplier<ImmutableRangeSet<Integer>> suppressedRegions =
memoize(() -> suppressedRegions(getState()));
private int position = 0;
private char currentCharacter = 0;
private boolean isUnicode = false;
private int lastBackslash = 0;
private UnicodeScanner(String source, VisitorState state) {
this.source = source;
this.state = state;
this.currentCharacter = source.charAt(0);
}
public void scan() {
for (; position < source.length(); processCharacter()) {
if (isUnicode && isBanned(currentCharacter)) {
if (currentCharacter == '\\' && peek() == 'u') {
continue;
}
if (suppressedRegions.get().contains(position)) {
continue;
}
state.reportMatch(
describeMatch(
new FixedPosition(state.getPath().getCompilationUnit(), position),
SuggestedFix.replace(
lastBackslash, position + 1, Character.toString(currentCharacter))));
}
}
}
private void processCharacter() {
if (currentCharacter == '\\') {
lastBackslash = position;
nextCharacter();
// The isUnicode check is important because the Unicode escape for backslash can escape any
// subsequent escape code... except "u".
if (currentCharacter == 'u' && !isUnicode) {
// The spec allows multiple "u" after the "\".
do {
nextCharacter();
} while (currentCharacter == 'u');
currentCharacter = (char) Integer.parseInt(source.substring(position, position + 4), 16);
position += 3;
isUnicode = true;
return;
}
// If it's not a Unicode escape, we don't care about what character it actually encodes,
// so let's just skip the char.
}
nextCharacter();
isUnicode = false;
}
private void nextCharacter() {
++position;
if (position < source.length()) {
currentCharacter = source.charAt(position);
}
}
/** Returns the next character, or {@code 0} if we're at the end of the file. */
private char peek() {
return position + 1 < source.length() ? source.charAt(position + 1) : 0;
}
private VisitorState getState() {
return state;
}
}
private static boolean isBanned(char c) {
return (c >= 0x20 && c <= 0x7E) || c == 0xA || c == 0xD;
}
}
| 4,435
| 34.488
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/PackageLocation.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static java.lang.Math.max;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.SuppressPackageLocation;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import java.util.List;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Package names should match the directory they are declared in",
severity = SUGGESTION,
documentSuppression = false,
suppressionAnnotations = SuppressPackageLocation.class,
tags = StandardTags.STYLE,
altNames = "PackageName")
public class PackageLocation extends BugChecker implements CompilationUnitTreeMatcher {
private static final Splitter DOT_SPLITTER = Splitter.on('.');
private static final Splitter PATH_SPLITTER = Splitter.on('/');
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
if (tree.getPackageName() == null) {
return Description.NO_MATCH;
}
// package-info annotations are special
// TODO(cushon): fix the core suppression logic to handle this
if (ASTHelpers.hasAnnotation(tree.getPackage(), SuppressPackageLocation.class, state)) {
return Description.NO_MATCH;
}
PackageSymbol packageSymbol = ((JCCompilationUnit) state.getPath().getCompilationUnit()).packge;
if (packageSymbol == null) {
return Description.NO_MATCH;
}
String packageName = packageSymbol.fullname.toString();
String actualFileName = ASTHelpers.getFileName(tree);
if (actualFileName == null) {
return Description.NO_MATCH;
}
List<String> actualPath =
PATH_SPLITTER.splitToList(actualFileName.substring(0, actualFileName.lastIndexOf('/')));
List<String> expectedSuffix = DOT_SPLITTER.splitToList(packageName);
List<String> actualSuffix =
actualPath.subList(max(0, actualPath.size() - expectedSuffix.size()), actualPath.size());
if (actualSuffix.equals(expectedSuffix)) {
return Description.NO_MATCH;
}
String message =
String.format(
"Expected package %s to be declared in a directory ending with %s, instead found %s",
packageName, Joiner.on('/').join(expectedSuffix), Joiner.on('/').join(actualSuffix));
return buildDescription(tree.getPackageName()).setMessage(message).build();
}
}
| 3,533
| 40.093023
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MissingCasesInEnumSwitch.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.SwitchTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.RuntimeVersion;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.SwitchTree;
import com.sun.tools.javac.code.Type;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.lang.model.element.ElementKind;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Switches on enum types should either handle all values, or have a default case.",
severity = WARNING)
public class MissingCasesInEnumSwitch extends BugChecker implements SwitchTreeMatcher {
public static final int MAX_CASES_TO_PRINT = 5;
@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()
.flatMap(MissingCasesInEnumSwitch::getExpressions)
.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();
}
/**
* Build the diagnostic message.
*
* <p>Examples:
*
* <ul>
* <li>Non-exhaustive switch, expected cases for: FOO
* <li>Non-exhaustive switch, expected cases for: FOO, BAR, BAZ, and 42 others.
* </ul>
*/
private static String buildMessage(Set<String> unhandled) {
StringBuilder message =
new StringBuilder(
"Non-exhaustive switch; either add a default or handle the remaining cases: ");
int numberToShow =
unhandled.size() > MAX_CASES_TO_PRINT
? 3 // if there are too many to print, only show three examples.
: unhandled.size();
message.append(unhandled.stream().limit(numberToShow).collect(Collectors.joining(", ")));
if (numberToShow < unhandled.size()) {
message.append(String.format(", and %d others", unhandled.size() - numberToShow));
}
return message.toString();
}
@SuppressWarnings("unchecked")
private static Stream<? extends ExpressionTree> getExpressions(CaseTree caseTree) {
try {
if (RuntimeVersion.isAtLeast12()) {
return ((List<? extends ExpressionTree>)
CaseTree.class.getMethod("getExpressions").invoke(caseTree))
.stream();
} else {
return Stream.of(caseTree.getExpression());
}
} catch (ReflectiveOperationException e) {
throw new LinkageError(e.getMessage(), e);
}
}
}
| 4,250
| 36.955357
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StringSplitter.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.hasNoExplicitType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static com.google.errorprone.util.Regexes.convertRegexToLiteral;
import static java.lang.String.format;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.SourceCodeEscapers;
import com.sun.source.tree.ArrayAccessTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "String.split(String) has surprising behavior", severity = WARNING)
public class StringSplitter extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
anyOf(
instanceMethod()
.onExactClass("java.lang.String")
.named("split")
.withParameters("java.lang.String"),
instanceMethod()
.onExactClass("java.util.regex.Pattern")
.named("split")
.withParameters("java.lang.CharSequence"));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
Optional<Fix> fix = buildFix(tree, state);
if (!fix.isPresent()) {
return NO_MATCH;
}
// TODO(b/112270644): skip Splitter fix if guava isn't on the classpath
return describeMatch(tree, fix.get());
}
public Optional<Fix> buildFix(MethodInvocationTree tree, VisitorState state) {
ExpressionTree arg = getOnlyElement(tree.getArguments());
Tree parent = state.getPath().getParentPath().getLeaf();
if (parent instanceof EnhancedForLoopTree
&& ((EnhancedForLoopTree) parent).getExpression().equals(tree)) {
// fix for `for (... : s.split(...)) {}` -> `for (... : Splitter.on(...).split(s)) {}`
return Optional.of(
replaceWithSplitter(
SuggestedFix.builder(), tree, arg, state, "split", /* mutableList= */ false)
.build());
}
if (parent instanceof ArrayAccessTree) {
ArrayAccessTree arrayAccessTree = (ArrayAccessTree) parent;
if (!arrayAccessTree.getExpression().equals(tree)) {
return Optional.empty();
}
SuggestedFix.Builder fix =
SuggestedFix.builder()
.addImport("com.google.common.collect.Iterables")
.replace(
getStartPosition(arrayAccessTree),
getStartPosition(arrayAccessTree),
"Iterables.get(")
.replace(
/* startPos= */ state.getEndPosition(arrayAccessTree.getExpression()),
/* endPos= */ getStartPosition(arrayAccessTree.getIndex()),
format(", "))
.replace(
state.getEndPosition(arrayAccessTree.getIndex()),
state.getEndPosition(arrayAccessTree),
")");
return Optional.of(
replaceWithSplitter(fix, tree, arg, state, "split", /* mutableList= */ false).build());
}
// If the result of split is assigned to a variable, try to fix all uses of the variable in the
// enclosing method. If we don't know how to fix any of them, bail out.
if (!(parent instanceof VariableTree)) {
return Optional.empty();
}
VariableTree varTree = (VariableTree) parent;
if (!varTree.getInitializer().equals(tree)) {
return Optional.empty();
}
VarSymbol sym = ASTHelpers.getSymbol(varTree);
TreePath enclosing = findEnclosing(state);
if (enclosing == null) {
return Optional.empty();
}
// find all uses of the variable in the enclosing method
List<TreePath> uses = new ArrayList<>();
new TreePathScanner<Void, Void>() {
@Override
public Void visitIdentifier(IdentifierTree tree, Void unused) {
if (Objects.equals(sym, ASTHelpers.getSymbol(tree))) {
uses.add(getCurrentPath());
}
return super.visitIdentifier(tree, null);
}
}.scan(enclosing, null);
SuggestedFix.Builder fix = SuggestedFix.builder();
// a mutable boolean to track whether we want split or splitToList
boolean[] needsList = {false};
boolean[] needsMutableList = {false};
// try to fix all uses of the variable
for (TreePath path : uses) {
class UseFixer extends TreePathScanner<Boolean, Void> {
@Override
public Boolean visitEnhancedForLoop(EnhancedForLoopTree tree, Void unused) {
// The syntax for looping over an array or iterable variable is the same, so there's no
// fix here.
return sym.equals(ASTHelpers.getSymbol(tree.getExpression()));
}
@Override
public Boolean visitArrayAccess(ArrayAccessTree tree, Void unused) {
// replace `pieces[N]` with `pieces.get(N)`
ExpressionTree expression = tree.getExpression();
ExpressionTree index = tree.getIndex();
if (!sym.equals(ASTHelpers.getSymbol(expression))) {
return false;
}
Tree parent = getCurrentPath().getParentPath().getLeaf();
if (parent instanceof AssignmentTree && ((AssignmentTree) parent).getVariable() == tree) {
AssignmentTree assignmentTree = (AssignmentTree) parent;
fix.replace(
/* startPos= */ state.getEndPosition(expression),
/* endPos= */ getStartPosition(index),
".set(")
.replace(
/* startPos= */ state.getEndPosition(index),
/* endPos= */ getStartPosition(assignmentTree.getExpression()),
", ")
.postfixWith(assignmentTree, ")");
needsMutableList[0] = true;
} else {
fix.replace(
/* startPos= */ state.getEndPosition(expression),
/* endPos= */ getStartPosition(index),
".get(")
.replace(state.getEndPosition(index), state.getEndPosition(tree), ")");
}
// we want a list for indexing
needsList[0] = true;
return true;
}
@Override
public Boolean visitMemberSelect(MemberSelectTree tree, Void unused) {
// replace `pieces.length` with `pieces.size`
if (sym.equals(ASTHelpers.getSymbol(tree.getExpression()))
&& tree.getIdentifier().contentEquals("length")) {
fix.replace(
state.getEndPosition(tree.getExpression()), state.getEndPosition(tree), ".size()");
needsList[0] = true;
return true;
}
return false;
}
}
if (!firstNonNull(new UseFixer().scan(path.getParentPath(), null), false)) {
return Optional.empty();
}
}
Tree varType = varTree.getType();
boolean isImplicitlyTyped = hasNoExplicitType(varTree, state); // Is it a use of `var`?
if (needsList[0]) {
if (!isImplicitlyTyped) {
fix.replace(varType, "List<String>").addImport("java.util.List");
}
replaceWithSplitter(fix, tree, arg, state, "splitToList", needsMutableList[0]);
} else {
if (!isImplicitlyTyped) {
fix.replace(varType, "Iterable<String>");
}
replaceWithSplitter(fix, tree, arg, state, "split", needsMutableList[0]);
}
return Optional.of(fix.build());
}
private static String getMethodAndArgument(Tree origArg, VisitorState state) {
String argSource = state.getSourceForNode(origArg);
Tree arg = ASTHelpers.stripParentheses(origArg);
if (arg.getKind() != Tree.Kind.STRING_LITERAL) {
// Even if the regex is a constant, it still needs to be treated as a regex, since the
// value comes from the symbol and/or a concatenation; the values of the subexpressions may be
// changed subsequently.
return String.format("onPattern(%s)", argSource);
}
String constValue = ASTHelpers.constValue(arg, String.class);
if (constValue == null) {
// Not a constant value, so we can't assume anything about pattern: have to treat it as a
// regex.
return String.format("onPattern(%s)", argSource);
}
Optional<String> regexAsLiteral = convertRegexToLiteral(constValue);
if (!regexAsLiteral.isPresent()) {
// Can't convert the regex to a literal string: have to treat it as a regex.
return String.format("onPattern(%s)", argSource);
}
String escaped = SourceCodeEscapers.javaCharEscaper().escape(regexAsLiteral.get());
if (regexAsLiteral.get().length() == 1) {
return String.format("on('%s')", escaped);
}
return String.format("on(\"%s\")", escaped);
}
private static SuggestedFix.Builder replaceWithSplitter(
SuggestedFix.Builder fix,
MethodInvocationTree tree,
ExpressionTree arg,
VisitorState state,
String splitMethod,
boolean mutableList) {
ExpressionTree receiver = ASTHelpers.getReceiver(tree);
if (mutableList) {
fix.addImport("java.util.ArrayList");
}
fix.addImport("com.google.common.base.Splitter");
Type receiverType = getType(receiver);
if (isSubtype(receiverType, state.getSymtab().stringType, state)) {
String methodAndArgument = getMethodAndArgument(arg, state);
return fix.prefixWith(
receiver,
String.format(
"%sSplitter.%s.%s(",
(mutableList ? "new ArrayList<>(" : ""), methodAndArgument, splitMethod))
.replace(
state.getEndPosition(receiver),
state.getEndPosition(tree),
(mutableList ? ")" : "") + ")");
}
if (isSubtype(receiverType, JAVA_UTIL_REGEX_PATTERN.get(state), state)) {
return fix.prefixWith(
receiver, String.format("%sSplitter.on(", (mutableList ? "new ArrayList<>(" : "")))
.postfixWith(receiver, ")")
.replace(
/* startPos= */ state.getEndPosition(receiver),
/* endPos= */ getStartPosition(arg),
String.format(".%s(", splitMethod))
.replace(
state.getEndPosition(arg),
state.getEndPosition(tree),
(mutableList ? ")" : "") + ")");
}
throw new AssertionError(receiver);
}
@Nullable
private static TreePath findEnclosing(VisitorState state) {
for (TreePath path = state.getPath(); path != null; path = path.getParentPath()) {
switch (path.getLeaf().getKind()) {
case METHOD:
case LAMBDA_EXPRESSION:
return path;
case CLASS:
return null;
default: // fall out
}
}
return null;
}
private static final Supplier<Type> JAVA_UTIL_REGEX_PATTERN =
VisitorState.memoize(state -> state.getTypeFromString("java.util.regex.Pattern"));
}
| 13,142
| 40.72381
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/IncrementInForLoopAndHeader.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ForLoopTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.UnaryTree;
import com.sun.tools.javac.code.Symbol;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* @author mariasam@google.com (Maria Sam)
*/
@BugPattern(
summary = "This for loop increments the same variable in the header and in the body",
severity = WARNING)
public class IncrementInForLoopAndHeader extends BugChecker implements ForLoopTreeMatcher {
private static final ImmutableSet<Kind> CONDITIONALS =
ImmutableSet.of(
Kind.IF, Kind.DO_WHILE_LOOP, Kind.WHILE_LOOP, Kind.FOR_LOOP, Kind.ENHANCED_FOR_LOOP);
@Override
public Description matchForLoop(ForLoopTree forLoopTree, VisitorState visitorState) {
List<? extends ExpressionStatementTree> updates = forLoopTree.getUpdate();
// keep track of all the symbols that are updated in the for loop header
ImmutableSet<Symbol> incrementedSymbols =
updates.stream()
.filter(expStateTree -> expStateTree.getExpression() instanceof UnaryTree)
.map(
expStateTree ->
ASTHelpers.getSymbol(
((UnaryTree) expStateTree.getExpression()).getExpression()))
.filter(Objects::nonNull)
.collect(toImmutableSet());
// track if they are updated in the body without a conditional surrounding them
StatementTree body = forLoopTree.getStatement();
List<? extends StatementTree> statementTrees =
body instanceof BlockTree ? ((BlockTree) body).getStatements() : ImmutableList.of(body);
for (StatementTree s : statementTrees) {
if (!CONDITIONALS.contains(s.getKind())) {
Optional<Symbol> opSymbol = returnUnarySym(s);
if (opSymbol.isPresent() && incrementedSymbols.contains(opSymbol.get())) {
// both ++ and --
return describeMatch(forLoopTree);
}
}
}
return Description.NO_MATCH;
}
private static Optional<Symbol> returnUnarySym(StatementTree s) {
if (s instanceof ExpressionStatementTree) {
if (((ExpressionStatementTree) s).getExpression() instanceof UnaryTree) {
UnaryTree unaryTree = (UnaryTree) ((ExpressionStatementTree) s).getExpression();
return Optional.ofNullable(ASTHelpers.getSymbol(unaryTree.getExpression()));
}
}
return Optional.empty();
}
}
| 3,696
| 38.752688
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ExtendingJUnitAssert.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.ErrorProneToken;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.parser.Tokens.TokenKind;
import java.util.List;
/**
* @author kayco@google.com (Kayla Walker)
*/
@BugPattern(
summary =
"When only using JUnit Assert's static methods, "
+ "you should import statically instead of extending.",
severity = WARNING)
public class ExtendingJUnitAssert extends BugChecker implements ClassTreeMatcher {
private static final Matcher<ExpressionTree> STATIC_ASSERT =
staticMethod().onClass("org.junit.Assert").withAnyName();
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
Tree extendsClause = tree.getExtendsClause();
Type type = ASTHelpers.getType(extendsClause);
if (ASTHelpers.isSameType(type, ORG_JUNIT_ASSERT.get(state), state)) {
return describeMatch(extendsClause, fixAsserts(tree, state));
}
return Description.NO_MATCH;
}
private SuggestedFix fixAsserts(ClassTree tree, VisitorState state) {
SuggestedFix.Builder fix = SuggestedFix.builder();
tree.accept(
new TreeScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
if (STATIC_ASSERT.matches(tree, state)) {
String assertType = ASTHelpers.getSymbol(tree).getSimpleName().toString();
fix.addStaticImport("org.junit.Assert." + assertType);
}
return super.visitMethodInvocation(tree, unused);
}
},
null);
Tree extendsClause = tree.getExtendsClause();
int endOfExtendsClause = state.getEndPosition(extendsClause);
List<ErrorProneToken> tokens = state.getOffsetTokensForNode(tree);
int startPos = 0;
for (ErrorProneToken token : tokens) {
if (token.pos() > endOfExtendsClause) {
break;
}
if (token.kind() == TokenKind.EXTENDS) {
int curr = token.pos();
if (curr > startPos) {
startPos = curr;
}
}
}
return fix.replace(startPos, endOfExtendsClause, "").build();
}
private static final Supplier<Type> ORG_JUNIT_ASSERT =
VisitorState.memoize(state -> state.getTypeFromString("org.junit.Assert"));
}
| 3,679
| 35.435644
| 88
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/URLEqualsHashCode.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import java.util.List;
/**
* Points out on creation of Set and HashMap of type java.net.URL.
*
* <p>equals() and hashCode() of java.net.URL class make blocking internet connections.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary =
"Avoid hash-based containers of java.net.URL--the containers rely on equals() and"
+ " hashCode(), which cause java.net.URL to make blocking internet connections.",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public class URLEqualsHashCode extends BugChecker
implements MethodInvocationTreeMatcher, NewClassTreeMatcher {
private static final String URL_CLASS = "java.net.URL";
private static final Matcher<ExpressionTree> CONTAINER_MATCHER =
anyOf(
new URLTypeArgumentMatcher("java.util.Set", 0),
new URLTypeArgumentMatcher("java.util.Map", 0),
// BiMap is a Map, so its first type argument is already being checked
new URLTypeArgumentMatcher("com.google.common.collect.BiMap", 1));
private static final Matcher<ExpressionTree> METHOD_INVOCATION_MATCHER =
allOf(
anyOf(
staticMethod()
.onClassAny(
ImmutableSet.class.getName(),
ImmutableMap.class.getName(),
HashBiMap.class.getName()),
instanceMethod()
.onExactClassAny(
ImmutableSet.Builder.class.getName(), ImmutableMap.Builder.class.getName())
.named("build")),
CONTAINER_MATCHER);
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (METHOD_INVOCATION_MATCHER.matches(tree, state)) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (CONTAINER_MATCHER.matches(tree, state)) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
private static class URLTypeArgumentMatcher implements Matcher<Tree> {
private final String clazz;
private final int typeArgumentIndex;
URLTypeArgumentMatcher(String clazz, int index) {
this.clazz = clazz;
this.typeArgumentIndex = index;
}
@Override
public boolean matches(Tree tree, VisitorState state) {
Symbol sym = state.getSymbolFromString(clazz);
if (sym == null) {
return false;
}
Type type = ASTHelpers.getType(tree);
if (!ASTHelpers.isSubtype(type, sym.type, state)) {
return false;
}
Types types = state.getTypes();
Type superType = types.asSuper(type, sym);
if (superType == null) {
return false;
}
List<Type> typeArguments = superType.getTypeArguments();
if (typeArguments.isEmpty()) {
return false;
}
return ASTHelpers.isSameType(
typeArguments.get(typeArgumentIndex), JAVA_NET_URL.get(state), state);
}
}
private static final Supplier<Type> JAVA_NET_URL =
VisitorState.memoize(state -> state.getTypeFromString(URL_CLASS));
}
| 5,089
| 36.153285
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StringCaseLocaleUsage.java
|
/*
* Copyright 2023 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.sun.tools.javac.parser.Tokens.TokenKind.RPAREN;
import com.google.common.collect.Streams;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.ErrorProneTokens;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.util.Position;
/**
* A {@link BugChecker} that flags calls to {@link String#toLowerCase()} and {@link
* String#toUpperCase()}, as these methods implicitly rely on the environment's default locale.
*/
@BugPattern(
summary =
"Specify a `Locale` when calling `String#to{Lower,Upper}Case`. (Note: there are multiple"
+ " suggested fixes; the third may be most appropriate if you're dealing with ASCII"
+ " Strings.)",
severity = WARNING)
public final class StringCaseLocaleUsage extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> DEFAULT_LOCALE_CASE_CONVERSION =
instanceMethod()
.onExactClass(String.class.getName())
.namedAnyOf("toLowerCase", "toUpperCase")
.withNoParameters();
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!DEFAULT_LOCALE_CASE_CONVERSION.matches(tree, state)) {
return Description.NO_MATCH;
}
int closingParenPosition = getClosingParenPosition(tree, state);
if (closingParenPosition == Position.NOPOS) {
return describeMatch(tree);
}
return buildDescription(tree)
.addFix(suggestLocale(closingParenPosition, "Locale.ROOT"))
.addFix(suggestLocale(closingParenPosition, "Locale.getDefault()"))
.addFix(suggestAscii(tree, state))
.build();
}
private static SuggestedFix suggestLocale(int insertPosition, String locale) {
return SuggestedFix.builder()
.addImport("java.util.Locale")
.replace(insertPosition, insertPosition, locale)
.build();
}
private static SuggestedFix suggestAscii(MethodInvocationTree tree, VisitorState state) {
ExpressionTree receiver = getReceiver(tree);
if (receiver == null) {
return SuggestedFix.emptyFix();
}
var fix =
SuggestedFix.builder()
.setShortDescription(
"Replace with Ascii.toLower/UpperCase; this changes behaviour for non-ASCII"
+ " Strings");
String ascii = SuggestedFixes.qualifyType(state, fix, "com.google.common.base.Ascii");
fix.replace(
tree,
String.format(
"%s.%s(%s)", ascii, getSymbol(tree).getSimpleName(), state.getSourceForNode(receiver)));
return fix.build();
}
// TODO: Consider making this a helper method in `SuggestedFixes`.
private static int getClosingParenPosition(MethodInvocationTree tree, VisitorState state) {
int startPosition = ASTHelpers.getStartPosition(tree);
if (startPosition == Position.NOPOS) {
return Position.NOPOS;
}
return Streams.findLast(
ErrorProneTokens.getTokens(state.getSourceForNode(tree), state.context).stream()
.filter(t -> t.kind() == RPAREN))
.map(token -> startPosition + token.pos())
.orElse(Position.NOPOS);
}
}
| 4,543
| 39.212389
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TreeToString.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.Streams.stream;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.predicates.TypePredicate;
import com.google.errorprone.predicates.TypePredicates;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.FindIdentifiers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import java.util.Optional;
import javax.inject.Inject;
/**
* Flags {@code com.sun.source.tree.Tree#toString} usage in {@link BugChecker}s.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary =
"Tree#toString shouldn't be used for Trees deriving from the code being compiled, as it"
+ " discards whitespace and comments.",
severity = ERROR)
public class TreeToString extends AbstractToString {
private static final Matcher<ClassTree> IS_BUGCHECKER =
Matchers.isSubtypeOf("com.google.errorprone.bugpatterns.BugChecker");
private static final TypePredicate IS_TREE =
TypePredicates.isDescendantOf("com.sun.source.tree.Tree");
private static final Matcher<ExpressionTree> TREEMAKER_LITERAL_CREATOR =
instanceMethod()
.onDescendantOf("com.sun.tools.javac.tree.TreeMaker")
.named("Literal")
.withParameters("java.lang.Object");
@Inject
TreeToString() {}
@Override
protected TypePredicate typePredicate() {
return this::treeToStringInBugChecker;
}
private boolean treeToStringInBugChecker(Type type, VisitorState state) {
return enclosingBugChecker(state) && IS_TREE.apply(type, state);
}
private boolean enclosingBugChecker(VisitorState state) {
return stream(state.getPath())
.anyMatch(t -> t instanceof ClassTree && IS_BUGCHECKER.matches((ClassTree) t, state));
}
@Override
protected Optional<String> descriptionMessageForDefaultMatch(Type type, VisitorState state) {
return Optional.of("Tree#toString shouldn't be used.");
}
@Override
protected Optional<Fix> implicitToStringFix(ExpressionTree tree, VisitorState state) {
return fix(tree, tree, state);
}
@Override
protected Optional<Fix> toStringFix(Tree parent, ExpressionTree tree, VisitorState state) {
if (!(parent instanceof MethodInvocationTree)) {
return Optional.empty();
}
ExpressionTree receiver = getReceiver((ExpressionTree) parent);
if (receiver == null) {
return Optional.empty();
}
return fix(receiver, parent, state);
}
private static Optional<Fix> fix(Tree target, Tree replace, VisitorState state) {
return FindIdentifiers.findAllIdents(state).stream()
.filter(s -> isSubtype(s.type, COM_GOOGLE_ERRORPRONE_VISITORSTATE.get(state), state))
.findFirst()
.map(s -> SuggestedFix.replace(replace, createStringReplacement(state, s, target)));
}
private static String createStringReplacement(
VisitorState state, VarSymbol visitorStateSymbol, Tree target) {
String visitorStateVariable = visitorStateSymbol.getSimpleName().toString();
if (target instanceof MethodInvocationTree) {
MethodInvocationTree targetMethodInvocationTree = (MethodInvocationTree) target;
if (TREEMAKER_LITERAL_CREATOR.matches(targetMethodInvocationTree, state)) {
return String.format(
"%s.getConstantExpression(%s)",
visitorStateVariable,
state.getSourceForNode(getOnlyElement(targetMethodInvocationTree.getArguments())));
}
}
return String.format(
"%s.getSourceForNode(%s)", visitorStateVariable, state.getSourceForNode(target));
}
private static final Supplier<Type> COM_GOOGLE_ERRORPRONE_VISITORSTATE =
VisitorState.memoize(state -> state.getTypeFromString("com.google.errorprone.VisitorState"));
}
| 5,165
| 37.552239
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InconsistentHashCode.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.equalsMethodDeclaration;
import static com.google.errorprone.matchers.Matchers.hashCodeMethodDeclaration;
import static com.google.errorprone.matchers.Matchers.instanceEqualsInvocation;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isStatic;
import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.lang.model.element.ElementKind;
/**
* Looks for hashCode implementations which are inconsistent with equals.
*
* @author ghm@google.com (Graeme Morgan)
*/
@BugPattern(
summary =
"Including fields in hashCode which are not compared in equals violates "
+ "the contract of hashCode.",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public final class InconsistentHashCode extends BugChecker implements ClassTreeMatcher {
public static final String MESSAGE =
"hashCode includes the fields %s, which equals does not. Two instances of this class "
+ "could compare equal, but have different hashCodes, which violates the hashCode "
+ "contract.";
/** Non-static methods that we might expect to see in #hashCode, and allow. */
private static final Matcher<ExpressionTree> HASH_CODE_METHODS =
instanceMethod().anyClass().named("hashCode").withNoParameters();
/** Non-static methods that we might expect to see in #equals, and allow. */
private static final Matcher<ExpressionTree> EQUALS_METHODS =
anyOf(instanceMethod().anyClass().named("getClass"), instanceEqualsInvocation());
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
ClassSymbol classSymbol = getSymbol(tree);
MethodTree equalsDeclaration = null;
MethodTree hashCodeDeclaration = null;
for (Tree member : tree.getMembers()) {
if (!(member instanceof MethodTree)) {
continue;
}
MethodTree methodTree = (MethodTree) member;
if (hashCodeMethodDeclaration().matches(methodTree, state)) {
hashCodeDeclaration = methodTree;
} else if (equalsMethodDeclaration().matches(methodTree, state)) {
equalsDeclaration = methodTree;
}
}
if (equalsDeclaration == null || hashCodeDeclaration == null) {
return Description.NO_MATCH;
}
// Build up a map of methods to the fields they access for simple methods, i.e. getters.
// Not a SetMultimap, because we do want to distinguish between "method was not analyzable" and
// "method accessed no fields".
Map<MethodSymbol, ImmutableSet<Symbol>> fieldsByMethod = new HashMap<>();
for (Tree member : tree.getMembers()) {
if (!(member instanceof MethodTree)) {
continue;
}
MethodTree methodTree = (MethodTree) member;
if (!methodTree.equals(equalsDeclaration) && !methodTree.equals(hashCodeDeclaration)) {
FieldAccessFinder finder = FieldAccessFinder.scanMethod(state, classSymbol, methodTree);
if (!finder.failed()) {
fieldsByMethod.put(getSymbol(methodTree), finder.accessedFields());
}
}
}
FieldAccessFinder equalsScanner =
FieldAccessFinder.scanMethod(
state, classSymbol, equalsDeclaration, fieldsByMethod, HASH_CODE_METHODS);
FieldAccessFinder hashCodeScanner =
FieldAccessFinder.scanMethod(
state, classSymbol, hashCodeDeclaration, fieldsByMethod, EQUALS_METHODS);
if (equalsScanner.failed() || hashCodeScanner.failed()) {
return Description.NO_MATCH;
}
ImmutableSet<Symbol> fieldsInHashCode = hashCodeScanner.accessedFields();
ImmutableSet<Symbol> fieldsInEquals = equalsScanner.accessedFields();
Set<Symbol> difference = new HashSet<>(Sets.difference(fieldsInHashCode, fieldsInEquals));
// Special-case the situation where #hashCode uses a field containing `hash` for memoization.
difference.removeIf(f -> Ascii.toLowerCase(f.toString()).contains("hash"));
String message = String.format(MESSAGE, difference);
// Skip cases where equals and hashCode compare the same fields, or equals compares none (and
// so is probably checking reference equality).
return difference.isEmpty() || fieldsInEquals.isEmpty()
? Description.NO_MATCH
: buildDescription(hashCodeDeclaration).setMessage(message).build();
}
/**
* Scans a method to find which fields are accessed from it. Fails if instance methods not
* matching {@code acceptableMethods} are found: that is, it's optimised for simple getters.
*/
private static final class FieldAccessFinder extends TreeScanner<Void, Void> {
private final Matcher<ExpressionTree> acceptableMethods;
private final Map<MethodSymbol, ImmutableSet<Symbol>> knownMethods;
private final ImmutableSet.Builder<Symbol> accessedFields = ImmutableSet.builder();
private final VisitorState state;
private final ClassSymbol classSymbol;
// We bail out if we got any unknown method calls to avoid reporting false positives.
private boolean failed = false;
private static FieldAccessFinder scanMethod(
VisitorState state, ClassSymbol classSymbol, MethodTree methodTree) {
return scanMethod(state, classSymbol, methodTree, ImmutableMap.of(), Matchers.nothing());
}
private static FieldAccessFinder scanMethod(
VisitorState state,
ClassSymbol classSymbol,
MethodTree methodTree,
Map<MethodSymbol, ImmutableSet<Symbol>> knownMethods,
Matcher<ExpressionTree> acceptableMethods) {
FieldAccessFinder finder =
new FieldAccessFinder(state, classSymbol, knownMethods, acceptableMethods);
methodTree.accept(finder, null);
return finder;
}
private FieldAccessFinder(
VisitorState state,
ClassSymbol classSymbol,
Map<MethodSymbol, ImmutableSet<Symbol>> knownMethods,
Matcher<ExpressionTree> acceptableMethods) {
this.state = state;
this.classSymbol = classSymbol;
this.knownMethods = knownMethods;
this.acceptableMethods = acceptableMethods;
}
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
MethodSymbol symbol = getSymbol(tree);
if (knownMethods.containsKey(symbol)) {
accessedFields.addAll(knownMethods.get(symbol));
} else if (!symbol.isStatic() && !acceptableMethods.matches(tree, state)) {
failed = true;
}
return super.visitMethodInvocation(tree, null);
}
@Override
public Void visitMemberSelect(MemberSelectTree tree, Void unused) {
ExpressionTree receiver = getReceiver(tree);
ExpressionTree e = tree.getExpression();
if (receiver == null
|| (e instanceof IdentifierTree
&& ((IdentifierTree) e).getName().contentEquals("this"))) {
Symbol symbol = ((JCFieldAccess) tree).sym;
handleSymbol(symbol);
}
return super.visitMemberSelect(tree, null);
}
@Override
public Void visitIdentifier(IdentifierTree tree, Void unused) {
Symbol symbol = getSymbol(tree);
handleSymbol(symbol);
return super.visitIdentifier(tree, null);
}
private void handleSymbol(Symbol symbol) {
if (symbol != null
&& symbol.getKind() == ElementKind.FIELD
&& !isStatic(symbol)
&& symbol.owner.equals(classSymbol)) {
String name = symbol.name.toString();
if (name.equals("this") || name.equals("super")) {
return;
}
accessedFields.add(symbol);
}
}
private ImmutableSet<Symbol> accessedFields() {
return accessedFields.build();
}
public boolean failed() {
return failed;
}
}
}
| 9,778
| 40.436441
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TypeParameterQualifier.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MemberSelectTree;
import com.sun.tools.javac.code.Symbol;
import javax.lang.model.element.ElementKind;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Type parameter used as type qualifier",
severity = ERROR,
suppressionAnnotations = {})
public class TypeParameterQualifier extends BugChecker implements MemberSelectTreeMatcher {
@Override
public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) {
Symbol baseSym = ASTHelpers.getSymbol(tree.getExpression());
if (baseSym == null || baseSym.getKind() != ElementKind.TYPE_PARAMETER) {
return Description.NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
fix.replace(tree, SuggestedFixes.qualifyType(state, fix, ASTHelpers.getSymbol(tree)));
return describeMatch(tree, fix.build());
}
}
| 1,995
| 38.92
| 91
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.