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/EqualsIncompatibleType.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.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.Matchers.instanceEqualsInvocation;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.staticEqualsInvocation;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.matchers.Matchers.toType;
import static com.google.errorprone.util.ASTHelpers.getGeneratedBy;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getReceiverType;
import static com.google.errorprone.util.ASTHelpers.getType;
import com.google.errorprone.BugPattern;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.TypeCompatibilityUtils.TypeCompatibilityReport;
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.ExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Type;
import javax.inject.Inject;
/**
* @author avenet@google.com (Arnaud J. Venet)
*/
@BugPattern(
summary = "An equality test between objects with incompatible types always returns false",
severity = WARNING)
public class EqualsIncompatibleType extends BugChecker
implements MethodInvocationTreeMatcher, MemberReferenceTreeMatcher {
private static final Matcher<ExpressionTree> STATIC_EQUALS_MATCHER = staticEqualsInvocation();
private static final Matcher<ExpressionTree> INSTANCE_EQUALS_MATCHER = instanceEqualsInvocation();
private static final Matcher<ExpressionTree> IS_EQUAL_MATCHER =
staticMethod().onClass("java.util.function.Predicate").named("isEqual");
private static final Matcher<Tree> ASSERT_FALSE_MATCHER =
toType(
MethodInvocationTree.class,
anyOf(
instanceMethod().anyClass().named("assertFalse"),
staticMethod().anyClass().named("assertFalse")));
private final TypeCompatibilityUtils typeCompatibilityUtils;
@Inject
EqualsIncompatibleType(ErrorProneFlags flags) {
this.typeCompatibilityUtils = TypeCompatibilityUtils.fromFlags(flags);
}
@Override
public Description matchMethodInvocation(
MethodInvocationTree invocationTree, VisitorState state) {
if (STATIC_EQUALS_MATCHER.matches(invocationTree, state)) {
return match(
invocationTree,
getType(invocationTree.getArguments().get(0)),
getType(invocationTree.getArguments().get(1)),
state);
}
if (INSTANCE_EQUALS_MATCHER.matches(invocationTree, state)) {
return match(
invocationTree,
getReceiverType(invocationTree),
getType(invocationTree.getArguments().get(0)),
state);
}
if (IS_EQUAL_MATCHER.matches(invocationTree, state)) {
Type targetType = ASTHelpers.targetType(state).type();
if (targetType.getTypeArguments().size() != 1) {
return NO_MATCH;
}
return match(
invocationTree,
getType(invocationTree.getArguments().get(0)),
state.getTypes().wildLowerBound(getOnlyElement(targetType.getTypeArguments())),
state);
}
return NO_MATCH;
}
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
if (STATIC_EQUALS_MATCHER.matches(tree, state)) {
Type type = state.getTypes().findDescriptorType(getType(tree));
return match(tree, type.getParameterTypes().get(0), type.getParameterTypes().get(1), state);
}
if (INSTANCE_EQUALS_MATCHER.matches(tree, state)) {
Type type = state.getTypes().findDescriptorType(getType(tree));
return match(tree, getType(getReceiver(tree)), type.getParameterTypes().get(0), state);
}
if (IS_EQUAL_MATCHER.matches(tree, state)) {
Type type = state.getTypes().findDescriptorType(getType(tree));
if (type.getReturnType().getTypeArguments().size() != 1) {
return NO_MATCH;
}
return match(
tree,
getOnlyElement(type.getReturnType().getTypeArguments()),
type.getParameterTypes().get(0),
state);
}
return NO_MATCH;
}
private Description match(
ExpressionTree invocationTree, Type receiverType, Type argumentType, VisitorState state) {
TypeCompatibilityReport compatibilityReport =
typeCompatibilityUtils.compatibilityOfTypes(receiverType, argumentType, state);
if (compatibilityReport.isCompatible()) {
return NO_MATCH;
}
// Ignore callsites wrapped inside assertFalse:
// assertFalse(objOfReceiverType.equals(objOfArgumentType))
if (ASSERT_FALSE_MATCHER.matches(state.getPath().getParentPath().getLeaf(), state)) {
return NO_MATCH;
}
if (getGeneratedBy(state).contains("com.google.auto.value.processor.AutoValueProcessor")) {
return NO_MATCH;
}
// When we reach this point, we know that the two following facts hold:
// (1) The types of the receiver and the argument to the eventual invocation of
// java.lang.Object.equals() are incompatible.
// (2) No common superclass (other than java.lang.Object) or interface of the receiver and the
// argument defines an override of java.lang.Object.equals().
// This equality test almost certainly evaluates to false, which is very unlikely to be the
// programmer's intent. Hence, this is reported as an error. There is no sensible fix to suggest
// in this situation.
return buildDescription(invocationTree)
.setMessage(
getMessage(
invocationTree,
receiverType,
argumentType,
compatibilityReport.lhs(),
compatibilityReport.rhs(),
state)
+ compatibilityReport.extraReason())
.build();
}
private static String getMessage(
ExpressionTree invocationTree,
Type receiverType,
Type argumentType,
Type conflictingReceiverType,
Type conflictingArgumentType,
VisitorState state) {
TypeStringPair typeStringPair = new TypeStringPair(receiverType, argumentType);
String baseMessage =
"Calling "
+ ASTHelpers.getSymbol(invocationTree).getSimpleName()
+ " on incompatible types "
+ typeStringPair.getReceiverTypeString()
+ " and "
+ typeStringPair.getArgumentTypeString();
if (state.getTypes().isSameType(receiverType, conflictingReceiverType)) {
return baseMessage;
}
// If receiver/argument are incompatible due to a conflict in the generic type, message that out
TypeStringPair conflictingTypes =
new TypeStringPair(conflictingReceiverType, conflictingArgumentType);
return baseMessage
+ ". They are incompatible because "
+ conflictingTypes.getReceiverTypeString()
+ " and "
+ conflictingTypes.getArgumentTypeString()
+ " are incompatible.";
}
private static class TypeStringPair {
private String receiverTypeString;
private String argumentTypeString;
private TypeStringPair(Type receiverType, Type argumentType) {
receiverTypeString = Signatures.prettyType(receiverType);
argumentTypeString = Signatures.prettyType(argumentType);
if (argumentTypeString.equals(receiverTypeString)) {
receiverTypeString = receiverType.toString();
argumentTypeString = argumentType.toString();
}
}
private String getReceiverTypeString() {
return receiverTypeString;
}
private String getArgumentTypeString() {
return argumentTypeString;
}
}
}
| 9,010
| 38.696035
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnusedAnonymousClass.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.common.collect.ImmutableList;
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.util.ASTHelpers;
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.tools.javac.code.Symbol.TypeSymbol;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "Instance created but never used", severity = ERROR)
public class UnusedAnonymousClass extends BugChecker implements NewClassTreeMatcher {
// An anonymous class creation cannot have side-effects if:
// (1) it is of an interface type (no super-class constructor side-effects)
// (2) and has no instance initializer blocks or field initializers
@Override
public Description matchNewClass(NewClassTree newClassTree, VisitorState state) {
if (state.getPath().getParentPath().getLeaf().getKind() != Kind.EXPRESSION_STATEMENT) {
return Description.NO_MATCH;
}
if (newClassTree.getClassBody() == null) {
return Description.NO_MATCH;
}
if (!newClassTree.getArguments().isEmpty()) {
return Description.NO_MATCH;
}
for (Tree def : newClassTree.getClassBody().getMembers()) {
switch (def.getKind()) {
case VARIABLE:
{
VariableTree variableTree = (VariableTree) def;
if (variableTree.getInitializer() != null) {
return Description.NO_MATCH;
}
break;
}
case BLOCK:
return Description.NO_MATCH;
default:
break;
}
}
if (!sideEffectFreeConstructor(ASTHelpers.getType(newClassTree.getIdentifier()).tsym, state)) {
return Description.NO_MATCH;
}
return describeMatch(newClassTree);
}
private static final ImmutableList<String> TYPES_WITH_SIDE_EFFECT_FREE_CONSTRUCTORS =
ImmutableList.of(Thread.class.getName());
private static boolean sideEffectFreeConstructor(TypeSymbol classType, VisitorState state) {
if (classType.isInterface()) {
return true;
}
for (String typeName : TYPES_WITH_SIDE_EFFECT_FREE_CONSTRUCTORS) {
if (ASTHelpers.isSameType(classType.type, state.getTypeFromString(typeName), state)) {
return true;
}
}
return false;
}
}
| 3,243
| 35.863636
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JUnitAssertSameCheck.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.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 java.util.List;
/**
* Points out if an object is tested for reference equality to itself using JUnit library.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary = "An object is tested for reference equality to itself using JUnit library.",
severity = ERROR)
public class JUnitAssertSameCheck extends BugChecker implements MethodInvocationTreeMatcher {
/**
* Cases:
*
* <ol>
* <li>org.junit.Assert.assertSame(a, a);
* <li>org.junit.Assert.assertSame("message", a, a);
* <li>junit.framework.Assert.assertSame(a, a);
* <li>junit.framework.Assert.assertSame("message", a, a);
* </ol>
*/
private static final Matcher<ExpressionTree> ASSERT_SAME_MATCHER =
staticMethod().onClassAny("org.junit.Assert", "junit.framework.Assert").named("assertSame");
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState state) {
if (!ASSERT_SAME_MATCHER.matches(methodInvocationTree, state)) {
return Description.NO_MATCH;
}
List<? extends ExpressionTree> args = methodInvocationTree.getArguments();
// cases: assertSame(a, a);
if (args.size() == 2 && ASTHelpers.sameVariable(args.get(0), args.get(1))) {
return describeMatch(methodInvocationTree);
}
// cases: assertSame("message", a, a);
if (args.size() == 3 && ASTHelpers.sameVariable(args.get(1), args.get(2))) {
return describeMatch(methodInvocationTree);
}
return Description.NO_MATCH;
}
}
| 2,729
| 35.4
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AbstractAsyncTypeReturnsNull.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.base.Preconditions.checkNotNull;
import static com.google.errorprone.util.ASTHelpers.findSuperMethods;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import com.google.common.util.concurrent.Futures;
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.sun.source.tree.MethodTree;
import com.sun.source.tree.ReturnTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.Optional;
/**
* Superclass for checks that {@code AsyncCallable} and {@code AsyncFunction} implementations do not
* directly {@code return null}.
*/
abstract class AbstractAsyncTypeReturnsNull extends AbstractMethodReturnsNull {
AbstractAsyncTypeReturnsNull(Class<?> asyncClass) {
super(overridesMethodOfClass(asyncClass));
}
@Override
protected Optional<Fix> provideFix(ReturnTree tree) {
return Optional.of(
SuggestedFix.builder()
.replace(tree.getExpression(), "immediateFuture(null)")
.addStaticImport(Futures.class.getName() + ".immediateFuture")
.build());
}
private static Matcher<MethodTree> overridesMethodOfClass(Class<?> clazz) {
checkNotNull(clazz);
return new Matcher<MethodTree>() {
@Override
public boolean matches(MethodTree tree, VisitorState state) {
MethodSymbol symbol = getSymbol(tree);
for (MethodSymbol superMethod : findSuperMethods(symbol, state.getTypes())) {
if (superMethod.owner != null
&& superMethod.owner.getQualifiedName().contentEquals(clazz.getName())) {
return true;
}
}
return false;
}
};
}
}
| 2,440
| 34.376812
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StreamToString.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.predicates.TypePredicates.isDescendantOf;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.predicates.TypePredicate;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.Tree;
import java.util.Optional;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Calling toString on a Stream does not provide useful information",
severity = ERROR)
public class StreamToString extends AbstractToString {
private static final TypePredicate STREAM = isDescendantOf("java.util.stream.Stream");
@Override
protected TypePredicate typePredicate() {
return STREAM;
}
@Override
protected Optional<Fix> implicitToStringFix(ExpressionTree tree, VisitorState state) {
return Optional.empty();
}
@Override
protected Optional<Fix> toStringFix(Tree parent, ExpressionTree tree, VisitorState state) {
return Optional.empty();
}
}
| 1,793
| 32.849057
| 93
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/EqualsGetClass.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.Matchers.equalsMethodDeclaration;
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.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
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.matchers.Matchers;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.tree.UnaryTree;
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.ClassSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import javax.lang.model.element.Modifier;
/**
* Discourages the use of {@link Object#getClass()} when implementing {@link Object#equals(Object)}
* for non-final classes.
*
* @author ghm@google.com (Graeme Morgan)
*/
@BugPattern(
summary = "Prefer instanceof to getClass when implementing Object#equals.",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public final class EqualsGetClass extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> GET_CLASS =
instanceMethod().onDescendantOf("java.lang.Object").named("getClass");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!GET_CLASS.matches(tree, state)) {
return Description.NO_MATCH;
}
TreePath methodTreePath = state.findPathToEnclosing(MethodTree.class);
if (methodTreePath == null) {
return Description.NO_MATCH;
}
ClassTree classTree = state.findEnclosing(ClassTree.class);
// Using getClass is harmless if a class is final (although instanceof provides the null check
// for free).
if (classTree == null || classTree.getModifiers().getFlags().contains(Modifier.FINAL)) {
return Description.NO_MATCH;
}
ClassSymbol classSymbol = getSymbol(classTree);
if (classSymbol.isAnonymous()) {
return Description.NO_MATCH;
}
MethodTree methodTree = (MethodTree) methodTreePath.getLeaf();
if (!equalsMethodDeclaration().matches(methodTree, state)) {
return Description.NO_MATCH;
}
VariableTree parameter = getOnlyElement(methodTree.getParameters());
ExpressionTree receiver = getReceiver(tree);
VarSymbol symbol = getSymbol(parameter);
if (receiver == null
|| receiver.getKind() != Kind.IDENTIFIER
|| !symbol.equals(getSymbol(receiver))) {
return Description.NO_MATCH;
}
EqualsFixer fixer = new EqualsFixer(symbol, getSymbol(classTree), state);
fixer.scan(methodTreePath, null);
return describeMatch(methodTree, fixer.getFix());
}
private static class EqualsFixer extends TreePathScanner<Void, Void> {
private static final Matcher<ExpressionTree> GET_CLASS =
instanceMethod().onDescendantOf("java.lang.Object").named("getClass").withNoParameters();
private static final Matcher<ExpressionTree> THIS_CLASS =
anyOf(
allOf(GET_CLASS, (tree, unused) -> matchesThis(tree)),
(tree, unused) -> matchesClass(tree));
private static boolean matchesThis(ExpressionTree tree) {
ExpressionTree receiver = getReceiver(tree);
if (receiver == null) {
return true;
}
while (!(receiver instanceof IdentifierTree)) {
if (receiver instanceof ParenthesizedTree) {
receiver = ((ParenthesizedTree) receiver).getExpression();
} else if (receiver instanceof TypeCastTree) {
receiver = ((TypeCastTree) receiver).getExpression();
} else {
return false;
}
}
Symbol symbol = getSymbol(receiver);
return symbol != null && symbol.getSimpleName().contentEquals("this");
}
private static boolean matchesClass(ExpressionTree tree) {
Symbol symbol = getSymbol(tree);
if (!(symbol instanceof VarSymbol)) {
return false;
}
VarSymbol varSymbol = (VarSymbol) symbol;
return varSymbol.getSimpleName().contentEquals("class");
}
private final Symbol parameter;
private final ClassSymbol classSymbol;
private final VisitorState state;
private final SuggestedFix.Builder fix = SuggestedFix.builder();
private final Matcher<ExpressionTree> isParameter;
private final Matcher<ExpressionTree> otherClass;
/** Whether we managed to rewrite a {@code getClass}. */
private boolean matchedGetClass = false;
/** Whether we failed to generate a satisfactory fix for a boolean replacement. */
private boolean failed = false;
private EqualsFixer(Symbol parameter, ClassSymbol classSymbol, VisitorState visitorState) {
this.parameter = parameter;
this.classSymbol = classSymbol;
this.state = visitorState;
this.isParameter = (tree, state) -> parameter.equals(getSymbol(tree));
this.otherClass =
allOf(GET_CLASS, (tree, state) -> parameter.equals(getSymbol(getReceiver(tree))));
}
@Override
public Void visitBinary(BinaryTree binaryTree, Void unused) {
if (binaryTree.getKind() != Kind.NOT_EQUAL_TO && binaryTree.getKind() != Kind.EQUAL_TO) {
return super.visitBinary(binaryTree, null);
}
if (matchesEitherWay(binaryTree, isParameter, Matchers.nullLiteral())) {
if (binaryTree.getKind() == Kind.NOT_EQUAL_TO) {
makeAlwaysTrue();
}
if (binaryTree.getKind() == Kind.EQUAL_TO) {
makeAlwaysFalse();
}
return null;
}
if (matchesEitherWay(binaryTree, THIS_CLASS, otherClass)) {
matchedGetClass = true;
String instanceOf =
String.format(
"%s instanceof %s", parameter.getSimpleName(), classSymbol.getSimpleName());
if (binaryTree.getKind() == Kind.EQUAL_TO) {
fix.replace(binaryTree, instanceOf);
}
if (binaryTree.getKind() == Kind.NOT_EQUAL_TO) {
fix.replace(binaryTree, String.format("!(%s)", instanceOf));
}
}
return super.visitBinary(binaryTree, null);
}
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void unused) {
if (!instanceEqualsInvocation().matches(node, state)) {
return null;
}
ExpressionTree argument = getOnlyElement(node.getArguments());
ExpressionTree receiver = getReceiver(node);
if (receiver == null) {
return null;
}
if (matchesEitherWay(argument, receiver, THIS_CLASS, otherClass)) {
matchedGetClass = true;
String replacement =
String.format(
"%s instanceof %s", parameter.getSimpleName(), classSymbol.getSimpleName());
if (getCurrentPath().getParentPath().getLeaf() instanceof UnaryTree) {
replacement = String.format("(%s)", replacement);
}
fix.replace(node, replacement);
}
return super.visitMethodInvocation(node, null);
}
private boolean matchesEitherWay(
BinaryTree binaryTree, Matcher<ExpressionTree> matcherA, Matcher<ExpressionTree> matcherB) {
return matchesEitherWay(
binaryTree.getLeftOperand(), binaryTree.getRightOperand(), matcherA, matcherB);
}
private boolean matchesEitherWay(
ExpressionTree treeA,
ExpressionTree treeB,
Matcher<ExpressionTree> matcherA,
Matcher<ExpressionTree> matcherB) {
return (matcherA.matches(treeA, state) && matcherB.matches(treeB, state))
|| (matcherA.matches(treeB, state) && matcherB.matches(treeA, state));
}
private void makeAlwaysTrue() {
removeFromBinary(Kind.CONDITIONAL_AND);
}
private void makeAlwaysFalse() {
TreePath enclosingPath = getCurrentPath().getParentPath();
while (enclosingPath.getLeaf() instanceof ParenthesizedTree) {
enclosingPath = enclosingPath.getParentPath();
}
Tree enclosing = enclosingPath.getLeaf();
if (enclosing instanceof IfTree) {
IfTree ifTree = (IfTree) enclosing;
if (ifTree.getElseStatement() == null) {
fix.replace(ifTree, "");
} else {
int stripExtra = ifTree.getElseStatement() instanceof BlockTree ? 1 : 0;
fix.replace(
getStartPosition(ifTree),
getStartPosition(ifTree.getElseStatement()) + stripExtra,
"")
.replace(
state.getEndPosition(ifTree.getElseStatement()) - stripExtra,
state.getEndPosition(ifTree.getElseStatement()),
"");
}
return;
}
removeFromBinary(Kind.CONDITIONAL_OR);
}
private void removeFromBinary(Kind ifKind) {
TreePath outsideParensPath = getCurrentPath().getParentPath();
TreePath justInsideBinaryPath = getCurrentPath();
while (outsideParensPath.getLeaf() instanceof ParenthesizedTree) {
justInsideBinaryPath = outsideParensPath;
outsideParensPath = outsideParensPath.getParentPath();
}
Tree superTree = outsideParensPath.getLeaf();
if (superTree.getKind() != ifKind) {
failed = true;
return;
}
BinaryTree superBinary = (BinaryTree) superTree;
if (superBinary.getLeftOperand().equals(justInsideBinaryPath.getLeaf())) {
removeLeftOperand(superBinary);
} else {
removeRightOperand(superBinary);
}
}
private void removeLeftOperand(BinaryTree superBinary) {
fix.replace(
getStartPosition(superBinary.getLeftOperand()),
getStartPosition(superBinary.getRightOperand()),
"");
}
private void removeRightOperand(BinaryTree superBinary) {
fix.replace(
state.getEndPosition(superBinary.getLeftOperand()),
state.getEndPosition(superBinary.getRightOperand()),
"");
}
private SuggestedFix getFix() {
return matchedGetClass && !failed ? fix.build() : SuggestedFix.emptyFix();
}
}
}
| 11,934
| 37.876221
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/OptionalMapUnusedValue.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.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.argument;
import static com.google.errorprone.matchers.Matchers.kindIs;
import static com.google.errorprone.matchers.Matchers.parentNode;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFixes;
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;
/** Replaces {@code Optional.map} with {@code Optional.ifPresent} if the value is unused. */
@BugPattern(
summary = "Optional.ifPresent is preferred over Optional.map when the return value is unused",
severity = ERROR)
public final class OptionalMapUnusedValue extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> METHOD_IS_OPTIONAL_MAP =
instanceMethod().onExactClass("java.util.Optional").named("map");
private static final Matcher<ExpressionTree> PARENT_IS_STATEMENT =
parentNode(kindIs(Kind.EXPRESSION_STATEMENT));
private static final Matcher<MethodInvocationTree> ARG_IS_VOID_COMPATIBLE =
argument(
0, anyOf(kindIs(Kind.MEMBER_REFERENCE), OptionalMapUnusedValue::isVoidCompatibleLambda));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (METHOD_IS_OPTIONAL_MAP.matches(tree, state)
&& PARENT_IS_STATEMENT.matches(tree, state)
&& ARG_IS_VOID_COMPATIBLE.matches(tree, state)) {
return describeMatch(tree, SuggestedFixes.renameMethodInvocation(tree, "ifPresent", state));
}
return NO_MATCH;
}
// TODO(b/170476239): Cover all the cases in which the argument is void-compatible, see
// JLS 15.12.2.1
private static boolean isVoidCompatibleLambda(ExpressionTree tree, VisitorState state) {
if (tree instanceof LambdaExpressionTree) {
LambdaExpressionTree lambdaTree = (LambdaExpressionTree) tree;
if (lambdaTree.getBodyKind().equals(LambdaExpressionTree.BodyKind.EXPRESSION)) {
return kindIs(Kind.METHOD_INVOCATION).matches(lambdaTree.getBody(), state);
}
}
return false;
}
}
| 3,329
| 43.4
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ShortCircuitBoolean.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.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static com.sun.source.tree.Tree.Kind.AND;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
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.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.TreeScanner;
import java.util.Iterator;
/**
* @author cushon@google.com (Liam Miller-Cushon)
* @author sulku@google.com (Marsela Sulku)
* @author mariasam@google.com (Maria Sam)
*/
@BugPattern(
summary = "Prefer the short-circuiting boolean operators && and || to & and |.",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public class ShortCircuitBoolean extends BugChecker implements BinaryTreeMatcher {
@Override
public Description matchBinary(BinaryTree tree, VisitorState state) {
switch (tree.getKind()) {
case AND:
case OR:
break;
default:
return NO_MATCH;
}
if (!isSameType(getType(tree), state.getSymtab().booleanType, state)) {
return NO_MATCH;
}
Iterator<Tree> stateIterator = state.getPath().getParentPath().iterator();
Tree parent = stateIterator.next();
if (parent instanceof BinaryTree
&& (parent.getKind() == Kind.AND || parent.getKind() == Kind.OR)) {
return NO_MATCH;
} else {
SuggestedFix.Builder fix = SuggestedFix.builder();
new TreeScannerBinary(state).scan(tree, fix);
return describeMatch(tree, fix.build());
}
}
/** Replaces the operators when visiting the binary nodes */
public static class TreeScannerBinary extends TreeScanner<Void, SuggestedFix.Builder> {
/** saved state */
public VisitorState state;
/** constructor */
public TreeScannerBinary(VisitorState currState) {
this.state = currState;
}
@Override
public Void visitBinary(BinaryTree tree, SuggestedFix.Builder p) {
if (tree.getKind() == Kind.AND || tree.getKind() == Kind.OR) {
p.replace(
/* startPos= */ state.getEndPosition(tree.getLeftOperand()),
/* endPos= */ getStartPosition(tree.getRightOperand()),
tree.getKind() == AND ? " && " : " || ");
}
return super.visitBinary(tree, p);
}
}
}
| 3,412
| 33.826531
| 89
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MathRoundIntLong.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 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.isSameType;
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.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;
/**
* Check for calls to Math's {@link Math#round} with an integer or long parameter.
*
* @author seibelsabrina@google.com (Sabrina Seibel)
*/
@BugPattern(
summary = "Math.round(Integer) results in truncation",
explanation =
"Math.round() called with an integer or long type results in truncation"
+ " because Math.round only accepts floats or doubles and some integers and longs can't"
+ " be represented with float.",
severity = ERROR)
public final class MathRoundIntLong extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MATH_ROUND_CALLS =
staticMethod().onClass("java.lang.Math").named("round");
private static final Matcher<MethodInvocationTree> ROUND_CALLS_WITH_INT_ARG =
allOf(
MATH_ROUND_CALLS, argument(0, anyOf(isSameType("int"), isSameType("java.lang.Integer"))));
private static final Matcher<MethodInvocationTree> ROUND_CALLS_WITH_LONG_ARG =
allOf(MATH_ROUND_CALLS, argument(0, anyOf(isSameType("long"), isSameType("java.lang.Long"))));
private static final Matcher<MethodInvocationTree> ROUND_CALLS_WITH_INT_OR_LONG_ARG =
anyOf(ROUND_CALLS_WITH_INT_ARG, ROUND_CALLS_WITH_LONG_ARG);
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return ROUND_CALLS_WITH_INT_OR_LONG_ARG.matches(tree, state)
? removeMathRoundCall(tree, state)
: Description.NO_MATCH;
}
private Description removeMathRoundCall(MethodInvocationTree tree, VisitorState state) {
if (ROUND_CALLS_WITH_INT_ARG.matches(tree, state)) {
if (ASTHelpers.requiresParentheses(Iterables.getOnlyElement(tree.getArguments()), state)) {
return describeMatch(
tree,
SuggestedFix.builder()
.prefixWith(tree, "(")
.replace(tree, state.getSourceForNode(tree.getArguments().get(0)))
.postfixWith(tree, ")")
.build());
}
return describeMatch(
tree, SuggestedFix.replace(tree, state.getSourceForNode(tree.getArguments().get(0))));
} else if (ROUND_CALLS_WITH_LONG_ARG.matches(tree, state)) {
// TODO(b/112270644): skip Ints.saturatedCast fix if guava isn't on the classpath
return describeMatch(
tree,
SuggestedFix.builder()
.addImport("com.google.common.primitives.Ints")
.prefixWith(tree, "Ints.saturatedCast(")
.replace(tree, state.getSourceForNode(tree.getArguments().get(0)))
.postfixWith(tree, ")")
.build());
}
throw new AssertionError(
"Unknown argument type to round call: " + state.getSourceForNode(tree));
}
}
| 4,296
| 42.846939
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ImpossibleNullComparison.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.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.getOnlyElement;
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.receiverOfInvocation;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
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 java.lang.String.format;
import static java.util.Arrays.stream;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.errorprone.BugPattern;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
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.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ParenthesizedTree;
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.tree.JCTree.JCFieldAccess;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import javax.inject.Inject;
/** Matches comparison of proto fields to {@code null}. */
@BugPattern(
summary = "This value cannot be null, and comparing it to null may be misleading.",
name = "ImpossibleNullComparison",
altNames = "ProtoFieldNullComparison",
severity = ERROR)
public final class ImpossibleNullComparison extends BugChecker
implements CompilationUnitTreeMatcher {
// TODO(b/111109484): Try to consolidate these with NullnessPropagationTransfer.
private static final Matcher<ExpressionTree> CHECK_NOT_NULL =
anyOf(
staticMethod().onClass("com.google.common.base.Preconditions").named("checkNotNull"),
staticMethod().onClass("com.google.common.base.Verify").named("verifyNotNull"),
staticMethod().onClass("java.util.Objects").named("requireNonNull"));
private static final Matcher<ExpressionTree> ASSERT_NOT_NULL =
anyOf(
staticMethod().onClass("junit.framework.Assert").named("assertNotNull"),
staticMethod().onClass("org.junit.Assert").named("assertNotNull"));
private static final Matcher<MethodInvocationTree> TRUTH_NOT_NULL =
allOf(
instanceMethod().anyClass().named("isNotNull"),
receiverOfInvocation(
anyOf(
staticMethod().anyClass().namedAnyOf("assertThat"),
instanceMethod()
.onDescendantOf("com.google.common.truth.StandardSubjectBuilder")
.named("that"))));
private static final Matcher<Tree> RETURNS_LIST = Matchers.isSubtypeOf("java.util.List");
private static final ImmutableSet<Kind> COMPARISON_OPERATORS =
Sets.immutableEnumSet(Kind.EQUAL_TO, Kind.NOT_EQUAL_TO);
private static final Matcher<ExpressionTree> EXTENSION_METHODS_WITH_FIX =
instanceMethod()
.onDescendantOf("com.google.protobuf.GeneratedMessage.ExtendableMessage")
.named("getExtension")
.withParameters("com.google.protobuf.ExtensionLite");
private static final Matcher<ExpressionTree> EXTENSION_METHODS_WITH_NO_FIX =
anyOf(
instanceMethod()
.onDescendantOf("com.google.protobuf.MessageOrBuilder")
.named("getRepeatedField")
.withParameters("com.google.protobuf.Descriptors.FieldDescriptor", "int"),
instanceMethod()
.onDescendantOf("com.google.protobuf.GeneratedMessage.ExtendableMessage")
.named("getExtension")
.withParameters("com.google.protobuf.ExtensionLite", "int"),
instanceMethod()
.onDescendantOf("com.google.protobuf.MessageOrBuilder")
.named("getField")
.withParameters("com.google.protobuf.Descriptors.FieldDescriptor"));
private static final Matcher<ExpressionTree> OF_NULLABLE =
anyOf(
staticMethod().onClass("java.util.Optional").named("ofNullable"),
staticMethod().onClass("com.google.common.base.Optional").named("fromNullable"));
private static boolean isNull(ExpressionTree tree) {
return tree.getKind() == Kind.NULL_LITERAL;
}
/** Matcher for generated protobufs. */
private static final Matcher<ExpressionTree> PROTO_RECEIVER =
instanceMethod()
.onDescendantOfAny(
"com.google.protobuf.GeneratedMessageLite", "com.google.protobuf.GeneratedMessage");
private final boolean matchTestAssertions;
@Inject
ImpossibleNullComparison(ErrorProneFlags flags) {
this.matchTestAssertions =
flags.getBoolean("ProtoFieldNullComparison:MatchTestAssertions").orElse(true);
}
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
NullComparisonScanner scanner = new NullComparisonScanner(state);
scanner.scan(state.getPath(), null);
return Description.NO_MATCH;
}
private class NullComparisonScanner extends TreePathScanner<Void, Void> {
private final Map<Symbol, ExpressionTree> effectivelyFinalValues = new HashMap<>();
private final VisitorState state;
private NullComparisonScanner(VisitorState state) {
this.state = state;
}
@Override
public Void visitMethod(MethodTree method, Void unused) {
return isSuppressed(method, state) ? null : super.visitMethod(method, unused);
}
@Override
public Void visitClass(ClassTree clazz, Void unused) {
return isSuppressed(clazz, state) ? null : super.visitClass(clazz, unused);
}
@Override
public Void visitVariable(VariableTree variable, Void unused) {
Symbol symbol = ASTHelpers.getSymbol(variable);
if (variable.getInitializer() != null && isConsideredFinal(symbol)) {
getInitializer(variable.getInitializer())
.ifPresent(e -> effectivelyFinalValues.put(symbol, e));
}
return isSuppressed(variable, state) ? null : super.visitVariable(variable, null);
}
private Optional<ExpressionTree> getInitializer(ExpressionTree tree) {
return Optional.ofNullable(
new SimpleTreeVisitor<ExpressionTree, Void>() {
@Nullable
@Override
public ExpressionTree visitMethodInvocation(MethodInvocationTree node, Void unused) {
return PROTO_RECEIVER.matches(node, state) ? node : null;
}
@Override
public ExpressionTree visitParenthesized(ParenthesizedTree node, Void unused) {
return visit(node.getExpression(), null);
}
@Override
public ExpressionTree visitTypeCast(TypeCastTree node, Void unused) {
return visit(node.getExpression(), null);
}
}.visit(tree, null));
}
@Override
public Void visitBinary(BinaryTree binary, Void unused) {
if (!COMPARISON_OPERATORS.contains(binary.getKind())) {
return super.visitBinary(binary, null);
}
VisitorState subState = state.withPath(getCurrentPath());
Optional<Fixer> fixer = Optional.empty();
if (isNull(binary.getLeftOperand())) {
fixer = getFixer(binary.getRightOperand(), subState);
}
if (isNull(binary.getRightOperand())) {
fixer = getFixer(binary.getLeftOperand(), subState);
}
fixer
.map(f -> describeMatch(binary, ProblemUsage.COMPARISON.fix(f, binary, subState)))
.ifPresent(state::reportMatch);
return super.visitBinary(binary, null);
}
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void unused) {
VisitorState subState = state.withPath(getCurrentPath());
ExpressionTree argument;
ProblemUsage problemType;
if (CHECK_NOT_NULL.matches(node, subState)) {
argument = node.getArguments().get(0);
problemType = ProblemUsage.CHECK_NOT_NULL;
} else if (matchTestAssertions && ASSERT_NOT_NULL.matches(node, subState)) {
argument = getLast(node.getArguments());
problemType = ProblemUsage.JUNIT;
} else if (OF_NULLABLE.matches(node, subState)) {
argument = getOnlyElement(node.getArguments());
problemType = ProblemUsage.OPTIONAL;
} else if (matchTestAssertions && TRUTH_NOT_NULL.matches(node, subState)) {
argument = getOnlyElement(((MethodInvocationTree) getReceiver(node)).getArguments());
problemType = ProblemUsage.TRUTH;
} else {
return super.visitMethodInvocation(node, null);
}
getFixer(argument, subState)
.map(f -> problemType.fix(f, node, subState))
.filter(f -> !f.isEmpty())
.map(f -> describeMatch(node, f))
.ifPresent(state::reportMatch);
return super.visitMethodInvocation(node, null);
}
private Optional<Fixer> getFixer(ExpressionTree tree, VisitorState state) {
ExpressionTree resolvedTree = getEffectiveTree(tree);
if (resolvedTree == null) {
return Optional.empty();
}
return stream(GetterTypes.values())
.map(type -> type.match(resolvedTree, state))
.filter(Objects::nonNull)
.findFirst();
}
@Nullable
private ExpressionTree getEffectiveTree(ExpressionTree tree) {
return tree.getKind() == Kind.IDENTIFIER
? effectivelyFinalValues.get(ASTHelpers.getSymbol(tree))
: tree;
}
}
private static String getMethodName(ExpressionTree tree) {
MethodInvocationTree method = (MethodInvocationTree) tree;
ExpressionTree expressionTree = method.getMethodSelect();
JCFieldAccess access = (JCFieldAccess) expressionTree;
return access.sym.getQualifiedName().toString();
}
private static String replaceLast(String text, String pattern, String replacement) {
StringBuilder builder = new StringBuilder(text);
int lastIndexOf = builder.lastIndexOf(pattern);
return builder.replace(lastIndexOf, lastIndexOf + pattern.length(), replacement).toString();
}
/** Generates a replacement, if available. */
private interface Fixer {
/**
* @param negated whether the replacement should be negated.
*/
Optional<String> getReplacement(boolean negated, VisitorState state);
}
private static final Matcher<ExpressionTree> OPTIONAL_GET_MATCHER =
instanceMethod().onExactClass("java.util.Optional").namedAnyOf("get", "orElseThrow");
private static final Matcher<ExpressionTree> GUAVA_OPTIONAL_GET_MATCHER =
instanceMethod().onExactClass("com.google.common.base.Optional").named("get");
private static final Matcher<ExpressionTree> MULTIMAP_GET_MATCHER =
instanceMethod().onDescendantOf("com.google.common.collect.Multimap").named("get");
private static final Matcher<ExpressionTree> TABLE_ROW_MATCHER =
instanceMethod().onDescendantOf("com.google.common.collect.Table").named("row");
private static final Matcher<ExpressionTree> TABLE_COLUMN_MATCHER =
instanceMethod().onDescendantOf("com.google.common.collect.Table").named("column");
private enum GetterTypes {
OPTIONAL_GET {
@Nullable
@Override
Fixer match(ExpressionTree tree, VisitorState state) {
if (!OPTIONAL_GET_MATCHER.matches(tree, state)) {
return null;
}
return (n, s) ->
Optional.of(
s.getSourceForNode(getReceiver(tree)) + (n ? ".isEmpty()" : ".isPresent()"));
}
},
GUAVA_OPTIONAL_GET {
@Nullable
@Override
Fixer match(ExpressionTree tree, VisitorState state) {
if (!GUAVA_OPTIONAL_GET_MATCHER.matches(tree, state)) {
return null;
}
return (n, s) ->
Optional.of((n ? "!" : "") + s.getSourceForNode(getReceiver(tree)) + ".isPresent()");
}
},
MULTIMAP_GET {
@Nullable
@Override
Fixer match(ExpressionTree tree, VisitorState state) {
if (!MULTIMAP_GET_MATCHER.matches(tree, state)) {
return null;
}
return (n, s) ->
Optional.of(
format(
"%s%s.containsKey(%s)",
n ? "!" : "",
s.getSourceForNode(getReceiver(tree)),
s.getSourceForNode(
getOnlyElement(((MethodInvocationTree) tree).getArguments()))));
}
},
TABLE_ROW_GET {
@Nullable
@Override
Fixer match(ExpressionTree tree, VisitorState state) {
if (!TABLE_ROW_MATCHER.matches(tree, state)) {
return null;
}
return (n, s) ->
Optional.of(
format(
"%s%s.containsRow(%s)",
n ? "!" : "",
s.getSourceForNode(getReceiver(tree)),
s.getSourceForNode(
getOnlyElement(((MethodInvocationTree) tree).getArguments()))));
}
},
TABLE_COLUMN_GET {
@Nullable
@Override
Fixer match(ExpressionTree tree, VisitorState state) {
if (!TABLE_COLUMN_MATCHER.matches(tree, state)) {
return null;
}
return (n, s) ->
Optional.of(
format(
"%s%s.containsColumn(%s)",
n ? "!" : "",
s.getSourceForNode(getReceiver(tree)),
s.getSourceForNode(
getOnlyElement(((MethodInvocationTree) tree).getArguments()))));
}
},
/** {@code proto.getFoo()} */
SCALAR {
@Nullable
@Override
Fixer match(ExpressionTree tree, VisitorState state) {
if (!PROTO_RECEIVER.matches(tree, state)) {
return null;
}
if (tree.getKind() != Kind.METHOD_INVOCATION) {
return null;
}
MethodInvocationTree method = (MethodInvocationTree) tree;
if (!method.getArguments().isEmpty()) {
return null;
}
if (RETURNS_LIST.matches(method, state)) {
return null;
}
ExpressionTree expressionTree = method.getMethodSelect();
return isGetter(expressionTree) ? (n, s) -> generateFix(method, n, s) : null;
}
private Optional<String> generateFix(
MethodInvocationTree methodInvocation, boolean negated, VisitorState state) {
String methodName = ASTHelpers.getSymbol(methodInvocation).getQualifiedName().toString();
String hasMethod = methodName.replaceFirst("get", "has");
// proto3 does not generate has methods for scalar types, e.g. ByteString and String.
// Do not provide a replacement in these cases.
Set<MethodSymbol> hasMethods =
ASTHelpers.findMatchingMethods(
state.getName(hasMethod),
ms -> ms.params().isEmpty(),
getType(getReceiver(methodInvocation)),
state.getTypes());
if (hasMethods.isEmpty()) {
return Optional.empty();
}
String replacement =
replaceLast(state.getSourceForNode(methodInvocation), methodName, hasMethod);
return Optional.of(negated ? ("!" + replacement) : replacement);
}
private String replaceLast(String text, String pattern, String replacement) {
StringBuilder builder = new StringBuilder(text);
int lastIndexOf = builder.lastIndexOf(pattern);
return builder.replace(lastIndexOf, lastIndexOf + pattern.length(), replacement).toString();
}
},
/** {@code proto.getRepeatedFoo(index)} */
VECTOR_INDEXED {
@Nullable
@Override
Fixer match(ExpressionTree tree, VisitorState state) {
if (!PROTO_RECEIVER.matches(tree, state)) {
return null;
}
if (tree.getKind() != Kind.METHOD_INVOCATION) {
return null;
}
MethodInvocationTree method = (MethodInvocationTree) tree;
if (method.getArguments().size() != 1 || !isGetter(method.getMethodSelect())) {
return null;
}
if (!isSameType(
getType(getOnlyElement(method.getArguments())), state.getSymtab().intType, state)) {
return null;
}
return (n, s) -> Optional.of(generateFix(method, n, state));
}
private String generateFix(
MethodInvocationTree methodInvocation, boolean negated, VisitorState visitorState) {
String methodName = ASTHelpers.getSymbol(methodInvocation).getQualifiedName().toString();
String countMethod = methodName + "Count";
return format(
"%s.%s() %s %s",
visitorState.getSourceForNode(getReceiver(methodInvocation)),
countMethod,
negated ? "<=" : ">",
visitorState.getSourceForNode(getOnlyElement(methodInvocation.getArguments())));
}
},
/** {@code proto.getRepeatedFooList()} */
VECTOR {
@Nullable
@Override
Fixer match(ExpressionTree tree, VisitorState state) {
if (!PROTO_RECEIVER.matches(tree, state)) {
return null;
}
if (tree.getKind() != Kind.METHOD_INVOCATION) {
return null;
}
MethodInvocationTree method = (MethodInvocationTree) tree;
if (!method.getArguments().isEmpty()) {
return null;
}
if (!RETURNS_LIST.matches(method, state)) {
return null;
}
ExpressionTree expressionTree = method.getMethodSelect();
return isGetter(expressionTree)
? (n, s) -> Optional.of(generateFix(n, method, state))
: null;
}
private String generateFix(
boolean negated, ExpressionTree methodInvocation, VisitorState state) {
String replacement = state.getSourceForNode(methodInvocation) + ".isEmpty()";
return negated ? replacement : ("!" + replacement);
}
},
/** {@code proto.getField(f)} or {@code proto.getExtension(outer, extension)}; */
EXTENSION_METHOD {
@Nullable
@Override
Fixer match(ExpressionTree tree, VisitorState state) {
if (!PROTO_RECEIVER.matches(tree, state)) {
return null;
}
if (EXTENSION_METHODS_WITH_NO_FIX.matches(tree, state)) {
return GetterTypes::emptyFix;
}
if (EXTENSION_METHODS_WITH_FIX.matches(tree, state)) {
// If the extension represents a repeated field (i.e.: it's an ExtensionLite<T, List<R>>),
// the suggested fix from get->has isn't appropriate,so we shouldn't suggest a replacement
MethodInvocationTree methodInvocation = (MethodInvocationTree) tree;
Type argumentType =
ASTHelpers.getType(Iterables.getOnlyElement(methodInvocation.getArguments()));
Symbol extension = COM_GOOGLE_PROTOBUF_EXTENSIONLITE.get(state);
Type genericsArgument = state.getTypes().asSuper(argumentType, extension);
// If there are not two arguments then it is a raw type
// We can't make a fix on a raw type because there is not a way to guarantee that
// it does not contain a repeated field
if (genericsArgument.getTypeArguments().size() != 2) {
return GetterTypes::emptyFix;
}
// If the second element within the generic argument is a subtype of list,
// that means it is a repeated field and therefore we cannot make a fix.
if (ASTHelpers.isSubtype(
genericsArgument.getTypeArguments().get(1), state.getSymtab().listType, state)) {
return GetterTypes::emptyFix;
}
// Now that it is guaranteed that there is not a repeated field, providing a fix is safe
return generateFix(methodInvocation);
}
return null;
}
private Fixer generateFix(MethodInvocationTree methodInvocation) {
return (negated, state) -> {
String methodName = getMethodName(methodInvocation);
String hasMethod = methodName.replaceFirst("get", "has");
String replacement =
replaceLast(state.getSourceForNode(methodInvocation), methodName, hasMethod);
return Optional.of(negated ? "!" + replacement : replacement);
};
}
};
/**
* Returns a Fixer representing a situation where we don't have a fix, but want to mark a
* callsite as containing a bug.
*/
private static Optional<String> emptyFix(boolean n, VisitorState s) {
return Optional.empty();
}
private static boolean isGetter(ExpressionTree expressionTree) {
if (!(expressionTree instanceof JCFieldAccess)) {
return false;
}
JCFieldAccess access = (JCFieldAccess) expressionTree;
String methodName = access.sym.getQualifiedName().toString();
return methodName.startsWith("get");
}
abstract Fixer match(ExpressionTree tree, VisitorState state);
}
private enum ProblemUsage {
/** Matches direct comparisons to null. */
COMPARISON {
@Override
SuggestedFix fix(Fixer fixer, ExpressionTree tree, VisitorState state) {
Optional<String> replacement = fixer.getReplacement(tree.getKind() == Kind.EQUAL_TO, state);
return replacement.map(r -> SuggestedFix.replace(tree, r)).orElse(SuggestedFix.emptyFix());
}
},
/** Matches comparisons with Truth, i.e. {@code assertThat(proto.getField()).isNull()}. */
TRUTH {
@Override
SuggestedFix fix(Fixer fixer, ExpressionTree tree, VisitorState state) {
return fixer
.getReplacement(/* negated= */ false, state)
.map(
r -> {
MethodInvocationTree receiver = (MethodInvocationTree) getReceiver(tree);
return SuggestedFix.replace(
tree,
format(
"%s(%s).isTrue()",
state.getSourceForNode(receiver.getMethodSelect()), r));
})
.orElse(SuggestedFix.emptyFix());
}
},
/** Matches comparisons with JUnit, i.e. {@code assertNotNull(proto.getField())}. */
JUNIT {
@Override
SuggestedFix fix(Fixer fixer, ExpressionTree tree, VisitorState state) {
MethodInvocationTree methodInvocationTree = (MethodInvocationTree) tree;
return fixer
.getReplacement(/* negated= */ false, state)
.map(
r -> {
int startPos = getStartPosition(methodInvocationTree);
return SuggestedFix.builder()
.replace(getLast(methodInvocationTree.getArguments()), r)
.replace(startPos, startPos + "assertNotNull".length(), "assertTrue")
.build();
})
.orElse(SuggestedFix.emptyFix());
}
},
/** Matches precondition checks, i.e. {@code checkNotNull(proto.getField())}. */
CHECK_NOT_NULL {
@Override
SuggestedFix fix(Fixer fixer, ExpressionTree tree, VisitorState state) {
MethodInvocationTree methodInvocationTree = (MethodInvocationTree) tree;
Tree parent = state.getPath().getParentPath().getLeaf();
return parent.getKind() == Kind.EXPRESSION_STATEMENT
? SuggestedFix.delete(parent)
: SuggestedFix.replace(
tree, state.getSourceForNode(methodInvocationTree.getArguments().get(0)));
}
},
/** Matches comparisons with JUnit, i.e. {@code assertNotNull(proto.getField())}. */
OPTIONAL {
@Override
SuggestedFix fix(Fixer fixer, ExpressionTree tree, VisitorState state) {
MethodInvocationTree methodInvocationTree = (MethodInvocationTree) tree;
return SuggestedFixes.renameMethodInvocation(methodInvocationTree, "of", state);
}
};
abstract SuggestedFix fix(Fixer fixer, ExpressionTree tree, VisitorState state);
}
private static final Supplier<Symbol> COM_GOOGLE_PROTOBUF_EXTENSIONLITE =
VisitorState.memoize(state -> state.getSymbolFromString("com.google.protobuf.ExtensionLite"));
}
| 26,118
| 39.557453
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/EqualsWrongThing.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.ImmutableSet.toImmutableSet;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.equalsMethodDeclaration;
import static com.google.errorprone.matchers.Matchers.instanceEqualsInvocation;
import static com.google.errorprone.matchers.Matchers.staticEqualsInvocation;
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 com.google.errorprone.util.ASTHelpers.isStatic;
import com.google.auto.value.AutoValue;
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.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.BinaryTree;
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.Tree.Kind;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import javax.lang.model.element.ElementKind;
/**
* Checks for {@code equals} implementations comparing non-corresponding fields.
*
* @author ghm@google.com (Graeme Morgan)
*/
@BugPattern(
summary =
"Comparing different pairs of fields/getters in an equals implementation is probably "
+ "a mistake.",
severity = ERROR)
public final class EqualsWrongThing extends BugChecker implements MethodTreeMatcher {
private static final Matcher<MethodInvocationTree> COMPARISON_METHOD =
anyOf(staticMethod().onClass("java.util.Arrays").named("equals"), staticEqualsInvocation());
private static final ImmutableSet<ElementKind> FIELD_TYPES =
Sets.immutableEnumSet(ElementKind.FIELD, ElementKind.METHOD);
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!equalsMethodDeclaration().matches(tree, state)) {
return NO_MATCH;
}
ClassSymbol classSymbol = getSymbol(tree).enclClass();
Set<ComparisonSite> suspiciousComparisons = new HashSet<>();
new TreeScanner<Void, Void>() {
@Override
public Void visitBinary(BinaryTree node, Void unused) {
if (node.getKind() == Kind.EQUAL_TO || node.getKind() == Kind.NOT_EQUAL_TO) {
getDubiousComparison(classSymbol, node, node.getLeftOperand(), node.getRightOperand())
.ifPresent(suspiciousComparisons::add);
}
return super.visitBinary(node, null);
}
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void unused) {
var args = node.getArguments();
if (COMPARISON_METHOD.matches(node, state)) {
// args.size() / 2 handles the six-arg overload of Arrays.equals (the 0th and 3rd args are
// the arrays).
getDubiousComparison(classSymbol, node, args.get(0), args.get(args.size() / 2))
.ifPresent(suspiciousComparisons::add);
}
if (instanceEqualsInvocation().matches(node, state)) {
ExpressionTree receiver = getReceiver(node);
if (receiver != null) {
// Special-case super, for odd cases like `super.equals(this)`.
if (!(receiver instanceof IdentifierTree
&& ((IdentifierTree) receiver).getName().contentEquals("super"))) {
getDubiousComparison(classSymbol, node, receiver, args.get(0))
.ifPresent(suspiciousComparisons::add);
}
}
}
return super.visitMethodInvocation(node, null);
}
}.scan(tree, null);
// Fast path return.
if (suspiciousComparisons.isEmpty()) {
return NO_MATCH;
}
// Special case where comparisons are made of (a, b) and (b, a) to imply that order doesn't
// matter.
ImmutableSet<ComparisonPair> suspiciousPairs =
suspiciousComparisons.stream().map(ComparisonSite::pair).collect(toImmutableSet());
suspiciousComparisons.stream()
.filter(p -> !suspiciousPairs.contains(p.pair().reversed()))
.map(
c ->
buildDescription(c.tree())
.setMessage(
String.format(
"Suspicious comparison between `%s` and `%s`",
c.pair().lhs(), c.pair().rhs()))
.build())
.forEach(state::reportMatch);
return NO_MATCH;
}
private static Optional<ComparisonSite> getDubiousComparison(
ClassSymbol encl, Tree tree, ExpressionTree lhs, ExpressionTree rhs) {
Symbol lhsSymbol = getSymbol(lhs);
Symbol rhsSymbol = getSymbol(rhs);
if (lhsSymbol == null || rhsSymbol == null || lhsSymbol.equals(rhsSymbol)) {
return Optional.empty();
}
if (isStatic(lhsSymbol) || isStatic(rhsSymbol)) {
return Optional.empty();
}
if (!encl.equals(lhsSymbol.enclClass()) || !encl.equals(rhsSymbol.enclClass())) {
return Optional.empty();
}
if (!FIELD_TYPES.contains(lhsSymbol.getKind()) || !FIELD_TYPES.contains(rhsSymbol.getKind())) {
return Optional.empty();
}
if (getKind(lhs) != getKind(rhs)) {
return Optional.empty();
}
return Optional.of(ComparisonSite.of(tree, lhsSymbol, rhsSymbol));
}
private static Kind getKind(Tree tree) {
Kind kind = tree.getKind();
// Treat identifiers as being similar to member selects for our purposes, as in a == that.a.
return kind == Kind.IDENTIFIER ? Kind.MEMBER_SELECT : kind;
}
@AutoValue
abstract static class ComparisonSite {
abstract Tree tree();
abstract ComparisonPair pair();
private static ComparisonSite of(Tree tree, Symbol lhs, Symbol rhs) {
return new AutoValue_EqualsWrongThing_ComparisonSite(tree, ComparisonPair.of(lhs, rhs));
}
}
@AutoValue
abstract static class ComparisonPair {
abstract Symbol lhs();
abstract Symbol rhs();
final ComparisonPair reversed() {
return of(rhs(), lhs());
}
private static ComparisonPair of(Symbol lhs, Symbol rhs) {
return new AutoValue_EqualsWrongThing_ComparisonPair(lhs, rhs);
}
}
}
| 7,384
| 37.264249
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MixedArrayDimensions.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.SUGGESTION;
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 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.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.ErrorProneToken;
import com.sun.source.tree.ArrayTypeTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.parser.Tokens.TokenKind;
import java.util.List;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "C-style array declarations should not be used",
severity = SUGGESTION,
tags = StandardTags.STYLE)
public class MixedArrayDimensions extends BugChecker
implements MethodTreeMatcher, VariableTreeMatcher {
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
return checkArrayDimensions(tree, tree.getReturnType(), state);
}
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
return checkArrayDimensions(tree, tree.getType(), state);
}
private Description checkArrayDimensions(Tree tree, Tree type, VisitorState state) {
if (!(type instanceof ArrayTypeTree)) {
return NO_MATCH;
}
CharSequence source = state.getSourceCode();
for (; type instanceof ArrayTypeTree; type = ((ArrayTypeTree) type).getType()) {
Tree elemType = ((ArrayTypeTree) type).getType();
int start = state.getEndPosition(elemType);
int end = state.getEndPosition(type);
if (start >= end) {
continue;
}
List<ErrorProneToken> tokens = state.getOffsetTokens(start, end);
if (tokens.size() > 2 && tokens.get(0).kind() == TokenKind.IDENTIFIER) {
String dim = source.subSequence(start, end).toString();
int nonWhitespace = CharMatcher.isNot(' ').indexIn(dim);
int idx = dim.indexOf("[]", nonWhitespace);
if (idx > nonWhitespace) {
String replacement = dim.substring(idx) + dim.substring(0, idx);
// SimpleCharStream generates violations in other packages, and is challenging to fix.
var enclosingClass = enclosingClass(getSymbol(tree));
if (enclosingClass != null && enclosingClass.name.contentEquals("SimpleCharStream")) {
return NO_MATCH;
}
return describeMatch(tree, SuggestedFix.replace(start, end, replacement));
}
}
}
return NO_MATCH;
}
}
| 3,652
| 40.044944
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StaticQualifiedUsingExpression.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.fixes.SuggestedFixes.qualifyType;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isStatic;
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.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
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.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.Objects;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@BugPattern(
summary = "A static variable or method should be qualified with a class name, not expression",
severity = ERROR,
altNames = {"static", "static-access", "StaticAccessedFromInstance"},
tags = StandardTags.FRAGILE_CODE)
public class StaticQualifiedUsingExpression extends BugChecker implements MemberSelectTreeMatcher {
@Override
public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) {
Symbol sym = getSymbol(tree);
if (sym == null) {
return NO_MATCH;
}
switch (sym.getKind()) {
case FIELD:
if (sym.getSimpleName().contentEquals("class")
|| sym.getSimpleName().contentEquals("super")) {
return NO_MATCH;
}
// fall through
case ENUM_CONSTANT:
case METHOD:
if (!isStatic(sym)) {
return NO_MATCH;
}
break; // continue below
default:
return NO_MATCH;
}
ClassSymbol owner = sym.owner.enclClass();
ExpressionTree expression = tree.getExpression();
switch (expression.getKind()) {
case MEMBER_SELECT:
case IDENTIFIER:
// References to static variables should be qualified by the type name of the owning type,
// or a sub-type. e.g.: if CONST is declared in Foo, and SubFoo extends Foo,
// allow `Foo.CONST` and `SubFoo.CONST` (but not, say, `new Foo().CONST`.
Symbol base = getSymbol(expression);
if (base instanceof ClassSymbol && base.isSubClass(owner, state.getTypes())) {
return NO_MATCH;
}
break;
default: // continue below
}
SuggestedFix.Builder fix = SuggestedFix.builder();
String replacement;
boolean isMethod = sym instanceof MethodSymbol;
if (isMethod && Objects.equals(getSymbol(state.findEnclosing(ClassTree.class)), owner)) {
replacement = sym.getSimpleName().toString();
} else {
replacement = qualifyType(state, fix, sym);
}
fix.replace(tree, replacement);
// Spill possibly side-effectful qualifier expressions to the top level.
// This doesn't preserve order of operations for non-trivial expressions, but we don't have
// letexprs and hopefully it'll call attention to the fact that just deleting the qualifier
// might not always be the right fix.
if (expression instanceof MethodInvocationTree || expression instanceof NewClassTree) {
StatementTree statement = state.findEnclosing(StatementTree.class);
if (statement != null) {
fix.prefixWith(statement, state.getSourceForNode(expression) + ";");
}
}
return buildDescription(tree)
.setMessage(
String.format(
"Static %s %s should not be accessed from an object instance; instead use %s",
isMethod ? "method" : "variable", sym.getSimpleName(), replacement))
.addFix(fix.build())
.build();
}
}
| 4,703
| 38.529412
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnsynchronizedOverridesSynchronized.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.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.util.ASTHelpers.isSameType;
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.bugpatterns.threadsafety.ConstantExpressions;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ExpressionStatementTree;
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.ReturnTree;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import javax.inject.Inject;
import javax.lang.model.element.Modifier;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Unsynchronized method overrides a synchronized method.",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public class UnsynchronizedOverridesSynchronized extends BugChecker implements MethodTreeMatcher {
private final ConstantExpressions constantExpressions;
@Inject
UnsynchronizedOverridesSynchronized(ConstantExpressions constantExpressions) {
this.constantExpressions = constantExpressions;
}
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
MethodSymbol methodSymbol = ASTHelpers.getSymbol(methodTree);
if (isSynchronized(methodSymbol)) {
return NO_MATCH;
}
for (MethodSymbol s : ASTHelpers.findSuperMethods(methodSymbol, state.getTypes())) {
if (isSynchronized(s)) {
// Input streams are typically not used across threads, so this case isn't
// worth enforcing.
if (isSameType(s.owner.type, JAVA_IO_INPUTSTREAM.get(state), state)) {
continue;
}
if (ignore(methodTree, state)) {
return NO_MATCH;
}
return buildDescription(methodTree)
.addFix(
SuggestedFixes.addModifiers(methodTree, state, Modifier.SYNCHRONIZED)
.orElse(SuggestedFix.emptyFix()))
.setMessage(
String.format(
"Unsynchronized method %s overrides synchronized method in %s",
methodSymbol.getSimpleName(), s.enclClass().getSimpleName()))
.build();
}
}
return NO_MATCH;
}
private static boolean isSynchronized(MethodSymbol sym) {
return sym.getModifiers().contains(Modifier.SYNCHRONIZED);
}
/**
* Don't flag methods that are empty, trivially delegate to a super-implementation, or return a
* constant.
*/
private boolean ignore(MethodTree method, VisitorState state) {
return firstNonNull(
new TreeScanner<Boolean, Void>() {
@Override
public Boolean visitBlock(BlockTree tree, Void unused) {
switch (tree.getStatements().size()) {
case 0:
return true;
case 1:
return scan(getOnlyElement(tree.getStatements()), null);
default:
return false;
}
}
@Override
public Boolean visitReturn(ReturnTree tree, Void unused) {
ExpressionTree expression = tree.getExpression();
if (expression == null
|| constantExpressions.constantExpression(expression, state).isPresent()) {
return true;
}
return scan(tree.getExpression(), null);
}
@Override
public Boolean visitExpressionStatement(ExpressionStatementTree tree, Void unused) {
return scan(tree.getExpression(), null);
}
@Override
public Boolean visitTypeCast(TypeCastTree tree, Void unused) {
return scan(tree.getExpression(), null);
}
@Override
public Boolean visitMethodInvocation(MethodInvocationTree node, Void unused) {
ExpressionTree receiver = ASTHelpers.getReceiver(node);
return receiver instanceof IdentifierTree
&& ((IdentifierTree) receiver).getName().contentEquals("super")
&& overrides(ASTHelpers.getSymbol(method), ASTHelpers.getSymbol(node));
}
private boolean overrides(MethodSymbol sym, MethodSymbol other) {
return !sym.isStatic()
&& !other.isStatic()
&& (((sym.flags() | other.flags()) & Flags.SYNTHETIC) == 0)
&& sym.name.contentEquals(other.name)
&& sym.overrides(
other, sym.owner.enclClass(), state.getTypes(), /* checkResult= */ false);
}
}.scan(method.getBody(), null),
false);
}
private static final Supplier<Type> JAVA_IO_INPUTSTREAM =
VisitorState.memoize(state -> state.getTypeFromString("java.io.InputStream"));
}
| 6,290
| 38.31875
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/RemoveUnusedImports.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.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.bugpatterns.StaticImports.StaticImportInfo;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.doctree.DocCommentTree;
import com.sun.source.doctree.ReferenceTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.DocTreePath;
import com.sun.source.util.DocTreePathScanner;
import com.sun.source.util.TreePathScanner;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.tree.DCTree.DCReference;
import java.util.LinkedHashSet;
import javax.annotation.Nullable;
/**
* @author gak@google.com (Gregory Kick)
*/
@BugPattern(
summary = "Unused imports",
severity = SUGGESTION,
documentSuppression = false,
tags = StandardTags.STYLE)
public final class RemoveUnusedImports extends BugChecker implements CompilationUnitTreeMatcher {
private static final Joiner COMMA_JOINER = Joiner.on(", ");
@Override
public Description matchCompilationUnit(
CompilationUnitTree compilationUnitTree, VisitorState state) {
ImmutableSetMultimap<ImportTree, Symbol> importedSymbols =
getImportedSymbols(compilationUnitTree, state);
if (importedSymbols.isEmpty()) {
return NO_MATCH;
}
LinkedHashSet<ImportTree> unusedImports = new LinkedHashSet<>(importedSymbols.keySet());
new TreeSymbolScanner(JavacTrees.instance(state.context))
.scan(
compilationUnitTree,
new SymbolSink() {
@Override
public boolean keepScanning() {
return !unusedImports.isEmpty();
}
@Override
public void accept(Symbol symbol) {
unusedImports.removeAll(importedSymbols.inverse().get(symbol));
}
});
if (unusedImports.isEmpty()) {
return NO_MATCH;
}
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
for (ImportTree unusedImport : unusedImports) {
fixBuilder.delete(unusedImport);
}
ImmutableList<String> unusedImportQualifiedNames =
unusedImports.stream()
.map(tree -> state.getSourceForNode(tree.getQualifiedIdentifier()))
.collect(toImmutableList());
return buildDescription(unusedImports.iterator().next())
.addFix(fixBuilder.build())
.setMessage(
String.format("Unused imports: %s", COMMA_JOINER.join(unusedImportQualifiedNames)))
.build();
}
/**
* A callback that provides actions for whenever you encounter a {@link Symbol}. Also provides a
* hook by which you can stop scanning.
*/
private interface SymbolSink {
boolean keepScanning();
void accept(Symbol symbol);
}
private static final class TreeSymbolScanner extends TreePathScanner<Void, SymbolSink> {
final DocTreeSymbolScanner docTreeSymbolScanner;
final JavacTrees trees;
private TreeSymbolScanner(JavacTrees trees) {
this.docTreeSymbolScanner = new DocTreeSymbolScanner();
this.trees = trees;
}
/** Skip the imports themselves when checking for usage. */
@Override
public Void visitImport(ImportTree importTree, SymbolSink usedSymbols) {
return null;
}
@Override
public Void visitIdentifier(IdentifierTree tree, SymbolSink sink) {
if (tree == null) {
return null;
}
Symbol symbol = getSymbol(tree);
if (symbol == null) {
return null;
}
sink.accept(symbol.baseSymbol());
return null;
}
@Override
public Void scan(Tree tree, SymbolSink sink) {
if (!sink.keepScanning()) {
return null;
}
if (tree == null) {
return null;
}
scanJavadoc(sink);
return super.scan(tree, sink);
}
private void scanJavadoc(SymbolSink sink) {
if (getCurrentPath() == null) {
return;
}
DocCommentTree commentTree = trees.getDocCommentTree(getCurrentPath());
if (commentTree == null) {
return;
}
docTreeSymbolScanner.scan(new DocTreePath(getCurrentPath(), commentTree), sink);
}
/**
* For the time being, this will just report any symbol referenced from javadoc as a usage.
* TODO(gak): improve this so that we can remove imports used only from javadoc and replace the
* usages with fully-qualified names.
*/
final class DocTreeSymbolScanner extends DocTreePathScanner<Void, SymbolSink> {
@Override
public Void visitReference(ReferenceTree referenceTree, SymbolSink sink) {
// do this first, it attributes the referenceTree as a side-effect
trees.getElement(getCurrentPath());
TreeScanner<Void, SymbolSink> nonRecursiveScanner =
new TreeScanner<Void, SymbolSink>() {
@Override
public Void visitIdentifier(IdentifierTree tree, SymbolSink sink) {
Symbol sym = ASTHelpers.getSymbol(tree);
if (sym != null) {
sink.accept(sym);
}
return null;
}
};
DCReference reference = (DCReference) referenceTree;
nonRecursiveScanner.scan(reference.qualifierExpression, sink);
nonRecursiveScanner.scan(reference.paramTypes, sink);
return null;
}
}
}
private static ImmutableSetMultimap<ImportTree, Symbol> getImportedSymbols(
CompilationUnitTree compilationUnitTree, VisitorState state) {
ImmutableSetMultimap.Builder<ImportTree, Symbol> builder = ImmutableSetMultimap.builder();
for (ImportTree importTree : compilationUnitTree.getImports()) {
builder.putAll(importTree, getImportedSymbols(importTree, state));
}
return builder.build();
}
private static ImmutableSet<Symbol> getImportedSymbols(
ImportTree importTree, VisitorState state) {
if (importTree.isStatic()) {
StaticImportInfo staticImportInfo = StaticImports.tryCreate(importTree, state);
return staticImportInfo == null ? ImmutableSet.<Symbol>of() : staticImportInfo.members();
} else {
@Nullable Symbol importedSymbol = getSymbol(importTree.getQualifiedIdentifier());
return importedSymbol == null ? ImmutableSet.<Symbol>of() : ImmutableSet.of(importedSymbol);
}
}
}
| 7,875
| 35.294931
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessarySetDefault.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.SUGGESTION;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher;
import com.google.common.base.Equivalence;
import com.google.common.base.Optional;
import com.google.common.base.Predicates;
import com.google.common.base.Stopwatch;
import com.google.common.base.Ticker;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedMultiset;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Range;
import com.google.common.io.ByteSource;
import com.google.common.io.CharSource;
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.ExpressionStatementTree;
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.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "Unnecessary call to NullPointerTester#setDefault", severity = SUGGESTION)
public class UnnecessarySetDefault extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> SET_DEFAULT =
instanceMethod()
.onExactClass("com.google.common.testing.NullPointerTester")
.withSignature("<T>setDefault(java.lang.Class<T>,T)");
@VisibleForTesting
static final ImmutableMap<String, Matcher<ExpressionTree>> DEFAULTS =
ImmutableMap.<String, Matcher<ExpressionTree>>builder()
.put("java.lang.reflect.Type", sourceMatcher("Object.class"))
.put("java.lang.reflect.GenericDeclaration", sourceMatcher("Object.class"))
.put("java.lang.reflect.AnnotatedElement", sourceMatcher("Object.class"))
.put(
"com.google.common.collect.SortedMapDifference",
sourceMatcher("Maps.difference(ImmutableSortedMap.of(), ImmutableSortedMap.of())"))
.put(
"com.google.common.collect.MapDifference",
sourceMatcher("Maps.difference(ImmutableMap.of(), ImmutableMap.of())"))
.put("com.google.common.collect.Range", factoryMatcher(Range.class, "all"))
.put(
"com.google.common.collect.ImmutableClassToInstanceMap",
sourceMatcher("ImmutableClassToInstanceMap.builder().build()"))
.put(
"com.google.common.collect.ClassToInstanceMap",
sourceMatcher("ImmutableClassToInstanceMap.builder().build()"))
.put(
"com.google.common.collect.RowSortedTable",
sourceMatcher("Tables.unmodifiableRowSortedTable(TreeBasedTable.create())"))
.put(
"com.google.common.collect.ImmutableTable",
factoryMatcher(ImmutableTable.class, "of"))
.put("com.google.common.collect.Table", factoryMatcher(ImmutableTable.class, "of"))
.put(
"com.google.common.collect.ImmutableBiMap",
factoryMatcher(ImmutableBiMap.class, "of"))
.put("com.google.common.collect.BiMap", factoryMatcher(ImmutableBiMap.class, "of"))
.put(
"com.google.common.collect.ImmutableSortedMultiset",
factoryMatcher(ImmutableSortedMultiset.class, "of"))
.put(
"com.google.common.collect.SortedMultiset",
factoryMatcher(ImmutableSortedMultiset.class, "of"))
.put(
"com.google.common.collect.ImmutableMultiset",
factoryMatcher(ImmutableMultiset.class, "of"))
.put("com.google.common.collect.Multiset", factoryMatcher(ImmutableMultiset.class, "of"))
.put(
"com.google.common.collect.SortedSetMultimap",
sourceMatcher("Multimaps.unmodifiableSortedSetMultimap(TreeMultimap.create())"))
.put(
"com.google.common.collect.ImmutableSetMultimap",
factoryMatcher(ImmutableSetMultimap.class, "of"))
.put(
"com.google.common.collect.SetMultimap",
factoryMatcher(ImmutableSetMultimap.class, "of"))
.put(
"com.google.common.collect.ImmutableListMultimap",
factoryMatcher(ImmutableListMultimap.class, "of"))
.put("com.google.common.collect.ListMultimap", factoryMatcher(ListMultimap.class, "of"))
.put(
"com.google.common.collect.ImmutableMultimap",
factoryMatcher(ImmutableMultimap.class, "of"))
.put("com.google.common.collect.Multimap", factoryMatcher(ImmutableMultimap.class, "of"))
.put(
"java.util.NavigableMap",
sourceMatcher("Maps.unmodifiableNavigableMap(Maps.newTreeMap())"))
.put(
"com.google.common.collect.ImmutableSortedMap",
factoryMatcher(ImmutableSortedMap.class, "of"))
.put("java.util.SortedMap", factoryMatcher(ImmutableSortedMap.class, "of"))
.put("com.google.common.collect.ImmutableMap", factoryMatcher(ImmutableMap.class, "of"))
.put("java.util.Map", factoryMatcher(ImmutableMap.class, "of"))
.put(
"java.util.NavigableSet",
sourceMatcher("Sets.unmodifiableNavigableSet(Sets.newTreeSet())"))
.put(
"com.google.common.collect.ImmutableSortedSet",
factoryMatcher(ImmutableSortedSet.class, "of"))
.put("java.util.SortedSet", factoryMatcher(ImmutableSortedSet.class, "of"))
.put("com.google.common.collect.ImmutableSet", factoryMatcher(ImmutableSet.class, "of"))
.put("java.util.Set", factoryMatcher(ImmutableSet.class, "of"))
.put("com.google.common.collect.ImmutableList", factoryMatcher(ImmutableList.class, "of"))
.put("java.util.List", factoryMatcher(ImmutableList.class, "of"))
.put(
"com.google.common.collect.ImmutableCollection",
factoryMatcher(ImmutableList.class, "of"))
.put("java.util.Collection", factoryMatcher(ImmutableList.class, "of"))
.put("java.lang.Iterable", factoryMatcher(ImmutableSet.class, "of"))
.put("java.util.ListIterator", sourceMatcher("ImmutableList.of().listIterator()"))
.put(
"com.google.common.collect.PeekingIterator",
sourceMatcher("Iterators.peekingIterator(ImmutableSet.of().iterator())"))
.put("java.util.Iterator", sourceMatcher("ImmutableSet.of().iterator()"))
.put("com.google.common.io.CharSource", factoryMatcher(CharSource.class, "empty"))
.put("com.google.common.io.ByteSource", factoryMatcher(ByteSource.class, "empty"))
.put("java.io.File", sourceMatcher("new File(\"\")"))
.put("java.nio.DoubleBuffer", sourceMatcher("DoubleBuffer.allocate(0)"))
.put("java.nio.FloatBuffer", sourceMatcher("FloatBuffer.allocate(0)"))
.put("java.nio.LongBuffer", sourceMatcher("LongBuffer.allocate(0)"))
.put("java.nio.IntBuffer", sourceMatcher("IntBuffer.allocate(0)"))
.put("java.nio.ShortBuffer", sourceMatcher("ShortBuffer.allocate(0)"))
.put("java.nio.ByteBuffer", sourceMatcher("ByteBuffer.allocate(0)"))
.put("java.nio.CharBuffer", sourceMatcher("CharBuffer.allocate(0)"))
.put("java.nio.Buffer", sourceMatcher("ByteBuffer.allocate(0)"))
.put("java.io.StringReader", sourceMatcher("new StringReader(\"\")"))
.put("java.io.Reader", sourceMatcher("new StringReader(\"\")"))
.put("java.lang.Readable", sourceMatcher("new StringReader(\"\")"))
.put(
"java.io.ByteArrayInputStream",
sourceMatcher("new ByteArrayInputStream(new byte[0])"))
.put("java.io.InputStream", sourceMatcher("new ByteArrayInputStream(new byte[0])"))
.put(
"com.google.common.base.Stopwatch",
factoryMatcher(Stopwatch.class, "createUnstarted"))
.put("com.google.common.base.Ticker", factoryMatcher(Ticker.class, "systemTicker"))
.put("com.google.common.base.Equivalence", factoryMatcher(Equivalence.class, "equals"))
.put("com.google.common.base.Predicate", factoryMatcher(Predicates.class, "alwaysTrue"))
.put("com.google.common.base.Optional", factoryMatcher(Optional.class, "absent"))
.put("com.google.common.base.Splitter", sourceMatcher("Splitter.on(',')"))
.put("com.google.common.base.Joiner", sourceMatcher("Joiner.on(',')"))
.put("com.google.common.base.CharMatcher", factoryMatcher(CharMatcher.class, "none"))
.put("java.util.Locale", sourceMatcher("Locale.US"))
.put("java.util.Currency", sourceMatcher("Currency.getInstance(Locale.US)"))
.put("java.nio.charset.Charset", sourceMatcher("Charsets.UTF_8"))
.put("java.util.concurrent.TimeUnit", sourceMatcher("TimeUnit.SECONDS"))
.put("java.util.regex.Pattern", sourceMatcher("Pattern.compile(\"\")"))
.put("java.lang.String", sourceMatcher("\"\""))
.put("java.lang.CharSequence", sourceMatcher("\"\""))
.put("java.math.BigDecimal", sourceMatcher("BigDecimal.ZERO"))
.put("java.math.BigInteger", sourceMatcher("BigInteger.ZERO"))
.put("com.google.common.primitives.UnsignedLong", sourceMatcher("UnsignedLong.ZERO"))
.put(
"com.google.common.primitives.UnsignedInteger", sourceMatcher("UnsignedInteger.ZERO"))
.put("java.lang.Number", sourceMatcher("0"))
.put("java.lang.Object", sourceMatcher("\"\""))
.put("Optional.class", factoryMatcher(java.util.Optional.class, "empty"))
.put("OptionalInt.class", factoryMatcher(OptionalInt.class, "empty"))
.put("OptionalLong.class", factoryMatcher(OptionalLong.class, "empty"))
.put("OptionalDouble.class", factoryMatcher(OptionalDouble.class, "empty"))
.buildOrThrow();
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!SET_DEFAULT.matches(tree, state)) {
return NO_MATCH;
}
Type type = ASTHelpers.getType(tree.getArguments().get(0));
if (type == null) {
return NO_MATCH;
}
Type classType = state.getTypes().asSuper(type, state.getSymtab().classType.asElement());
if (classType == null || classType.getTypeArguments().isEmpty()) {
return NO_MATCH;
}
String defaultTypeName =
getOnlyElement(classType.getTypeArguments()).asElement().getQualifiedName().toString();
if (!DEFAULTS.containsKey(defaultTypeName)) {
return NO_MATCH;
}
Matcher<ExpressionTree> defaultType = DEFAULTS.get(defaultTypeName);
if (!defaultType.matches(tree.getArguments().get(1), state)) {
return NO_MATCH;
}
Description.Builder description = buildDescription(tree);
ExpressionTree receiver = ASTHelpers.getReceiver(tree);
Tree ancestor = state.getPath().getParentPath().getLeaf();
if (ancestor instanceof ExpressionStatementTree) {
description.addFix(SuggestedFix.delete(ancestor));
} else if (receiver != null) {
description.addFix(
SuggestedFix.replace(state.getEndPosition(receiver), state.getEndPosition(tree), ""));
}
return description.build();
}
private static Matcher<ExpressionTree> factoryMatcher(Class<?> clazz, String name) {
return staticMethod().onClass(clazz.getCanonicalName()).named(name).withNoParameters();
}
static Matcher<ExpressionTree> sourceMatcher(String source) {
return (tree, state) -> state.getSourceForNode(tree).equals(source);
}
}
| 13,543
| 53.176
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CharacterGetNumericValue.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.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;
/**
* Checks for use of Character.getNumericValue and UCharacter.getNumericValue
*
* @author conklinh@google.com
*/
@BugPattern(
summary =
"getNumericValue has unexpected behaviour: it interprets A-Z as base-36 digits with values"
+ " 10-35, but also supports non-arabic numerals and miscellaneous numeric unicode"
+ " characters like ㊷; consider using Character.digit or"
+ " UCharacter.getUnicodeNumericValue instead",
severity = WARNING)
public class CharacterGetNumericValue extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<MethodInvocationTree> GET_NUMERIC_VALUE =
anyOf(
staticMethod().onClass("com.ibm.icu.lang.UCharacter").named("getNumericValue"),
staticMethod().onClass("java.lang.Character").named("getNumericValue"));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return GET_NUMERIC_VALUE.matches(tree, state) ? describeMatch(tree) : Description.NO_MATCH;
}
}
| 2,228
| 40.277778
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NonCanonicalStaticMemberImport.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 com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ImportTreeMatcher;
import com.google.errorprone.bugpatterns.StaticImports.StaticImportInfo;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.ImportTree;
/**
* Members shouldn't be statically imported by their non-canonical name.
*
* @author cushon@google.com (Liam Miller-Cushon)
*/
@BugPattern(
summary = "Static import of member uses non-canonical name",
severity = WARNING,
documentSuppression = false)
public class NonCanonicalStaticMemberImport extends BugChecker implements ImportTreeMatcher {
@Override
public Description matchImport(ImportTree tree, VisitorState state) {
StaticImportInfo importInfo = StaticImports.tryCreate(tree, state);
if (importInfo == null || importInfo.isCanonical() || importInfo.members().isEmpty()) {
return Description.NO_MATCH;
}
return describeMatch(tree, SuggestedFix.replace(tree, importInfo.importStatement()));
}
}
| 1,841
| 36.591837
| 93
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryAnonymousClass.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.ImmutableList.toImmutableList;
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.util.ASTHelpers.canBeRemoved;
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.isGeneratedConstructor;
import static com.google.errorprone.util.ASTHelpers.isStatic;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Range;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.fixes.Replacement;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
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.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.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
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 =
"Implementing a functional interface is unnecessary; prefer to implement the functional"
+ " interface method directly and use a method reference instead.",
severity = WARNING)
public class UnnecessaryAnonymousClass extends BugChecker implements VariableTreeMatcher {
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
if (tree.getInitializer() == null) {
return NO_MATCH;
}
if (!(tree.getInitializer() instanceof NewClassTree)) {
return NO_MATCH;
}
NewClassTree classTree = (NewClassTree) tree.getInitializer();
if (classTree.getClassBody() == null) {
return NO_MATCH;
}
ImmutableList<? extends Tree> members =
classTree.getClassBody().getMembers().stream()
.filter(x -> !(x instanceof MethodTree && isGeneratedConstructor((MethodTree) x)))
.collect(toImmutableList());
if (members.size() != 1) {
return NO_MATCH;
}
Tree member = getOnlyElement(members);
if (!(member instanceof MethodTree)) {
return NO_MATCH;
}
VarSymbol varSym = getSymbol(tree);
if (varSym.getKind() != ElementKind.FIELD
|| !canBeRemoved(varSym)
|| !varSym.getModifiers().contains(Modifier.FINAL)) {
return NO_MATCH;
}
MethodTree implementation = (MethodTree) member;
Type type = getType(tree.getType());
if (type == null || !state.getTypes().isFunctionalInterface(type)) {
return NO_MATCH;
}
MethodSymbol methodSymbol = getSymbol(implementation);
Symbol descriptorSymbol = state.getTypes().findDescriptorSymbol(type.tsym);
if (!methodSymbol.getSimpleName().contentEquals(descriptorSymbol.getSimpleName())) {
return NO_MATCH;
}
if (!methodSymbol.overrides(
descriptorSymbol, methodSymbol.owner.enclClass(), state.getTypes(), false)) {
return NO_MATCH;
}
if (tree.getModifiers().getAnnotations().stream()
.anyMatch(at -> getSymbol(at).getQualifiedName().contentEquals("org.mockito.Spy"))) {
return NO_MATCH;
}
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
// Derive new method name from identifier.
String newName =
varSym.isStatic()
? UPPER_UNDERSCORE.converterTo(LOWER_CAMEL).convert(tree.getName().toString())
: tree.getName().toString();
fixBuilder.merge(SuggestedFixes.renameMethod(implementation, newName, state));
// Make non-final.
SuggestedFixes.removeModifiers(tree, state, Modifier.FINAL).ifPresent(fixBuilder::merge);
// Convert the anonymous class and variable assignment to a method definition.
fixBuilder.merge(trimToMethodDef(tree, state, implementation));
// Replace all uses of the identifier with a method reference.
Optional<SuggestedFix> methodReferenceReplacement =
replaceUsesWithMethodReference(newName, varSym, implementation, state);
if (!methodReferenceReplacement.isPresent()) {
return NO_MATCH;
}
fixBuilder.merge(methodReferenceReplacement.get());
return describeMatch(tree, fixBuilder.build());
}
/** Remove anonymous class definition beginning and end, leaving only the method definition. */
private static SuggestedFix trimToMethodDef(
VariableTree varDefinitionTree, VisitorState state, MethodTree implementation) {
int methodModifiersEndPos = state.getEndPosition(implementation.getModifiers());
if (methodModifiersEndPos == -1) {
methodModifiersEndPos = getStartPosition(implementation);
}
int methodDefEndPos = state.getEndPosition(implementation);
int varModifiersEndPos = state.getEndPosition(varDefinitionTree.getModifiers()) + 1;
int varDefEndPos = state.getEndPosition(varDefinitionTree);
return SuggestedFix.builder()
.replace(varModifiersEndPos, methodModifiersEndPos, "")
.replace(methodDefEndPos, varDefEndPos, "")
.build();
}
/**
* Replace all uses of {@code varSym} within the enclosing compilation unit with a method
* reference, as specified by {@code newName}.
*/
private static Optional<SuggestedFix> replaceUsesWithMethodReference(
String newName, Symbol varSym, MethodTree implementation, VisitorState state) {
// Extract method body.
JCTree methodBody = (JCTree) implementation.getBody();
// Scan entire compilation unit to replace all uses of the variable with method references.
JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit();
ReplaceUsesScanner replaceUsesScanner = new ReplaceUsesScanner(varSym, newName, state);
replaceUsesScanner.scan(compilationUnit, null);
return replaceUsesScanner
.getFixes()
.map(fix -> ensureFixesDoNotOverlap(methodBody, compilationUnit, fix, state));
}
private static SuggestedFix ensureFixesDoNotOverlap(
JCTree methodBody, JCCompilationUnit compilationUnit, SuggestedFix fix, VisitorState state) {
StringBuilder methodBodySource =
new StringBuilder(Objects.requireNonNull(state.getSourceForNode(methodBody)));
Range<Integer> methodBodyPositionRange =
Range.closedOpen(methodBody.getStartPosition(), state.getEndPosition(methodBody));
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
// Apply each fix generated by ReplaceUsesScanner to fixBuilder.
for (Replacement replacement : fix.getReplacements(compilationUnit.endPositions)) {
if (replacement.range().isConnected(methodBodyPositionRange)) {
// If the usage replacement overlaps with the method body, apply it to the method body
// source directly, to avoid fix collisions when we replace the whole thing.
methodBodySource.replace(
replacement.startPosition() - methodBodyPositionRange.lowerEndpoint(),
replacement.endPosition() - methodBodyPositionRange.lowerEndpoint(),
replacement.replaceWith());
} else {
// Otherwise, just add directly to fixBuilder.
fixBuilder.replace(
replacement.startPosition(), replacement.endPosition(), replacement.replaceWith());
}
}
return fixBuilder.replace(methodBody, methodBodySource.toString()).build();
}
private static class ReplaceUsesScanner extends TreePathScanner<Void, Void> {
private final Symbol sym;
private final String newName;
private final VisitorState state;
private final SuggestedFix.Builder fix = SuggestedFix.builder();
private boolean failed = false;
ReplaceUsesScanner(Symbol sym, String newName, VisitorState state) {
this.sym = sym;
this.newName = newName;
this.state = state;
}
@Override
public Void visitMemberSelect(MemberSelectTree node, Void unused) {
if (Objects.equals(getSymbol(node), sym)) {
fix.merge(replaceUseWithMethodReference(node, state.withPath(getCurrentPath())));
}
return super.visitMemberSelect(node, null);
}
@Override
public Void visitIdentifier(IdentifierTree node, Void unused) {
if (Objects.equals(getSymbol(node), sym)) {
fix.merge(replaceUseWithMethodReference(node, state.withPath(getCurrentPath())));
}
return super.visitIdentifier(node, null);
}
/**
* Replace the given {@code node} with the method reference specified by {@code this.newName}.
*/
@Nullable
private SuggestedFix replaceUseWithMethodReference(ExpressionTree node, VisitorState state) {
Tree parent = state.getPath().getParentPath().getLeaf();
if (parent instanceof MemberSelectTree
&& ((MemberSelectTree) parent).getExpression().equals(node)) {
Symbol symbol = getSymbol(parent);
// If anything other than the abstract method is used on this anonymous class, we can't hope
// to generate a fix.
if (symbol.getKind() != ElementKind.METHOD
|| !symbol.getModifiers().contains(Modifier.ABSTRACT)) {
failed = true;
return null;
}
Tree receiver = node.getKind() == Tree.Kind.IDENTIFIER ? null : getReceiver(node);
return SuggestedFix.replace(
receiver != null ? state.getEndPosition(receiver) : getStartPosition(node),
state.getEndPosition(parent),
newName);
} else {
Symbol sym = getSymbol(node);
return SuggestedFix.replace(
node,
String.format(
"%s::%s", isStatic(sym) ? sym.owner.enclClass().getSimpleName() : "this", newName));
}
}
public Optional<SuggestedFix> getFixes() {
return failed ? Optional.empty() : Optional.of(fix.build());
}
}
}
| 11,532
| 42.033582
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JUnit3FloatingPointComparisonWithoutDelta.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 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.fixes.Fix;
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.MethodInvocationTree;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.tree.JCTree;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.type.TypeKind;
/**
* Detects floating-point assertEquals() calls that will not work in JUnit 4.
*
* <p>JUnit 4 bans most but not all floating-point comparisons without a delta argument. This check
* will be as strict as JUnit 4, no more and no less.
*
* @author mwacker@google.com (Mike Wacker)
*/
@BugPattern(
summary = "Floating-point comparison without error tolerance",
// First sentence copied directly from JUnit 4.
severity = WARNING)
public class JUnit3FloatingPointComparisonWithoutDelta extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> ASSERT_EQUALS_MATCHER =
MethodMatchers.staticMethod().onClass("junit.framework.TestCase").named("assertEquals");
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState state) {
if (!ASSERT_EQUALS_MATCHER.matches(methodInvocationTree, state)) {
return Description.NO_MATCH;
}
List<Type> argumentTypes = getArgumentTypesWithoutMessage(methodInvocationTree, state);
if (canBeConvertedToJUnit4(state, argumentTypes)) {
return Description.NO_MATCH;
}
Fix fix = addDeltaArgument(methodInvocationTree, state, argumentTypes);
return describeMatch(methodInvocationTree, fix);
}
/** Gets the argument types, excluding the message argument if present. */
private static List<Type> getArgumentTypesWithoutMessage(
MethodInvocationTree methodInvocationTree, VisitorState state) {
List<Type> argumentTypes = new ArrayList<>();
for (ExpressionTree argument : methodInvocationTree.getArguments()) {
JCTree tree = (JCTree) argument;
argumentTypes.add(tree.type);
}
removeMessageArgumentIfPresent(state, argumentTypes);
return argumentTypes;
}
/** Removes the message argument if it is present. */
private static void removeMessageArgumentIfPresent(VisitorState state, List<Type> argumentTypes) {
if (argumentTypes.size() == 2) {
return;
}
Types types = state.getTypes();
Type firstType = argumentTypes.get(0);
if (types.isSameType(firstType, state.getSymtab().stringType)) {
argumentTypes.remove(0);
}
}
/**
* Determines if the invocation can be safely converted to JUnit 4 based on its argument types.
*/
private static boolean canBeConvertedToJUnit4(VisitorState state, List<Type> argumentTypes) {
// Delta argument is used.
if (argumentTypes.size() > 2) {
return true;
}
Type firstType = argumentTypes.get(0);
Type secondType = argumentTypes.get(1);
// Neither argument is floating-point.
if (!isFloatingPoint(state, firstType) && !isFloatingPoint(state, secondType)) {
return true;
}
// One argument is not numeric.
if (!isNumeric(state, firstType) || !isNumeric(state, secondType)) {
return true;
}
// Neither argument is primitive.
if (!firstType.isPrimitive() && !secondType.isPrimitive()) {
return true;
}
return false;
}
/** Determines if the type is a floating-point type, including reference types. */
private static boolean isFloatingPoint(VisitorState state, Type type) {
Type trueType = unboxedTypeOrType(state, type);
return (trueType.getKind() == TypeKind.DOUBLE) || (trueType.getKind() == TypeKind.FLOAT);
}
/**
* Determines if the type is a numeric type, including reference types.
*
* <p>Type.isNumeric() does not handle reference types properly.
*/
private static boolean isNumeric(VisitorState state, Type type) {
Type trueType = unboxedTypeOrType(state, type);
return trueType.isNumeric();
}
/** Gets the unboxed type, or the original type if it is not unboxable. */
private static Type unboxedTypeOrType(VisitorState state, Type type) {
Types types = state.getTypes();
return types.unboxedTypeOrType(type);
}
/** Creates the fix to add a delta argument. */
private static Fix addDeltaArgument(
MethodInvocationTree methodInvocationTree, VisitorState state, List<Type> argumentTypes) {
int insertionIndex = getDeltaInsertionIndex(methodInvocationTree, state);
String deltaArgument = getDeltaArgument(state, argumentTypes);
return SuggestedFix.replace(insertionIndex, insertionIndex, deltaArgument);
}
/** Gets the index of where to insert the delta argument. */
private static int getDeltaInsertionIndex(
MethodInvocationTree methodInvocationTree, VisitorState state) {
JCTree lastArgument = (JCTree) Iterables.getLast(methodInvocationTree.getArguments());
return state.getEndPosition(lastArgument);
}
/** Gets the text for the delta argument to be added. */
private static String getDeltaArgument(VisitorState state, List<Type> argumentTypes) {
Type firstType = argumentTypes.get(0);
Type secondType = argumentTypes.get(1);
boolean doublePrecisionUsed = isDouble(state, firstType) || isDouble(state, secondType);
return doublePrecisionUsed ? ", 0.0" : ", 0.0f";
}
/** Determines if the type is a double, including reference types. */
private static boolean isDouble(VisitorState state, Type type) {
Type trueType = unboxedTypeOrType(state, type);
return trueType.getKind() == TypeKind.DOUBLE;
}
}
| 6,736
| 38.168605
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/IncompatibleModifiersChecker.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.LinkType.NONE;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.MoreAnnotations.getValue;
import com.google.common.collect.Sets;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
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.AnnotationTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Symbol;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.SimpleAnnotationValueVisitor8;
/**
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
name = "IncompatibleModifiers",
summary =
"This annotation has incompatible modifiers as specified by its "
+ "@IncompatibleModifiers annotation",
linkType = NONE,
severity = ERROR)
public class IncompatibleModifiersChecker extends BugChecker implements AnnotationTreeMatcher {
private static final String INCOMPATIBLE_MODIFIERS =
"com.google.errorprone.annotations.IncompatibleModifiers";
@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
Symbol sym = ASTHelpers.getSymbol(tree);
if (sym == null) {
return NO_MATCH;
}
Attribute.Compound annotation =
sym.getRawAttributes().stream()
.filter(a -> a.type.tsym.getQualifiedName().contentEquals(INCOMPATIBLE_MODIFIERS))
.findAny()
.orElse(null);
if (annotation == null) {
return NO_MATCH;
}
Set<Modifier> incompatibleModifiers = new LinkedHashSet<>();
getValue(annotation, "value").ifPresent(a -> getModifiers(incompatibleModifiers, a));
getValue(annotation, "modifier").ifPresent(a -> getModifiers(incompatibleModifiers, a));
if (incompatibleModifiers.isEmpty()) {
return NO_MATCH;
}
Tree parent = state.getPath().getParentPath().getLeaf();
if (!(parent instanceof ModifiersTree)) {
// e.g. An annotated package name
return NO_MATCH;
}
Set<Modifier> incompatible =
Sets.intersection(incompatibleModifiers, ((ModifiersTree) parent).getFlags());
if (incompatible.isEmpty()) {
return NO_MATCH;
}
String annotationName = ASTHelpers.getAnnotationName(tree);
String nameString =
annotationName != null
? String.format("The annotation '@%s'", annotationName)
: "This annotation";
String message =
String.format(
"%s has specified that it should not be used together with the following modifiers: %s",
nameString, incompatible);
return buildDescription(tree)
.addFix(
SuggestedFixes.removeModifiers((ModifiersTree) parent, state, incompatible)
.orElse(SuggestedFix.emptyFix()))
.setMessage(message)
.build();
}
private static void getModifiers(Collection<Modifier> modifiers, Attribute attribute) {
class Visitor extends SimpleAnnotationValueVisitor8<Void, Void> {
@Override
public Void visitEnumConstant(VariableElement c, Void unused) {
modifiers.add(Modifier.valueOf(c.getSimpleName().toString()));
return null;
}
@Override
public Void visitArray(List<? extends AnnotationValue> vals, Void unused) {
vals.forEach(val -> val.accept(this, null));
return null;
}
}
attribute.accept(new Visitor(), null);
}
}
| 4,709
| 35.511628
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MemoizeConstantVisitorStateLookups.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.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.sun.source.tree.Tree.Kind.STRING_LITERAL;
import static java.util.Comparator.comparingInt;
import static java.util.Comparator.naturalOrder;
import static java.util.stream.Collectors.groupingBy;
import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
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.fixes.SuggestedFixes;
import com.google.errorprone.fixes.SuggestedFixes.AdditionPosition;
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.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.util.Name;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Consumer;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Anytime you need to look up a constant value from VisitorState, improve performance by"
+ " creating a cache for it with VisitorState.memoize",
severity = SeverityLevel.WARNING)
public class MemoizeConstantVisitorStateLookups extends BugChecker
implements CompilationUnitTreeMatcher {
private static final Matcher<ExpressionTree> CONSTANT_LOOKUP =
instanceMethod()
.onExactClass(VisitorState.class.getName())
.namedAnyOf("getName", "getTypeFromString", "getSymbolFromString")
.withParameters(String.class.getName());
private static final Matcher<ExpressionTree> MEMOIZE_CALL =
staticMethod().onClass(VisitorState.class.getName()).named("memoize");
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
tree.getTypeDecls().stream()
.filter(t -> t instanceof ClassTree)
.forEach(t -> state.reportMatch(fixLookupsInClass((ClassTree) t, state)));
return NO_MATCH;
}
private Description fixLookupsInClass(ClassTree tree, VisitorState state) {
ImmutableList<CallSite> lookups = findConstantLookups(tree, state);
if (lookups.isEmpty()) {
return NO_MATCH;
}
Map<String, Map<Name, List<CallSite>>> groupedCallSites =
lookups.stream()
.collect(
groupingBy(
callSite -> callSite.argumentValue, groupingBy(callSite -> callSite.method)));
// addMembers can only be called once per class, so we emit just one fix for all occurrences.
SuggestedFix.Builder fix = SuggestedFix.builder();
ImmutableSortedSet.Builder<String> membersToAdd =
new ImmutableSortedSet.Builder<>(naturalOrder());
for (Map.Entry<String, Map<Name, List<CallSite>>> lookup : groupedCallSites.entrySet()) {
String argument = lookup.getKey();
Map<Name, List<CallSite>> usages = lookup.getValue();
if (usages.size() == 1) {
// The common case: we have state.foo(argument), and never state.bar(argument), so we can
// name the constant after just argument.
Map.Entry<Name, List<CallSite>> useSites = usages.entrySet().iterator().next();
Name methodName = useSites.getKey();
List<CallSite> instances = useSites.getValue();
memoizeSupplier(
state, fix, membersToAdd::add, argument, methodName, instances, (name, type) -> name);
} else {
// Sadly we have both state.foo(argument) and also state.bar(argument), so we need two
// constants based on argument and must disambiguate their names.
for (Map.Entry<Name, List<CallSite>> usage : usages.entrySet()) {
Name methodName = usage.getKey();
List<CallSite> instances = usage.getValue();
memoizeSupplier(
state,
fix,
membersToAdd::add,
argument,
methodName,
instances,
(name, type) -> name + "_" + type);
}
}
}
SuggestedFixes.addMembers(tree, state, AdditionPosition.LAST, membersToAdd.build())
.ifPresent(fix::merge);
// Report the fix on the first of the call site trees.
MethodInvocationTree fixTree =
lookups.stream()
.map(cs -> cs.entireTree)
.min(comparingInt(ASTHelpers::getStartPosition))
.get(); // Always succeeds, lookups is not empty.
return describeMatch(fixTree, fix.build());
}
private static final class CallSite {
/** The method on VisitorState being called. */
final Name method;
/** The compile-time constant value being passed to that method. */
final String argumentValue;
/** The actual expression with that value: a string literal, or a constant with such a value. */
final ExpressionTree argumentExpression;
/** The entire invocation of the VisitorState method. */
final MethodInvocationTree entireTree;
CallSite(
Name method,
String argumentValue,
ExpressionTree argumentExpression,
MethodInvocationTree entireTree) {
this.method = method;
this.argumentValue = argumentValue;
this.argumentExpression = argumentExpression;
this.entireTree = entireTree;
}
}
private ImmutableList<CallSite> findConstantLookups(ClassTree tree, VisitorState state) {
ImmutableList.Builder<CallSite> result = ImmutableList.builder();
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
if (CONSTANT_LOOKUP.matches(tree, state)) {
handleConstantLookup(tree);
} else if (MEMOIZE_CALL.matches(tree, state)) {
// Don't descend into calls to memoize, because they're already properly memoized!
return null;
}
return super.visitMethodInvocation(tree, null);
}
/** Adds to result if the call uses a compile-time constant argument. */
private void handleConstantLookup(MethodInvocationTree tree) {
ExpressionTree argumentExpr = tree.getArguments().get(0);
String argumentValue = ASTHelpers.constValue(argumentExpr, String.class);
if (argumentValue != null) {
ExpressionTree methodSelect = tree.getMethodSelect();
if (methodSelect instanceof JCFieldAccess) {
JCFieldAccess fieldAccess = (JCFieldAccess) methodSelect;
Name method = fieldAccess.name;
result.add(new CallSite(method, argumentValue, argumentExpr, tree));
} else {
// Just give up on calls we can't understand - maybe from inside VisitorState itself?
}
}
}
}.scan(state.getPath(), null);
return result.build();
}
/**
* Adds to {@code fix} the changes necessary to memoize all the callsites in {@code instances},
* and offers {@code memberConsumer} a new constant to which the fixed callsites will refer.
*/
private static void memoizeSupplier(
VisitorState state,
SuggestedFix.Builder fix,
Consumer<String> memberConsumer,
String argument,
Name methodName,
List<CallSite> instances,
BiFunction<String, String, String> namingStrategy) {
CallSite prototype = bestCallsite(instances);
MethodSymbol sym = ASTHelpers.getSymbol(prototype.entireTree);
TypeSymbol returnType = sym.getReturnType().tsym;
String returnTypeName = returnType.getSimpleName().toString();
String newConstantPrefix = Ascii.toUpperCase(argument).replaceAll("\\W", "_");
String newConstantName =
namingStrategy.apply(newConstantPrefix, Ascii.toUpperCase(returnTypeName));
memberConsumer.accept(
String.format(
"private static final %s<%s> %s = %s.memoize(state -> state.%s(%s));",
SuggestedFixes.qualifyType(state, fix, Supplier.class.getCanonicalName()),
SuggestedFixes.qualifyType(state, fix, returnType.getQualifiedName().toString()),
newConstantName,
SuggestedFixes.qualifyType(state, fix, VisitorState.class.getCanonicalName()),
methodName,
state.getSourceForNode(prototype.argumentExpression)));
for (CallSite instance : instances) {
ExpressionTree visitorStateExpr = ASTHelpers.getReceiver(instance.entireTree);
fix.replace(
instance.entireTree,
String.format("%s.get(%s)", newConstantName, state.getSourceForNode(visitorStateExpr)));
}
}
/**
* Chooses one call site to use for understanding all related callsites. This is used to determine
* what type is being looked up and what source text to use as the argument to the VisitorState
* method. The idea is that if someone writes both getName("foo") and getName(FOO), we want to
* only define one constant for them. In case there are two callsites with different arguments, we
* prefer defined constants rather than x-raying through to a string literal, i.e., getName(FOO).
*/
private static CallSite bestCallsite(List<CallSite> instances) {
return instances.stream()
.max(
Comparator.comparingInt(
callsite -> callsite.argumentExpression.getKind() == STRING_LITERAL ? 0 : 1))
.orElseThrow(
() -> // Impossible, since we got here by groupingBy
new IllegalArgumentException("No callsites"));
}
}
| 10,842
| 42.372
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AnnotationValueToString.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.SUGGESTION;
import static com.google.errorprone.fixes.SuggestedFixes.qualifyType;
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.predicates.TypePredicate;
import com.google.errorprone.predicates.TypePredicates;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.Tree;
import java.util.Optional;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"AnnotationValue#toString doesn't use fully qualified type names, prefer auto-common's"
+ " AnnotationValues#toString",
severity = SUGGESTION)
public class AnnotationValueToString extends AbstractToString {
private static final TypePredicate TYPE_PREDICATE =
TypePredicates.isExactType("javax.lang.model.element.AnnotationValue");
@Override
protected TypePredicate typePredicate() {
return TYPE_PREDICATE;
}
@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) {
return fix(parent, tree, state);
}
private static Optional<Fix> fix(Tree replace, Tree with, VisitorState state) {
SuggestedFix.Builder fix = SuggestedFix.builder();
return Optional.of(
fix.replace(
replace,
String.format(
"%s.toString(%s)",
qualifyType(state, fix, "com.google.auto.common.AnnotationValues"),
state.getSourceForNode(with)))
.build());
}
}
| 2,490
| 34.585714
| 95
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MockNotUsedInProduction.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.Range.closedOpen;
import static com.google.common.collect.Streams.stream;
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.Matchers.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.canBeRemoved;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static java.util.stream.Stream.concat;
import static javax.lang.model.element.ElementKind.FIELD;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableRangeSet;
import com.google.common.collect.Range;
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.sun.source.tree.AssignmentTree;
import com.sun.source.tree.CompilationUnitTree;
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.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.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
/** A BugPattern; see the summary. */
@BugPattern(
severity = WARNING,
summary =
"This mock is instantiated and configured, but is never passed to production code. It"
+ " should be either removed or used.")
public final class MockNotUsedInProduction extends BugChecker
implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
ImmutableMap<VarSymbol, Tree> mocks = findMocks(state);
if (mocks.isEmpty()) {
return NO_MATCH;
}
Set<VarSymbol> usedMocks = new HashSet<>();
new TreePathScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(MethodInvocationTree invocation, Void unused) {
// Don't count references to mocks within the arguments of a when(...) call to be a usage.
// We still need to scan the receiver for the case of
// `doReturn(someMockWhichIsAUsage).when(aMockWhichIsNotAUsage);`
if (WHEN_OR_VERIFY.matches(invocation, state)) {
scan(invocation.getMethodSelect(), null);
return null;
}
return super.visitMethodInvocation(invocation, null);
}
@Override
public Void visitAssignment(AssignmentTree tree, Void unused) {
return scan(tree.getExpression(), null);
}
@Override
public Void visitMemberSelect(MemberSelectTree memberSelect, Void unused) {
handle(memberSelect);
return super.visitMemberSelect(memberSelect, null);
}
@Override
public Void visitIdentifier(IdentifierTree identifier, Void unused) {
handle(identifier);
return super.visitIdentifier(identifier, null);
}
private void handle(Tree tree) {
var symbol = getSymbol(tree);
if (symbol instanceof VarSymbol) {
usedMocks.add((VarSymbol) symbol);
}
}
}.scan(state.getPath(), null);
mocks.forEach(
(sym, mockTree) -> {
if (usedMocks.contains(sym)) {
return;
}
state.reportMatch(describeMatch(mockTree, generateFix(sym, state)));
});
return NO_MATCH;
}
/**
* Very crudely deletes every variable or expression statement which contains a reference to
* {@code sym}. This is inefficient insofar as we scan the entire file again, but only when
* generating a fix.
*/
private static SuggestedFix generateFix(VarSymbol sym, VisitorState state) {
ImmutableList.Builder<Range<Integer>> deletions = ImmutableList.builder();
new TreePathScanner<Void, Void>() {
@Override
public Void scan(Tree tree, Void unused) {
if (Objects.equals(getSymbol(tree), sym)) {
// Yes, at this point, the current path hasn't been updated to include `tree`...
concat(Stream.of(tree), stream(getCurrentPath()))
.filter(t -> t instanceof ExpressionStatementTree || t instanceof VariableTree)
.findFirst()
.ifPresent(
t -> deletions.add(closedOpen(getStartPosition(t), state.getEndPosition(t))));
}
return super.scan(tree, null);
}
}.scan(state.getPath().getCompilationUnit(), null);
var fix = SuggestedFix.builder();
for (Range<Integer> range : ImmutableRangeSet.unionOf(deletions.build()).asRanges()) {
fix.replace(range.lowerEndpoint(), range.upperEndpoint(), "");
}
return fix.build();
}
private ImmutableMap<VarSymbol, Tree> findMocks(VisitorState state) {
Map<VarSymbol, Tree> mocks = new HashMap<>();
AtomicBoolean injectMocks = new AtomicBoolean(false);
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitVariable(VariableTree tree, Void unused) {
VarSymbol symbol = getSymbol(tree);
if (INJECT_MOCKS_ANNOTATED.matches(tree, state)) {
injectMocks.set(true);
}
if (isEligible(symbol)
&& (MOCK_OR_SPY_ANNOTATED.matches(tree, state)
|| (tree.getInitializer() != null && MOCK.matches(tree.getInitializer(), state)))) {
mocks.put(symbol, tree);
}
return super.visitVariable(tree, null);
}
@Override
public Void visitAssignment(AssignmentTree tree, Void unused) {
if (MOCK.matches(tree.getExpression(), state)) {
var symbol = getSymbol(tree.getVariable());
if (isEligible(symbol)) {
mocks.put((VarSymbol) symbol, tree);
}
}
return super.visitAssignment(tree, null);
}
private boolean isEligible(Symbol symbol) {
return symbol instanceof VarSymbol
&& (!symbol.getKind().equals(FIELD) || canBeRemoved((VarSymbol) symbol))
&& annotatedAtMostMock(symbol);
}
private boolean annotatedAtMostMock(Symbol symbol) {
return symbol.getAnnotationMirrors().stream()
.allMatch(a -> a.getAnnotationType().asElement().getSimpleName().contentEquals("Mock"));
}
}.scan(state.getPath().getCompilationUnit(), null);
// A bit hacky: but if we saw InjectMocks, just claim there are no potentially unused mocks.
return injectMocks.get() ? ImmutableMap.of() : ImmutableMap.copyOf(mocks);
}
private static final Matcher<ExpressionTree> MOCK =
staticMethod().onClass("org.mockito.Mockito").namedAnyOf("mock", "spy");
private static final Matcher<VariableTree> MOCK_OR_SPY_ANNOTATED =
anyOf(hasAnnotation("org.mockito.Mock"), hasAnnotation("org.mockito.Spy"));
private static final Matcher<VariableTree> INJECT_MOCKS_ANNOTATED =
hasAnnotation("org.mockito.InjectMocks");
private static final Matcher<ExpressionTree> WHEN_OR_VERIFY =
anyOf(
staticMethod().anyClass().namedAnyOf("when", "verify"),
instanceMethod().onDescendantOf("org.mockito.stubbing.Stubber").namedAnyOf("when"));
}
| 8,628
| 39.895735
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/EqualsUsingHashCode.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.enclosingMethod;
import static com.google.errorprone.matchers.Matchers.equalsMethodDeclaration;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
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.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.util.TreeScanner;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Discourages implementing {@code equals} using {@code hashCode}.
*
* @author ghm@google.com (Graeme Morgan)
*/
@BugPattern(
summary =
"Implementing #equals by just comparing hashCodes is fragile. Hashes collide "
+ "frequently, and this will lead to false positives in #equals.",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public final class EqualsUsingHashCode extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
allOf(
instanceMethod().anyClass().named("hashCode"),
enclosingMethod(equalsMethodDeclaration()));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
ReturnTree returnTree = state.findEnclosing(ReturnTree.class);
if (returnTree == null) {
return NO_MATCH;
}
AtomicBoolean isTerminalCondition = new AtomicBoolean(false);
returnTree.accept(
new TreeScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(MethodInvocationTree methodTree, Void unused) {
if (methodTree.equals(tree)) {
isTerminalCondition.set(true);
}
return super.visitMethodInvocation(methodTree, null);
}
@Override
public Void visitBinary(BinaryTree binaryTree, Void unused) {
return scan(binaryTree.getRightOperand(), null);
}
},
null);
return isTerminalCondition.get() ? describeMatch(tree) : NO_MATCH;
}
}
| 3,311
| 37.511628
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ClassName.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.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import com.google.common.base.Joiner;
import com.google.common.io.Files;
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.Tree;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.element.Modifier;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
altNames = {"TopLevelName"},
summary = "The source file name should match the name of the top-level class it contains",
severity = ERROR,
documentSuppression = false,
linkType = CUSTOM,
link = "https://google.github.io/styleguide/javaguide.html#s2.1-file-name")
public class ClassName extends BugChecker implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
if (tree.getTypeDecls().isEmpty() || tree.getPackageName() == null) {
return Description.NO_MATCH;
}
String filename = Files.getNameWithoutExtension(ASTHelpers.getFileName(tree));
List<String> names = new ArrayList<>();
for (Tree member : tree.getTypeDecls()) {
if (member instanceof ClassTree) {
ClassTree classMember = (ClassTree) member;
if (isSuppressed(classMember, state)) {
// If any top-level classes have @SuppressWarnings("ClassName"), ignore
// this compilation unit. We can't rely on the normal suppression
// mechanism because the only enclosing element is the package declaration,
// and @SuppressWarnings can't be applied to packages.
return Description.NO_MATCH;
}
if (classMember.getSimpleName().contentEquals(filename)) {
return Description.NO_MATCH;
}
if (classMember.getModifiers().getFlags().contains(Modifier.PUBLIC)) {
// If any of the top-level types are public, javac will complain
// if the filename doesn't match. We don't want to double-report
// the error.
return Description.NO_MATCH;
}
names.add(classMember.getSimpleName().toString());
}
}
String message =
String.format(
"Expected a class declaration named %s inside %s.java, instead found: %s",
filename, filename, Joiner.on(", ").join(names));
return buildDescription(tree.getPackageName()).setMessage(message).build();
}
}
| 3,465
| 41.268293
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ModifySourceCollectionInStream.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.isSubtypeOf;
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.MemberReferenceTreeMatcher;
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.LambdaExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import javax.annotation.Nullable;
/**
* Identify the backing collection source of a stream and reports if the source is mutated during
* the stream operations.
*
* @author deltazulu@google.com (Donald Duo Zhao)
*/
@BugPattern(
summary = "Modifying the backing source during stream operations may cause unintended results.",
severity = WARNING)
public class ModifySourceCollectionInStream extends BugChecker
implements MemberReferenceTreeMatcher, MethodInvocationTreeMatcher {
private static final ImmutableList<String> STATE_MUTATION_METHOD_NAMES =
ImmutableList.of("add", "addAll", "clear", "remove", "removeAll", "retainAll");
private static final ImmutableList<String> STREAM_CREATION_METHOD_NAMES =
ImmutableList.of("stream", "parallelStream");
private static final Matcher<ExpressionTree> COLLECTION_TO_STREAM_MATCHER =
instanceMethod()
.onDescendantOf("java.util.Collection")
.namedAnyOf(STREAM_CREATION_METHOD_NAMES);
/** Covers common stream structures, including Stream, IntStream, LongStream, DoubleStream. */
private static final Matcher<ExpressionTree> STREAM_API_INVOCATION_MATCHER =
instanceMethod().onDescendantOfAny("java.util.stream.BaseStream");
private static final Matcher<ExpressionTree> MUTATION_METHOD_MATCHER =
instanceMethod()
.onDescendantOf("java.util.Collection")
.namedAnyOf(STATE_MUTATION_METHOD_NAMES);
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
if (!isSubtypeOf("java.util.Collection").matches(tree.getQualifierExpression(), state)
|| STATE_MUTATION_METHOD_NAMES.stream()
.noneMatch(methodName -> methodName.contentEquals(tree.getName()))) {
return Description.NO_MATCH;
}
MethodInvocationTree methodInvocationTree = state.findEnclosing(MethodInvocationTree.class);
return isStreamApiInvocationOnStreamSource(
methodInvocationTree, ASTHelpers.getReceiver(tree), state)
? describeMatch(tree)
: Description.NO_MATCH;
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MUTATION_METHOD_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
// The enclosing method invocation of the method reference doesn't dereferenced an expression.
// e.g. calling other methods defined in the same class.
ExpressionTree mutatedReceiver = ASTHelpers.getReceiver(tree);
if (mutatedReceiver == null) {
return Description.NO_MATCH;
}
TreePath pathToLambdaExpression = state.findPathToEnclosing(LambdaExpressionTree.class);
// Case for a method reference not enclosed in a lambda expression,
// e.g. BiConsumer<ArrayList, Integer> biConsumer = ArrayList::add;
if (pathToLambdaExpression == null) {
return Description.NO_MATCH;
}
// Starting from the immediate enclosing method invocation of the lambda expression.
Tree parentNode = pathToLambdaExpression.getParentPath().getLeaf();
if (!(parentNode instanceof ExpressionTree)) {
return Description.NO_MATCH;
}
return isStreamApiInvocationOnStreamSource((ExpressionTree) parentNode, mutatedReceiver, state)
? describeMatch(tree)
: Description.NO_MATCH;
}
/**
* Returns true if and only if the given MethodInvocationTree
*
* <p>1) is a Stream API invocation, .e.g. map, filter, collect 2) the source of the stream has
* the same expression representation as streamSourceExpression.
*/
private static boolean isStreamApiInvocationOnStreamSource(
@Nullable ExpressionTree rootTree,
ExpressionTree streamSourceExpression,
VisitorState visitorState) {
ExpressionTree expressionTree = rootTree;
while (STREAM_API_INVOCATION_MATCHER.matches(expressionTree, visitorState)) {
expressionTree = ASTHelpers.getReceiver(expressionTree);
}
if (!COLLECTION_TO_STREAM_MATCHER.matches(expressionTree, visitorState)) {
return false;
}
return isSameExpression(ASTHelpers.getReceiver(expressionTree), streamSourceExpression);
}
// TODO(b/125767228): Consider a rigorous implementation to check tree structure equivalence.
@SuppressWarnings("TreeToString") // Indented to ignore whitespace, comments, and source position.
private static boolean isSameExpression(ExpressionTree leftTree, ExpressionTree rightTree) {
// The left tree and right tree must have the same symbol resolution.
// This ensures the symbol kind on field, parameter or local var.
if (ASTHelpers.getSymbol(leftTree) != ASTHelpers.getSymbol(rightTree)) {
return false;
}
String leftTreeTextRepr = stripPrefixIfPresent(leftTree.toString(), "this.");
String rightTreeTextRepr = stripPrefixIfPresent(rightTree.toString(), "this.");
return leftTreeTextRepr.contentEquals(rightTreeTextRepr);
}
private static String stripPrefixIfPresent(String originalText, String prefix) {
return originalText.startsWith(prefix) ? originalText.substring(prefix.length()) : originalText;
}
}
| 6,701
| 41.687898
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StaticImports.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.Iterables.getOnlyElement;
import static com.google.errorprone.util.ASTHelpers.enclosingPackage;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isStatic;
import com.google.auto.value.AutoValue;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.VisitorState;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.MemberSelectTree;
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.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.Name;
import javax.annotation.Nullable;
/**
* Logic for inspecting static imports used by {@link NonCanonicalStaticImport}, {@link
* NonCanonicalStaticMemberImport}, and {@link UnnecessaryStaticImport}.
*/
public final class StaticImports {
/** Information about a static import. */
@AutoValue
public abstract static class StaticImportInfo {
/** The fully qualified name used to import the type (possibly non-canonical). */
public abstract String importedName();
/** The fully-qualified canonical name of the type. */
public abstract String canonicalName();
/** The simple name of the imported member. */
public abstract Optional<String> simpleName();
/** The field or variable symbol for a static non-type member import. */
public abstract ImmutableSet<Symbol> members();
/**
* Returns whether the import is canonical, i.e. the fully qualified name used to import the
* type matches the scopes it was declared in.
*/
public boolean isCanonical() {
return canonicalName().equals(importedName());
}
/** Builds the canonical import statement for the type. */
public String importStatement() {
if (members().isEmpty()) {
return String.format("import %s;", canonicalName());
} else {
return String.format("import static %s.%s;", canonicalName(), simpleName().get());
}
}
private static StaticImportInfo create(String importedName, String canonicalName) {
return new AutoValue_StaticImports_StaticImportInfo(
importedName, canonicalName, Optional.<String>absent(), ImmutableSet.<Symbol>of());
}
private static StaticImportInfo create(
String importedName, String canonicalName, String simpleName, Iterable<Symbol> members) {
return new AutoValue_StaticImports_StaticImportInfo(
importedName, canonicalName, Optional.of(simpleName), ImmutableSet.copyOf(members));
}
}
/**
* Returns a {@link StaticImportInfo} if the given import is a static single-type import. Returns
* {@code null} otherwise, e.g. because the import is non-static, or an on-demand import, or
* statically imports a field or method.
*/
@Nullable
public static StaticImportInfo tryCreate(ImportTree tree, VisitorState state) {
if (!tree.isStatic()) {
return null;
}
if (!(tree.getQualifiedIdentifier() instanceof JCTree.JCFieldAccess)) {
return null;
}
JCTree.JCFieldAccess access = (JCTree.JCFieldAccess) tree.getQualifiedIdentifier();
Name identifier = access.getIdentifier();
if (identifier.contentEquals("*")) {
// Java doesn't allow non-canonical types inside wildcard imports,
// so there's nothing to do here.
return null;
}
return tryCreate(access, state);
}
@Nullable
public static StaticImportInfo tryCreate(MemberSelectTree access, VisitorState state) {
Name identifier = (Name) access.getIdentifier();
Symbol importedType = getSymbol(access.getExpression());
if (importedType == null) {
return null;
}
Types types = state.getTypes();
Type canonicalType = types.erasure(importedType.asType());
if (canonicalType == null) {
return null;
}
Symbol sym = getSymbol(access.getExpression());
if (!(sym instanceof Symbol.TypeSymbol)) {
return null;
}
Symbol.TypeSymbol baseType = (Symbol.TypeSymbol) sym;
Symbol.PackageSymbol pkgSym =
((JCTree.JCCompilationUnit) state.getPath().getCompilationUnit()).packge;
ImmutableSet<Symbol> members = lookup(baseType, baseType, identifier, types, pkgSym);
if (members.isEmpty()) {
return null;
}
// Find the most specific subtype that defines one of the members that is imported.
// TODO(gak): we should instead find the most specific subtype with a member that is _used_
Type canonicalOwner = null;
for (Symbol member : members) {
Type owner = types.erasure(member.owner.type);
if (canonicalOwner == null || types.isSubtype(owner, canonicalOwner)) {
canonicalOwner = owner;
}
}
if (canonicalOwner == null) {
return null;
}
if (members.size() == 1 && getOnlyElement(members) instanceof ClassSymbol) {
return StaticImportInfo.create(access.toString(), getOnlyElement(members).toString());
}
return StaticImportInfo.create(
access.getExpression().toString(),
canonicalOwner.toString(),
identifier.toString(),
members);
}
/**
* Looks for a field or method with the given {@code identifier}, in {@code typeSym} or one of its
* super-types or super-interfaces, and that is visible from the {@code start} symbol.
*/
// TODO(cushon): does javac really not expose this anywhere?
//
// Resolve.resolveInternal{Method,Field} almost work, but we don't want
// to filter on method signature.
private static ImmutableSet<Symbol> lookup(
Symbol.TypeSymbol typeSym,
Symbol.TypeSymbol start,
Name identifier,
Types types,
Symbol.PackageSymbol pkg) {
if (typeSym == null) {
return ImmutableSet.of();
}
ImmutableSet.Builder<Symbol> members = ImmutableSet.builder();
members.addAll(lookup(types.supertype(typeSym.type).tsym, start, identifier, types, pkg));
for (Type type : types.interfaces(typeSym.type)) {
members.addAll(lookup(type.tsym, start, identifier, types, pkg));
}
for (Symbol member : typeSym.members().getSymbolsByName(identifier)) {
if (!isStatic(member)) {
continue;
}
switch ((int) (member.flags() & Flags.AccessFlags)) {
case Flags.PRIVATE:
continue;
case 0:
case Flags.PROTECTED:
if (enclosingPackage(member) != pkg) {
continue;
}
break;
case Flags.PUBLIC:
default:
break;
}
if (member.isMemberOf(start, types)) {
members.add(member);
}
}
return members.build();
}
private StaticImports() {}
}
| 7,504
| 33.74537
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/Incomparable.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.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.constructor;
import static com.google.errorprone.predicates.TypePredicates.isExactTypeAny;
import static com.google.errorprone.util.ASTHelpers.getType;
import com.google.common.collect.ImmutableList;
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.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.NewClassTree;
import com.sun.tools.javac.code.Type;
import java.util.List;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Types contained in sorted collections must implement Comparable.",
severity = ERROR)
public class Incomparable extends BugChecker implements NewClassTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
anyOf(
constructor()
.forClass(
isExactTypeAny(
ImmutableList.of(
"java.util.TreeMap", "java.util.concurrent.ConcurrentSkipListMap")))
.withParameters("java.util.Map"),
constructor()
.forClass(
isExactTypeAny(
ImmutableList.of(
"java.util.TreeSet", "java.util.concurrent.ConcurrentSkipListSet")))
.withParameters("java.util.Set"),
constructor()
.forClass(
isExactTypeAny(
ImmutableList.of(
"java.util.TreeMap",
"java.util.TreeSet",
"java.util.concurrent.ConcurrentSkipListMap",
"java.util.concurrent.ConcurrentSkipListSet")))
.withNoParameters());
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
Type type;
ASTHelpers.TargetType targetType = ASTHelpers.targetType(state);
if (targetType != null) {
type = targetType.type();
} else {
type = getType(tree.getIdentifier());
}
List<Type> typeArguments = type.getTypeArguments();
if (typeArguments.isEmpty()) {
return NO_MATCH;
}
Type keyType = typeArguments.get(0);
if (ASTHelpers.isCastable(keyType, state.getSymtab().comparableType, state)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage(String.format("%s does not implement Comparable", keyType))
.build();
}
}
| 3,631
| 38.053763
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/EqualsNull.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.BugPattern.StandardTags.FRAGILE_CODE;
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.argument;
import static com.google.errorprone.matchers.Matchers.enclosingClass;
import static com.google.errorprone.matchers.Matchers.enclosingNode;
import static com.google.errorprone.matchers.Matchers.instanceEqualsInvocation;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.kindIs;
import static com.google.errorprone.matchers.Matchers.toType;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
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.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"The contract of Object.equals() states that for any non-null reference value x,"
+ " x.equals(null) should return false. If x is null, a NullPointerException is thrown."
+ " Consider replacing equals() with the == operator.",
tags = FRAGILE_CODE,
severity = ERROR)
public final class EqualsNull extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<MethodInvocationTree> EQUALS_NULL =
allOf(instanceEqualsInvocation(), argument(0, kindIs(Kind.NULL_LITERAL)));
private static final Matcher<Tree> INSIDE_ASSERT_CLASS =
enclosingClass(anyOf(isSubtypeOf("org.junit.Assert"), isSubtypeOf("junit.framework.Assert")));
private static final Matcher<Tree> ENCLOSED_BY_ASSERT =
enclosingNode(
toType(
MethodInvocationTree.class,
staticMethod()
.onClassAny(
"com.google.common.truth.Truth",
"com.google.common.truth.Truth8",
"junit.framework.Assert",
"org.junit.Assert")));
@Override
public Description matchMethodInvocation(
MethodInvocationTree invocationTree, VisitorState state) {
if (!EQUALS_NULL.matches(invocationTree, state)) {
return NO_MATCH;
}
if (ASTHelpers.isJUnitTestCode(state)
|| ASTHelpers.isTestNgTestCode(state)
|| INSIDE_ASSERT_CLASS.matches(invocationTree, state)
|| ENCLOSED_BY_ASSERT.matches(invocationTree, state)) {
// Allow x.equals(null) in test code for testing the equals contract.
return NO_MATCH;
}
Tree parentTree = state.getPath().getParentPath().getLeaf();
boolean negated = parentTree.getKind() == Kind.LOGICAL_COMPLEMENT;
String operator = negated ? "!=" : "==";
Tree treeToFix = negated ? parentTree : invocationTree;
String fixedCode =
String.format("%s %s null", state.getSourceForNode(getReceiver(invocationTree)), operator);
return describeMatch(treeToFix, SuggestedFix.replace(treeToFix, fixedCode));
}
}
| 4,288
| 44.62766
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnusedMethod.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.ImmutableListMultimap.toImmutableListMultimap;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.size;
import static com.google.common.collect.Multimaps.asMap;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFix.emptyFix;
import static com.google.errorprone.fixes.SuggestedFixes.replaceIncludingComments;
import static com.google.errorprone.matchers.Matchers.SERIALIZATION_METHODS;
import static com.google.errorprone.suppliers.Suppliers.typeFromString;
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.isGeneratedConstructor;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static com.google.errorprone.util.ASTHelpers.scope;
import static com.google.errorprone.util.ASTHelpers.shouldKeep;
import static com.google.errorprone.util.MoreAnnotations.asStrings;
import static com.google.errorprone.util.MoreAnnotations.getAnnotationValue;
import static java.lang.String.format;
import static javax.lang.model.element.ElementKind.CONSTRUCTOR;
import static javax.lang.model.element.ElementKind.FIELD;
import static javax.lang.model.element.Modifier.FINAL;
import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableListMultimap;
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.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.suppliers.Supplier;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
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.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
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.TypeSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCAssign;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.inject.Inject;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
/** Bugpattern to detect unused declarations. */
@BugPattern(
altNames = {"Unused", "unused", "UnusedParameters"},
summary = "Unused.",
severity = WARNING,
documentSuppression = false)
public final class UnusedMethod extends BugChecker implements CompilationUnitTreeMatcher {
private static final String GWT_JAVASCRIPT_OBJECT = "com.google.gwt.core.client.JavaScriptObject";
private static final String EXEMPT_PREFIX = "unused";
private static final String JUNIT_PARAMS_VALUE = "value";
private static final String JUNIT_PARAMS_ANNOTATION_TYPE = "junitparams.Parameters";
private static final ImmutableSet<String> EXEMPTING_METHOD_ANNOTATIONS =
ImmutableSet.of(
"com.fasterxml.jackson.annotation.JsonCreator",
"com.fasterxml.jackson.annotation.JsonValue",
"com.google.acai.AfterTest",
"com.google.acai.BeforeSuite",
"com.google.acai.BeforeTest",
"com.google.caliper.Benchmark",
"com.google.common.eventbus.Subscribe",
"com.google.inject.Provides",
"com.google.inject.Inject",
"com.google.inject.multibindings.ProvidesIntoMap",
"com.google.inject.multibindings.ProvidesIntoSet",
"com.google.inject.throwingproviders.CheckedProvides",
"com.tngtech.java.junit.dataprovider.DataProvider",
"jakarta.annotation.PreDestroy",
"jakarta.annotation.PostConstruct",
"jakarta.inject.Inject",
"jakarta.persistence.PostLoad",
"jakarta.persistence.PostPersist",
"jakarta.persistence.PostRemove",
"jakarta.persistence.PostUpdate",
"jakarta.persistence.PrePersist",
"jakarta.persistence.PreRemove",
"jakarta.persistence.PreUpdate",
"javax.annotation.PreDestroy",
"javax.annotation.PostConstruct",
"javax.inject.Inject",
"javax.persistence.PostLoad",
"javax.persistence.PostPersist",
"javax.persistence.PostRemove",
"javax.persistence.PostUpdate",
"javax.persistence.PrePersist",
"javax.persistence.PreRemove",
"javax.persistence.PreUpdate",
"org.apache.beam.sdk.transforms.DoFn.ProcessElement",
"org.aspectj.lang.annotation.Pointcut",
"org.aspectj.lang.annotation.After",
"org.aspectj.lang.annotation.Before",
"org.springframework.context.annotation.Bean",
"org.testng.annotations.AfterClass",
"org.testng.annotations.AfterMethod",
"org.testng.annotations.BeforeClass",
"org.testng.annotations.BeforeMethod",
"org.testng.annotations.DataProvider",
"org.junit.jupiter.api.BeforeAll",
"org.junit.jupiter.api.AfterAll",
"org.junit.jupiter.api.AfterEach",
"org.junit.jupiter.api.BeforeEach",
"org.junit.jupiter.api.RepeatedTest",
"org.junit.jupiter.api.Test",
"org.junit.jupiter.params.ParameterizedTest");
/** The set of types exempting a type that is extending or implementing them. */
private static final ImmutableSet<String> EXEMPTING_SUPER_TYPES = ImmutableSet.of();
private final ImmutableSet<String> additionalExemptingMethodAnnotations;
@Inject
UnusedMethod(ErrorProneFlags errorProneFlags) {
this.additionalExemptingMethodAnnotations =
errorProneFlags
.getList("UnusedMethod:ExemptingMethodAnnotations")
.map(ImmutableSet::copyOf)
.orElseGet(ImmutableSet::of);
}
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
// Map of symbols to method declarations. Initially this is a map of all of the methods. As we
// go we remove those variables which are used.
Map<Symbol, TreePath> unusedMethods = new HashMap<>();
// We will skip reporting on the whole compilation if there are any native methods found.
// Use a TreeScanner to find all local variables and fields.
if (hasNativeMethods(tree)) {
return Description.NO_MATCH;
}
AtomicBoolean ignoreUnusedMethods = new AtomicBoolean(false);
ImmutableSet<ClassSymbol> classesMadeVisible = getVisibleClasses(tree);
class MethodFinder extends SuppressibleTreePathScanner<Void, Void> {
MethodFinder(VisitorState state) {
super(state);
}
@Override
public Void visitClass(ClassTree tree, Void unused) {
if (exemptedBySuperType(getType(tree), state)) {
return null;
}
return super.visitClass(tree, null);
}
private boolean exemptedBySuperType(Type type, VisitorState state) {
return EXEMPTING_SUPER_TYPES.stream()
.anyMatch(t -> isSubtype(type, typeFromString(t).get(state), state));
}
@Override
public Void visitMethod(MethodTree tree, Void unused) {
if (hasJUnitParamsParametersForMethodAnnotation(tree.getModifiers().getAnnotations())) {
// Since this method uses @Parameters, there will be another method that appears to
// be unused. Don't warn about unusedMethods at all in this case.
ignoreUnusedMethods.set(true);
}
if (isMethodSymbolEligibleForChecking(tree, classesMadeVisible)) {
unusedMethods.put(getSymbol(tree), getCurrentPath());
}
return super.visitMethod(tree, unused);
}
private boolean hasJUnitParamsParametersForMethodAnnotation(
Collection<? extends AnnotationTree> annotations) {
for (AnnotationTree tree : annotations) {
JCAnnotation annotation = (JCAnnotation) tree;
if (annotation.getAnnotationType().type != null
&& annotation
.getAnnotationType()
.type
.toString()
.equals(JUNIT_PARAMS_ANNOTATION_TYPE)) {
if (annotation.getArguments().isEmpty()) {
// @Parameters, which uses implicit provider methods
return true;
}
for (JCExpression arg : annotation.getArguments()) {
if (arg.getKind() != Kind.ASSIGNMENT) {
// Implicit value annotation, e.g. @Parameters({"1"}); no exemption required.
return false;
}
JCExpression var = ((JCAssign) arg).getVariable();
if (var.getKind() == Kind.IDENTIFIER) {
// Anything that is not @Parameters(value = ...), e.g.
// @Parameters(source = ...) or @Parameters(method = ...)
if (!((IdentifierTree) var).getName().contentEquals(JUNIT_PARAMS_VALUE)) {
return true;
}
}
}
}
}
return false;
}
private boolean isMethodSymbolEligibleForChecking(
MethodTree tree, Set<ClassSymbol> classesMadeVisible) {
if (exemptedByName(tree.getName())) {
return false;
}
// Assume the method is called if annotated with a called-reflectively annotation.
if (exemptedByAnnotation(tree.getModifiers().getAnnotations())) {
return false;
}
if (shouldKeep(tree)) {
return false;
}
MethodSymbol methodSymbol = getSymbol(tree);
if (!canBeRemoved(methodSymbol, state)) {
return false;
}
if (isExemptedConstructor(methodSymbol, state)
|| isGeneratedConstructor(tree)
|| SERIALIZATION_METHODS.matches(tree, state)) {
return false;
}
// Ignore this method if the last parameter is a GWT JavaScriptObject.
if (!tree.getParameters().isEmpty()) {
Type lastParamType = getType(getLast(tree.getParameters()));
if (lastParamType != null && lastParamType.toString().equals(GWT_JAVASCRIPT_OBJECT)) {
return false;
}
}
if (!methodSymbol.isPrivate()
&& classesMadeVisible.stream()
.anyMatch(t -> isSubtype(t.type, methodSymbol.owner.type, state))) {
return false;
}
return true;
}
private boolean isExemptedConstructor(MethodSymbol methodSymbol, VisitorState state) {
if (!methodSymbol.getKind().equals(CONSTRUCTOR)) {
return false;
}
// Don't delete unused zero-arg constructors, given those are often there to limit
// instantiating the class at all (e.g. in utility classes).
if (methodSymbol.params().isEmpty()) {
return true;
}
return false;
}
}
new MethodFinder(state).scan(state.getPath(), null);
class FilterUsedMethods extends TreePathScanner<Void, Void> {
@Override
public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void unused) {
Symbol symbol = getSymbol(memberSelectTree);
unusedMethods.remove(symbol);
return super.visitMemberSelect(memberSelectTree, null);
}
@Override
public Void visitMemberReference(MemberReferenceTree tree, Void unused) {
super.visitMemberReference(tree, null);
MethodSymbol symbol = getSymbol(tree);
unusedMethods.remove(symbol);
symbol.getParameters().forEach(unusedMethods::remove);
return null;
}
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
handle(getSymbol(tree));
return super.visitMethodInvocation(tree, null);
}
@Override
public Void visitNewClass(NewClassTree tree, Void unused) {
handle(getSymbol(tree));
return super.visitNewClass(tree, null);
}
@Override
public Void visitAssignment(AssignmentTree tree, Void unused) {
handle(getSymbol(tree.getVariable()));
return super.visitAssignment(tree, unused);
}
private void handle(Symbol symbol) {
if (symbol instanceof MethodSymbol) {
unusedMethods.remove(symbol);
}
}
@Override
public Void visitMethod(MethodTree tree, Void unused) {
handleMethodSource(tree);
return super.visitMethod(tree, null);
}
/**
* If a method is annotated with @MethodSource, the annotation value refers to another method
* that is used reflectively to supply test parameters, so that method should not be
* considered unused.
*/
private void handleMethodSource(MethodTree tree) {
MethodSymbol sym = getSymbol(tree);
Name name = ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHODSOURCE.get(state);
sym.getRawAttributes().stream()
.filter(a -> a.type.tsym.getQualifiedName().equals(name))
.findAny()
// get the annotation value array as a set of Names
.flatMap(a -> getAnnotationValue(a, "value"))
.map(
y -> asStrings(y).map(state::getName).map(Name::toString).collect(toImmutableSet()))
// remove all potentially unused methods referenced by the @MethodSource
.ifPresent(
referencedNames ->
unusedMethods
.entrySet()
.removeIf(
e -> {
Symbol unusedSym = e.getKey();
String simpleName = unusedSym.getSimpleName().toString();
return referencedNames.contains(simpleName)
|| referencedNames.contains(
unusedSym.owner.getQualifiedName() + "#" + simpleName);
}));
}
}
new FilterUsedMethods().scan(state.getPath(), null);
if (ignoreUnusedMethods.get()) {
return Description.NO_MATCH;
}
fixNonConstructors(
unusedMethods.values().stream()
.filter(t -> !getSymbol(t.getLeaf()).isConstructor())
.collect(toImmutableList()),
state);
// Group unused constructors by the owning class to generate fixes, so that if we remove the
// last constructor, we add a private one.
ImmutableListMultimap<Symbol, TreePath> unusedConstructors =
unusedMethods.values().stream()
.filter(t -> getSymbol(t.getLeaf()).isConstructor())
.collect(toImmutableListMultimap(t -> getSymbol(t.getLeaf()).owner, t -> t));
fixConstructors(unusedConstructors, state);
return Description.NO_MATCH;
}
private ImmutableSet<ClassSymbol> getVisibleClasses(CompilationUnitTree tree) {
ImmutableSet.Builder<ClassSymbol> classesMadeVisible = ImmutableSet.builder();
new TreePathScanner<Void, Void>() {
@Override
public Void visitClass(ClassTree tree, Void unused) {
var symbol = getSymbol(tree);
if (!canBeRemoved(symbol)) {
classesMadeVisible.add(symbol);
}
return super.visitClass(tree, null);
}
}.scan(tree, null);
return classesMadeVisible.build();
}
private void fixNonConstructors(Iterable<TreePath> unusedPaths, VisitorState state) {
for (TreePath unusedPath : unusedPaths) {
Tree unusedTree = unusedPath.getLeaf();
MethodSymbol symbol = getSymbol((MethodTree) unusedTree);
String message = String.format("Method '%s' is never used.", symbol.getSimpleName());
state.reportMatch(
buildDescription(unusedTree)
.addFix(replaceIncludingComments(unusedPath, "", state))
.setMessage(message)
.build());
}
}
private void fixConstructors(
ImmutableListMultimap<Symbol, TreePath> unusedConstructors, VisitorState state) {
for (Map.Entry<Symbol, List<TreePath>> entry : asMap(unusedConstructors).entrySet()) {
Symbol symbol = entry.getKey();
List<TreePath> trees = entry.getValue();
SuggestedFix.Builder fix = SuggestedFix.builder();
int constructorCount = size(scope(symbol.members()).getSymbols(Symbol::isConstructor));
int finalFields =
size(
scope(symbol.members())
.getSymbols(s -> s.getKind().equals(FIELD) && s.getModifiers().contains(FINAL)));
boolean fixable;
if (constructorCount == trees.size()) {
fix.postfixWith(
getLast(trees).getLeaf(), format("private %s() {}", symbol.getSimpleName()));
fixable = finalFields == 0;
} else {
fixable = true;
}
String message = String.format("Constructor '%s' is never used.", symbol.getSimpleName());
trees.forEach(t -> fix.merge(replaceIncludingComments(t, "", state)));
state.reportMatch(
buildDescription(trees.get(0).getLeaf())
.addFix(fixable ? fix.build() : emptyFix())
.setMessage(message)
.build());
}
}
private static boolean hasNativeMethods(CompilationUnitTree tree) {
AtomicBoolean hasAnyNativeMethods = new AtomicBoolean(false);
new TreeScanner<Void, Void>() {
@Override
public Void visitMethod(MethodTree tree, Void unused) {
if (tree.getModifiers().getFlags().contains(Modifier.NATIVE)) {
hasAnyNativeMethods.set(true);
}
return null;
}
}.scan(tree, null);
return hasAnyNativeMethods.get();
}
/**
* Looks at the list of {@code annotations} and see if there is any annotation which exists {@code
* exemptingAnnotations}.
*/
private boolean exemptedByAnnotation(List<? extends AnnotationTree> annotations) {
for (AnnotationTree annotation : annotations) {
Type annotationType = getType(annotation);
if (annotationType == null) {
continue;
}
TypeSymbol tsym = annotationType.tsym;
String annotationName = tsym.getQualifiedName().toString();
if (EXEMPTING_METHOD_ANNOTATIONS.contains(annotationName)
|| additionalExemptingMethodAnnotations.contains(annotationName)) {
return true;
}
}
return false;
}
private static boolean exemptedByName(Name name) {
return Ascii.toLowerCase(name.toString()).startsWith(EXEMPT_PREFIX);
}
private static final Supplier<com.sun.tools.javac.util.Name>
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHODSOURCE =
VisitorState.memoize(
state -> state.getName("org.junit.jupiter.params.provider.MethodSource"));
}
| 20,465
| 39.687873
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SelfComparison.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.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.receiverSameAsArgument;
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;
/**
* Points out if an object is compared to itself.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(summary = "An object is compared to itself", severity = ERROR)
public class SelfComparison extends BugChecker implements MethodInvocationTreeMatcher {
/**
* Matches calls to any instance method called "compareTo" with exactly one argument in which the
* receiver is the same reference as the argument.
*
* <p>Example: foo.compareTo(foo)
*/
private static final Matcher<MethodInvocationTree> COMPARE_TO_MATCHER =
allOf(
instanceMethod().onDescendantOf("java.lang.Comparable").named("compareTo"),
receiverSameAsArgument(0));
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState state) {
if (!COMPARE_TO_MATCHER.matches(methodInvocationTree, state)) {
return Description.NO_MATCH;
}
return describeMatch(methodInvocationTree);
}
}
| 2,226
| 36.116667
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InconsistentCapitalization.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.ImmutableMap.toImmutableMap;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
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.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.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MethodTree;
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 java.util.Map;
import javax.lang.model.element.ElementKind;
/** Checker for variables under the same scope that only differ in capitalization. */
@BugPattern(
summary =
"It is confusing to have a field and a parameter under the same scope that differ only in "
+ "capitalization.",
severity = WARNING)
public class InconsistentCapitalization extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
ImmutableSet<Symbol> fields = FieldScanner.findFields(tree);
if (fields.isEmpty()) {
return Description.NO_MATCH;
}
ImmutableMap<String, Symbol> fieldNamesMap =
fields.stream()
.collect(
toImmutableMap(
symbol -> Ascii.toLowerCase(symbol.toString()), x -> x, (x, y) -> x));
ImmutableMap<TreePath, Symbol> matchedParameters =
MatchingParametersScanner.findMatchingParameters(fieldNamesMap, state.getPath());
if (matchedParameters.isEmpty()) {
return Description.NO_MATCH;
}
for (Map.Entry<TreePath, Symbol> entry : matchedParameters.entrySet()) {
TreePath parameterPath = entry.getKey();
Symbol field = entry.getValue();
String fieldName = field.getSimpleName().toString();
VariableTree parameterTree = (VariableTree) parameterPath.getLeaf();
SuggestedFix.Builder fix =
SuggestedFix.builder()
.merge(SuggestedFixes.renameVariable(parameterTree, fieldName, state));
if (parameterPath.getParentPath() != null) {
String qualifiedName =
getExplicitQualification(parameterPath, tree, state) + field.getSimpleName();
// If the field was accessed in a non-qualified way, by renaming the parameter this may
// cause clashes with it. Thus, it is required to qualify all uses of the field within the
// parameter's scope just in case.
parameterPath
.getParentPath()
.getLeaf()
.accept(
new TreeScanner<Void, Void>() {
@Override
public Void visitIdentifier(IdentifierTree tree, Void unused) {
if (field.equals(ASTHelpers.getSymbol(tree))) {
fix.replace(tree, qualifiedName);
}
return null;
}
},
null);
}
state.reportMatch(
buildDescription(parameterPath.getLeaf())
.setMessage(
String.format(
"Found the field '%s' with the same name as the parameter '%s' but with "
+ "different capitalization.",
fieldName, ((VariableTree) parameterPath.getLeaf()).getName()))
.addFix(fix.build())
.build());
}
return Description.NO_MATCH;
}
/**
* Returns the qualification to access a field of the given class node from within the given tree
* path (which MUST be within the class node scope).
*/
private static String getExplicitQualification(
TreePath path, ClassTree tree, VisitorState state) {
for (Tree node : path) {
if (node.equals(tree)) {
break;
}
if (node instanceof ClassTree) {
if (ASTHelpers.getSymbol(node).isSubClass(ASTHelpers.getSymbol(tree), state.getTypes())) {
return "super.";
}
return tree.getSimpleName() + ".this.";
}
}
return "this.";
}
/** Returns true if the given symbol has static modifier and is all upper case. */
private static boolean isUpperCaseAndStatic(Symbol symbol) {
return isStatic(symbol) && symbol.name.contentEquals(Ascii.toUpperCase(symbol.name.toString()));
}
/**
* Matcher for all fields of the given class node that are either instance members or not all
* upper case.
*/
private static class FieldScanner extends TreeScanner<Void, Void> {
static ImmutableSet<Symbol> findFields(ClassTree tree) {
ImmutableSet.Builder<Symbol> fieldsBuilder = ImmutableSet.builder();
new FieldScanner(fieldsBuilder, tree).scan(tree, null);
return fieldsBuilder.build();
}
private final ImmutableSet.Builder<Symbol> fields;
private final Symbol classSymbol;
private FieldScanner(ImmutableSet.Builder<Symbol> fields, Tree classTree) {
this.fields = fields;
this.classSymbol = ASTHelpers.getSymbol(classTree);
}
@Override
public Void visitVariable(VariableTree tree, Void unused) {
Symbol symbol = ASTHelpers.getSymbol(tree);
/* It is quite common to have upper case static field names that match variable names,
* as for example between HTTP request parameters name definitions and their corresponding
* extracted value. */
if (symbol.getKind().equals(ElementKind.FIELD)
&& !isUpperCaseAndStatic(symbol)
&& ASTHelpers.enclosingClass(symbol).equals(classSymbol)) {
fields.add(symbol);
}
return super.visitVariable(tree, unused);
}
}
/**
* Matcher for all parameters (methods, constructors, lambda expressions) that have the same name
* as one of the provided fields but with different capitalization.
*/
private static class MatchingParametersScanner extends TreePathScanner<Void, Void> {
static ImmutableMap<TreePath, Symbol> findMatchingParameters(
ImmutableMap<String, Symbol> fieldNamesMap, TreePath path) {
ImmutableMap.Builder<TreePath, Symbol> matchedParametersBuilder = ImmutableMap.builder();
new MatchingParametersScanner(fieldNamesMap, matchedParametersBuilder).scan(path, null);
return matchedParametersBuilder.buildOrThrow();
}
private final ImmutableMap<String, Symbol> fields;
private final ImmutableMap.Builder<TreePath, Symbol> matchedParameters;
private MatchingParametersScanner(
ImmutableMap<String, Symbol> fields,
ImmutableMap.Builder<TreePath, Symbol> matchedParameters) {
this.fields = fields;
this.matchedParameters = matchedParameters;
}
@Override
public Void visitMethod(MethodTree tree, Void unused) {
// Ignore synthetic constructors:
if (ASTHelpers.isGeneratedConstructor(tree)) {
return null;
}
return super.visitMethod(tree, null);
}
@Override
public Void visitVariable(VariableTree tree, Void unused) {
Symbol symbol = ASTHelpers.getSymbol(tree);
if (!symbol.getKind().equals(ElementKind.PARAMETER)) {
return super.visitVariable(tree, unused);
}
String variableName = symbol.toString();
Symbol matchedField = fields.get(Ascii.toLowerCase(variableName));
if (matchedField != null) {
String fieldName = matchedField.toString();
if (!variableName.equals(fieldName)) {
matchedParameters.put(getCurrentPath(), matchedField);
}
}
return super.visitVariable(tree, unused);
}
}
}
| 8,729
| 37.45815
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/RedundantThrows.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.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import com.google.common.base.Joiner;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.SetMultimap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "Thrown exception is a subtype of another", severity = WARNING)
public class RedundantThrows extends BugChecker implements MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
List<? extends ExpressionTree> thrown = tree.getThrows();
if (thrown.isEmpty()) {
return NO_MATCH;
}
SetMultimap<Symbol, ExpressionTree> exceptionsBySuper = LinkedHashMultimap.create();
for (ExpressionTree exception : thrown) {
Type type = getType(exception);
do {
type = state.getTypes().supertype(type);
exceptionsBySuper.put(type.tsym, exception);
} while (!state.getTypes().isSameType(type, state.getSymtab().objectType));
}
Set<ExpressionTree> toRemove = new HashSet<>();
List<String> messages = new ArrayList<>();
for (ExpressionTree exception : thrown) {
Symbol sym = getSymbol(exception);
if (exceptionsBySuper.containsKey(sym)) {
Set<ExpressionTree> sub = exceptionsBySuper.get(sym);
messages.add(
String.format(
"%s %s of %s",
oxfordJoin(", ", sub),
sub.size() == 1 ? "is a subtype" : "are subtypes",
sym.getSimpleName()));
toRemove.addAll(sub);
}
}
if (toRemove.isEmpty()) {
return NO_MATCH;
}
// sort by order in input
ImmutableList<ExpressionTree> delete =
ImmutableList.<ExpressionTree>copyOf(
Iterables.filter(tree.getThrows(), Predicates.in(toRemove)));
return buildDescription(delete.get(0))
.setMessage("Redundant throws clause: " + oxfordJoin("; ", messages))
.addFix(SuggestedFixes.deleteExceptions(tree, state, delete))
.build();
}
static String oxfordJoin(String on, Iterable<?> pieces) {
StringBuilder result = new StringBuilder();
int size = Iterables.size(pieces);
if (size == 2) {
return Joiner.on(" and ").join(pieces);
}
int idx = 0;
for (Object piece : pieces) {
if (idx > 0) {
result.append(on);
if (idx == size - 1) {
result.append("and ");
}
}
result.append(piece);
idx++;
}
return result.toString();
}
}
| 4,051
| 36.174312
| 90
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SwitchDefault.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.errorprone.BugPattern.SeverityLevel.SUGGESTION;
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.SwitchTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.Reachability;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.SwitchTree;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "The default case of a switch should appear at the end of the last statement group",
tags = BugPattern.StandardTags.STYLE,
severity = SUGGESTION)
public class SwitchDefault extends BugChecker implements SwitchTreeMatcher {
@Override
public Description matchSwitch(SwitchTree tree, VisitorState state) {
Optional<? extends CaseTree> maybeDefault =
tree.getCases().stream().filter(c -> c.getExpression() == null).findAny();
if (!maybeDefault.isPresent()) {
return NO_MATCH;
}
// Collect all case trees in the statement group containing the default
List<CaseTree> defaultStatementGroup = new ArrayList<>();
Iterator<? extends CaseTree> it = tree.getCases().iterator();
while (it.hasNext()) {
CaseTree caseTree = it.next();
defaultStatementGroup.add(caseTree);
if (caseTree.getExpression() == null) {
while (it.hasNext() && isNullOrEmpty(caseTree.getStatements())) {
caseTree = it.next();
defaultStatementGroup.add(caseTree);
}
break;
}
if (!isNullOrEmpty(caseTree.getStatements())) {
defaultStatementGroup.clear();
}
}
// Find the position of the default case within the statement group
int idx = defaultStatementGroup.indexOf(maybeDefault.get());
SuggestedFix.Builder fix = SuggestedFix.builder();
CaseTree defaultTree = defaultStatementGroup.get(idx);
if (it.hasNext()) {
// If there are trailing cases after the default statement group, move the default to the end.
// Only emit a fix if the default doesn't fall through.
if (!Reachability.canCompleteNormally(getLast(defaultStatementGroup))) {
int start = getStartPosition(defaultStatementGroup.get(0));
int end = state.getEndPosition(getLast(defaultStatementGroup));
String replacement;
String source = state.getSourceCode().toString();
// If the default case isn't the last case in its statement group, move it to the end.
if (idx != defaultStatementGroup.size() - 1) {
int caseEnd = getStartPosition(getLast(defaultStatementGroup).getStatements().get(0));
int cutStart = getStartPosition(defaultTree);
int cutEnd = state.getEndPosition(defaultTree);
replacement =
source.substring(start, cutStart)
+ source.substring(cutEnd, caseEnd)
+ "\n"
+ source.substring(cutStart, cutEnd)
+ source.substring(caseEnd, end);
} else {
replacement = source.substring(start, end);
}
// If the last statement group falls out of the switch, add a `break;` before moving
// the default to the end.
CaseTree last = getLast(tree.getCases());
if (last.getExpression() == null || Reachability.canCompleteNormally(last)) {
replacement = "break;\n" + replacement;
}
fix.replace(start, end, "").postfixWith(getLast(tree.getCases()), replacement);
}
} else if (idx != defaultStatementGroup.size() - 1) {
// If the default case isn't the last case in its statement group, move it to the end.
fix.delete(defaultTree);
CaseTree lastCase = getLast(defaultStatementGroup);
if (!isNullOrEmpty(lastCase.getStatements())) {
fix.prefixWith(lastCase.getStatements().get(0), state.getSourceForNode(defaultTree));
} else {
fix.postfixWith(lastCase, state.getSourceForNode(defaultTree));
}
} else {
return NO_MATCH;
}
Description.Builder description = buildDescription(defaultStatementGroup.get(0));
if (!fix.isEmpty()) {
description.addFix(fix.build());
}
return description.build();
}
private static <T> boolean isNullOrEmpty(@Nullable List<T> elementList) {
return elementList == null || elementList.isEmpty();
}
}
| 5,445
| 41.88189
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/IterablePathParameter.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.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.isSameType;
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.ASTHelpers;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.WildcardType;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.tree.JCTree.JCLambda;
import com.sun.tools.javac.tree.JCTree.JCLambda.ParameterKind;
import java.nio.file.Path;
import javax.lang.model.element.ElementKind;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Path implements Iterable<Path>; prefer Collection<Path> for clarity",
severity = ERROR)
public class IterablePathParameter extends BugChecker implements VariableTreeMatcher {
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
Type type = ASTHelpers.getType(tree);
VarSymbol symbol = ASTHelpers.getSymbol(tree);
if (type == null) {
return NO_MATCH;
}
if (symbol.getKind() != ElementKind.PARAMETER) {
return NO_MATCH;
}
if (!isSameType(type, state.getSymtab().iterableType, state)) {
return NO_MATCH;
}
if (type.getTypeArguments().isEmpty()) {
return NO_MATCH;
}
if (!isSameType(
wildBound(getOnlyElement(type.getTypeArguments())),
state.getTypeFromString(Path.class.getName()),
state)) {
return NO_MATCH;
}
Description.Builder description = buildDescription(tree);
Tree parent = state.getPath().getParentPath().getLeaf();
if (tree.getType() instanceof ParameterizedTypeTree
&& (!(parent instanceof JCLambda)
|| ((JCLambda) parent).paramKind == ParameterKind.EXPLICIT)) {
description.addFix(
SuggestedFix.builder()
.addImport("java.util.Collection")
.replace(((ParameterizedTypeTree) tree.getType()).getType(), "Collection")
.build());
}
return description.build();
}
static Type wildBound(Type type) {
return type.hasTag(TypeTag.WILDCARD) ? ((WildcardType) type).type : type;
}
}
| 3,361
| 37.643678
| 90
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LogicalAssignment.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.getStartPosition;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.DoWhileLoopTreeMatcher;
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.AssignmentTree;
import com.sun.source.tree.DoWhileLoopTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.WhileLoopTree;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Assignment where a boolean expression was expected;"
+ " use == if this assignment wasn't expected or add parentheses for clarity.",
severity = WARNING,
tags = StandardTags.LIKELY_ERROR)
public class LogicalAssignment extends BugChecker
implements IfTreeMatcher, WhileLoopTreeMatcher, DoWhileLoopTreeMatcher, ForLoopTreeMatcher {
@Override
public Description matchIf(IfTree tree, VisitorState state) {
return checkCondition(skipOneParen(tree.getCondition()), state);
}
@Override
public Description matchDoWhileLoop(DoWhileLoopTree tree, VisitorState state) {
return checkCondition(skipOneParen(tree.getCondition()), state);
}
@Override
public Description matchForLoop(ForLoopTree tree, VisitorState state) {
// for loop condition expressions don't have an extra ParenthesizedTree
return checkCondition(tree.getCondition(), state);
}
@Override
public Description matchWhileLoop(WhileLoopTree tree, VisitorState state) {
return checkCondition(skipOneParen(tree.getCondition()), state);
}
private static ExpressionTree skipOneParen(ExpressionTree tree) {
// javac includes a ParenthesizedTree for the mandatory parens in if statement and loop
// conditions, e.g. in `if (true) {}` the condition is a paren tree containing a literal.
return tree instanceof ParenthesizedTree ? ((ParenthesizedTree) tree).getExpression() : tree;
}
private Description checkCondition(ExpressionTree condition, VisitorState state) {
if (!(condition instanceof AssignmentTree)) {
return NO_MATCH;
}
AssignmentTree assign = (AssignmentTree) condition;
return buildDescription(condition)
.addFix(
SuggestedFix.builder().prefixWith(condition, "(").postfixWith(condition, ")").build())
.addFix(
SuggestedFix.replace(
/* startPos= */ state.getEndPosition(assign.getVariable()),
/* endPos= */ getStartPosition(assign.getExpression()),
" == "))
.build();
}
}
| 3,848
| 40.387097
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/RedundantOverride.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.ImmutableSet.toImmutableSet;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.enclosingPackage;
import static com.google.errorprone.util.ASTHelpers.findSuperMethod;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
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.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.doctree.DocCommentTree;
import com.sun.source.tree.ExpressionStatementTree;
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.ReturnTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.lang.model.element.Modifier;
/** Removes overrides which purely pass through to the method in the super class. */
@BugPattern(
summary = "This overriding method is redundant, and can be removed.",
severity = WARNING)
public final class RedundantOverride extends BugChecker implements MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
MethodSymbol methodSymbol = getSymbol(tree);
Optional<MethodSymbol> maybeSuperMethod = findSuperMethod(methodSymbol, state.getTypes());
if (!maybeSuperMethod.isPresent()) {
return NO_MATCH;
}
MethodSymbol superMethod = maybeSuperMethod.get();
if (tree.getBody() == null || tree.getBody().getStatements().size() != 1) {
return NO_MATCH;
}
StatementTree statement = tree.getBody().getStatements().get(0);
ExpressionTree expression = getSingleInvocation(statement);
if (expression == null) {
return NO_MATCH;
}
MethodInvocationTree methodInvocationTree = (MethodInvocationTree) expression;
if (!getSymbol(methodInvocationTree).equals(superMethod)) {
return NO_MATCH;
}
ExpressionTree receiver = getReceiver(methodInvocationTree);
if (!(receiver instanceof IdentifierTree)) {
return NO_MATCH;
}
if (!((IdentifierTree) receiver).getName().contentEquals("super")) {
return NO_MATCH;
}
// Exempt Javadocs; the override might be here to add documentation.
DocCommentTree docCommentTree =
JavacTrees.instance(state.context).getDocCommentTree(state.getPath());
if (docCommentTree != null) {
return NO_MATCH;
}
// Exempt broadening of visibility.
if (!methodSymbol.getModifiers().equals(superMethod.getModifiers())) {
return NO_MATCH;
}
// Overriding a protected member in another package broadens the visibility to the new package.
if (methodSymbol.getModifiers().contains(Modifier.PROTECTED)
&& !Objects.equals(enclosingPackage(superMethod), enclosingPackage(methodSymbol))) {
return NO_MATCH;
}
// Exempt any change in annotations (aside from @Override).
ImmutableSet<Symbol> superAnnotations = getAnnotations(superMethod);
ImmutableSet<Symbol> methodAnnotations = getAnnotations(methodSymbol);
if (!Sets.difference(
Sets.symmetricDifference(superAnnotations, methodAnnotations),
ImmutableSet.of(state.getSymtab().overrideType.tsym))
.isEmpty()) {
return NO_MATCH;
}
// we're matching parameter by parameter.
for (int i = 0; i < tree.getParameters().size(); ++i) {
if (!(methodInvocationTree.getArguments().get(i) instanceof IdentifierTree)) {
return NO_MATCH;
}
VarSymbol varSymbol = getSymbol(tree.getParameters().get(i));
if (!varSymbol.equals(getSymbol(methodInvocationTree.getArguments().get(i)))) {
return NO_MATCH;
}
ImmutableSet<Symbol> paramAnnotations = getAnnotations(varSymbol);
ImmutableSet<Symbol> superParamAnnotations = getAnnotations(superMethod.params.get(i));
if (!superParamAnnotations.equals(paramAnnotations)) {
return NO_MATCH;
}
}
// Exempt if there are comments within the body. (Do this last, as it's expensive.)
if (state.getOffsetTokensForNode(tree.getBody()).stream()
.anyMatch(t -> !t.comments().isEmpty())) {
return NO_MATCH;
}
return describeMatch(tree, SuggestedFix.delete(tree));
}
@Nullable
private static MethodInvocationTree getSingleInvocation(StatementTree statement) {
return statement.accept(
new SimpleTreeVisitor<MethodInvocationTree, Void>() {
@Override
public MethodInvocationTree visitReturn(ReturnTree returnTree, Void unused) {
return visit(returnTree.getExpression(), null);
}
@Override
public MethodInvocationTree visitExpressionStatement(
ExpressionStatementTree expressionStatement, Void unused) {
return visit(expressionStatement.getExpression(), null);
}
@Override
public MethodInvocationTree visitMethodInvocation(
MethodInvocationTree methodInvocationTree, Void unused) {
return methodInvocationTree;
}
},
null);
}
private static ImmutableSet<Symbol> getAnnotations(Symbol symbol) {
return symbol.getRawAttributes().stream().map(a -> a.type.tsym).collect(toImmutableSet());
}
}
| 6,644
| 40.273292
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StaticAssignmentOfThrowable.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.isStatic;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
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.matchers.Description;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
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;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import javax.lang.model.element.Modifier;
/** Checks for static fields being assigned with {@code Throwable}. */
@BugPattern(
severity = WARNING,
summary =
"Saving instances of Throwable in static fields is discouraged, prefer to create them"
+ " on-demand when an exception is thrown")
public final class StaticAssignmentOfThrowable extends BugChecker
implements MethodTreeMatcher, VariableTreeMatcher {
@Override
public Description matchVariable(VariableTree variableTree, VisitorState state) {
if (state.errorProneOptions().isTestOnlyTarget()
|| !variableTree.getModifiers().getFlags().contains(Modifier.STATIC)) {
return NO_MATCH;
}
ExpressionTree initializer = variableTree.getInitializer();
if (initializer == null) {
return NO_MATCH;
}
Type throwableType = state.getSymtab().throwableType;
Type variableType = getType(variableTree.getType());
if (!isSubtype(variableType, throwableType, state)) {
return NO_MATCH;
}
return describeMatch(variableTree);
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (state.errorProneOptions().isTestOnlyTarget()) {
return NO_MATCH;
}
MethodSymbol methodSymbol = getSymbol(tree);
if (methodSymbol.isConstructor()) {
// To avoid duplicate/conflicting findings, this scenario delegated to
// StaticAssignmentInConstructor
return NO_MATCH;
}
buildTreeScanner(state).scan(tree.getBody(), null);
return NO_MATCH;
}
/* Builds a {@code TreeScanner} that searches for assignments to static {@code Throwable} fields,
* and reports matches. */
private final TreeScanner<Void, Void> buildTreeScanner(VisitorState state) {
Type throwableType = state.getSymtab().throwableType;
return new TreeScanner<Void, Void>() {
@Override
public Void visitClass(ClassTree classTree, Void unused) {
return null;
}
@Override
public Void visitMethod(MethodTree methodTree, Void unused) {
return null;
}
@Override
public Void visitAssignment(AssignmentTree assignmentTree, Void unused) {
Symbol variableSymbol = getSymbol(assignmentTree.getVariable());
Type variableType = getType(assignmentTree.getVariable());
if (variableSymbol != null
&& isStatic(variableSymbol)
&& isSubtype(variableType, throwableType, state)) {
state.reportMatch(describeMatch(assignmentTree));
}
return super.visitAssignment(assignmentTree, null);
}
};
}
}
| 4,316
| 34.385246
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/PreconditionsInvalidPlaceholder.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.anyOf;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
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.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.regex.Pattern;
/**
* @author Louis Wasserman
*/
@BugPattern(
summary = "Preconditions only accepts the %s placeholder in error message strings",
severity = ERROR,
tags = StandardTags.LIKELY_ERROR)
public class PreconditionsInvalidPlaceholder extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> PRECONDITIONS_CHECK =
allOf(
anyOf(
staticMethod().onClass("com.google.common.base.Preconditions"),
staticMethod().onClass("com.google.common.base.Verify")),
PreconditionsInvalidPlaceholder::secondParameterIsString);
private static boolean secondParameterIsString(ExpressionTree tree, VisitorState state) {
Symbol symbol = getSymbol(tree);
if (!(symbol instanceof MethodSymbol)) {
return false;
}
MethodSymbol methodSymbol = (MethodSymbol) symbol;
return methodSymbol.getParameters().size() >= 2
&& isSubtype(methodSymbol.getParameters().get(1).type, state.getSymtab().stringType, state);
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (PRECONDITIONS_CHECK.matches(tree, state)
&& tree.getArguments().get(1) instanceof LiteralTree) {
LiteralTree formatStringTree = (LiteralTree) tree.getArguments().get(1);
if (formatStringTree.getValue() instanceof String) {
String formatString = (String) formatStringTree.getValue();
int expectedArgs = expectedArguments(formatString);
if (expectedArgs < tree.getArguments().size() - 2
&& BAD_PLACEHOLDER_REGEX.matcher(formatString).find()) {
return describe(tree, state);
}
}
}
return Description.NO_MATCH;
}
/**
* Matches most {@code java.util.Formatter} and {@code java.text.MessageFormat} format
* placeholders, other than %s itself.
*
* <p>This does not need to be completely exhaustive, since it is only used to suggest fixes.
*/
private static final Pattern BAD_PLACEHOLDER_REGEX =
Pattern.compile("\\$s|%(?:\\d+\\$)??[dbBhHScCoxXeEfgGaAtTn]|\\{\\d+}");
public Description describe(MethodInvocationTree tree, VisitorState state) {
LiteralTree formatTree = (LiteralTree) tree.getArguments().get(1);
String fixedFormatString =
BAD_PLACEHOLDER_REGEX.matcher(state.getSourceForNode(formatTree)).replaceAll("%s");
if (expectedArguments(fixedFormatString) == tree.getArguments().size() - 2) {
return describeMatch(formatTree, SuggestedFix.replace(formatTree, fixedFormatString));
}
int missing = tree.getArguments().size() - 2 - expectedArguments(fixedFormatString);
StringBuilder builder = new StringBuilder(fixedFormatString);
builder.deleteCharAt(builder.length() - 1);
builder.append(" [%s");
for (int i = 1; i < missing; i++) {
builder.append(", %s");
}
builder.append("]\"");
return describeMatch(tree, SuggestedFix.replace(formatTree, builder.toString()));
}
private static int expectedArguments(String formatString) {
int count = 0;
for (int i = formatString.indexOf("%s"); i != -1; i = formatString.indexOf("%s", i + 1)) {
count++;
}
return count;
}
}
| 4,890
| 39.758333
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnusedException.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.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.STYLE;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.collect.Streams;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CatchTreeMatcher;
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.CatchTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.VariableTree;
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.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCNewClass;
import com.sun.tools.javac.tree.JCTree.JCThrow;
import com.sun.tools.javac.tree.JCTree.JCTry;
import com.sun.tools.javac.tree.TreeScanner;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.lang.model.element.Modifier;
/**
* Bugpattern for catch blocks which catch an exception but throw another one without wrapping the
* original.
*
* @author ghm@google.com (Graeme Morgan)
*/
@BugPattern(
summary =
"This catch block catches an exception and re-throws another, but swallows the caught"
+ " exception rather than setting it as a cause. This can make debugging harder.",
severity = WARNING,
tags = STYLE,
documentSuppression = false)
public final class UnusedException extends BugChecker implements CatchTreeMatcher {
private static final ImmutableSet<Modifier> VISIBILITY_MODIFIERS =
ImmutableSet.of(Modifier.PRIVATE, Modifier.PROTECTED, Modifier.PUBLIC);
@Override
public Description matchCatch(CatchTree tree, VisitorState state) {
if (isSuppressed(tree.getParameter(), state) || isSuppressedViaName(tree.getParameter())) {
return Description.NO_MATCH;
}
VarSymbol exceptionSymbol = ASTHelpers.getSymbol(tree.getParameter());
Type exceptionType = exceptionSymbol.asType();
if (isSameType(exceptionType, state.getSymtab().interruptedExceptionType, state)
|| isSameType(exceptionType, JAVA_IO_INTERRUPTEDIOEXCEPTION.get(state), state)) {
return Description.NO_MATCH;
}
AtomicBoolean symbolUsed = new AtomicBoolean(false);
((JCTree) tree)
.accept(
new TreeScanner() {
@Override
public void visitIdent(JCIdent identTree) {
if (exceptionSymbol.equals(identTree.sym)) {
symbolUsed.set(true);
}
}
});
if (symbolUsed.get()) {
return Description.NO_MATCH;
}
Set<JCThrow> throwTrees = new HashSet<>();
((JCTree) tree)
.accept(
new TreeScanner() {
@Override
public void visitThrow(JCThrow throwTree) {
super.visitThrow(throwTree);
throwTrees.add(throwTree);
}
// Don't visit nested try blocks.
@Override
public void visitTry(JCTry tryTree) {}
});
if (throwTrees.isEmpty()) {
return Description.NO_MATCH;
}
SuggestedFix.Builder allFixes = SuggestedFix.builder();
throwTrees.stream()
.filter(badThrow -> badThrow.getExpression() instanceof NewClassTree)
.forEach(
badThrow ->
fixConstructor((NewClassTree) badThrow.getExpression(), exceptionSymbol, state)
.ifPresent(allFixes::merge));
return describeMatch(tree, allFixes.build());
}
private static boolean isSuppressedViaName(VariableTree parameter) {
return parameter.getName().toString().startsWith("unused");
}
private static Optional<SuggestedFix> fixConstructor(
NewClassTree constructor, VarSymbol exception, VisitorState state) {
Symbol symbol = ASTHelpers.getSymbol(((JCNewClass) constructor).clazz);
if (!(symbol instanceof ClassSymbol)) {
return Optional.empty();
}
ImmutableList<MethodSymbol> constructors = ASTHelpers.getConstructors((ClassSymbol) symbol);
MethodSymbol constructorSymbol = ASTHelpers.getSymbol(constructor);
List<Type> types = getParameterTypes(constructorSymbol);
for (MethodSymbol proposedConstructor : constructors) {
List<Type> proposedTypes = getParameterTypes(proposedConstructor);
if (proposedTypes.size() != types.size() + 1) {
continue;
}
Set<Modifier> constructorVisibility =
Sets.intersection(constructorSymbol.getModifiers(), VISIBILITY_MODIFIERS);
Set<Modifier> replacementVisibility =
Sets.intersection(proposedConstructor.getModifiers(), VISIBILITY_MODIFIERS);
if (constructor.getClassBody() == null
&& !constructorVisibility.equals(replacementVisibility)) {
continue;
}
if (typesEqual(proposedTypes.subList(0, types.size()), types, state)
&& state.getTypes().isAssignable(exception.type, getLast(proposedTypes))) {
return Optional.of(
appendArgument(constructor, exception.getSimpleName().toString(), state, types));
}
}
return Optional.empty();
}
private static boolean typesEqual(List<Type> typesA, List<Type> typesB, VisitorState state) {
return Streams.zip(
typesA.stream(), typesB.stream(), (a, b) -> ASTHelpers.isSameType(a, b, state))
.allMatch(x -> x);
}
private static SuggestedFix appendArgument(
NewClassTree constructor, String exception, VisitorState state, List<Type> types) {
if (types.isEmpty()) {
// Skip past the opening '(' of the constructor.
String source = state.getSourceForNode(constructor);
int startPosition = getStartPosition(constructor);
int pos =
source.indexOf('(', state.getEndPosition(constructor.getIdentifier()) - startPosition)
+ startPosition
+ 1;
return SuggestedFix.replace(pos, pos, exception);
}
return SuggestedFix.postfixWith(
getLast(constructor.getArguments()), String.format(", %s", exception));
}
private static List<Type> getParameterTypes(MethodSymbol constructorSymbol) {
return constructorSymbol.type.getParameterTypes();
}
private static final Supplier<Type> JAVA_IO_INTERRUPTEDIOEXCEPTION =
VisitorState.memoize(state -> state.getTypeFromString("java.io.InterruptedIOException"));
}
| 7,771
| 38.85641
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LockOnNonEnclosingClassLiteral.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.util.ASTHelpers.stripParentheses;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.SynchronizedTreeMatcher;
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.MemberSelectTree;
import com.sun.source.tree.SynchronizedTree;
import com.sun.source.tree.Tree;
/**
* Bug checker to detect the usage of lock on the class other than the enclosing class of the code
* block.
*/
@BugPattern(
summary =
"Lock on the class other than the enclosing class of the code block can unintentionally"
+ " prevent the locked class being used properly.",
severity = SeverityLevel.WARNING)
public class LockOnNonEnclosingClassLiteral extends BugChecker implements SynchronizedTreeMatcher {
@Override
public Description matchSynchronized(SynchronizedTree tree, VisitorState state) {
ExpressionTree lock = stripParentheses(tree.getExpression());
Matcher<SynchronizedTree> lockOnEnclosingClassMatcher =
Matchers.enclosingClass(
(t, s) ->
ASTHelpers.getSymbol(t)
.equals(ASTHelpers.getSymbol(((MemberSelectTree) lock).getExpression())));
if (isClassLiteral(lock) && !lockOnEnclosingClassMatcher.matches(tree, state)) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
private static boolean isClassLiteral(Tree tree) {
if (tree.getKind() != Tree.Kind.MEMBER_SELECT) {
return false;
}
return ((MemberSelectTree) tree).getIdentifier().contentEquals("class");
}
}
| 2,535
| 36.294118
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MultipleParallelOrSequentialCalls.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.instanceMethod;
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.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.util.TreePath;
/**
* @author mariasam@google.com (Maria Sam)
*/
@BugPattern(
summary =
"Multiple calls to either parallel or sequential are unnecessary and cause confusion.",
severity = WARNING)
public class MultipleParallelOrSequentialCalls extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> STREAM =
instanceMethod().onDescendantOf("java.util.Collection").named("stream");
private static final Matcher<ExpressionTree> PARALLELSTREAM =
instanceMethod().onDescendantOf("java.util.Collection").named("parallelStream");
@Override
public Description matchMethodInvocation(MethodInvocationTree t, VisitorState state) {
if (STREAM.matches(t, state) || PARALLELSTREAM.matches(t, state)) {
int appropriateAmount = STREAM.matches(t, state) ? 1 : 0;
SuggestedFix.Builder builder = SuggestedFix.builder();
TreePath pathToMet =
ASTHelpers.findPathFromEnclosingNodeToTopLevel(
state.getPath(), MethodInvocationTree.class);
// counts how many instances of parallel / sequential
int count = 0;
String toReplace = "empty";
while (pathToMet != null) {
MethodInvocationTree methodInvocationTree = (MethodInvocationTree) pathToMet.getLeaf();
// this check makes it so that we stop iterating up once it's done
if (methodInvocationTree.getArguments().stream()
.map(m -> state.getSourceForNode(m))
.anyMatch(m -> m.contains(state.getSourceForNode(t)))) {
break;
}
if (methodInvocationTree.getMethodSelect() instanceof MemberSelectTree) {
MemberSelectTree memberSelectTree =
(MemberSelectTree) methodInvocationTree.getMethodSelect();
String memberSelectIdentifier = memberSelectTree.getIdentifier().toString();
// checks for the first instance of parallel / sequential
if (toReplace.equals("empty")
&& (memberSelectIdentifier.equals("parallel")
|| memberSelectIdentifier.equals("sequential"))) {
toReplace = memberSelectIdentifier.equals("parallel") ? "parallel" : "sequential";
}
// immediately removes any instances of the appropriate string
if (memberSelectIdentifier.equals(toReplace)) {
int endOfExpression = state.getEndPosition(memberSelectTree.getExpression());
builder.replace(endOfExpression, state.getEndPosition(methodInvocationTree), "");
count++;
}
}
pathToMet =
ASTHelpers.findPathFromEnclosingNodeToTopLevel(pathToMet, MethodInvocationTree.class);
}
// if there are too many parallel / sequential calls, then we describe match and actually
// use the builder's replacements and add a postfix
if (count > appropriateAmount) {
// parallel stream doesn't need a postfix
if (appropriateAmount == 1) {
builder.postfixWith(t, "." + toReplace + "()");
}
return describeMatch(t, builder.build());
}
}
return Description.NO_MATCH;
}
}
| 4,460
| 42.31068
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LambdaFunctionalInterface.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.ImmutableList.toImmutableList;
import static com.google.common.collect.Streams.findLast;
import static com.google.common.collect.Streams.stream;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static java.util.Optional.ofNullable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
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.ClassTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import java.util.Optional;
/**
* @author amesbah@google.com (Ali Mesbah)
*/
@BugPattern(
summary =
"Use Java's utility functional interfaces instead of Function<A, B> for primitive types.",
severity = SUGGESTION)
public class LambdaFunctionalInterface extends BugChecker implements MethodTreeMatcher {
private static final String JAVA_UTIL_FUNCTION_FUNCTION = "java.util.function.Function";
private static final String JAVA_LANG_NUMBER = "java.lang.Number";
private static final ImmutableMap<String, String> METHOD_MAPPINGS =
ImmutableMap.<String, String>builder()
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<java.lang.Double,java.lang.Double>",
"java.util.function.DoubleFunction<Double>")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<java.lang.Double,java.lang.Integer>",
"java.util.function.DoubleToIntFunction")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<java.lang.Double,java.lang.Long>",
"java.util.function.DoubleToLongFunction")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<java.lang.Double,T>",
"java.util.function.DoubleFunction<T>")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<java.lang.Integer,java.lang.Integer>",
"java.util.function.IntFunction<Integer>")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<java.lang.Integer,java.lang.Double>",
"java.util.function.IntToDoubleFunction")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<java.lang.Integer,java.lang.Long>",
"java.util.function.IntToLongFunction")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<java.lang.Integer,T>",
"java.util.function.IntFunction<T>")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<java.lang.Long,java.lang.Long>",
"java.util.function.LongFunction<Long>")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<java.lang.Long,java.lang.Integer>",
"java.util.function.LongToIntFunction")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<java.lang.Long,java.lang.Double>",
"java.util.function.LongToDoubleFunction")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<java.lang.Long,T>",
"java.util.function.LongFunction<T>")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<T,java.lang.Long>",
"java.util.function.ToLongFunction<T>")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<T,java.lang.Integer>",
"java.util.function.ToIntFunction<T>")
.put(
JAVA_UTIL_FUNCTION_FUNCTION + "<T,java.lang.Double>",
"java.util.function.ToDoubleFunction<T>")
.buildOrThrow();
private static final ImmutableMap<String, String> APPLY_MAPPINGS =
ImmutableMap.<String, String>builder()
.put("java.util.function.DoubleToIntFunction", "applyAsInt")
.put("java.util.function.DoubleToLongFunction", "applyAsLong")
.put("java.util.function.IntToDoubleFunction", "applyAsDouble")
.put("java.util.function.IntToLongFunction", "applyAsLong")
.put("java.util.function.LongToIntFunction", "applyAsInt")
.put("java.util.function.LongToDoubleFunction", "applyAsDouble")
.put("java.util.function.ToIntFunction<T>", "applyAsInt")
.put("java.util.function.ToDoubleFunction<T>", "applyAsDouble")
.put("java.util.function.ToLongFunction<T>", "applyAsLong")
.buildOrThrow();
/**
* Identifies methods with parameters that have a generic argument with Int, Long, or Double. If
* pre-conditions are met, it refactors them to the primitive specializations.
*
* <pre>PreConditions:
* (1): The method declaration has to be private (to do a safe refactoring)
* (2): Its parameters have to meet the following conditions:
* 2.1 Contain type java.util.function.Function
* 2.2 At least one argument type of the Function must be subtype of Number
* (3): All its invocations in the top-level enclosing class have to meet the following
* conditions as well:
* 3.1: lambda argument of Kind.LAMBDA_EXPRESSION
* 3.2: same as 2.1
* 3.3: same as 2.2
* </pre>
*
* <pre>
* Refactoring Changes for matched methods:
* (1) Add the imports
* (2) Change the method signature to use utility function instead of Function
* (3) Find and change the 'apply' calls to the corresponding applyAsT
* </pre>
*/
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
MethodSymbol methodSym = ASTHelpers.getSymbol(tree);
// precondition (1)
if (!ASTHelpers.canBeRemoved(methodSym, state)) {
return Description.NO_MATCH;
}
ImmutableList<Tree> params =
tree.getParameters().stream()
.filter(param -> hasFunctionAsArg(param, state))
.filter(
param ->
isFunctionArgSubtypeOf(
param, 0, state.getTypeFromString(JAVA_LANG_NUMBER), state)
|| isFunctionArgSubtypeOf(
param, 1, state.getTypeFromString(JAVA_LANG_NUMBER), state))
.collect(toImmutableList());
// preconditions (2) and (3)
if (params.isEmpty() || !methodCallsMeetConditions(methodSym, state)) {
return Description.NO_MATCH;
}
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
for (Tree param : params) {
getMappingForFunctionFromTree(param)
.ifPresent(
mappedFunction -> {
fixBuilder.addImport(getImportName(mappedFunction));
fixBuilder.replace(
param,
getFunctionName(mappedFunction) + " " + ASTHelpers.getSymbol(param).name);
refactorInternalApplyMethods(tree, fixBuilder, param, mappedFunction);
});
}
return describeMatch(tree, fixBuilder.build());
}
private void refactorInternalApplyMethods(
MethodTree tree, SuggestedFix.Builder fixBuilder, Tree param, String mappedFunction) {
getMappingForApply(mappedFunction)
.ifPresent(
apply -> {
tree.accept(
new TreeScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(MethodInvocationTree callTree, Void unused) {
if (getSymbol(callTree).name.contentEquals("apply")) {
Symbol receiverSym = getSymbol(getReceiver(callTree));
if (receiverSym != null
&& receiverSym.equals(ASTHelpers.getSymbol(param))) {
fixBuilder.replace(
callTree.getMethodSelect(), receiverSym.name + "." + apply);
}
}
return super.visitMethodInvocation(callTree, unused);
}
},
null);
});
}
private boolean methodCallsMeetConditions(Symbol sym, VisitorState state) {
ImmutableMultimap<String, MethodInvocationTree> methodCallMap =
methodCallsForSymbol(sym, getTopLevelClassTree(state));
if (methodCallMap.isEmpty()) {
// no method invocations for this method, safe to refactor
return true;
}
for (MethodInvocationTree methodInvocationTree : methodCallMap.values()) {
if (methodInvocationTree.getArguments().stream()
.filter(a -> a.getKind().equals(Kind.LAMBDA_EXPRESSION))
.filter(a -> hasFunctionAsArg(a, state))
.noneMatch(
a ->
isFunctionArgSubtypeOf(a, 0, state.getTypeFromString(JAVA_LANG_NUMBER), state)
|| isFunctionArgSubtypeOf(
a, 1, state.getTypeFromString(JAVA_LANG_NUMBER), state))) {
return false;
}
}
return true;
}
private static ClassTree getTopLevelClassTree(VisitorState state) {
return findLast(
stream(state.getPath().iterator())
.filter(ClassTree.class::isInstance)
.map(ClassTree.class::cast))
.orElseThrow(() -> new IllegalArgumentException("No enclosing class found"));
}
private ImmutableMultimap<String, MethodInvocationTree> methodCallsForSymbol(
Symbol sym, ClassTree classTree) {
ImmutableMultimap.Builder<String, MethodInvocationTree> methodMap = ImmutableMultimap.builder();
classTree.accept(
new TreeScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(MethodInvocationTree callTree, Void unused) {
MethodSymbol methodSymbol = getSymbol(callTree);
if (sym.equals(methodSymbol)) {
methodMap.put(methodSymbol.toString(), callTree);
}
return super.visitMethodInvocation(callTree, unused);
}
},
null);
return methodMap.build();
}
private static boolean hasFunctionAsArg(Tree param, VisitorState state) {
return ASTHelpers.isSameType(
ASTHelpers.getType(param), state.getTypeFromString(JAVA_UTIL_FUNCTION_FUNCTION), state);
}
private static boolean isFunctionArgSubtypeOf(
Tree param, int argIndex, Type type, VisitorState state) {
return ASTHelpers.isSubtype(
ASTHelpers.getType(param).getTypeArguments().get(argIndex), type, state);
}
private static Optional<String> getMappingForFunctionFromTree(Tree param) {
return ofNullable(ASTHelpers.getType(param)).flatMap(t -> getMappingForFunction(t.toString()));
}
private static Optional<String> getMappingForFunction(String function) {
return ofNullable(METHOD_MAPPINGS.get(function));
}
private static Optional<String> getMappingForApply(String apply) {
return ofNullable(APPLY_MAPPINGS.get(apply));
}
private static String getFunctionName(String fullyQualifiedName) {
return fullyQualifiedName.substring(fullyQualifiedName.lastIndexOf('.') + 1);
}
private static String getImportName(String fullyQualifiedName) {
int cutPosition = fullyQualifiedName.indexOf('<');
return (cutPosition < 0) ? fullyQualifiedName : fullyQualifiedName.substring(0, cutPosition);
}
}
| 12,302
| 40.846939
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnicodeInCode.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.Streams.concat;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ErrorProneTokens.getTokens;
import static com.google.errorprone.util.SourceCodeEscapers.javaCharEscaper;
import static java.lang.String.format;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableRangeSet;
import com.google.common.collect.Range;
import com.google.common.collect.RangeSet;
import com.google.common.collect.TreeRangeSet;
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.matchers.Description;
import com.google.errorprone.util.ErrorProneToken;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.tools.javac.parser.Tokens.TokenKind;
/** Bans using non-ASCII Unicode characters outside string literals and comments. */
@BugPattern(
severity = ERROR,
summary =
"Avoid using non-ASCII Unicode characters outside of comments and literals, as they can be"
+ " confusing.")
public final class UnicodeInCode extends BugChecker implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
RangeSet<Integer> violations = TreeRangeSet.create();
String sourceCode = state.getSourceCode().toString();
for (int i = 0; i < sourceCode.length(); ++i) {
if (!isAcceptableAscii(sourceCode, i)) {
violations.add(Range.closedOpen(i, i + 1));
}
}
if (violations.isEmpty()) {
return NO_MATCH;
}
ImmutableRangeSet<Integer> permissibleUnicodeRegions =
suppressedRegions(state).union(commentsAndLiterals(state, sourceCode));
for (var range : violations.asDescendingSetOfRanges()) {
if (!permissibleUnicodeRegions.encloses(range)) {
state.reportMatch(
buildDescription(new FixedPosition(tree, range.lowerEndpoint()))
.setMessage(
format(
"Avoid using non-ASCII Unicode character (%s) outside of comments and"
+ " literals, as they can be confusing.",
javaCharEscaper()
.escape(
sourceCode.substring(
range.lowerEndpoint(), range.upperEndpoint()))))
.build());
}
}
return NO_MATCH;
}
private static boolean isAcceptableAscii(String sourceCode, int i) {
char c = sourceCode.charAt(i);
if (isAcceptableAscii(c)) {
return true;
}
if (c == 0x1a && i == sourceCode.length() - 1) {
// javac inserts ASCII_SUB characters at the end of the input, see:
// https://github.com/google/error-prone/issues/3092
return true;
}
return false;
}
private static boolean isAcceptableAscii(char c) {
return (c >= 0x20 && c <= 0x7E) || c == '\n' || c == '\r' || c == '\t';
}
private static ImmutableRangeSet<Integer> commentsAndLiterals(VisitorState state, String source) {
ImmutableList<ErrorProneToken> tokens = getTokens(source, state.context);
return ImmutableRangeSet.unionOf(
concat(
tokens.stream()
.filter(
t ->
t.kind().equals(TokenKind.STRINGLITERAL)
|| t.kind().equals(TokenKind.CHARLITERAL))
.map(t -> Range.closed(t.pos(), t.endPos())),
tokens.stream()
.flatMap(t -> t.comments().stream())
.map(
c ->
Range.closed(
c.getSourcePos(0), c.getSourcePos(0) + c.getText().length())))
.collect(toImmutableList()));
}
}
| 4,811
| 39.1
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnsafeReflectiveConstructionCast.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.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
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.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.ExpressionTree;
import com.sun.source.tree.TypeCastTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import java.lang.reflect.Constructor;
/**
* Checks unsafe instance creation via reflection.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary =
"Prefer `asSubclass` instead of casting the result of `newInstance`,"
+ " to detect classes of incorrect type before invoking their constructors."
+ "This way, if the class is of the incorrect type,"
+ "it will throw an exception before invoking its constructor.",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public class UnsafeReflectiveConstructionCast extends BugChecker implements TypeCastTreeMatcher {
private static final Matcher<ExpressionTree> CLASS_FOR_NAME =
staticMethod().onClass(Class.class.getName()).named("forName");
private static final Matcher<ExpressionTree> CLASS_GET_CONSTRUCTOR =
instanceMethod()
.onExactClass(Class.class.getName())
.namedAnyOf("getDeclaredConstructor", "getConstructor");
private static final Matcher<ExpressionTree> CTOR_NEW_INSTANCE =
instanceMethod().onExactClass(Constructor.class.getName()).named("newInstance");
@Override
public Description matchTypeCast(TypeCastTree typeCastTree, VisitorState state) {
// typeCastTree = (Foo) Class.forName(someString).getDeclaredConstructor(...).newInstance(args);
ExpressionTree newInstanceTree = ASTHelpers.stripParentheses(typeCastTree.getExpression());
// tree = Class.forName(someString).getDeclaredConstructor(...).newInstance(args);
if (!CTOR_NEW_INSTANCE.matches(newInstanceTree, state)) {
return Description.NO_MATCH;
}
ExpressionTree treeReceiver = ASTHelpers.getReceiver(newInstanceTree);
// treeReceiver = Class.forName(someString).getDeclaredConstructor(...)
if (!CLASS_GET_CONSTRUCTOR.matches(treeReceiver, state)) {
return Description.NO_MATCH;
}
ExpressionTree classForName = ASTHelpers.getReceiver(treeReceiver);
// classForName = Class.forName(someString)
if (!CLASS_FOR_NAME.matches(classForName, state)) {
return Description.NO_MATCH;
}
Symbol typeSym = ASTHelpers.getSymbol(typeCastTree.getType());
if (typeSym == null) {
return Description.NO_MATCH;
}
Types types = state.getTypes();
Type typeCastTreeType = ASTHelpers.getType(typeCastTree.getType());
Type erasedType = types.erasure(typeCastTreeType);
if (ASTHelpers.isSameType(erasedType, state.getSymtab().objectType, state)) {
// unbounded type parameter
return Description.NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
String typeSource = SuggestedFixes.qualifyType(state, fix, erasedType);
// what we want :
// Class.forName(someString).asSubclass(Foo.class).getDeclaredConstructor().newInstance();
// add .asSubclass(Foo.class)
fix.postfixWith(classForName, ".asSubclass(" + typeSource + ".class)");
if (types.isSameType(typeCastTreeType, erasedType)) {
// remove the type
fix.replace(
getStartPosition(typeCastTree), getStartPosition(typeCastTree.getExpression()), "");
}
return describeMatch(classForName, fix.build());
}
}
| 4,787
| 43.747664
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LockOnBoxedPrimitive.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.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.isBoxedPrimitiveType;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.stripParentheses;
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.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.SynchronizedTreeMatcher;
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.suppliers.Suppliers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.SynchronizedTree;
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.VarSymbol;
import javax.lang.model.element.ElementKind;
/** Detects locks on boxed primitives. */
@BugPattern(
summary =
"It is dangerous to use a boxed primitive as a lock as it can unintentionally lead to"
+ " sharing a lock with another piece of code.",
severity = SeverityLevel.ERROR)
public class LockOnBoxedPrimitive extends BugChecker
implements SynchronizedTreeMatcher, MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> LOCKING_METHOD =
anyOf(
instanceMethod()
.anyClass()
.named("wait")
.withParametersOfType(ImmutableList.of(Suppliers.LONG_TYPE)),
instanceMethod()
.anyClass()
.named("wait")
.withParametersOfType(ImmutableList.of(Suppliers.LONG_TYPE, Suppliers.INT_TYPE)),
instanceMethod().anyClass().namedAnyOf("wait", "notify", "notifyAll").withNoParameters());
private static final Matcher<ExpressionTree> BOXED_PRIMITIVE = isBoxedPrimitiveType();
@Override
public Description matchSynchronized(SynchronizedTree tree, VisitorState state) {
ExpressionTree locked = stripParentheses(tree.getExpression());
if (!isDefinitelyBoxedPrimitive(locked, state)) {
return NO_MATCH;
}
return describeMatch(tree, createFix(locked, state));
}
private SuggestedFix createFix(ExpressionTree locked, VisitorState state) {
Symbol lock = getSymbol(locked);
if (lock == null) {
return SuggestedFix.emptyFix();
}
if (!lock.getKind().equals(ElementKind.FIELD)) {
return SuggestedFix.emptyFix();
}
SuggestedFix.Builder fix = SuggestedFix.builder();
String lockName = lock.getSimpleName() + "Lock";
new TreeScanner<Void, Void>() {
@Override
public Void visitVariable(VariableTree node, Void unused) {
VarSymbol sym = getSymbol(node);
if (lock.equals(sym)) {
String unboxedType =
SuggestedFixes.qualifyType(state, fix, state.getTypes().unboxedType(getType(node)));
fix.prefixWith(
node,
String.format(
"private final Object %s = new Object();\n@GuardedBy(\"%s\")",
lockName, lockName))
.replace(node.getType(), unboxedType)
.addImport("com.google.errorprone.annotations.concurrent.GuardedBy");
}
return super.visitVariable(node, null);
}
@Override
public Void visitSynchronized(SynchronizedTree node, Void aVoid) {
ExpressionTree expression = stripParentheses(node.getExpression());
if (lock.equals(getSymbol(expression))) {
fix.replace(expression, lockName);
}
return super.visitSynchronized(node, aVoid);
}
}.scan(state.getPath().getCompilationUnit(), null);
return fix.build();
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (LOCKING_METHOD.matches(tree, state)
&& isDefinitelyBoxedPrimitive(ASTHelpers.getReceiver(tree), state)) {
return describeMatch(tree.getMethodSelect());
}
return NO_MATCH;
}
/** Returns true if the expression tree is definitely referring to a boxed primitive. */
private static boolean isDefinitelyBoxedPrimitive(ExpressionTree tree, VisitorState state) {
return BOXED_PRIMITIVE.matches(tree, state);
}
}
| 5,505
| 40.089552
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DateFormatConstant.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.fixes.SuggestedFixes.renameVariable;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import com.google.common.base.Ascii;
import com.google.common.base.CaseFormat;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.fixes.Fix;
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.CompilationUnitTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import java.util.Objects;
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 = "DateFormat is not thread-safe, and should not be used as a constant field.",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public class DateFormatConstant extends BugChecker implements VariableTreeMatcher {
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
if (tree.getInitializer() == null) {
return NO_MATCH;
}
VarSymbol sym = ASTHelpers.getSymbol(tree);
if (sym.getKind() != ElementKind.FIELD) {
return NO_MATCH;
}
String name = sym.getSimpleName().toString();
if (!(sym.isStatic() && sym.getModifiers().contains(Modifier.FINAL))) {
return NO_MATCH;
}
if (!name.equals(Ascii.toUpperCase(name))) {
return NO_MATCH;
}
if (!isSubtype(getType(tree), JAVA_TEXT_DATEFORMAT.get(state), state)) {
return NO_MATCH;
}
SuggestedFix rename =
renameVariable(
tree,
CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, tree.getName().toString()),
state);
return buildDescription(tree)
.addFix(threadLocalFix(tree, state, sym, rename))
.addFix(rename)
.build();
}
private static Fix threadLocalFix(
VariableTree tree, VisitorState state, VarSymbol sym, SuggestedFix rename) {
SuggestedFix.Builder fix =
SuggestedFix.builder()
.merge(rename)
.replace(
tree.getType(),
String.format("ThreadLocal<%s>", state.getSourceForNode(tree.getType())))
.prefixWith(tree.getInitializer(), "ThreadLocal.withInitial(() -> ")
.postfixWith(tree.getInitializer(), ")");
CompilationUnitTree unit = state.getPath().getCompilationUnit();
unit.accept(
new TreeScanner<Void, Void>() {
@Override
public Void visitIdentifier(IdentifierTree tree, Void unused) {
if (Objects.equals(ASTHelpers.getSymbol(tree), sym)) {
fix.postfixWith(tree, ".get()");
}
return null;
}
},
null);
return fix.build();
}
private static final Supplier<Type> JAVA_TEXT_DATEFORMAT =
VisitorState.memoize(state -> state.getTypeFromString("java.text.DateFormat"));
}
| 4,249
| 37.288288
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CheckReturnValue.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.ImmutableList.toImmutableList;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.bugpatterns.CheckReturnValue.MessageTrailerStyle.NONE;
import static com.google.errorprone.bugpatterns.checkreturnvalue.AutoValueRules.autoBuilders;
import static com.google.errorprone.bugpatterns.checkreturnvalue.AutoValueRules.autoValueBuilders;
import static com.google.errorprone.bugpatterns.checkreturnvalue.AutoValueRules.autoValues;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ErrorMessages.annotationOnVoid;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ErrorMessages.conflictingAnnotations;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ErrorMessages.invocationResultIgnored;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ErrorMessages.methodReferenceIgnoresResult;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ExternalCanIgnoreReturnValue.externalIgnoreList;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ExternalCanIgnoreReturnValue.methodNameAndParams;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ExternalCanIgnoreReturnValue.surroundingClass;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ProtoRules.mutableProtos;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ProtoRules.protoBuilders;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ResultUsePolicy.EXPECTED;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ResultUsePolicy.OPTIONAL;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ResultUsePolicy.UNSPECIFIED;
import static com.google.errorprone.bugpatterns.checkreturnvalue.Rules.globalDefault;
import static com.google.errorprone.bugpatterns.checkreturnvalue.Rules.mapAnnotationSimpleName;
import static com.google.errorprone.fixes.SuggestedFix.emptyFix;
import static com.google.errorprone.fixes.SuggestedFixes.qualifyType;
import static com.google.errorprone.util.ASTHelpers.enclosingClass;
import static com.google.errorprone.util.ASTHelpers.enclosingElements;
import static com.google.errorprone.util.ASTHelpers.getAnnotationsWithSimpleName;
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.isGeneratedConstructor;
import static com.google.errorprone.util.ASTHelpers.isLocal;
import static com.sun.source.tree.Tree.Kind.METHOD;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.bugpatterns.checkreturnvalue.PackagesRule;
import com.google.errorprone.bugpatterns.checkreturnvalue.ResultUsePolicy;
import com.google.errorprone.bugpatterns.checkreturnvalue.ResultUsePolicyEvaluator;
import com.google.errorprone.bugpatterns.checkreturnvalue.ResultUsePolicyEvaluator.MethodInfo;
import com.google.errorprone.bugpatterns.checkreturnvalue.ResultUseRule.RuleScope;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions;
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.ClassTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
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.PackageSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import java.util.Optional;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.lang.model.element.ElementKind;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@BugPattern(
altNames = {"ResultOfMethodCallIgnored", "ReturnValueIgnored"},
summary = "The result of this call must be used",
documentSuppression = false, // We prefer `var unused`, as covered in CheckReturnValue.md.
severity = ERROR)
public class CheckReturnValue extends AbstractReturnValueIgnored
implements MethodTreeMatcher, ClassTreeMatcher {
private static final String CHECK_RETURN_VALUE = "CheckReturnValue";
private static final String CAN_IGNORE_RETURN_VALUE = "CanIgnoreReturnValue";
private static final ImmutableList<String> MUTUALLY_EXCLUSIVE_ANNOTATIONS =
ImmutableList.of(CHECK_RETURN_VALUE, CAN_IGNORE_RETURN_VALUE);
public static final String CHECK_ALL_CONSTRUCTORS = "CheckReturnValue:CheckAllConstructors";
public static final String CHECK_ALL_METHODS = "CheckReturnValue:CheckAllMethods";
static final String CRV_PACKAGES = "CheckReturnValue:Packages";
private static final MethodInfo<VisitorState, Symbol, MethodSymbol> METHOD_INFO =
new MethodInfo<>() {
@Override
public Stream<Symbol> scopeMembers(
RuleScope scope, MethodSymbol method, VisitorState context) {
switch (scope) {
case ENCLOSING_ELEMENTS:
return enclosingElements(method)
.filter(s -> s instanceof ClassSymbol || s instanceof PackageSymbol);
case GLOBAL:
case METHOD:
return Stream.of(method);
}
throw new AssertionError(scope);
}
@Override
public MethodKind getMethodKind(MethodSymbol method) {
switch (method.getKind()) {
case METHOD:
return MethodKind.METHOD;
case CONSTRUCTOR:
return MethodKind.CONSTRUCTOR;
default:
return MethodKind.OTHER;
}
}
};
private final MessageTrailerStyle messageTrailerStyle;
private final ResultUsePolicyEvaluator<VisitorState, Symbol, MethodSymbol> evaluator;
@Inject
CheckReturnValue(ErrorProneFlags flags, ConstantExpressions constantExpressions) {
super(constantExpressions);
this.messageTrailerStyle =
flags
.getEnum("CheckReturnValue:MessageTrailerStyle", MessageTrailerStyle.class)
.orElse(NONE);
ResultUsePolicyEvaluator.Builder<VisitorState, Symbol, MethodSymbol> builder =
ResultUsePolicyEvaluator.builder(METHOD_INFO)
.addRules(
// The order of these rules matters somewhat because when checking a method, we'll
// evaluate them in the order they're listed here and stop as soon as one of them
// returns a result. The order shouldn't matter because most of these, with the
// exception of perhaps the external ignore list, are equivalent in importance and
// we should be checking declarations to ensure they aren't producing differing
// results (i.e. ensuring an @AutoValue.Builder setter method isn't annotated @CRV).
mapAnnotationSimpleName(CHECK_RETURN_VALUE, EXPECTED),
mapAnnotationSimpleName(CAN_IGNORE_RETURN_VALUE, OPTIONAL),
protoBuilders(),
mutableProtos(),
autoValues(),
autoValueBuilders(),
autoBuilders(),
// This is conceptually lower precedence than the above rules.
externalIgnoreList());
flags
.getList(CRV_PACKAGES)
.ifPresent(packagePatterns -> builder.addRule(PackagesRule.fromPatterns(packagePatterns)));
this.evaluator =
builder
.addRule(
globalDefault(
defaultPolicy(flags, CHECK_ALL_METHODS),
defaultPolicy(flags, CHECK_ALL_CONSTRUCTORS)))
.build();
}
private static Optional<ResultUsePolicy> defaultPolicy(ErrorProneFlags flags, String flag) {
return flags.getBoolean(flag).map(check -> check ? EXPECTED : OPTIONAL);
}
/**
* Return a matcher for method invocations in which the method being called should be considered
* must-be-used.
*/
@Override
public Matcher<ExpressionTree> specializedMatcher() {
return (tree, state) -> getMethodPolicy(tree, state).equals(EXPECTED);
}
private static Optional<MethodSymbol> methodToInspect(ExpressionTree tree) {
// If we're in the middle of calling an anonymous class, we want to actually look at the
// corresponding constructor of the supertype (e.g.: if I extend a class with a @CIRV
// constructor that I delegate to, then my anonymous class's constructor should *also* be
// considered @CIRV).
if (tree instanceof NewClassTree) {
ClassTree anonymousClazz = ((NewClassTree) tree).getClassBody();
if (anonymousClazz != null) {
// There should be a single defined constructor in the anonymous class body
var constructor =
anonymousClazz.getMembers().stream()
.filter(MethodTree.class::isInstance)
.map(MethodTree.class::cast)
.filter(mt -> getSymbol(mt).isConstructor())
.findFirst();
// and its first statement should be a super() call to the method in question.
return constructor
.map(MethodTree::getBody)
.map(block -> block.getStatements().get(0))
.map(ExpressionStatementTree.class::cast)
.map(ExpressionStatementTree::getExpression)
.map(MethodInvocationTree.class::cast)
.map(ASTHelpers::getSymbol);
}
}
return methodSymbol(tree);
}
private static Optional<MethodSymbol> methodSymbol(ExpressionTree tree) {
Symbol sym = ASTHelpers.getSymbol(tree);
return sym instanceof MethodSymbol ? Optional.of((MethodSymbol) sym) : Optional.empty();
}
@Override
public ResultUsePolicy getMethodPolicy(ExpressionTree expression, VisitorState state) {
return methodToInspect(expression)
.map(method -> evaluator.evaluate(method, state))
.orElse(UNSPECIFIED);
}
@Override
public boolean isCovered(ExpressionTree tree, VisitorState state) {
return methodToInspect(tree).stream()
.flatMap(method -> evaluator.evaluations(method, state))
.findFirst()
.isPresent();
}
@Override
public ImmutableMap<String, ?> getMatchMetadata(ExpressionTree tree, VisitorState state) {
return methodToInspect(tree).stream()
.flatMap(method -> evaluator.evaluations(method, state))
.findFirst()
.map(
evaluation ->
ImmutableMap.of(
"rule", evaluation.rule(),
"policy", evaluation.policy(),
"scope", evaluation.scope()))
.orElse(ImmutableMap.of());
}
/**
* Validate {@code @CheckReturnValue} and {@link CanIgnoreReturnValue} usage on methods.
*
* <p>The annotations should not both be applied to the same method.
*
* <p>The annotations should not be applied to void-returning methods. Doing so makes no sense,
* because there is no return value to check.
*/
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
MethodSymbol method = ASTHelpers.getSymbol(tree);
ImmutableList<String> presentAnnotations = presentCrvRelevantAnnotations(method);
switch (presentAnnotations.size()) {
case 0:
return Description.NO_MATCH;
case 1:
break;
default:
// TODO(cgdecker): We can check this with evaluator.checkForConflicts now, though I want to
// think more about how we build and format error messages in that.
return buildDescription(tree)
.setMessage(conflictingAnnotations(presentAnnotations, "method"))
.build();
}
if (method.getKind() != ElementKind.METHOD) {
// skip constructors (which javac thinks are void-returning)
return Description.NO_MATCH;
}
if (!ASTHelpers.isVoidType(method.getReturnType(), state)) {
return Description.NO_MATCH;
}
String message = annotationOnVoid(presentAnnotations.get(0), "methods");
return buildDescription(tree).setMessage(message).build();
}
private static ImmutableList<String> presentCrvRelevantAnnotations(Symbol symbol) {
return MUTUALLY_EXCLUSIVE_ANNOTATIONS.stream()
.filter(a -> hasDirectAnnotationWithSimpleName(symbol, a))
.collect(toImmutableList());
}
/**
* Validate that at most one of {@code CheckReturnValue} and {@code CanIgnoreReturnValue} are
* applied to a class (or interface or enum).
*/
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
ImmutableList<String> presentAnnotations = presentCrvRelevantAnnotations(getSymbol(tree));
if (presentAnnotations.size() > 1) {
return buildDescription(tree)
.setMessage(conflictingAnnotations(presentAnnotations, "class"))
.build();
}
return Description.NO_MATCH;
}
private Description describeInvocationResultIgnored(
ExpressionTree invocationTree, String shortCall, MethodSymbol symbol, VisitorState state) {
String assignmentToUnused = "var unused = ...";
String message =
invocationResultIgnored(shortCall, assignmentToUnused, apiTrailer(symbol, state));
return buildDescription(invocationTree)
.addFix(fixAtDeclarationSite(symbol, state))
.addAllFixes(fixesAtCallSite(invocationTree, state))
.setMessage(message)
.build();
}
@Override
protected Description describeReturnValueIgnored(MethodInvocationTree tree, VisitorState state) {
MethodSymbol symbol = getSymbol(tree);
String shortCall = symbol.name + (tree.getArguments().isEmpty() ? "()" : "(...)");
return describeInvocationResultIgnored(tree, shortCall, symbol, state);
}
@Override
protected Description describeReturnValueIgnored(NewClassTree tree, VisitorState state) {
MethodSymbol symbol = getSymbol(tree);
String shortCall =
"new "
+ state.getSourceForNode(tree.getIdentifier())
+ (tree.getArguments().isEmpty() ? "()" : "(...)");
return describeInvocationResultIgnored(tree, shortCall, symbol, state);
}
@Override
protected Description describeReturnValueIgnored(MemberReferenceTree tree, VisitorState state) {
MethodSymbol symbol = getSymbol(tree);
Type type = state.getTypes().memberType(getType(tree.getQualifierExpression()), symbol);
String parensAndMaybeEllipsis = type.getParameterTypes().isEmpty() ? "()" : "(...)";
String shortCall =
(tree.getMode() == ReferenceMode.NEW
? "new " + state.getSourceForNode(tree.getQualifierExpression())
: tree.getName())
+ parensAndMaybeEllipsis;
String implementedMethod =
getType(tree).asElement().getSimpleName()
+ "."
+ state.getTypes().findDescriptorSymbol(getType(tree).asElement()).getSimpleName();
String methodReference = state.getSourceForNode(tree);
String assignmentLambda = parensAndMaybeEllipsis + " -> { var unused = ...; }";
String message =
methodReferenceIgnoresResult(
shortCall,
methodReference,
implementedMethod,
assignmentLambda,
apiTrailer(symbol, state));
return buildDescription(tree)
.setMessage(message)
.addFix(fixAtDeclarationSite(symbol, state))
.build();
}
private String apiTrailer(MethodSymbol symbol, VisitorState state) {
// (isLocal returns true for both local classes and anonymous classes. That's good for us.)
if (isLocal(enclosingClass(symbol))) {
/*
* We don't have a defined format for members of local and anonymous classes. After all, their
* generated class names can change easily as other such classes are introduced.
*/
return "";
}
switch (messageTrailerStyle) {
case NONE:
return "";
case API_ERASED_SIGNATURE:
return "\n\nFull API: "
+ surroundingClass(symbol)
+ "#"
+ methodNameAndParams(symbol, state.getTypes());
}
throw new AssertionError();
}
enum MessageTrailerStyle {
NONE,
API_ERASED_SIGNATURE,
}
/** Returns a fix that adds {@code @CanIgnoreReturnValue} to the given symbol, if possible. */
private static Fix fixAtDeclarationSite(MethodSymbol symbol, VisitorState state) {
MethodTree method = findDeclaration(symbol, state);
if (method == null || isGeneratedConstructor(method)) {
return emptyFix();
}
SuggestedFix.Builder fix = SuggestedFix.builder();
fix.prefixWith(
method, "@" + qualifyType(state, fix, CanIgnoreReturnValue.class.getName()) + " ");
getAnnotationsWithSimpleName(method.getModifiers().getAnnotations(), CHECK_RETURN_VALUE)
.forEach(fix::delete);
fix.setShortDescription("Annotate the method with @CanIgnoreReturnValue");
return fix.build();
}
private static @Nullable MethodTree findDeclaration(Symbol symbol, VisitorState state) {
JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(state.context);
TreePath declPath = Trees.instance(javacEnv).getPath(symbol);
// Skip fields declared in other compilation units since we can't make a fix for them here.
if (declPath != null
&& declPath.getCompilationUnit() == state.getPath().getCompilationUnit()
&& (declPath.getLeaf().getKind() == METHOD)) {
return (MethodTree) declPath.getLeaf();
}
return null;
}
}
| 19,134
| 43.396752
| 114
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AlreadyChecked.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.Multisets.removeOccurrences;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static java.lang.String.format;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions.ConstantExpression;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions.Truthiness;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.ThrowTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Set;
import javax.inject.Inject;
import org.checkerframework.checker.nullness.qual.Nullable;
/** Bugpattern to find conditions which are checked more than once. */
@BugPattern(severity = WARNING, summary = "This condition has already been checked.")
public final class AlreadyChecked extends BugChecker implements CompilationUnitTreeMatcher {
private final ConstantExpressions constantExpressions;
@Inject
AlreadyChecked(ConstantExpressions constantExpressions) {
this.constantExpressions = constantExpressions;
}
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
new IfScanner(state).scan(state.getPath(), null);
return NO_MATCH;
}
/** Scans a compilation unit, keeping track of which things are known to be true and false. */
private final class IfScanner extends SuppressibleTreePathScanner<Void, Void> {
private final Deque<TreePath> enclosingMethod = new ArrayDeque<>();
private final Deque<Set<ConstantExpression>> truthsInMethod = new ArrayDeque<>();
private final Deque<Set<ConstantExpression>> falsehoodsInMethod = new ArrayDeque<>();
private final Multiset<ConstantExpression> truths = HashMultiset.create();
private final Multiset<ConstantExpression> falsehoods = HashMultiset.create();
private final VisitorState state;
private IfScanner(VisitorState state) {
super(state);
this.state = state;
}
@Override
public Void visitIf(IfTree tree, Void unused) {
scan(tree.getCondition(), null);
Truthiness truthiness =
constantExpressions.truthiness(tree.getCondition(), /* not= */ false, state);
withinScope(truthiness, tree.getThenStatement());
withinScope(
constantExpressions.truthiness(tree.getCondition(), /* not= */ true, state),
tree.getElseStatement());
return null;
}
@Override
public Void visitReturn(ReturnTree tree, Void unused) {
super.visitReturn(tree, null);
handleMethodExitingStatement();
return null;
}
@Override
public Void visitThrow(ThrowTree tree, Void unused) {
super.visitThrow(tree, null);
handleMethodExitingStatement();
return null;
}
private void handleMethodExitingStatement() {
TreePath ifPath = getCurrentPath().getParentPath();
Tree previous = getCurrentPath().getLeaf();
while (ifPath != null && ifPath.getLeaf() instanceof BlockTree) {
previous = ifPath.getLeaf();
ifPath = ifPath.getParentPath();
}
if (ifPath == null) {
return;
}
TreePath methodPath = escapeBlock(ifPath.getParentPath());
if (methodPath == null || !(ifPath.getLeaf() instanceof IfTree)) {
return;
}
IfTree ifTree = (IfTree) ifPath.getLeaf();
boolean then = ifTree.getThenStatement().equals(previous);
if (!enclosingMethod.isEmpty()
&& enclosingMethod.getLast().getLeaf().equals(methodPath.getLeaf())) {
Truthiness truthiness =
constantExpressions.truthiness(ifTree.getCondition(), /* not= */ then, state);
truths.addAll(truthiness.requiredTrue());
falsehoods.addAll(truthiness.requiredFalse());
truthsInMethod.getLast().addAll(truthiness.requiredTrue());
falsehoodsInMethod.getLast().addAll(truthiness.requiredFalse());
}
}
private @Nullable TreePath escapeBlock(@Nullable TreePath path) {
while (path != null && path.getLeaf() instanceof BlockTree) {
path = path.getParentPath();
}
return path;
}
@Override
public Void visitLambdaExpression(LambdaExpressionTree tree, Void unused) {
withinMethod(() -> super.visitLambdaExpression(tree, null));
return null;
}
@Override
public Void visitMethod(MethodTree tree, Void unused) {
withinMethod(() -> super.visitMethod(tree, null));
return null;
}
private void withinMethod(Runnable runnable) {
enclosingMethod.addLast(getCurrentPath());
truthsInMethod.addLast(new HashSet<>());
falsehoodsInMethod.addLast(new HashSet<>());
runnable.run();
enclosingMethod.removeLast();
removeOccurrences(truths, truthsInMethod.removeLast());
removeOccurrences(falsehoods, falsehoodsInMethod.removeLast());
}
private void withinScope(Truthiness truthiness, Tree tree) {
truths.addAll(truthiness.requiredTrue());
falsehoods.addAll(truthiness.requiredFalse());
scan(tree, null);
removeOccurrences(truths, truthiness.requiredTrue());
removeOccurrences(falsehoods, truthiness.requiredFalse());
}
@Override
public Void visitConditionalExpression(ConditionalExpressionTree tree, Void unused) {
scan(tree.getCondition(), null);
Truthiness truthiness =
constantExpressions.truthiness(tree.getCondition(), /* not= */ false, state);
withinScope(truthiness, tree.getTrueExpression());
withinScope(
constantExpressions.truthiness(tree.getCondition(), /* not= */ true, state),
tree.getFalseExpression());
return null;
}
@Override
public Void scan(Tree tree, Void unused) {
// Fast path out if we don't know anything.
if (truths.isEmpty() && falsehoods.isEmpty()) {
return super.scan(tree, null);
}
// As a heuristic, it's fairly harmless to do `if (a) { foo(a); }`. It's possibly nicer than
// a parameter comment for a literal boolean.
if (getCurrentPath().getLeaf() instanceof MethodInvocationTree
|| getCurrentPath().getLeaf() instanceof NewClassTree) {
return super.scan(tree, null);
}
if (!(tree instanceof ExpressionTree)
|| !isSameType(getType(tree), state.getSymtab().booleanType, state)) {
return super.scan(tree, null);
}
constantExpressions
.constantExpression((ExpressionTree) tree, state)
.ifPresent(
e -> {
if (truths.contains(e)) {
state.reportMatch(
buildDescription(tree)
.setMessage(
format(
"This condition (on %s) is already known to be true; it (or its"
+ " complement) has already been checked.",
e))
.build());
}
if (falsehoods.contains(e)) {
state.reportMatch(
buildDescription(tree)
.setMessage(
format(
"This condition (on %s) is known to be false here. It (or its"
+ " complement) has already been checked.",
e))
.build());
}
});
return super.scan(tree, null);
}
}
}
| 9,234
| 37.004115
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/VariableNameSameAsType.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.util.ASTHelpers.getType;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
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.VariableTree;
import com.sun.tools.javac.code.Symbol;
import javax.lang.model.element.Name;
/** Check for variables and types with the same name */
@BugPattern(
summary =
"variableName and type with the same name "
+ "would refer to the static field instead of the class",
severity = WARNING)
public class VariableNameSameAsType extends BugChecker implements VariableTreeMatcher {
@Override
public Description matchVariable(VariableTree varTree, VisitorState state) {
Name varName = varTree.getName();
Matcher<VariableTree> nameSameAsType =
Matchers.variableType(
(typeTree, s) -> {
Symbol typeSymbol = ASTHelpers.getSymbol(typeTree);
if (typeSymbol != null) {
return typeSymbol.getSimpleName().contentEquals(varName);
}
return false;
});
if (!nameSameAsType.matches(varTree, state)) {
return Description.NO_MATCH;
}
String message =
String.format(
"Variable named %s has the type %s. Calling methods using \"%s.something\" are "
+ "difficult to distinguish between static and instance methods.",
varName, SuggestedFixes.prettyType(getType(varTree), /* state= */ null), varName);
return buildDescription(varTree).setMessage(message).build();
}
}
| 2,578
| 37.492537
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/PrimitiveArrayPassedToVarargsMethod.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.Iterables.getLast;
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.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodInvocationTree;
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.Type.ArrayType;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import java.util.List;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@BugPattern(
summary = "Passing a primitive array to a varargs method is usually wrong",
severity = WARNING)
public class PrimitiveArrayPassedToVarargsMethod extends BugChecker
implements MethodInvocationTreeMatcher {
@Override
public Description matchMethodInvocation(MethodInvocationTree t, VisitorState state) {
return isVarargs(t, state) ? describeMatch(t) : NO_MATCH;
}
/**
* Assuming the argument in the varargs position is a single one of type int[], here is the truth
* table: Param type Should return Why int... false Exact type match int[]... false Exact type
* match for the array element type T... true Will cause boxing Object... true Will cause boxing
*/
private static boolean isVarargs(MethodInvocationTree tree, VisitorState state) {
MethodSymbol symbol = ASTHelpers.getSymbol(tree);
// Bail out quickly if the method is not varargs
if (!symbol.isVarArgs()) {
return false;
}
// Last param must be varags
List<VarSymbol> params = symbol.getParameters();
int varargsPosition = params.size() - 1;
ArrayType varargsParamType = (ArrayType) getLast(params).type;
// Is the argument at the varargsPosition the only varargs argument and a primitive array?
JCMethodInvocation methodInvocation = (JCMethodInvocation) tree;
List<JCExpression> arguments = methodInvocation.getArguments();
Types types = state.getTypes();
if (arguments.size() != params.size()) {
return false;
}
Type varargsArgumentType = arguments.get(varargsPosition).type;
if (!types.isArray(varargsArgumentType) || !types.elemtype(varargsArgumentType).isPrimitive()) {
return false;
}
// Do the param and argument types actually match? i.e. can boxing even happen?
return !(types.isSameType(varargsParamType, varargsArgumentType)
|| types.isSameType(varargsParamType.getComponentType(), varargsArgumentType));
}
}
| 3,520
| 39.471264
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CompareToZero.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.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.constValue;
import com.google.common.collect.ImmutableMap;
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.util.ASTHelpers;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.source.util.TreePath;
/** Suggests comparing the result of {@code compareTo} to only {@code 0}. */
@BugPattern(
summary =
"The result of #compareTo or #compare should only be compared to 0. It is an "
+ "implementation detail whether a given type returns strictly the values {-1, 0, +1} "
+ "or others.",
severity = WARNING)
public final class CompareToZero extends BugChecker implements MethodInvocationTreeMatcher {
private static final String SUGGEST_IMPROVEMENT =
"It is generally more robust (and readable) to compare the result of #compareTo/#compare to "
+ "0. Although the suggested replacement is identical in this case, we'd suggest it for "
+ "consistency.";
private static final ImmutableSet<Kind> COMPARISONS =
ImmutableSet.of(
Kind.EQUAL_TO,
Kind.NOT_EQUAL_TO,
Kind.LESS_THAN,
Kind.LESS_THAN_EQUAL,
Kind.GREATER_THAN,
Kind.GREATER_THAN_EQUAL);
private static final ImmutableMap<Kind, Kind> REVERSE =
ImmutableMap.of(
Kind.LESS_THAN, Kind.GREATER_THAN,
Kind.LESS_THAN_EQUAL, Kind.GREATER_THAN_EQUAL,
Kind.GREATER_THAN, Kind.LESS_THAN,
Kind.GREATER_THAN_EQUAL, Kind.LESS_THAN_EQUAL);
private static final ImmutableSet<Kind> OTHER_STRANGE_OPERATIONS =
ImmutableSet.of(Kind.PLUS, Kind.MINUS);
private static final Matcher<ExpressionTree> COMPARE_TO =
anyOf(
instanceMethod().onDescendantOf("java.lang.Comparable").named("compareTo"),
instanceMethod().onDescendantOf("java.util.Comparator").named("compare"));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (COMPARE_TO.matches(tree, state)) {
new Visitor().visitParent(state);
}
return NO_MATCH;
}
private final class Visitor extends SimpleTreeVisitor<Void, VisitorState> {
private Tree child;
@Override
public Void visitParenthesized(ParenthesizedTree parenthesizedTree, VisitorState state) {
return visitParent(state);
}
@Override
public Void visitBinary(BinaryTree binaryTree, VisitorState state) {
Kind kind = binaryTree.getKind();
// `child` is the Tree we had before bubbling up to this BinaryTree. Check which side it
// corresponds to.
boolean reversed = binaryTree.getRightOperand() == child;
ExpressionTree comparatorSide =
reversed ? binaryTree.getRightOperand() : binaryTree.getLeftOperand();
ExpressionTree otherSide =
reversed ? binaryTree.getLeftOperand() : binaryTree.getRightOperand();
if (OTHER_STRANGE_OPERATIONS.contains(kind)) {
// Consider string concatenation with the result of compareTo to be OK, but otherwise
// raise the alarm.
if (!(kind.equals(Kind.PLUS)
&& ASTHelpers.isSameType(
ASTHelpers.getType(otherSide), state.getSymtab().stringType, state))) {
state.reportMatch(describeMatch(binaryTree));
}
return null;
}
Integer constantInt = constValue(otherSide, Integer.class);
if (constantInt == null) {
return null;
}
if (constantInt == 0) {
return null;
}
if (binaryTree.getKind() == Kind.EQUAL_TO) {
SuggestedFix fix =
generateFix(binaryTree, state, comparatorSide, constantInt < 0 ? "<" : ">");
state.reportMatch(describeMatch(binaryTree, fix));
return null;
}
if (reversed) {
kind = REVERSE.get(kind);
}
if (kind == null) {
return null;
}
if ((kind == Kind.GREATER_THAN || kind == Kind.NOT_EQUAL_TO) && constantInt == -1) {
SuggestedFix fix = generateFix(binaryTree, state, comparatorSide, ">=");
state.reportMatch(describeMatch(binaryTree, fix));
return null;
}
if ((kind == Kind.LESS_THAN || kind == Kind.NOT_EQUAL_TO) && constantInt == 1) {
SuggestedFix fix = generateFix(binaryTree, state, comparatorSide, "<=");
state.reportMatch(describeMatch(binaryTree, fix));
return null;
}
if (kind == Kind.LESS_THAN_EQUAL && constantInt == -1) {
SuggestedFix fix = generateFix(binaryTree, state, comparatorSide, "<");
state.reportMatch(
buildDescription(binaryTree).setMessage(SUGGEST_IMPROVEMENT).addFix(fix).build());
return null;
}
if (kind == Kind.GREATER_THAN_EQUAL && constantInt == 1) {
SuggestedFix fix = generateFix(binaryTree, state, comparatorSide, ">");
state.reportMatch(
buildDescription(binaryTree).setMessage(SUGGEST_IMPROVEMENT).addFix(fix).build());
return null;
}
if (COMPARISONS.contains(binaryTree.getKind())) {
state.reportMatch(describeMatch(binaryTree));
}
return null;
}
private SuggestedFix generateFix(
BinaryTree binaryTree,
VisitorState state,
ExpressionTree comparatorSide,
String comparator) {
return SuggestedFix.replace(
binaryTree, String.format("%s %s 0", state.getSourceForNode(comparatorSide), comparator));
}
private Void visitParent(VisitorState state) {
child = state.getPath().getLeaf();
TreePath parentPath = state.getPath().getParentPath();
return visit(parentPath.getLeaf(), state.withPath(parentPath));
}
}
}
| 7,209
| 38.615385
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NonOverridingEquals.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.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.enclosingClass;
import static com.google.errorprone.matchers.Matchers.hasMethod;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.isStatic;
import static com.google.errorprone.matchers.Matchers.methodHasParameters;
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.Matchers.not;
import static com.google.errorprone.matchers.Matchers.variableType;
import static com.google.errorprone.suppliers.Suppliers.BOOLEAN_TYPE;
import static com.google.errorprone.suppliers.Suppliers.JAVA_LANG_BOOLEAN_TYPE;
import static com.google.errorprone.suppliers.Suppliers.OBJECT_TYPE;
import static com.sun.tools.javac.code.Flags.ENUM;
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.matchers.Matcher;
import com.google.errorprone.matchers.MethodVisibility.Visibility;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.Name;
/** Bug checker for equals methods that don't actually override equals. */
@BugPattern(
summary = "equals method doesn't override Object.equals",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public class NonOverridingEquals extends BugChecker implements MethodTreeMatcher {
private static final String MESSAGE_BASE = "equals method doesn't override Object.equals";
/**
* Matches any method definition that: 1) is named `equals` 2) takes a single argument of a type
* other than Object 3) returns a boolean or Boolean
*/
private static final Matcher<MethodTree> MATCHER =
allOf(
methodIsNamed("equals"),
methodHasParameters(variableType(not(isSameType("java.lang.Object")))),
anyOf(methodReturns(BOOLEAN_TYPE), methodReturns(JAVA_LANG_BOOLEAN_TYPE)));
/** Matches if the enclosing class overrides Object#equals. */
private static final Matcher<MethodTree> enclosingClassOverridesEquals =
enclosingClass(
hasMethod(
allOf(
methodIsNamed("equals"),
methodReturns(BOOLEAN_TYPE),
methodHasParameters(variableType(isSameType(OBJECT_TYPE))),
not(isStatic()))));
/**
* Matches method declarations for which we cannot provide a fix. Our default fix rewrites the
* equals method to override Object.equals. In these (uncommon) cases, our rewrite algorithm
* doesn't work:
*
* <ul>
* <li>the method is static
* <li>the method is not public
* <li>the method returns a boxed Boolean
* </ul>
*/
private static final Matcher<MethodTree> noFixMatcher =
anyOf(
isStatic(),
not(methodHasVisibility(Visibility.PUBLIC)),
methodReturns(JAVA_LANG_BOOLEAN_TYPE));
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
if (!MATCHER.matches(methodTree, state)) {
return Description.NO_MATCH;
}
// If an overriding equals method has already been defined in the enclosing class, assume
// this is a type-specific helper method and give advice to either inline it or rename it.
if (enclosingClassOverridesEquals.matches(methodTree, state)) {
return buildDescription(methodTree)
.setMessage(
MESSAGE_BASE
+ "; if this is a type-specific helper for a method that does"
+ " override Object.equals, either inline it into the callers or rename it to"
+ " avoid ambiguity")
.build();
}
// Don't provide a fix if the method is static, non-public, or returns a boxed Boolean
if (noFixMatcher.matches(methodTree, state)) {
return describeMatch(methodTree);
}
JCClassDecl cls = (JCClassDecl) state.findEnclosing(ClassTree.class);
if ((cls.getModifiers().flags & ENUM) != 0) {
/* If the enclosing class is an enum, then just delete the equals method since enums
* should always be compared for reference equality. Enum defines a final equals method for
* just this reason. */
return buildDescription(methodTree)
.setMessage(
MESSAGE_BASE
+ "; enum instances can safely be compared by reference "
+ "equality, so please delete this")
.addFix(SuggestedFix.delete(methodTree))
.build();
} else {
/* Otherwise, change the covariant equals method to override Object.equals. */
SuggestedFix.Builder fix = SuggestedFix.builder();
// Add @Override annotation if not present.
if (ASTHelpers.getAnnotation(methodTree, Override.class) == null) {
fix.prefixWith(methodTree, "@Override\n");
}
// Change method signature, substituting Object for parameter type.
JCTree parameterType = (JCTree) methodTree.getParameters().get(0).getType();
Name parameterName = ((JCVariableDecl) methodTree.getParameters().get(0)).getName();
fix.replace(parameterType, "Object");
// If there is a method body...
if (methodTree.getBody() != null) {
// Add type check at start
String typeCheckStmt =
"if (!("
+ parameterName
+ " instanceof "
+ state.getSourceForNode(parameterType)
+ ")) {\n"
+ " return false;\n"
+ "}\n";
fix.prefixWith(methodTree.getBody().getStatements().get(0), typeCheckStmt);
// Cast all uses of the parameter name using a recursive TreeScanner.
new CastScanner()
.scan(
methodTree.getBody(),
new CastState(parameterName, state.getSourceForNode(parameterType), fix));
}
return describeMatch(methodTree, fix.build());
}
}
private static class CastState {
final Name name;
final String castToType;
final SuggestedFix.Builder fix;
public CastState(Name name, String castToType, SuggestedFix.Builder fix) {
this.name = name;
this.castToType = castToType;
this.fix = fix;
}
}
/** A Scanner used to replace all references to a variable with a casted version. */
private static class CastScanner extends TreeScanner<Void, CastState> {
@Override
public Void visitIdentifier(IdentifierTree node, CastState state) {
if (state.name.equals(node.getName())) {
state.fix.replace(node, "((" + state.castToType + ") " + state.name + ")");
}
return super.visitIdentifier(node, state);
}
}
}
| 8,175
| 39.676617
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/RequiredModifiersChecker.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.LinkType.NONE;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.MoreAnnotations.getValue;
import com.google.common.collect.Sets;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
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.AnnotationTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Symbol;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.SimpleAnnotationValueVisitor8;
/**
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
name = "RequiredModifiers",
summary =
"This annotation is missing required modifiers as specified by its "
+ "@RequiredModifiers annotation",
linkType = NONE,
severity = ERROR)
public class RequiredModifiersChecker extends BugChecker implements AnnotationTreeMatcher {
private static final String REQUIRED_MODIFIERS =
"com.google.errorprone.annotations.RequiredModifiers";
@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
Symbol sym = ASTHelpers.getSymbol(tree);
if (sym == null) {
return NO_MATCH;
}
Attribute.Compound annotation =
sym.getRawAttributes().stream()
.filter(a -> a.type.tsym.getQualifiedName().contentEquals(REQUIRED_MODIFIERS))
.findAny()
.orElse(null);
if (annotation == null) {
return NO_MATCH;
}
Set<Modifier> requiredModifiers = new LinkedHashSet<>();
getValue(annotation, "value").ifPresent(a -> getModifiers(requiredModifiers, a));
getValue(annotation, "modifier").ifPresent(a -> getModifiers(requiredModifiers, a));
if (requiredModifiers.isEmpty()) {
return NO_MATCH;
}
Tree parent = state.getPath().getParentPath().getLeaf();
if (!(parent instanceof ModifiersTree)) {
// e.g. An annotated package name
return NO_MATCH;
}
Set<Modifier> missing = Sets.difference(requiredModifiers, ((ModifiersTree) parent).getFlags());
if (missing.isEmpty()) {
return NO_MATCH;
}
String annotationName = ASTHelpers.getAnnotationName(tree);
String nameString =
annotationName != null
? String.format("The annotation '@%s'", annotationName)
: "This annotation";
String customMessage =
String.format(
"%s has specified that it must be used together with the following modifiers: %s",
nameString, missing);
return buildDescription(tree)
.addFix(
SuggestedFixes.addModifiers(
state.getPath().getParentPath().getParentPath().getLeaf(),
(ModifiersTree) parent,
state,
missing)
.orElse(SuggestedFix.emptyFix()))
.setMessage(customMessage)
.build();
}
private static void getModifiers(Collection<Modifier> modifiers, Attribute attribute) {
class Visitor extends SimpleAnnotationValueVisitor8<Void, Void> {
@Override
public Void visitEnumConstant(VariableElement c, Void unused) {
modifiers.add(Modifier.valueOf(c.getSimpleName().toString()));
return null;
}
@Override
public Void visitArray(List<? extends AnnotationValue> vals, Void unused) {
vals.forEach(val -> val.accept(this, null));
return null;
}
}
attribute.accept(new Visitor(), null);
}
}
| 4,781
| 35.227273
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnusedNestedClass.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.Ascii.toLowerCase;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.canBeRemoved;
import static com.google.errorprone.util.ASTHelpers.enclosingClass;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.shouldKeep;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
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.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/** Bugpattern to detect unused nested classes. */
@BugPattern(
altNames = "unused",
summary = "This nested class is unused, and can be removed.",
severity = WARNING,
documentSuppression = false)
public final class UnusedNestedClass extends BugChecker implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
PrivateNestedClassScanner privateNestedClassScanner = new PrivateNestedClassScanner(state);
privateNestedClassScanner.scan(state.getPath(), null);
Map<ClassSymbol, TreePath> privateNestedClasses = privateNestedClassScanner.classes;
ClassUsageScanner classUsageScanner = new ClassUsageScanner();
classUsageScanner.scan(state.getPath(), null);
privateNestedClasses.keySet().removeAll(classUsageScanner.usedClasses);
for (TreePath path : privateNestedClasses.values()) {
state.reportMatch(
describeMatch(path.getLeaf(), SuggestedFixes.replaceIncludingComments(path, "", state)));
}
return NO_MATCH;
}
private final class PrivateNestedClassScanner extends TreePathScanner<Void, Void> {
private final Map<ClassSymbol, TreePath> classes = new HashMap<>();
private final VisitorState state;
private PrivateNestedClassScanner(VisitorState state) {
this.state = state;
}
@Override
public Void visitClass(ClassTree classTree, Void unused) {
if (ignoreUnusedClass(classTree, state)) {
return null;
}
ClassSymbol symbol = getSymbol(classTree);
boolean isAnonymous = classTree.getSimpleName().length() == 0;
if (!isAnonymous && (canBeRemoved(symbol) || symbol.owner instanceof MethodSymbol)) {
classes.put(symbol, getCurrentPath());
}
return super.visitClass(classTree, null);
}
private boolean ignoreUnusedClass(ClassTree classTree, VisitorState state) {
return isSuppressed(classTree, state)
|| shouldKeep(classTree)
|| toLowerCase(classTree.getSimpleName().toString()).startsWith("unused");
}
}
private static final class ClassUsageScanner extends TreePathScanner<Void, Void> {
private final Set<ClassSymbol> withinClasses = new HashSet<>();
private final Set<ClassSymbol> usedClasses = new HashSet<>();
@Override
public Void visitClass(ClassTree classTree, Void unused) {
ClassSymbol symbol = getSymbol(classTree);
withinClasses.add(symbol);
super.visitClass(classTree, null);
withinClasses.remove(symbol);
return 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 node) {
for (Symbol symbol = getSymbol(node); symbol != null; symbol = enclosingClass(symbol)) {
if (symbol instanceof ClassSymbol && !withinClasses.contains(symbol)) {
usedClasses.add((ClassSymbol) symbol);
}
}
}
}
}
| 5,151
| 37.162963
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TypeParameterNaming.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.ImmutableList.toImmutableList;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.util.ASTHelpers.isStatic;
import com.google.common.base.Ascii;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Streams;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.TypeParameterTreeMatcher;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.names.NamingConventions;
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.source.util.TreePath;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.TypeVariableSymbol;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.lang.model.element.Name;
/**
* Enforces type parameters match the google style guide.
*
* @author siyuanl@google.com (Siyuan Liu)
* @author glorioso@google.com (Nick Glorioso)
*/
@BugPattern(
summary =
"Type parameters must be a single letter with an optional numeric suffix,"
+ " or an UpperCamelCase name followed by the letter 'T'.",
severity = SUGGESTION,
linkType = LinkType.CUSTOM,
link = "https://google.github.io/styleguide/javaguide.html#s5.2.8-type-variable-names")
public class TypeParameterNaming extends BugChecker implements TypeParameterTreeMatcher {
private static final Pattern TRAILING_DIGIT_EXTRACTOR = Pattern.compile("^(.*?)(\\d+)$");
private static final Pattern SINGLE_PLUS_MAYBE_DIGITS = Pattern.compile("[A-Z]\\d*");
private static String upperCamelToken(String s) {
return "" + Ascii.toUpperCase(s.charAt(0)) + (s.length() == 1 ? "" : s.substring(1));
}
/**
* An enum that classifies a String name into different types, based on the Google Java Style
* Guide's rules for Type Parameters.
*/
public enum TypeParameterNamingClassification {
/** Examples: B, Q, R2, T1, A9 */
LETTER_WITH_MAYBE_NUMERAL(true),
/**
* A valid Type Parameter name, that follows the style guide rule:
*
* <p>Examples: DataTypeT, FooT, BarT
*/
CLASS_NAME_WITH_T(true),
/**
* Names of the form which are not camel case, but nonetheless have a Capital T at the end and
* this shouldn't suggest to add more.
*
* <p>Examples; IDataT, CConverterT. BART, FOOT
*/
NON_CLASS_NAME_WITH_T_SUFFIX(false),
/** Anything else. */
UNCLASSIFIED(false);
private final boolean isValidName;
TypeParameterNamingClassification(boolean isValidName) {
this.isValidName = isValidName;
}
public static TypeParameterNamingClassification classify(String name) {
if (SINGLE_PLUS_MAYBE_DIGITS.matcher(name).matches()) {
return LETTER_WITH_MAYBE_NUMERAL;
}
if (!name.endsWith("T")) {
return UNCLASSIFIED;
}
ImmutableList<String> tokens = NamingConventions.splitToLowercaseTerms(name);
// Combine the tokens back into UpperCamelTokens and make sure it matches the identifier
String reassembled =
tokens.stream().map(TypeParameterNaming::upperCamelToken).collect(Collectors.joining());
return name.equals(reassembled) ? CLASS_NAME_WITH_T : NON_CLASS_NAME_WITH_T_SUFFIX;
}
public boolean isValidName() {
return isValidName;
}
}
@Override
public Description matchTypeParameter(TypeParameterTree tree, VisitorState state) {
TypeParameterNamingClassification classification =
TypeParameterNamingClassification.classify(tree.getName().toString());
if (classification.isValidName()) {
return Description.NO_MATCH;
}
Description.Builder descriptionBuilder =
buildDescription(tree).setMessage(errorMessage(tree.getName(), classification));
TreePath enclosingPath = enclosingMethodOrClass(state.getPath());
if (classification != TypeParameterNamingClassification.NON_CLASS_NAME_WITH_T_SUFFIX) {
descriptionBuilder.addFix(
SuggestedFixes.renameTypeParameter(
tree,
state.getPath().getParentPath().getLeaf(),
suggestedNameFollowedWithT(tree.getName().toString()),
state.withPath(enclosingPath)));
}
return descriptionBuilder
.addFix(
SuggestedFixes.renameTypeParameter(
tree,
state.getPath().getParentPath().getLeaf(),
suggestedSingleLetter(tree.getName().toString(), tree),
state.withPath(enclosingPath)))
.build();
}
private static TreePath enclosingMethodOrClass(TreePath path) {
for (TreePath parent = path; parent != null; parent = parent.getParentPath()) {
if (parent.getLeaf() instanceof MethodTree || parent.getLeaf() instanceof ClassTree) {
return parent;
}
}
return path;
}
private static String errorMessage(Name name, TypeParameterNamingClassification classification) {
Preconditions.checkArgument(!classification.isValidName());
if (classification == TypeParameterNamingClassification.NON_CLASS_NAME_WITH_T_SUFFIX) {
return String.format(
"Type Parameters should be an UpperCamelCase name followed by the letter 'T'. "
+ "%s ends in T, but is not a valid UpperCamelCase name",
name);
}
return String.format(
"Type Parameter %s must be a single letter with an optional numeric"
+ " suffix, or an UpperCamelCase name followed by the letter 'T'.",
name);
}
// Get list of type params of every enclosing class
private static List<TypeVariableSymbol> typeVariablesEnclosing(Symbol sym) {
List<TypeVariableSymbol> typeVarScopes = new ArrayList<>();
outer:
while (!isStatic(sym)) {
sym = sym.owner;
switch (sym.getKind()) {
case PACKAGE:
break outer;
case METHOD:
case CLASS:
typeVarScopes.addAll(0, sym.getTypeParameters());
break;
default: // fall out
}
}
return typeVarScopes;
}
private static String suggestedSingleLetter(String id, Tree tree) {
char firstLetter =
Ascii.toUpperCase(NamingConventions.splitToLowercaseTerms(id).get(0).charAt(0));
Symbol sym = ASTHelpers.getSymbol(tree);
List<TypeVariableSymbol> enclosingTypeSymbols = typeVariablesEnclosing(sym);
for (TypeVariableSymbol typeName : enclosingTypeSymbols) {
char enclosingTypeFirstLetter = typeName.toString().charAt(0);
if (enclosingTypeFirstLetter == firstLetter
&& !TypeParameterNamingClassification.classify(typeName.name.toString()).isValidName()) {
ImmutableList<String> typeVarsInScope =
Streams.concat(enclosingTypeSymbols.stream(), sym.getTypeParameters().stream())
.map(v -> v.name.toString())
.collect(toImmutableList());
return firstLetterReplacementName(id, typeVarsInScope);
}
}
return Character.toString(firstLetter);
}
// T -> T2
// T2 -> T3
// T -> T4 (if T2 and T3 already exist)
// TODO(user) : combine this method with TypeParameterShadowing.replacementTypeVarName
private static String firstLetterReplacementName(String name, List<String> superTypeVars) {
String firstLetterOfBase = Character.toString(name.charAt(0));
int typeVarNum = 2;
boolean first = true;
Matcher matcher = TRAILING_DIGIT_EXTRACTOR.matcher(name);
if (matcher.matches()) {
name = matcher.group(1);
typeVarNum = Integer.parseInt(matcher.group(2)) + 1;
}
String replacementName = "";
// Look at the type names to the left of the current type
// Since this bugchecker doesn't rename as it goes, we have to check which type names
// would've been renamed before the current ones
for (String superTypeVar : superTypeVars) {
if (superTypeVar.equals(name)) {
if (typeVarNum == 2 && first) {
return firstLetterOfBase;
}
break;
} else if (superTypeVar.charAt(0) == name.charAt(0)) {
if (!first) {
typeVarNum++;
} else {
first = false;
}
replacementName = firstLetterOfBase + typeVarNum;
}
}
while (superTypeVars.contains(replacementName)) {
typeVarNum++;
replacementName = firstLetterOfBase + typeVarNum;
}
return replacementName;
}
private static String suggestedNameFollowedWithT(String identifier) {
Preconditions.checkArgument(!identifier.isEmpty());
// Some early checks:
// TFoo => FooT
if (identifier.length() > 2
&& identifier.charAt(0) == 'T'
&& Ascii.isUpperCase(identifier.charAt(1))
&& Ascii.isLowerCase(identifier.charAt(2))) {
// splitToLowercaseTerms thinks "TFooBar" is ["tfoo", "bar"], so we remove "t", have it parse
// as ["foo", "bar"], then staple "t" back on the end.
ImmutableList<String> tokens =
NamingConventions.splitToLowercaseTerms(identifier.substring(1));
return Streams.concat(tokens.stream(), Stream.of("T"))
.map(TypeParameterNaming::upperCamelToken)
.collect(Collectors.joining());
}
ImmutableList<String> tokens = NamingConventions.splitToLowercaseTerms(identifier);
// UPPERCASE => UppercaseT
if (tokens.size() == 1) {
String token = tokens.get(0);
if (Ascii.toUpperCase(token).equals(identifier)) {
return upperCamelToken(token) + "T";
}
}
// FooType => FooT
if (Iterables.getLast(tokens).equals("type")) {
return Streams.concat(tokens.subList(0, tokens.size() - 1).stream(), Stream.of("T"))
.map(TypeParameterNaming::upperCamelToken)
.collect(Collectors.joining());
}
return identifier + "T";
}
}
| 10,993
| 34.694805
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ProtectedMembersInFinalClass.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.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.hasModifier;
import static java.util.stream.Collectors.joining;
import static javax.lang.model.element.Modifier.FINAL;
import static javax.lang.model.element.Modifier.PROTECTED;
import com.google.common.collect.ImmutableList;
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.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.VariableTree;
import com.sun.tools.javac.code.Symbol;
import javax.lang.model.element.Modifier;
/**
* Flags protected members in final classes.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary = "Protected members in final classes can be package-private",
severity = WARNING)
public class ProtectedMembersInFinalClass extends BugChecker implements ClassTreeMatcher {
private static final Matcher<ClassTree> HAS_FINAL = hasModifier(FINAL);
private static final Matcher<Tree> HAS_PROTECTED = hasModifier(PROTECTED);
private static boolean methodHasNoParentMethod(MethodTree methodTree, VisitorState state) {
return ASTHelpers.findSuperMethods(ASTHelpers.getSymbol(methodTree), state.getTypes())
.isEmpty();
}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (!HAS_FINAL.matches(tree, state)) {
return NO_MATCH;
}
ImmutableList<Tree> relevantMembers =
tree.getMembers().stream()
.filter(m -> (m instanceof MethodTree || m instanceof VariableTree))
.filter(m -> HAS_PROTECTED.matches(m, state))
.filter(
m -> !(m instanceof MethodTree) || methodHasNoParentMethod((MethodTree) m, state))
.filter(m -> !isSuppressed(m, state))
.collect(toImmutableList());
if (relevantMembers.isEmpty()) {
return NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
relevantMembers.forEach(
m -> SuggestedFixes.removeModifiers(m, state, Modifier.PROTECTED).ifPresent(fix::merge));
if (fix.isEmpty()) {
return NO_MATCH;
}
String message =
String.format(
"Make members of final classes package-private: %s",
relevantMembers.stream()
.map(
m -> {
Symbol symbol = ASTHelpers.getSymbol(m);
return symbol.isConstructor()
? symbol.owner.name.toString()
: symbol.name.toString();
})
.collect(joining(", ")));
return buildDescription(relevantMembers.get(0)).setMessage(message).addFix(fix.build()).build();
}
}
| 3,920
| 38.21
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JavaLangClash.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.getFirst;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static javax.lang.model.element.Modifier.PUBLIC;
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.ClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.TypeParameterTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
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.Symtab;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.util.Name;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Never reuse class names from java.lang",
severity = WARNING,
tags = StandardTags.STYLE)
public class JavaLangClash extends BugChecker
implements ClassTreeMatcher, TypeParameterTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
Name simpleName = ((JCClassDecl) tree).getSimpleName();
return check(tree, simpleName, state);
}
@Override
public Description matchTypeParameter(TypeParameterTree tree, VisitorState state) {
return check(tree, ((JCTypeParameter) tree).getName(), state);
}
private static final ImmutableSet<String> IGNORED =
ImmutableSet.of(
// java.lang.Compiler is deprecated for removal in 9 and should not be used, so we don't
// care
// if other types named 'Compiler' are declared
"Compiler",
// References to java.lang.Module are rare, and it is a commonly used simple name
"Module");
private Description check(Tree tree, Name simpleName, VisitorState state) {
Symtab symtab = state.getSymtab();
PackageSymbol javaLang = symtab.enterPackage(symtab.java_base, state.getNames().java_lang);
Symbol other =
getFirst(
ASTHelpers.scope(javaLang.members())
.getSymbolsByName(simpleName, s -> s.getModifiers().contains(PUBLIC)),
null);
Symbol symbol = ASTHelpers.getSymbol(tree);
if (other == null || other.equals(symbol)) {
return NO_MATCH;
}
if (IGNORED.contains(simpleName.toString())) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage(String.format("%s clashes with %s\n", symbol, other))
.build();
}
}
| 3,548
| 38.433333
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MissingFail.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.JUnitMatchers.JUNIT_AFTER_ANNOTATION;
import static com.google.errorprone.matchers.JUnitMatchers.JUNIT_BEFORE_ANNOTATION;
import static com.google.errorprone.matchers.JUnitMatchers.hasJUnit4TestCases;
import static com.google.errorprone.matchers.JUnitMatchers.hasJUnit4TestRunner;
import static com.google.errorprone.matchers.JUnitMatchers.isTestCaseDescendant;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.assertStatement;
import static com.google.errorprone.matchers.Matchers.assignment;
import static com.google.errorprone.matchers.Matchers.booleanConstant;
import static com.google.errorprone.matchers.Matchers.booleanLiteral;
import static com.google.errorprone.matchers.Matchers.contains;
import static com.google.errorprone.matchers.Matchers.continueStatement;
import static com.google.errorprone.matchers.Matchers.ignoreParens;
import static com.google.errorprone.matchers.Matchers.isInstanceField;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.isVariable;
import static com.google.errorprone.matchers.Matchers.methodInvocation;
import static com.google.errorprone.matchers.Matchers.nextStatement;
import static com.google.errorprone.matchers.Matchers.returnStatement;
import static com.google.errorprone.matchers.Matchers.throwStatement;
import static com.google.errorprone.matchers.Matchers.toType;
import static com.google.errorprone.matchers.method.MethodMatchers.anyMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
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.fixes.SuggestedFix;
import com.google.errorprone.matchers.ChildMultiMatcher;
import com.google.errorprone.matchers.ChildMultiMatcher.MatchType;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.JUnitMatchers;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.DoWhileLoopTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.LiteralTree;
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 com.sun.source.tree.VariableTree;
import com.sun.source.tree.WhileLoopTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import javax.lang.model.element.Name;
/**
* @author schmitt@google.com (Peter Schmitt)
*/
@BugPattern(
altNames = "missing-fail",
summary = "Not calling fail() when expecting an exception masks bugs",
severity = WARNING)
public class MissingFail extends BugChecker implements TryTreeMatcher {
// Many test writers don't seem to know about `fail()`. They instead use synonyms of varying
// complexity instead.
//
// One category of synonyms replaces `fail()` with a single, equivalent statement
// such as `assertTrue(false)`, `assertFalse(true)` or `throw new
// AssertionError()`. In these cases we will simply skip any further analysis, they
// work perfectly fine.
//
// Other, more complex synonyms tend to use boolean variables, like such:
//
// ```java
// boolean thrown = false;
// try {
// throwingExpression();
// } catch (SomeException e) {
// thrown = true;
// }
// assertTrue(thrown);
// ```
private static final Matcher<ExpressionTree> ASSERT_EQUALS = Matchers.assertEqualsInvocation();
private static final Matcher<Tree> ASSERT_UNEQUAL =
toType(MethodInvocationTree.class, new UnequalIntegerLiteralMatcher(ASSERT_EQUALS));
private static final Matcher<ExpressionTree> ASSERT_TRUE =
Matchers.anyOf(
staticMethod().onClass("org.junit.Assert").named("assertTrue"),
staticMethod().onClass("junit.framework.Assert").named("assertTrue"),
staticMethod().onClass("junit.framework.TestCase").named("assertTrue"));
private static final Matcher<ExpressionTree> ASSERT_FALSE =
Matchers.anyOf(
staticMethod().onClass("org.junit.Assert").named("assertFalse"),
staticMethod().onClass("junit.framework.Assert").named("assertFalse"),
staticMethod().onClass("junit.framework.TestCase").named("assertFalse"));
private static final Matcher<ExpressionTree> ASSERT_TRUE_FALSE =
methodInvocation(
ASSERT_TRUE,
MatchType.AT_LEAST_ONE,
Matchers.anyOf(booleanLiteral(false), booleanConstant(false)));
private static final Matcher<ExpressionTree> ASSERT_FALSE_TRUE =
methodInvocation(
ASSERT_FALSE,
MatchType.AT_LEAST_ONE,
Matchers.anyOf(booleanLiteral(true), booleanConstant(true)));
private static final Matcher<ExpressionTree> ASSERT_TRUE_TRUE =
methodInvocation(
ASSERT_TRUE,
MatchType.AT_LEAST_ONE,
Matchers.anyOf(booleanLiteral(true), booleanConstant(true)));
private static final Matcher<ExpressionTree> ASSERT_FALSE_FALSE =
methodInvocation(
ASSERT_FALSE,
MatchType.AT_LEAST_ONE,
Matchers.anyOf(booleanLiteral(false), booleanConstant(false)));
private static final Matcher<StatementTree> JAVA_ASSERT_FALSE =
assertStatement(ignoreParens(Matchers.anyOf(booleanLiteral(false), booleanConstant(false))));
private static final Matcher<ExpressionTree> LOG_CALL =
anyOf(
instanceMethod()
.onClass((t, s) -> t.asElement().getSimpleName().toString().contains("Logger"))
.withAnyName(),
instanceMethod().anyClass().withNameMatching(Pattern.compile("log.*")));
private static final Matcher<Tree> LOG_IN_BLOCK =
contains(toType(ExpressionTree.class, LOG_CALL));
private static final Pattern FAIL_PATTERN = Pattern.compile(".*(?i:fail).*");
private static final Matcher<ExpressionTree> FAIL =
anyMethod().anyClass().withNameMatching(FAIL_PATTERN);
private static final Matcher<ExpressionTree> ASSERT_CALL =
methodInvocation(new AssertMethodMatcher());
private static final Matcher<ExpressionTree> REAL_ASSERT_CALL =
Matchers.allOf(
ASSERT_CALL, Matchers.not(Matchers.anyOf(ASSERT_FALSE_FALSE, ASSERT_TRUE_TRUE)));
private static final Matcher<ExpressionTree> VERIFY_CALL =
staticMethod().onClass("org.mockito.Mockito").named("verify");
private static final MultiMatcher<TryTree, Tree> ASSERT_LAST_CALL_IN_TRY =
new ChildOfTryMatcher(
MatchType.LAST,
contains(toType(ExpressionTree.class, Matchers.anyOf(REAL_ASSERT_CALL, VERIFY_CALL))));
private static final Matcher<Tree> ASSERT_IN_BLOCK =
contains(toType(ExpressionTree.class, REAL_ASSERT_CALL));
private static final Matcher<StatementTree> THROW_STATEMENT = throwStatement(Matchers.anything());
private static final Matcher<Tree> THROW_OR_FAIL_IN_BLOCK =
contains(
Matchers.anyOf(
toType(StatementTree.class, THROW_STATEMENT),
// TODO(schmitt): Include Preconditions.checkState(false)?
toType(ExpressionTree.class, ASSERT_TRUE_FALSE),
toType(ExpressionTree.class, ASSERT_FALSE_TRUE),
toType(ExpressionTree.class, ASSERT_UNEQUAL),
toType(StatementTree.class, JAVA_ASSERT_FALSE),
toType(ExpressionTree.class, FAIL)));
private static final Matcher<TryTree> NON_TEST_METHOD = new IgnoredEnclosingMethodMatcher();
private static final Matcher<Tree> RETURN_IN_BLOCK =
contains(toType(StatementTree.class, returnStatement(Matchers.anything())));
private static final Matcher<StatementTree> RETURN_AFTER =
nextStatement(returnStatement(Matchers.anything()));
private static final Matcher<VariableTree> INAPPLICABLE_EXCEPTION =
Matchers.anyOf(
isSameType("java.lang.InterruptedException"),
isSameType("java.lang.AssertionError"),
isSameType("java.lang.Throwable"),
isSameType("junit.framework.AssertionFailedError"));
private static final InLoopMatcher IN_LOOP = new InLoopMatcher();
private static final Matcher<Tree> WHILE_TRUE_IN_BLOCK =
contains(toType(WhileLoopTree.class, new WhileTrueLoopMatcher()));
private static final Matcher<Tree> CONTINUE_IN_BLOCK =
contains(toType(StatementTree.class, continueStatement()));
private static final Matcher<AssignmentTree> FIELD_ASSIGNMENT =
assignment(isInstanceField(), Matchers.<ExpressionTree>anything());
private static final Matcher<Tree> FIELD_ASSIGNMENT_IN_BLOCK =
contains(toType(AssignmentTree.class, FIELD_ASSIGNMENT));
private static final Matcher<ExpressionTree> BOOLEAN_ASSERT_VAR =
methodInvocation(
Matchers.anyOf(ASSERT_FALSE, ASSERT_TRUE),
MatchType.AT_LEAST_ONE,
Matchers.anyOf(isInstanceField(), isVariable()));
private static final Matcher<Tree> BOOLEAN_ASSERT_VAR_IN_BLOCK =
contains(toType(ExpressionTree.class, BOOLEAN_ASSERT_VAR));
// Subtly different from JUnitMatchers: We want to match test base classes too.
private static final Matcher<ClassTree> TEST_CLASS =
Matchers.anyOf(isTestCaseDescendant, hasJUnit4TestRunner, hasJUnit4TestCases);
@Override
public Description matchTry(TryTree tree, VisitorState state) {
if (tryTreeMatches(tree, state)) {
List<? extends StatementTree> tryStatements = tree.getBlock().getStatements();
StatementTree lastTryStatement = tryStatements.get(tryStatements.size() - 1);
Optional<Fix> assertThrowsFix =
AssertThrowsUtils.tryFailToAssertThrows(tree, tryStatements, Optional.empty(), state);
Fix failFix = addFailCall(tree, lastTryStatement, state);
return buildDescription(lastTryStatement)
.addFix(assertThrowsFix.orElse(SuggestedFix.emptyFix()))
.addFix(failFix)
.build();
} else {
return Description.NO_MATCH;
}
}
public static Fix addFailCall(TryTree tree, StatementTree lastTryStatement, VisitorState state) {
String failCall = String.format("\nfail(\"Expected %s\");", exceptionToString(tree, state));
SuggestedFix.Builder fixBuilder =
SuggestedFix.builder().postfixWith(lastTryStatement, failCall);
// Make sure that when the fail import is added it doesn't conflict with existing ones.
fixBuilder.removeStaticImport("junit.framework.Assert.fail");
fixBuilder.removeStaticImport("junit.framework.TestCase.fail");
fixBuilder.addStaticImport("org.junit.Assert.fail");
return fixBuilder.build();
}
/**
* Returns a string describing the exception type caught by the given try tree's catch
* statement(s), defaulting to {@code "Exception"} if more than one exception type is caught.
*/
private static String exceptionToString(TryTree tree, VisitorState state) {
if (tree.getCatches().size() != 1) {
return "Exception";
}
Tree exceptionType = tree.getCatches().iterator().next().getParameter().getType();
Type type = ASTHelpers.getType(exceptionType);
if (type != null && type.isUnion()) {
return "Exception";
}
return state.getSourceForNode(exceptionType);
}
private static boolean tryTreeMatches(TryTree tree, VisitorState state) {
if (!isInClass(tree, state, TEST_CLASS)) {
return false;
}
if (hasToleratedException(tree)) {
return false;
}
boolean assertInCatch = hasAssertInCatch(tree, state);
if (!hasExpectedException(tree) && !assertInCatch) {
return false;
}
if (hasThrowOrFail(tree, state)
|| isInInapplicableMethod(tree, state)
|| returnsInTryCatchOrAfter(tree, state)
|| isInapplicableExceptionType(tree, state)
|| isInLoop(state, tree)
|| hasWhileTrue(tree, state)
|| hasContinue(tree, state)
|| hasFinally(tree)
|| logsInCatch(state, tree)) {
return false;
}
if (assertInCatch
&& (hasFieldAssignmentInCatch(tree, state)
|| hasBooleanAssertVariableInCatch(tree, state)
|| lastTryStatementIsAssert(tree, state))) {
return false;
}
if (tree.getBlock().getStatements().isEmpty()) {
return false;
}
return true;
}
private static boolean hasWhileTrue(TryTree tree, VisitorState state) {
return WHILE_TRUE_IN_BLOCK.matches(tree, state);
}
private static boolean isInClass(TryTree tree, VisitorState state, Matcher<ClassTree> classTree) {
return Matchers.enclosingNode(toType(ClassTree.class, classTree)).matches(tree, state);
}
private static boolean hasBooleanAssertVariableInCatch(TryTree tree, VisitorState state) {
return anyCatchBlockMatches(tree, state, BOOLEAN_ASSERT_VAR_IN_BLOCK);
}
private static boolean lastTryStatementIsAssert(TryTree tree, VisitorState state) {
return ASSERT_LAST_CALL_IN_TRY.matches(tree, state);
}
private static boolean hasFieldAssignmentInCatch(TryTree tree, VisitorState state) {
return anyCatchBlockMatches(tree, state, FIELD_ASSIGNMENT_IN_BLOCK);
}
private static boolean logsInCatch(VisitorState state, TryTree tree) {
return anyCatchBlockMatches(tree, state, LOG_IN_BLOCK);
}
private static boolean hasFinally(TryTree tree) {
return tree.getFinallyBlock() != null;
}
private static boolean hasContinue(TryTree tree, VisitorState state) {
return CONTINUE_IN_BLOCK.matches(tree, state);
}
private static boolean isInLoop(VisitorState state, TryTree tree) {
return IN_LOOP.matches(tree, state);
}
private static boolean isInapplicableExceptionType(TryTree tree, VisitorState state) {
for (CatchTree catchTree : tree.getCatches()) {
if (INAPPLICABLE_EXCEPTION.matches(catchTree.getParameter(), state)) {
return true;
}
}
return false;
}
private static boolean returnsInTryCatchOrAfter(TryTree tree, VisitorState state) {
return RETURN_IN_BLOCK.matches(tree, state) || RETURN_AFTER.matches(tree, state);
}
private static boolean isInInapplicableMethod(TryTree tree, VisitorState state) {
return NON_TEST_METHOD.matches(tree, state);
}
private static boolean hasThrowOrFail(TryTree tree, VisitorState state) {
return THROW_OR_FAIL_IN_BLOCK.matches(tree, state);
}
private static boolean hasAssertInCatch(TryTree tree, VisitorState state) {
return anyCatchBlockMatches(tree, state, ASSERT_IN_BLOCK);
}
private static boolean hasToleratedException(TryTree tree) {
for (CatchTree catchTree : tree.getCatches()) {
if (catchTree.getParameter().getName().contentEquals("tolerated")) {
return true;
}
}
return false;
}
private static boolean hasExpectedException(TryTree tree) {
for (CatchTree catchTree : tree.getCatches()) {
if (catchTree.getParameter().getName().contentEquals("expected")) {
return true;
}
}
return false;
}
private static boolean anyCatchBlockMatches(
TryTree tree, VisitorState state, Matcher<Tree> matcher) {
for (CatchTree catchTree : tree.getCatches()) {
if (matcher.matches(catchTree.getBlock(), state)) {
return true;
}
}
return false;
}
private static class AssertMethodMatcher implements Matcher<ExpressionTree> {
@Override
public boolean matches(ExpressionTree expressionTree, VisitorState state) {
Symbol sym = ASTHelpers.getSymbol(expressionTree);
if (sym == null) {
return false;
}
String symSimpleName = sym.getSimpleName().toString();
return symSimpleName.startsWith("assert") || symSimpleName.startsWith("verify");
}
}
/** Matches any try-tree that is enclosed in a loop. */
private static class InLoopMatcher implements Matcher<TryTree> {
@Override
public boolean matches(TryTree tryTree, VisitorState state) {
return ASTHelpers.findEnclosingNode(state.getPath(), DoWhileLoopTree.class) != null
|| ASTHelpers.findEnclosingNode(state.getPath(), EnhancedForLoopTree.class) != null
|| ASTHelpers.findEnclosingNode(state.getPath(), WhileLoopTree.class) != null
|| ASTHelpers.findEnclosingNode(state.getPath(), ForLoopTree.class) != null;
}
}
private static class WhileTrueLoopMatcher implements Matcher<WhileLoopTree> {
@Override
public boolean matches(WhileLoopTree tree, VisitorState state) {
return ignoreParens(booleanLiteral(true)).matches(tree.getCondition(), state);
}
}
/**
* Matches any try-tree that is in a JUNit3 {@code setUp} or {@code tearDown} method, their JUnit4
* equivalents, a JUnit {@code suite()} method or a {@code main} method.
*/
private static class IgnoredEnclosingMethodMatcher implements Matcher<TryTree> {
@Override
public boolean matches(TryTree tryTree, VisitorState state) {
MethodTree enclosingMethodTree =
ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class);
if (enclosingMethodTree == null) {
// e.g. a class initializer
return true;
}
Name name = enclosingMethodTree.getName();
return JUnitMatchers.looksLikeJUnit3SetUp.matches(enclosingMethodTree, state)
|| JUnitMatchers.looksLikeJUnit3TearDown.matches(enclosingMethodTree, state)
|| name.contentEquals("main")
// TODO(schmitt): Move to JUnitMatchers?
|| name.contentEquals("suite")
|| Matchers.hasAnnotation(JUNIT_BEFORE_ANNOTATION).matches(enclosingMethodTree, state)
|| Matchers.hasAnnotation(JUNIT_AFTER_ANNOTATION).matches(enclosingMethodTree, state);
}
}
/**
* Matches if any two of the given list of expressions are integer literals with different values.
*/
private static class UnequalIntegerLiteralMatcher implements Matcher<MethodInvocationTree> {
private final Matcher<ExpressionTree> methodSelectMatcher;
private UnequalIntegerLiteralMatcher(Matcher<ExpressionTree> methodSelectMatcher) {
this.methodSelectMatcher = methodSelectMatcher;
}
@Override
public boolean matches(MethodInvocationTree methodInvocationTree, VisitorState state) {
return methodSelectMatcher.matches(methodInvocationTree, state)
&& matches(methodInvocationTree.getArguments());
}
private static boolean matches(List<? extends ExpressionTree> expressionTrees) {
Set<Integer> foundValues = new HashSet<>();
for (Tree tree : expressionTrees) {
if (tree instanceof LiteralTree) {
Object value = ((LiteralTree) tree).getValue();
if (value instanceof Integer) {
boolean duplicate = !foundValues.add((Integer) value);
if (!duplicate && foundValues.size() > 1) {
return true;
}
}
}
}
return false;
}
}
private static class ChildOfTryMatcher extends ChildMultiMatcher<TryTree, Tree> {
public ChildOfTryMatcher(MatchType matchType, Matcher<Tree> nodeMatcher) {
super(matchType, nodeMatcher);
}
@Override
protected Iterable<? extends StatementTree> getChildNodes(TryTree tree, VisitorState state) {
return tree.getBlock().getStatements();
}
}
}
| 20,689
| 39.64833
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ObjectsHashCodePrimitive.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.argument;
import static com.google.errorprone.matchers.Matchers.isPrimitiveType;
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.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.MethodInvocationTree;
import java.util.Objects;
/**
* Check for calls to Objects' {@link Objects#hashCode} with a primitive parameter.
*
* @author seibelsabrina@google.com (Sabrina Seibel)
*/
@BugPattern(
summary = "Objects.hashCode(Object o) should not be passed a primitive value",
severity = WARNING)
public final class ObjectsHashCodePrimitive extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Matcher<MethodInvocationTree> OBJECTS_HASHCODE_CALLS =
allOf(
staticMethod().onClass("java.util.Objects").named("hashCode"),
argument(0, isPrimitiveType()));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return OBJECTS_HASHCODE_CALLS.matches(tree, state)
? describeMatch(tree, adjustHashCodeCall(tree, state))
: Description.NO_MATCH;
}
private static Fix adjustHashCodeCall(MethodInvocationTree tree, VisitorState state) {
String argumentClass =
state
.getTypes()
.boxedTypeOrType(ASTHelpers.getType(tree.getArguments().get(0)))
.tsym
.getSimpleName()
.toString();
return SuggestedFix.builder()
.prefixWith(tree, argumentClass + ".hashCode(")
.replace(tree, state.getSourceForNode(tree.getArguments().get(0)))
.postfixWith(tree, ")")
.build();
}
}
| 2,819
| 38.71831
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BooleanParameter.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.getStartPosition;
import static com.sun.tools.javac.parser.Tokens.Comment.CommentStyle.BLOCK;
import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Range;
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.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.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.Tree.Kind;
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.TypeTag;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Use parameter comments to document ambiguous literals",
severity = SUGGESTION)
public class BooleanParameter extends BugChecker
implements MethodInvocationTreeMatcher, NewClassTreeMatcher {
private static final ImmutableSet<String> EXCLUDED_NAMES =
ImmutableSet.of("default", "defValue", "defaultValue", "value");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
handleArguments(tree, tree.getArguments(), state);
return NO_MATCH;
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
handleArguments(tree, tree.getArguments(), state);
return NO_MATCH;
}
private void handleArguments(
Tree tree, List<? extends ExpressionTree> arguments, VisitorState state) {
if (arguments.size() < 2 && areSingleArgumentsSelfDocumenting(tree)) {
// single-argument methods are often self-documenting
return;
}
if (arguments.stream().noneMatch(BooleanParameter::isBooleanLiteral)) {
return;
}
MethodSymbol sym = (MethodSymbol) ASTHelpers.getSymbol(tree);
if (NamedParameterComment.containsSyntheticParameterName(sym)) {
return;
}
int start = getStartPosition(tree);
int end = state.getEndPosition(getLast(arguments));
Deque<ErrorProneToken> tokens = new ArrayDeque<>(state.getOffsetTokens(start, end));
forEachPair(
sym.getParameters().stream(),
arguments.stream(),
(p, c) -> checkParameter(p, c, tokens, state));
}
private void checkParameter(
VarSymbol paramSym, ExpressionTree a, Deque<ErrorProneToken> tokens, VisitorState state) {
if (!isBooleanLiteral(a)) {
return;
}
if (state.getTypes().unboxedTypeOrType(paramSym.type).getTag() != TypeTag.BOOLEAN) {
// don't suggest on non-boolean (e.g., generic) parameters)
return;
}
String name = paramSym.getSimpleName().toString();
if (name.length() < 2) {
// single-character parameter names aren't helpful
return;
}
if (EXCLUDED_NAMES.contains(name)) {
return;
}
while (!tokens.isEmpty() && tokens.getFirst().pos() < getStartPosition(a)) {
tokens.removeFirst();
}
if (tokens.isEmpty()) {
return;
}
Range<Integer> argRange = Range.closedOpen(getStartPosition(a), state.getEndPosition(a));
if (!argRange.contains(tokens.getFirst().pos())) {
return;
}
if (hasParameterComment(tokens.removeFirst())) {
return;
}
state.reportMatch(
describeMatch(
a, SuggestedFix.prefixWith(a, String.format("/* %s= */", paramSym.getSimpleName()))));
}
private static boolean hasParameterComment(ErrorProneToken token) {
return token.comments().stream()
.filter(c -> c.getStyle() == BLOCK)
.anyMatch(
c ->
NamedParameterComment.PARAMETER_COMMENT_PATTERN
.matcher(Comments.getTextFromComment(c))
.matches());
}
private static boolean isBooleanLiteral(ExpressionTree tree) {
return tree.getKind() == Kind.BOOLEAN_LITERAL;
}
private static boolean areSingleArgumentsSelfDocumenting(Tree tree) {
// Consider single-argument booleans for classes whose names contain "Boolean" to be self-
// documenting. This is aimed at classes like AtomicBoolean which simply wrap a value.
if (tree instanceof NewClassTree) {
Symbol symbol = ASTHelpers.getSymbol(((NewClassTree) tree).getIdentifier());
return symbol != null && Ascii.toLowerCase(symbol.getSimpleName()).contains("boolean");
}
return true;
}
}
| 5,977
| 37.567742
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AutoValueImmutableFields.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.hasModifier;
import static com.google.errorprone.matchers.Matchers.isArrayType;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import static com.google.errorprone.suppliers.Suppliers.typeFromString;
import com.google.common.collect.ImmutableListMultimap;
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.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.Map;
import javax.lang.model.element.Modifier;
/**
* Flags mutable collections in AutoValue.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
altNames = "mutable",
summary = "AutoValue recommends using immutable collections",
severity = WARNING,
documentSuppression = false)
public class AutoValueImmutableFields extends BugChecker implements ClassTreeMatcher {
private static final ImmutableListMultimap<String, Matcher<MethodTree>> REPLACEMENT_TO_MATCHERS =
ImmutableListMultimap.<String, Matcher<MethodTree>>builder()
.put("ImmutableCollection", returning("java.util.Collection"))
.putAll(
"ImmutableList",
methodReturns(isArrayType()),
returning("java.util.List"),
returning("java.util.ArrayList"),
returning("java.util.LinkedList"),
returning("com.google.common.collect.ImmutableList.Builder"))
.putAll(
"ImmutableMap",
returning("java.util.Map"),
returning("java.util.HashMap"),
returning("java.util.LinkedHashMap"),
returning("com.google.common.collect.ImmutableMap.Builder"))
.putAll(
"ImmutableSortedMap",
returning("java.util.SortedMap"),
returning("java.util.TreeMap"),
returning("com.google.common.collect.ImmutableSortedMap.Builder"))
.putAll(
"ImmutableBiMap",
returning("com.google.common.collect.BiMap"),
returning("com.google.common.collect.ImmutableBiMap.Builder"))
.putAll(
"ImmutableSet",
returning("java.util.Set"),
returning("java.util.HashSet"),
returning("java.util.LinkedHashSet"),
returning("com.google.common.collect.ImmutableSet.Builder"))
.putAll(
"ImmutableSortedSet",
returning("java.util.SortedSet"),
returning("java.util.TreeSet"),
returning("com.google.common.collect.ImmutableSortedSet.Builder"))
.putAll(
"ImmutableMultimap",
returning("com.google.common.collect.Multimap"),
returning("com.google.common.collect.ImmutableMultimap.Builder"))
.putAll(
"ImmutableListMultimap",
returning("com.google.common.collect.ListMultimap"),
returning("com.google.common.collect.ImmutableListMultimap.Builder"))
.putAll(
"ImmutableSetMultimap",
returning("com.google.common.collect.SetMultimap"),
returning("com.google.common.collect.ImmutableSetMultimap.Builder"))
.putAll(
"ImmutableMultiset",
returning("com.google.common.collect.Multiset"),
returning("com.google.common.collect.ImmutableMultiset.Builder"))
.putAll(
"ImmutableSortedMultiset",
returning("com.google.common.collect.SortedMultiset"),
returning("com.google.common.collect.ImmutableSortedMultiset.Builder"))
.putAll(
"ImmutableTable",
returning("com.google.common.collect.Table"),
returning("com.google.common.collect.ImmutableTable.Builder"))
.putAll(
"ImmutableRangeMap",
returning("com.google.common.collect.RangeMap"),
returning("com.google.common.collect.ImmutableRangeMap.Builder"))
.putAll(
"ImmutableRangeSet",
returning("com.google.common.collect.RangeSet"),
returning("com.google.common.collect.ImmutableRangeSet.Builder"))
.putAll(
"ImmutablePrefixTrie",
returning("com.google.common.collect.PrefixTrie"),
returning("com.google.common.collect.ImmutablePrefixTrie.Builder"))
.build();
private static Matcher<MethodTree> returning(String type) {
return methodReturns(typeFromString(type));
}
private static final Matcher<MethodTree> ABSTRACT_MATCHER = hasModifier(Modifier.ABSTRACT);
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (ASTHelpers.hasAnnotation(tree, "com.google.auto.value.AutoValue", state)) {
for (Tree memberTree : tree.getMembers()) {
if (memberTree instanceof MethodTree && !isSuppressed(memberTree, state)) {
MethodTree methodTree = (MethodTree) memberTree;
if (ABSTRACT_MATCHER.matches(methodTree, state)) {
for (Map.Entry<String, Matcher<MethodTree>> entry : REPLACEMENT_TO_MATCHERS.entries()) {
if (entry.getValue().matches(methodTree, state)) {
state.reportMatch(
buildDescription(methodTree)
.setMessage(
String.format(
"AutoValue instances should be deeply immutable. Therefore, we"
+ " recommend returning %s instead.",
entry.getKey()))
.build());
}
}
}
}
}
}
return NO_MATCH;
}
}
| 6,809
| 42.653846
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StronglyTypeByteString.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.staticMethod;
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.matchers.Matcher;
import com.google.errorprone.suppliers.Suppliers;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
/**
* Flags fields which would be better expressed as ByteStrings rather than primitive byte arrays.
*/
@BugPattern(
summary =
"This primitive byte array is only used to construct ByteStrings. It would be"
+ " clearer to strongly type the field instead.",
severity = WARNING)
public final class StronglyTypeByteString extends BugChecker implements CompilationUnitTreeMatcher {
private static final Matcher<ExpressionTree> BYTE_STRING_FACTORY =
anyOf(
staticMethod()
.onClass("com.google.protobuf.ByteString")
.namedAnyOf("copyFrom")
.withParametersOfType(ImmutableSet.of(Suppliers.arrayOf(Suppliers.BYTE_TYPE))));
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
return StronglyType.forCheck(this)
.addType(state.arrayTypeForType(state.getSymtab().byteType))
.setFactoryMatcher(BYTE_STRING_FACTORY)
.build()
.match(tree, state);
}
}
| 2,320
| 38.338983
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CatchFail.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.ImmutableList.toImmutableList;
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.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.expressionStatement;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static java.util.stream.Collectors.joining;
import com.google.common.collect.ImmutableList;
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.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.util.ASTHelpers;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.TryTree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Attribute.Compound;
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.Type.UnionClassType;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.util.Name;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Ignoring exceptions and calling fail() is unnecessary, and makes test output less useful",
severity = WARNING)
public class CatchFail extends BugChecker implements TryTreeMatcher {
private static final Matcher<StatementTree> FAIL_METHOD =
expressionStatement(
anyOf(
staticMethod().onClass("org.junit.Assert").named("fail"),
staticMethod().onClass("junit.framework.Assert").named("fail"),
staticMethod().onClass("junit.framework.TestCase").named("fail")));
@Override
public Description matchTry(TryTree tree, VisitorState state) {
if (tree.getCatches().isEmpty()) {
return NO_MATCH;
}
// Find catch blocks that contain only a call to fail, and that ignore the caught exception.
ImmutableList<CatchTree> catchBlocks =
tree.getCatches().stream()
.filter(
c ->
c.getBlock().getStatements().size() == 1
&& FAIL_METHOD.matches(getOnlyElement(c.getBlock().getStatements()), state))
.filter(c -> !catchVariableIsUsed(c))
.collect(toImmutableList());
if (catchBlocks.isEmpty()) {
return NO_MATCH;
}
Description.Builder description = buildDescription(tree);
rethrowFix(catchBlocks, state).ifPresent(description::addFix);
deleteFix(tree, catchBlocks, state).ifPresent(description::addFix);
return description.build();
}
private static String getMessageOrFormat(MethodInvocationTree tree, VisitorState state) {
if (tree.getArguments().size() > 1) {
return "String.format("
+ state
.getSourceCode()
.subSequence(
getStartPosition(tree.getArguments().get(0)),
state.getEndPosition(getLast(tree.getArguments())))
+ ")";
}
return state.getSourceForNode(getOnlyElement(tree.getArguments()));
}
private static Optional<Fix> rethrowFix(
ImmutableList<CatchTree> catchBlocks, VisitorState state) {
SuggestedFix.Builder fix = SuggestedFix.builder();
catchBlocks.forEach(
c -> {
// e.g.
// fail("message") -> throw new AssertionError("message", cause);
// assertWithMessage("message format %s", 42) ->
// throw new AssertionError(String.format("message format %s", 42), cause);
StatementTree statementTree = getOnlyElement(c.getBlock().getStatements());
MethodInvocationTree methodInvocationTree =
(MethodInvocationTree) ((ExpressionStatementTree) statementTree).getExpression();
if (!methodInvocationTree.getArguments().isEmpty()) {
String message = getMessageOrFormat(methodInvocationTree, state);
// only catch and rethrow to add additional context, not for raw `fail()` calls
fix.replace(
statementTree,
String.format(
"throw new AssertionError(%s, %s);", message, c.getParameter().getName()));
}
});
return fix.isEmpty() ? Optional.empty() : Optional.of(fix.build());
}
// Extract the argument to a call to assertWithMessage, e.g. in:
// assertWithMessage("message").fail();
Optional<Fix> deleteFix(TryTree tree, ImmutableList<CatchTree> catchBlocks, VisitorState state) {
SuggestedFix.Builder fix = SuggestedFix.builder();
if (tree.getFinallyBlock() != null || catchBlocks.size() < tree.getCatches().size()) {
// If the try statement has a finally region, or other catch blocks, delete only the
// unnecessary blocks.
catchBlocks.forEach(fix::delete);
} else {
// The try statement has no finally region and all catch blocks are unnecessary. Replace it
// with the try statements, deleting all catches.
List<? extends StatementTree> tryStatements = tree.getBlock().getStatements();
// If the try block is empty, all of the catches are dead, so just delete the whole try and
// don't modify the signature of the method
if (tryStatements.isEmpty()) {
return Optional.of(fix.delete(tree).build());
} else {
String source = state.getSourceCode().toString();
// Replace the full region to work around a GJF partial formatting bug that prevents it from
// re-indenting unchanged lines. This means that fixes may overlap, but that's (hopefully)
// unlikely.
// TODO(b/24140798): emit more precise replacements if GJF is fixed
fix.replace(
tree,
source.substring(
getStartPosition(tryStatements.get(0)),
state.getEndPosition(getLast(tryStatements))));
}
}
MethodTree enclosing = ASTHelpers.findEnclosingMethod(state);
if (enclosing == null) {
// There isn't an enclosing method, possibly because we're in a lambda or initializer block.
return Optional.empty();
}
if (isExpectedExceptionTest(ASTHelpers.getSymbol(enclosing), state)) {
// Replacing the original exception with fail() may break badly-structured expected-exception
// tests, so don't use that fix for methods annotated with @Test(expected=...).
return Optional.empty();
}
// Fix up the enclosing method's throws declaration to include the new thrown exception types.
List<Type> thrownTypes = ASTHelpers.getSymbol(enclosing).getThrownTypes();
Types types = state.getTypes();
// Find all types in the deleted catch blocks that are not already in the throws declaration.
ImmutableList<Type> toThrow =
catchBlocks.stream()
.map(c -> ASTHelpers.getType(c.getParameter()))
// convert multi-catch to a list of component types
.flatMap(
t ->
t instanceof UnionClassType
? ImmutableList.copyOf(((UnionClassType) t).getAlternativeTypes()).stream()
: Stream.of(t))
.filter(t -> thrownTypes.stream().noneMatch(x -> types.isAssignable(t, x)))
.collect(toImmutableList());
if (!toThrow.isEmpty()) {
if (!JUnitMatchers.TEST_CASE.matches(enclosing, state)) {
// Don't add throws declarations to methods that don't look like test cases, since it may
// not be a safe local refactoring.
return Optional.empty();
}
String throwsString =
toThrow.stream()
.map(t -> SuggestedFixes.qualifyType(state, fix, t))
.distinct()
.collect(joining(", "));
if (enclosing.getThrows().isEmpty()) {
// Add a new throws declaration.
fix.prefixWith(enclosing.getBody(), "throws " + throwsString);
} else {
// Append to an existing throws declaration.
fix.postfixWith(Iterables.getLast(enclosing.getThrows()), ", " + throwsString);
}
}
return Optional.of(fix.build());
}
/** Returns true if the given method symbol has a {@code @Test(expected=...)} annotation. */
private static boolean isExpectedExceptionTest(MethodSymbol sym, VisitorState state) {
Compound attribute = sym.attribute(ORG_JUNIT_TEST.get(state));
if (attribute == null) {
return false;
}
return attribute.member(EXPECTED.get(state)) != null;
}
private boolean catchVariableIsUsed(CatchTree c) {
VarSymbol sym = ASTHelpers.getSymbol(c.getParameter());
boolean[] found = {false};
c.getBlock()
.accept(
new TreeScanner<Void, Void>() {
@Override
public Void visitIdentifier(IdentifierTree node, Void unused) {
if (Objects.equals(sym, ASTHelpers.getSymbol(node))) {
found[0] = true;
}
return super.visitIdentifier(node, unused);
}
},
null);
return found[0];
}
private static final Supplier<Name> EXPECTED =
VisitorState.memoize(state -> state.getName("expected"));
private static final Supplier<Symbol> ORG_JUNIT_TEST =
VisitorState.memoize(
state -> state.getSymbolFromString(JUnitMatchers.JUNIT4_TEST_ANNOTATION));
}
| 11,050
| 43.027888
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DefaultPackage.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.common.io.Files;
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.CompilationUnitTree;
/**
* Java classes shouldn't use default package.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(summary = "Java classes shouldn't use default package", severity = WARNING)
public final class DefaultPackage extends BugChecker implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
if (state.errorProneOptions().isTestOnlyTarget()) {
return Description.NO_MATCH;
}
if (tree.getTypeDecls().stream().anyMatch(s -> isSuppressed(s, state))) {
return Description.NO_MATCH;
}
if (tree.getTypeDecls().stream()
.map(ASTHelpers::getSymbol)
.filter(x -> x != null)
.anyMatch(s -> !ASTHelpers.getGeneratedBy(s, state).isEmpty())) {
return Description.NO_MATCH;
}
if (tree.getPackageName() != null) {
return Description.NO_MATCH;
}
// module-info.* is a special file name so ignore it.
if (Files.getNameWithoutExtension(ASTHelpers.getFileName(tree)).equals("module-info")) {
return Description.NO_MATCH;
}
return describeMatch(tree);
}
}
| 2,207
| 35.196721
| 92
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ShouldHaveEvenArgs.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.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
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.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import java.util.List;
/**
* Checks that variable argument methods have even number of arguments.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary = "This method must be called with an even number of arguments.",
severity = ERROR)
public class ShouldHaveEvenArgs extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
instanceMethod()
.onDescendantOfAny(
"com.google.common.truth.MapSubject",
"com.google.common.truth.MapSubject.UsingCorrespondence",
"com.google.common.truth.MultimapSubject",
"com.google.common.truth.MultimapSubject.UsingCorrespondence")
.named("containsExactly");
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState state) {
if (!MATCHER.matches(methodInvocationTree, state)) {
return Description.NO_MATCH;
}
if (methodInvocationTree.getArguments().size() % 2 == 0) {
return Description.NO_MATCH;
}
List<? extends ExpressionTree> arguments = methodInvocationTree.getArguments();
MethodSymbol methodSymbol = getSymbol(methodInvocationTree);
if (!methodSymbol.isVarArgs()) {
return Description.NO_MATCH;
}
Type varArgsArrayType = getLast(methodSymbol.params()).type;
Type lastArgType = ASTHelpers.getType(getLast(arguments));
if (arguments.size() == methodSymbol.params().size()
&& ASTHelpers.isSameType(varArgsArrayType, lastArgType, state)) {
return Description.NO_MATCH;
}
return describeMatch(methodInvocationTree);
}
}
| 3,084
| 38.050633
| 91
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MutablePublicArray.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.hasModifier;
import static com.google.errorprone.matchers.Matchers.isArrayType;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
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.VariableTree;
import com.sun.tools.javac.tree.JCTree.JCNewArray;
import java.util.Objects;
import javax.lang.model.element.Modifier;
/** Check for public static final declaration of Arrays. */
@BugPattern(
summary =
"Non-empty arrays are mutable, so this `public static final` array is not a constant"
+ " and can be modified by clients of this class. Prefer an ImmutableList, or provide"
+ " an accessor method that returns a defensive copy.",
severity = WARNING)
public class MutablePublicArray extends BugChecker implements VariableTreeMatcher {
private static final Matcher<VariableTree> MATCHER =
allOf(
hasModifier(Modifier.PUBLIC),
hasModifier(Modifier.STATIC),
hasModifier(Modifier.FINAL),
MutablePublicArray::nonEmptyArrayMatcher);
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
if (hasAnnotation(tree, "org.junit.experimental.theories.DataPoints", state)) {
return NO_MATCH;
}
return describeMatch(tree);
}
private static boolean nonEmptyArrayMatcher(VariableTree arrayExpression, VisitorState state) {
if (!isArrayType().matches(arrayExpression, state)) {
return false;
}
ExpressionTree initializer = arrayExpression.getInitializer();
if (!(initializer instanceof JCNewArray)) {
return false;
}
JCNewArray newArray = (JCNewArray) initializer;
if (!newArray.getDimensions().isEmpty()) {
return !newArray.getDimensions().stream()
.allMatch(e -> Objects.equals(ASTHelpers.constValue(e, Integer.class), 0));
}
// For in line array initializer.
return newArray.getInitializers() != null && !newArray.getInitializers().isEmpty();
}
}
| 3,259
| 38.756098
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NCopiesOfChar.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.Description.NO_MATCH;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.getType;
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.MethodInvocationTree;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Types;
import java.util.List;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"The first argument to nCopies is the number of copies, and the second is the item to copy",
severity = ERROR)
public class NCopiesOfChar extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
staticMethod().onClass("java.util.Collections").named("nCopies");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
List<? extends ExpressionTree> arguments = tree.getArguments();
Symtab syms = state.getSymtab();
Types types = state.getTypes();
if (types.isSameType(types.unboxedTypeOrType(getType(arguments.get(1))), syms.intType)
&& types.isSameType(types.unboxedTypeOrType(getType(arguments.get(0))), syms.charType)) {
return describeMatch(
tree,
SuggestedFix.builder()
.replace(arguments.get(0), state.getSourceForNode(arguments.get(1)))
.replace(arguments.get(1), state.getSourceForNode(arguments.get(0)))
.build());
}
return NO_MATCH;
}
}
| 2,701
| 40.569231
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JUnit4ClassAnnotationNonStatic.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.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.JUnitMatchers.JUNIT_AFTER_CLASS_ANNOTATION;
import static com.google.errorprone.matchers.JUnitMatchers.JUNIT_BEFORE_CLASS_ANNOTATION;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.isStatic;
import static com.google.errorprone.matchers.Matchers.isType;
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.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.matchers.MultiMatcher.MultiMatchResult;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.Signatures;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.MethodTree;
import java.util.List;
import java.util.stream.Collectors;
import javax.lang.model.element.Modifier;
/** {@code @BeforeClass} or {@code @AfterClass} should be applied to static methods. */
@BugPattern(summary = "This method should be static", severity = ERROR)
public class JUnit4ClassAnnotationNonStatic extends BugChecker implements MethodTreeMatcher {
private static final MultiMatcher<MethodTree, AnnotationTree> CLASS_INIT_ANNOTATION =
annotations(
AT_LEAST_ONE,
anyOf(isType(JUNIT_AFTER_CLASS_ANNOTATION), isType(JUNIT_BEFORE_CLASS_ANNOTATION)));
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
MultiMatchResult<AnnotationTree> matchResult =
CLASS_INIT_ANNOTATION.multiMatchResult(tree, state);
if (!matchResult.matches() || isStatic().matches(tree, state)) {
return Description.NO_MATCH;
}
return buildDescription(tree)
.setMessage(messageForAnnos(matchResult.matchingNodes()))
.addFix(
SuggestedFixes.addModifiers(tree, state, Modifier.STATIC)
.orElse(SuggestedFix.emptyFix()))
.build();
}
// Might be a bit overkill just in case people add @BeforeClass and @AfterClass to the same
// method.
private static String messageForAnnos(List<AnnotationTree> annotationTrees) {
String annoNames =
annotationTrees.stream()
.map(a -> Signatures.prettyType(ASTHelpers.getType(a)))
.collect(Collectors.joining(" and "));
return annoNames + " can only be applied to static methods.";
}
}
| 3,428
| 42.405063
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/FallThrough.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.Iterables.getOnlyElement;
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.common.collect.Iterators;
import com.google.common.collect.PeekingIterator;
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.Reachability;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.SwitchTree;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.Position;
import java.util.List;
import java.util.regex.Pattern;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(altNames = "fallthrough", summary = "Switch case may fall through", severity = WARNING)
public class FallThrough extends BugChecker implements SwitchTreeMatcher {
private static final Pattern FALL_THROUGH_PATTERN =
Pattern.compile("\\bfalls?.?through\\b", Pattern.CASE_INSENSITIVE);
@Override
public Description matchSwitch(SwitchTree tree, VisitorState state) {
PeekingIterator<CaseTree> it = Iterators.peekingIterator(tree.getCases().iterator());
while (it.hasNext()) {
CaseTree caseTree = it.next();
if (!it.hasNext()) {
break;
}
CaseTree next = it.peek();
List<? extends StatementTree> statements = caseTree.getStatements();
if (statements == null || statements.isEmpty()) {
continue;
}
// We only care whether the last statement completes; javac would have already
// reported an error if that statement wasn't reachable, and the answer is
// independent of any preceding statements.
boolean completes = Reachability.canCompleteNormally(getLast(statements));
int endPos = caseEndPosition(state, caseTree);
if (endPos == Position.NOPOS) {
break;
}
String comments =
state
.getSourceCode()
.subSequence(endPos, ((JCTree) next).getStartPosition())
.toString()
.trim();
if (completes && !FALL_THROUGH_PATTERN.matcher(comments).find()) {
state.reportMatch(
buildDescription(next)
.setMessage(
"Execution may fall through from the previous case; add a `// fall through`"
+ " comment before this line if it was deliberate")
.build());
} else if (!completes && FALL_THROUGH_PATTERN.matcher(comments).find()) {
state.reportMatch(
buildDescription(next)
.setMessage(
"Switch case has 'fall through' comment, but execution cannot fall through"
+ " from the previous case")
.build());
}
}
return NO_MATCH;
}
private static int caseEndPosition(VisitorState state, CaseTree caseTree) {
// if the statement group is a single block statement, handle fall through comments at the
// end of the block
if (caseTree.getStatements().size() == 1) {
StatementTree only = getOnlyElement(caseTree.getStatements());
if (only instanceof BlockTree) {
BlockTree blockTree = (BlockTree) only;
return blockTree.getStatements().isEmpty()
? getStartPosition(blockTree)
: state.getEndPosition(getLast(blockTree.getStatements()));
}
}
return state.getEndPosition(caseTree);
}
}
| 4,484
| 40.146789
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DeprecatedVariable.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.getAnnotationWithSimpleName;
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.ASTHelpers;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol;
import java.util.Optional;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Applying the @Deprecated annotation to local variables or parameters has no effect",
severity = WARNING)
public class DeprecatedVariable extends BugChecker implements VariableTreeMatcher {
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
Symbol.VarSymbol sym = ASTHelpers.getSymbol(tree);
if (!ASTHelpers.hasAnnotation(sym, Deprecated.class, state)) {
return NO_MATCH;
}
switch (sym.getKind()) {
case LOCAL_VARIABLE:
case PARAMETER:
break;
default:
return NO_MATCH;
}
Description.Builder description = buildDescription(tree);
Optional.ofNullable(
getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "Deprecated"))
.map(SuggestedFix::delete)
.ifPresent(description::addFix);
return description.build();
}
}
| 2,268
| 37.457627
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ArraysAsListPrimitiveArray.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.staticMethod;
import com.google.common.collect.ImmutableMap;
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.fixes.Fix;
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.MethodInvocationTree;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ArrayType;
import java.util.EnumMap;
import java.util.Map;
import javax.lang.model.type.TypeKind;
@BugPattern(
summary = "Arrays.asList does not autobox primitive arrays, as one might expect.",
severity = ERROR)
public class ArraysAsListPrimitiveArray extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<MethodInvocationTree> ARRAYS_AS_LIST_SINGLE_ARRAY =
allOf(
staticMethod().onClass("java.util.Arrays").named("asList"),
Matchers.argumentCount(1),
Matchers.argument(0, Matchers.<ExpressionTree>isArrayType()));
private static final ImmutableMap<TypeKind, String> GUAVA_UTILS = getGuavaUtils();
static ImmutableMap<TypeKind, String> getGuavaUtils() {
Map<TypeKind, String> guavaUtils = new EnumMap<>(TypeKind.class);
guavaUtils.put(TypeKind.BOOLEAN, "Booleans");
guavaUtils.put(TypeKind.BYTE, "Bytes");
guavaUtils.put(TypeKind.SHORT, "Shorts");
guavaUtils.put(TypeKind.INT, "Ints");
guavaUtils.put(TypeKind.LONG, "Longs");
guavaUtils.put(TypeKind.CHAR, "Chars");
guavaUtils.put(TypeKind.FLOAT, "Floats");
guavaUtils.put(TypeKind.DOUBLE, "Doubles");
return ImmutableMap.copyOf(guavaUtils);
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!ARRAYS_AS_LIST_SINGLE_ARRAY.matches(tree, state)) {
return NO_MATCH;
}
ExpressionTree array = Iterables.getOnlyElement(tree.getArguments());
Type componentType = ((ArrayType) ASTHelpers.getType(array)).getComponentType();
if (!componentType.isPrimitive()) {
return NO_MATCH;
}
String guavaUtils = GUAVA_UTILS.get(componentType.getKind());
if (guavaUtils == null) {
return NO_MATCH;
}
Fix fix =
SuggestedFix.builder()
.addImport("com.google.common.primitives." + guavaUtils)
.replace(tree.getMethodSelect(), guavaUtils + ".asList")
.build();
return describeMatch(tree, fix);
}
}
| 3,643
| 39.043956
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InvalidZoneId.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.ERROR;
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.matchers.method.MethodMatchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import java.time.DateTimeException;
import java.time.ZoneId;
/**
* Validates ZoneId.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary = "Invalid zone identifier. ZoneId.of(String) will throw exception at runtime.",
severity = ERROR)
public class InvalidZoneId extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> METHOD_MATCHER =
MethodMatchers.staticMethod()
.onClass("java.time.ZoneId")
.named("of")
.withParameters("java.lang.String");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!METHOD_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
String value = ASTHelpers.constValue(getOnlyElement(tree.getArguments()), String.class);
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)) {
return Description.NO_MATCH;
}
return describeMatch(tree);
}
// https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html#of-java.lang.String-
private static boolean isValidId(String value) {
try {
ZoneId.of(value);
} catch (DateTimeException e) { // ZoneRulesException is subclass of DateTimeException
return false;
}
return true;
}
}
| 2,671
| 33.701299
| 92
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CatchAndPrintStackTrace.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.expressionStatement;
import static com.google.errorprone.matchers.Matchers.matchSingleStatementBlock;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CatchTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CatchTree;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Logging or rethrowing exceptions should usually be preferred to catching and calling"
+ " printStackTrace",
severity = WARNING)
public class CatchAndPrintStackTrace extends BugChecker implements CatchTreeMatcher {
private static final Matcher<BlockTree> MATCHER =
matchSingleStatementBlock(
expressionStatement(
instanceMethod()
.onDescendantOf("java.lang.Throwable")
.named("printStackTrace")
.withNoParameters()));
@Override
public Description matchCatch(CatchTree tree, VisitorState state) {
if (MATCHER.matches(tree.getBlock(), state)) {
return describeMatch(Iterables.getOnlyElement(tree.getBlock().getStatements()));
}
return NO_MATCH;
}
}
| 2,304
| 38.741379
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/IsInstanceIncompatibleType.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.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isCastable;
import static com.google.errorprone.util.Signatures.prettyType;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher;
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.MemberReferenceTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Type;
import java.util.List;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* @author cushon@google.com (Liam Miller-Cushon)
* @author eleanorh@google.com (Eleanor Harris)
*/
@BugPattern(summary = "This use of isInstance will always evaluate to false.", severity = ERROR)
public final class IsInstanceIncompatibleType extends BugChecker
implements MethodInvocationTreeMatcher, MemberReferenceTreeMatcher {
private static final Matcher<ExpressionTree> IS_INSTANCE =
instanceMethod().onExactClass("java.lang.Class").named("isInstance");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!IS_INSTANCE.matches(tree, state)) {
return NO_MATCH;
}
Type receiverType = classTypeArgument(tree);
if (receiverType == null) {
return NO_MATCH;
}
Type argumentType = getType(tree.getArguments().get(0));
return isCastable(argumentType, receiverType, state)
? NO_MATCH
: buildMessage(argumentType, receiverType, tree, state);
}
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
if (!IS_INSTANCE.matches(tree, state)) {
return NO_MATCH;
}
Type type = state.getTypes().findDescriptorType(getType(tree));
Type receiverType = classTypeArgument(tree);
if (receiverType == null) {
return NO_MATCH;
}
Type argumentType = ASTHelpers.getUpperBound(type.getParameterTypes().get(0), state.getTypes());
return isCastable(argumentType, receiverType, state)
? NO_MATCH
: buildMessage(argumentType, receiverType, tree, state);
}
private static @Nullable Type classTypeArgument(ExpressionTree tree) {
ExpressionTree receiver = getReceiver(tree);
if (receiver == null) {
return null;
}
List<Type> receiverTypeArguments = getType(receiver).getTypeArguments();
return !receiverTypeArguments.isEmpty() ? getOnlyElement(receiverTypeArguments) : null;
}
private Description buildMessage(Type type1, Type type2, Tree tree, VisitorState state) {
return buildDescription(tree)
.setMessage(
String.format(
"This expression will always evaluate to false because %s cannot be cast to %s",
prettyType(state.getTypes().erasure(type1)),
prettyType(state.getTypes().erasure(type2))))
.build();
}
}
| 4,209
| 38.345794
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/GetClassOnClass.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.instanceMethod;
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.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
/**
* @author chy@google.com (Christine Yang)
* @author kmuhlrad@google.com (Katy Muhlrad)
*/
@BugPattern(
summary =
"Calling getClass() on an object of type Class returns the Class object for "
+ "java.lang.Class; you probably meant to operate on the object directly",
severity = ERROR)
public class GetClassOnClass extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> getClassMethodMatcher =
instanceMethod().onExactClass("java.lang.Class").named("getClass");
/** Suggests removing getClass() or changing to Class.class. */
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (getClassMethodMatcher.matches(tree, state)) {
String methodInvoker = state.getSourceForNode(ASTHelpers.getReceiver(tree));
Fix removeGetClass = SuggestedFix.replace(tree, methodInvoker);
Fix changeToClassDotClass = SuggestedFix.replace(tree, "Class.class");
return buildDescription(tree).addFix(removeGetClass).addFix(changeToClassDotClass).build();
}
return Description.NO_MATCH;
}
}
| 2,435
| 40.288136
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ForOverrideChecker.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.ImmutableList.toImmutableList;
import static com.google.common.collect.Streams.findLast;
import static com.google.common.collect.Streams.stream;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import static com.google.errorprone.util.ASTHelpers.streamSuperMethods;
import static java.util.stream.Stream.concat;
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.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
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.tree.Tree.Kind;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Type;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.lang.model.element.Modifier;
/**
* Verifies that methods marked {@link com.google.errorprone.annotations.ForOverride} are only
* called from the defining class.
*
* <p>Specifically, all calls to the method have to occur within the context of the outermost class
* where the method is defined.
*/
@BugPattern(
name = "ForOverride",
summary =
"Method annotated @ForOverride must be protected or package-private and only invoked from "
+ "declaring class, or from an override of the method",
severity = ERROR)
public class ForOverrideChecker extends BugChecker
implements MethodInvocationTreeMatcher, MethodTreeMatcher {
private static final String FOR_OVERRIDE = "com.google.errorprone.annotations.ForOverride";
private static final String MESSAGE_BASE = "Method annotated @ForOverride ";
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
MethodSymbol method = ASTHelpers.getSymbol(tree);
Type currentClass = getOutermostClass(state);
if (method.isStatic() || method.isConstructor() || currentClass == null) {
return Description.NO_MATCH;
}
// allow super.foo() calls to @ForOverride methods from overriding methods
if (isSuperCall(currentClass, tree, state)) {
MethodTree currentMethod = findDirectMethod(state.getPath());
// currentMethod might be null if we are in a field initializer
if (currentMethod != null) {
// MethodSymbol.overrides doesn't check that names match, so we need to do that first.
if (currentMethod.getName().equals(method.name)) {
MethodSymbol currentMethodSymbol = ASTHelpers.getSymbol(currentMethod);
if (currentMethodSymbol.overrides(
method, (TypeSymbol) method.owner, state.getTypes(), /* checkResult= */ true)) {
return Description.NO_MATCH;
}
}
}
}
ImmutableList<MethodSymbol> overriddenMethods = getOverriddenMethods(state, method);
for (Symbol overriddenMethod : overriddenMethods) {
Type declaringClass = ASTHelpers.outermostClass(overriddenMethod).asType();
if (!ASTHelpers.isSameType(declaringClass, currentClass, state)) {
String customMessage =
MESSAGE_BASE
+ "must not be invoked directly "
+ "(except by the declaring class, "
+ declaringClass
+ ")";
return buildDescription(tree).setMessage(customMessage).build();
}
}
return Description.NO_MATCH;
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
MethodSymbol method = ASTHelpers.getSymbol(tree);
if (method.isStatic() || method.isConstructor()) {
return Description.NO_MATCH;
}
if (method.getModifiers().contains(Modifier.PUBLIC)
|| method.getModifiers().contains(Modifier.PRIVATE)) {
ImmutableList<MethodSymbol> overriddenMethods = getOverriddenMethods(state, method);
if (!overriddenMethods.isEmpty()) {
MethodSymbol nearestForOverrideMethod = overriddenMethods.get(0);
String customMessage = "must have protected or package-private visibility";
if (nearestForOverrideMethod.equals(method)) {
// The method itself is @ForOverride but is too visible
customMessage = MESSAGE_BASE + customMessage;
} else {
// The method overrides an @ForOverride method and expands its visibility
customMessage =
String.format(
"Method overrides @ForOverride method %s.%s, so it %s",
nearestForOverrideMethod.enclClass(), nearestForOverrideMethod, customMessage);
}
return buildDescription(tree).setMessage(customMessage).build();
}
}
return Description.NO_MATCH;
}
/**
* Returns the method that 'directly' contains the leaf element of the given path.
*
* <p>By 'direct', we mean that if the leaf is part of a field initializer of a class, then it is
* considered to not be part of any method.
*/
@Nullable
private static MethodTree findDirectMethod(TreePath path) {
while (true) {
path = path.getParentPath();
if (path != null) {
Tree leaf = path.getLeaf();
if (leaf instanceof MethodTree) {
return (MethodTree) leaf;
}
// if we find a ClassTree before a MethodTree, we must be an initializer
if (leaf instanceof ClassTree) {
return null;
}
} else {
return null;
}
}
}
/** Returns true if this method invocation is of the form {@code super.foo()} */
private static boolean isSuperCall(Type type, MethodInvocationTree tree, VisitorState state) {
if (tree.getMethodSelect().getKind() == Kind.MEMBER_SELECT) {
MemberSelectTree select = (MemberSelectTree) tree.getMethodSelect();
if (select.getExpression().getKind() == Kind.IDENTIFIER) {
IdentifierTree ident = (IdentifierTree) select.getExpression();
return ident.getName().contentEquals("super");
} else if (select.getExpression().getKind() == Kind.MEMBER_SELECT) {
MemberSelectTree subSelect = (MemberSelectTree) select.getExpression();
return subSelect.getIdentifier().contentEquals("super")
&& ASTHelpers.isSameType(ASTHelpers.getType(subSelect.getExpression()), type, state);
}
}
return false;
}
/**
* Get overridden @ForOverride methods.
*
* @param state the VisitorState
* @param method the method to find overrides for
* @return a list of methods annotated @ForOverride that the method overrides, including the
* method itself if it has the annotation
*/
private static ImmutableList<MethodSymbol> getOverriddenMethods(
VisitorState state, MethodSymbol method) {
// Static methods cannot override, only overload.
if (method.isStatic()) {
throw new IllegalArgumentException(
"getOverriddenMethods may not be called on a static method");
}
return concat(Stream.of(method), streamSuperMethods(method, state.getTypes()))
.filter(member -> hasAnnotation(member, FOR_OVERRIDE, state))
.collect(toImmutableList());
}
/** Get the outermost class/interface/enum of an element, or null if none. */
@Nullable
private static Type getOutermostClass(VisitorState state) {
return findLast(
stream(state.getPath())
.filter(t -> t instanceof ClassTree)
.map(t -> ASTHelpers.getType(t)))
.orElse(null);
}
}
| 8,659
| 38.907834
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AbstractToString.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.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.matchers.Matchers.symbolHasAnnotation;
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 com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.FormatMethod;
import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.CompoundAssignmentTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.predicates.TypePredicate;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.CompoundAssignmentTree;
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.source.util.TreePath;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.MethodType;
import java.util.List;
import java.util.Optional;
import javax.lang.model.type.TypeKind;
/**
* An abstract matcher for implicit and explicit calls to {@code Object.toString()}, for use on
* types that do not have a human-readable {@code toString()} implementation.
*
* <p>See examples in {@link StreamToString} and {@link ArrayToString}.
*/
public abstract class AbstractToString extends BugChecker
implements BinaryTreeMatcher, MethodInvocationTreeMatcher, CompoundAssignmentTreeMatcher {
/** The type to match on. */
protected abstract TypePredicate typePredicate();
/**
* Constructs a fix for an implicit toString call, e.g. from string concatenation or from passing
* an argument to {@code println} or {@code StringBuilder.append}.
*
* @param tree the tree node for the expression being converted to a String
*/
protected abstract Optional<Fix> implicitToStringFix(ExpressionTree tree, VisitorState state);
/** Adds the description message for match on the type without fixes. */
protected Optional<String> descriptionMessageForDefaultMatch(Type type, VisitorState state) {
return Optional.empty();
}
/** Whether this kind of toString call is allowable for this check. */
protected boolean allowableToStringKind(ToStringKind toStringKind) {
return false;
}
/**
* Constructs a fix for an explicit toString call, e.g. from {@code Object.toString()} or {@code
* String.valueOf()}.
*
* @param parent the expression's parent (e.g. {@code String.valueOf(expression)})
*/
protected abstract Optional<Fix> toStringFix(
Tree parent, ExpressionTree expression, VisitorState state);
private static final Matcher<ExpressionTree> TO_STRING =
instanceMethod().anyClass().named("toString").withNoParameters();
private static final Matcher<ExpressionTree> FLOGGER_LOG =
instanceMethod().onDescendantOf("com.google.common.flogger.LoggingApi").named("log");
private static final Matcher<ExpressionTree> FORMAT_METHOD =
symbolHasAnnotation(FormatMethod.class);
private static final Matcher<ExpressionTree> STRING_FORMAT =
staticMethod().onClass("java.lang.String").named("format");
private static final Matcher<ExpressionTree> VALUE_OF =
staticMethod()
.onClass("java.lang.String")
.named("valueOf")
.withParameters("java.lang.Object");
private static final Matcher<ExpressionTree> PRINT_STRING =
anyOf(
instanceMethod()
.onDescendantOf("java.io.PrintStream")
.namedAnyOf("print", "println")
.withParameters("java.lang.Object"),
instanceMethod()
.onExactClass("java.lang.StringBuilder")
.named("append")
.withParameters("java.lang.Object"));
private static boolean isInVarargsPosition(
ExpressionTree argTree, MethodInvocationTree methodInvocationTree, VisitorState state) {
int parameterCount = getSymbol(methodInvocationTree).getParameters().size();
List<? extends ExpressionTree> arguments = methodInvocationTree.getArguments();
// Don't match if we're passing an array into a varargs parameter, but do match if there are
// other parameters along with it.
return (arguments.size() > parameterCount || !state.getTypes().isArray(getType(argTree)))
&& arguments.indexOf(argTree) >= parameterCount - 1;
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (PRINT_STRING.matches(tree, state)) {
for (ExpressionTree argTree : tree.getArguments()) {
handleStringifiedTree(argTree, ToStringKind.IMPLICIT, state);
}
}
if (VALUE_OF.matches(tree, state)) {
for (ExpressionTree argTree : tree.getArguments()) {
handleStringifiedTree(
tree,
argTree,
ToStringKind.EXPLICIT,
state.withPath(new TreePath(state.getPath(), argTree)));
}
}
if (TO_STRING.matches(tree, state)) {
ExpressionTree receiver = getReceiver(tree);
if (receiver != null) {
handleStringifiedTree(tree, receiver, ToStringKind.EXPLICIT, state);
}
}
if (FORMAT_METHOD.matches(tree, state)) {
for (ExpressionTree argTree : tree.getArguments()) {
if (isInVarargsPosition(argTree, tree, state)) {
handleStringifiedTree(argTree, ToStringKind.FORMAT_METHOD, state);
}
}
}
if (STRING_FORMAT.matches(tree, state)) {
for (ExpressionTree argTree : tree.getArguments()) {
if (isInVarargsPosition(argTree, tree, state)) {
handleStringifiedTree(argTree, ToStringKind.IMPLICIT, state);
}
}
}
if (FLOGGER_LOG.matches(tree, state)) {
for (ExpressionTree argTree : tree.getArguments()) {
handleStringifiedTree(argTree, ToStringKind.FLOGGER, state);
}
}
return NO_MATCH;
}
@Override
public Description matchBinary(BinaryTree tree, VisitorState state) {
if (!state.getTypes().isSameType(getType(tree), state.getSymtab().stringType)) {
return NO_MATCH;
}
if (tree.getKind() == Kind.PLUS) {
handleStringifiedTree(tree.getLeftOperand(), ToStringKind.IMPLICIT, state);
handleStringifiedTree(tree.getRightOperand(), ToStringKind.IMPLICIT, state);
}
if (tree.getKind() == Kind.PLUS_ASSIGNMENT) {
handleStringifiedTree(tree.getRightOperand(), ToStringKind.IMPLICIT, state);
}
return NO_MATCH;
}
@Override
public Description matchCompoundAssignment(CompoundAssignmentTree tree, VisitorState state) {
if (state.getTypes().isSameType(getType(tree.getVariable()), state.getSymtab().stringType)
&& tree.getKind() == Kind.PLUS_ASSIGNMENT) {
handleStringifiedTree(tree.getExpression(), ToStringKind.IMPLICIT, state);
}
return NO_MATCH;
}
private void handleStringifiedTree(
ExpressionTree tree, ToStringKind toStringKind, VisitorState state) {
handleStringifiedTree(tree, tree, toStringKind, state);
}
private void handleStringifiedTree(
Tree parent, ExpressionTree tree, ToStringKind toStringKind, VisitorState state) {
Type type = type(tree);
if (type.getKind() == TypeKind.NULL
|| !typePredicate().apply(type, state)
|| allowableToStringKind(toStringKind)) {
return;
}
state.reportMatch(maybeFix(tree, state, type, getFix(tree, state, parent, toStringKind)));
}
private static Type type(ExpressionTree tree) {
Type type = getType(tree);
if (type instanceof MethodType) {
return type.getReturnType();
}
return type;
}
private Optional<Fix> getFix(
ExpressionTree tree, VisitorState state, Tree parent, ToStringKind toStringKind) {
switch (toStringKind) {
case IMPLICIT:
case FLOGGER:
case FORMAT_METHOD:
return implicitToStringFix(tree, state);
case EXPLICIT:
return toStringFix(parent, tree, state);
case NONE:
// fall out
}
throw new AssertionError();
}
private Description maybeFix(Tree tree, VisitorState state, Type matchedType, Optional<Fix> fix) {
Description.Builder description = buildDescription(tree);
fix.ifPresent(description::addFix);
descriptionMessageForDefaultMatch(matchedType, state).ifPresent(description::setMessage);
return description.build();
}
enum ToStringKind {
/** String concatenation, or an enclosing print method. */
IMPLICIT,
/** {@code String.valueOf()} or {@code #toString()}. */
EXPLICIT,
FORMAT_METHOD,
FLOGGER,
NONE,
}
}
| 9,700
| 37.496032
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SwigMemoryLeak.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 com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.LiteralTreeMatcher;
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.LiteralTree;
import com.sun.source.tree.MethodTree;
import javax.lang.model.element.Name;
/**
* @author irogers@google.com (Ian Rogers)
*/
@BugPattern(
summary = "SWIG generated code that can't call a C++ destructor will leak memory",
severity = WARNING)
public class SwigMemoryLeak extends BugChecker implements LiteralTreeMatcher {
private static final Matcher<MethodTree> ENCLOSING_CLASS_HAS_FINALIZER =
Matchers.enclosingClass(Matchers.hasMethod(Matchers.methodIsNamed("finalize")));
@Override
public Description matchLiteral(LiteralTree tree, VisitorState state) {
// Is there a literal matching the message SWIG uses to indicate a
// destructor problem?
if (tree.getValue() == null
|| !tree.getValue().equals("C++ destructor does not have public access")) {
return NO_MATCH;
}
// Is it within a delete method?
MethodTree enclosingMethodTree =
ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class);
Name name = enclosingMethodTree.getName();
if (!name.contentEquals("delete")) {
return NO_MATCH;
}
// Does the enclosing class lack a finalizer?
if (ENCLOSING_CLASS_HAS_FINALIZER.matches(enclosingMethodTree, state)) {
return NO_MATCH;
}
return buildDescription(tree).build();
}
}
| 2,472
| 37.046154
| 86
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ObjectToString.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.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.predicates.TypePredicate;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.util.Names;
import java.util.Optional;
/**
* Warns against calling toString() on Objects which don't have toString() method overridden and
* won't produce meaningful output.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary =
"Calling toString on Objects that don't override toString() doesn't"
+ " provide useful information",
severity = WARNING)
public class ObjectToString extends AbstractToString {
private static boolean finalNoOverrides(Type type, VisitorState state) {
if (type == null) {
return false;
}
// We don't flag use of toString() on non-final objects because sub classes might have a
// meaningful toString() override.
if (!type.isFinal()) {
return false;
}
Types types = state.getTypes();
Names names = state.getNames();
// find Object.toString
MethodSymbol toString =
(MethodSymbol) state.getSymtab().objectType.tsym.members().findFirst(names.toString);
// We explore the superclasses of the receiver type as well as the interfaces it
// implements and we collect all overrides of java.lang.Object.toString(). If one of those
// overrides is present, then we don't flag it.
return Iterables.isEmpty(
ASTHelpers.scope(types.membersClosure(type, /* skipInterface= */ false))
.getSymbolsByName(
names.toString,
m ->
m != toString
&& m.overrides(toString, type.tsym, types, /* checkResult= */ false)));
}
@Override
protected TypePredicate typePredicate() {
return ObjectToString::finalNoOverrides;
}
@Override
protected Optional<String> descriptionMessageForDefaultMatch(Type type, VisitorState state) {
return Optional.of(
String.format(
"%1$s is final and does not override Object.toString, so converting it to a string"
+ " will print its identity (e.g. `%2$s@4488aabb`) instead of useful information.",
SuggestedFixes.prettyType(type, state), type.tsym.getSimpleName()));
}
@Override
protected Optional<Fix> implicitToStringFix(ExpressionTree tree, VisitorState state) {
return Optional.empty();
}
@Override
protected Optional<Fix> toStringFix(Tree parent, ExpressionTree tree, VisitorState state) {
return Optional.empty();
}
}
| 3,651
| 35.888889
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InterfaceWithOnlyStatics.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.errorprone.bugpatterns.inject.dagger.DaggerAnnotations.isAnyModule;
import static com.google.errorprone.util.ASTHelpers.createPrivateConstructor;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isStatic;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
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.ErrorProneToken;
import com.sun.source.tree.ClassTree;
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;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.parser.Tokens.TokenKind;
import java.util.List;
import javax.lang.model.element.Modifier;
/**
* Bugpattern to detect interfaces used only to store static fields/methods.
*
* @author ghm@google.com (Graeme Morgan)
*/
@BugPattern(
summary =
"This interface only contains static fields and methods; consider making it a final class "
+ "instead to prevent subclassing.",
severity = SeverityLevel.WARNING)
public final class InterfaceWithOnlyStatics extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (!tree.getImplementsClause().isEmpty()) {
return Description.NO_MATCH;
}
if (isAnyModule().matches(tree, state)) {
return Description.NO_MATCH;
}
List<? extends Tree> members = tree.getMembers();
ClassSymbol symbol = getSymbol(tree);
if (!symbol.isInterface() || symbol.isAnnotationType()) {
return Description.NO_MATCH;
}
int staticMembers = 0;
int nonStaticMembers = 0;
for (Tree member : members) {
Symbol memberSymbol = getSymbol(member);
if (memberSymbol == null) {
return Description.NO_MATCH;
}
if (isStatic(memberSymbol)) {
staticMembers++;
} else {
nonStaticMembers++;
}
}
if (nonStaticMembers > 0 || staticMembers == 0) {
return Description.NO_MATCH;
}
SuggestedFix.Builder suggestedFix = SuggestedFix.builder();
for (Tree member : members) {
if (member instanceof VariableTree) {
VariableTree variableTree = (VariableTree) member;
SuggestedFixes.addModifiers(
variableTree, state, Modifier.FINAL, Modifier.STATIC, Modifier.PUBLIC)
.ifPresent(suggestedFix::merge);
}
if (member instanceof MethodTree) {
MethodTree methodTree = (MethodTree) member;
SuggestedFixes.addModifiers(methodTree, state, Modifier.PUBLIC)
.ifPresent(suggestedFix::merge);
}
}
suggestedFix
.merge(fixClass(tree, state))
.postfixWith(getLast(members), "\n" + createPrivateConstructor(tree));
return describeMatch(tree, suggestedFix.build());
}
private static SuggestedFix fixClass(ClassTree classTree, VisitorState state) {
int startPos = getStartPosition(classTree);
int endPos = getStartPosition(classTree.getMembers().get(0));
List<ErrorProneToken> tokens = state.getOffsetTokens(startPos, endPos);
String modifiers =
getSymbol(classTree).owner.enclClass() == null ? "final class" : "static final class";
SuggestedFix.Builder fix = SuggestedFix.builder();
for (ErrorProneToken token : tokens) {
if (token.kind() == TokenKind.INTERFACE) {
fix.replace(token.pos(), token.endPos(), modifiers);
}
}
return fix.build();
}
}
| 4,615
| 37.789916
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MisusedDayOfYear.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.ERROR;
import com.google.errorprone.BugPattern;
import java.util.Optional;
/** Ban use of D (day-of-year) in a date format pattern that also contains M (month-of-year). */
@BugPattern(
summary =
"Use of 'DD' (day of year) in a date pattern with 'MM' (month of year) is not likely to be"
+ " intentional, as it would lead to dates like 'March 73rd'.",
severity = ERROR)
public final class MisusedDayOfYear extends MisusedDateFormat {
@Override
Optional<String> rewriteTo(String pattern) {
boolean[] containsD = new boolean[1];
boolean[] containsM = new boolean[1];
parseDateFormat(
pattern,
new DateFormatConsumer() {
@Override
public void consumeLiteral(char literal) {}
@Override
public void consumeSpecial(char special) {
if (special == 'D') {
containsD[0] = true;
}
if (special == 'M') {
containsM[0] = true;
}
}
});
if (containsD[0] && containsM[0]) {
return Optional.of(replaceFormatChar(pattern, 'D', 'd'));
}
return Optional.empty();
}
}
| 1,876
| 31.929825
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BoxedPrimitiveConstructor.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.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.toType;
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.isSameType;
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.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.LiteralTree;
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.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import javax.annotation.Nullable;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "valueOf or autoboxing provides better time and space performance",
severity = SeverityLevel.WARNING,
tags = StandardTags.PERFORMANCE)
public class BoxedPrimitiveConstructor extends BugChecker implements NewClassTreeMatcher {
private static final Matcher<Tree> TO_STRING =
toType(
ExpressionTree.class, instanceMethod().anyClass().named("toString").withNoParameters());
private static final Matcher<Tree> HASH_CODE =
toType(
ExpressionTree.class, instanceMethod().anyClass().named("hashCode").withNoParameters());
private static final Matcher<Tree> COMPARE_TO =
toType(
ExpressionTree.class,
instanceMethod().onDescendantOf("java.lang.Comparable").named("compareTo"));
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
Symbol sym = ASTHelpers.getSymbol(tree.getIdentifier());
if (sym == null) {
return NO_MATCH;
}
Types types = state.getTypes();
Symtab symtab = state.getSymtab();
// TODO(cushon): consider handling String also
if (sym.equals(types.boxedClass(symtab.byteType))
|| sym.equals(types.boxedClass(symtab.charType))
|| sym.equals(types.boxedClass(symtab.shortType))
|| sym.equals(types.boxedClass(symtab.intType))
|| sym.equals(types.boxedClass(symtab.longType))
|| sym.equals(types.boxedClass(symtab.doubleType))
|| sym.equals(types.boxedClass(symtab.floatType))
|| sym.equals(types.boxedClass(symtab.booleanType))) {
return describeMatch(tree, buildFix(tree, state));
}
return NO_MATCH;
}
private static Fix buildFix(NewClassTree tree, VisitorState state) {
boolean autoboxFix = shouldAutoboxFix(state);
Types types = state.getTypes();
Type type = types.unboxedTypeOrType(getType(tree));
if (types.isSameType(type, state.getSymtab().booleanType)) {
Object value = literalValue(tree.getArguments().iterator().next());
if (value instanceof Boolean) {
return SuggestedFix.replace(tree, literalFix((boolean) value, autoboxFix));
} else if (value instanceof String) {
return SuggestedFix.replace(
tree, literalFix(Boolean.parseBoolean((String) value), autoboxFix));
}
}
// Primitive constructors are all unary
JCTree.JCExpression arg = (JCTree.JCExpression) getOnlyElement(tree.getArguments());
Type argType = getType(arg);
if (autoboxFix && argType.isPrimitive()) {
return SuggestedFix.builder()
.replace(getStartPosition(tree), arg.getStartPosition(), maybeCast(state, type, argType))
.replace(state.getEndPosition(arg), state.getEndPosition(tree), "")
.build();
}
JCTree parent = (JCTree) state.getPath().getParentPath().getParentPath().getLeaf();
if (TO_STRING.matches(parent, state)) {
// e.g. new Integer($A).toString() -> String.valueOf($A)
return SuggestedFix.builder()
.replace(parent.getStartPosition(), arg.getStartPosition(), "String.valueOf(")
.replace(state.getEndPosition(arg), state.getEndPosition(parent), ")")
.build();
}
String typeName = state.getSourceForNode(tree.getIdentifier());
DoubleAndFloatStatus doubleAndFloatStatus = doubleAndFloatStatus(state, type, argType);
if (HASH_CODE.matches(parent, state)) {
// e.g. new Integer($A).hashCode() -> Integer.hashCode($A)
SuggestedFix.Builder fix = SuggestedFix.builder();
String optionalCast = "";
String optionalSuffix = "";
switch (doubleAndFloatStatus) {
case PRIMITIVE_DOUBLE_INTO_FLOAT:
// new Float(double).compareTo($foo) => Float.compare((float) double, foo)
optionalCast = "(float) ";
break;
case BOXED_DOUBLE_INTO_FLOAT:
// new Float(Double).compareTo($foo) => Float.compare(Double.floatValue(), foo)
optionalSuffix = ".floatValue()";
break;
default:
break;
}
String replacement = String.format("%s.hashCode(", typeName);
return fix.replace(
parent.getStartPosition(), arg.getStartPosition(), replacement + optionalCast)
.replace(state.getEndPosition(arg), state.getEndPosition(parent), optionalSuffix + ")")
.build();
}
if (COMPARE_TO.matches(parent, state)
&& ASTHelpers.getReceiver((ExpressionTree) parent).equals(tree)) {
JCMethodInvocation compareTo = (JCMethodInvocation) parent;
// e.g. new Integer($A).compareTo($B) -> Integer.compare($A, $B)
JCTree.JCExpression rhs = getOnlyElement(compareTo.getArguments());
String optionalCast = "";
String optionalSuffix = "";
switch (doubleAndFloatStatus) {
case PRIMITIVE_DOUBLE_INTO_FLOAT:
// new Float(double).compareTo($foo) => Float.compare((float) double, foo)
optionalCast = "(float) ";
break;
case BOXED_DOUBLE_INTO_FLOAT:
// new Float(Double).compareTo($foo) => Float.compare(Double.floatValue(), foo)
optionalSuffix = ".floatValue()";
break;
default:
break;
}
return SuggestedFix.builder()
.replace(
compareTo.getStartPosition(),
arg.getStartPosition(),
String.format("%s.compare(%s", typeName, optionalCast))
.replace(
/* startPos= */ state.getEndPosition(arg),
/* endPos= */ rhs.getStartPosition(),
String.format("%s, ", optionalSuffix))
.replace(state.getEndPosition(rhs), state.getEndPosition(compareTo), ")")
.build();
}
// Patch new Float(Double) => Float.valueOf(float) by downcasting the double, since
// neither valueOf(float) nor valueOf(String) match.
String prefixToArg;
String suffix = "";
switch (doubleAndFloatStatus) {
case PRIMITIVE_DOUBLE_INTO_FLOAT:
// new Float(double) => Float.valueOf((float) double)
prefixToArg = String.format("%s.valueOf(%s", typeName, "(float) ");
break;
case BOXED_DOUBLE_INTO_FLOAT:
// new Float(Double) => Double.floatValue()
prefixToArg = "";
suffix = ".floatValue(";
break;
default:
prefixToArg = String.format("%s.valueOf(", typeName);
break;
}
return SuggestedFix.builder()
.replace(getStartPosition(tree), arg.getStartPosition(), prefixToArg)
.postfixWith(arg, suffix)
.build();
}
private static String maybeCast(VisitorState state, Type type, Type argType) {
if (doubleAndFloatStatus(state, type, argType)
== DoubleAndFloatStatus.PRIMITIVE_DOUBLE_INTO_FLOAT) {
// e.g.: new Float(3.0d) => (float) 3.0d
return "(float) ";
}
// primitive widening conversions can't be combined with autoboxing, so add a
// explicit widening cast unless we're sure the expression doesn't get autoboxed
ASTHelpers.TargetType targetType = ASTHelpers.targetType(state);
if (targetType != null
&& !isSameType(type, argType, state)
&& !isSameType(targetType.type(), type, state)) {
return String.format("(%s) ", type);
}
return "";
}
private enum DoubleAndFloatStatus {
NONE,
PRIMITIVE_DOUBLE_INTO_FLOAT,
BOXED_DOUBLE_INTO_FLOAT
}
private static DoubleAndFloatStatus doubleAndFloatStatus(
VisitorState state, Type receiverType, Type argType) {
Types types = state.getTypes();
if (!types.isSameType(receiverType, state.getSymtab().floatType)) {
return DoubleAndFloatStatus.NONE;
}
if (types.isSameType(argType, types.boxedClass(state.getSymtab().doubleType).type)) {
return DoubleAndFloatStatus.BOXED_DOUBLE_INTO_FLOAT;
}
if (types.isSameType(argType, state.getSymtab().doubleType)) {
return DoubleAndFloatStatus.PRIMITIVE_DOUBLE_INTO_FLOAT;
}
return DoubleAndFloatStatus.NONE;
}
private static boolean shouldAutoboxFix(VisitorState state) {
switch (state.getPath().getParentPath().getLeaf().getKind()) {
case METHOD_INVOCATION:
// autoboxing a method argument affects overload resolution
return false;
case MEMBER_SELECT:
// can't select members on primitives (e.g. `theInteger.toString()`)
return false;
case TYPE_CAST:
// can't combine autoboxing and casts to reference types
return false;
default:
return true;
}
}
private static String literalFix(boolean value, boolean autoboxFix) {
if (autoboxFix) {
return value ? "true" : "false";
}
return value ? "Boolean.TRUE" : "Boolean.FALSE";
}
@Nullable
private static Object literalValue(Tree arg) {
if (!(arg instanceof LiteralTree)) {
return null;
}
return ((LiteralTree) arg).getValue();
}
}
| 11,039
| 38.428571
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/WrongOneof.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.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.getLast;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.predicates.TypePredicates.isDescendantOf;
import static com.google.errorprone.util.ASTHelpers.enumValues;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.stripParentheses;
import static com.google.errorprone.util.Reachability.canCompleteNormally;
import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.SwitchTreeMatcher;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions.ConstantExpression;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.predicates.TypePredicate;
import com.sun.source.tree.CaseTree;
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.StatementTree;
import com.sun.source.tree.SwitchTree;
import com.sun.source.util.TreePath;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
/** Matches always-default expressions in oneof switches. */
@BugPattern(
severity = ERROR,
summary = "This field is guaranteed not to be set given it's within a switch over a one_of.")
public final class WrongOneof extends BugChecker implements SwitchTreeMatcher {
private static final TypePredicate ONE_OF_ENUM =
isDescendantOf("com.google.protobuf.AbstractMessageLite.InternalOneOfEnum");
private final ConstantExpressions constantExpressions;
@Inject
WrongOneof(ConstantExpressions constantExpressions) {
this.constantExpressions = constantExpressions;
}
@Override
public Description matchSwitch(SwitchTree tree, VisitorState state) {
if (!ONE_OF_ENUM.apply(getType(tree.getExpression()), state)) {
return NO_MATCH;
}
ExpressionTree expression = stripParentheses(tree.getExpression());
if (!(expression instanceof MethodInvocationTree)) {
return NO_MATCH;
}
ExpressionTree receiver = getReceiver(expression);
if (receiver == null) {
return NO_MATCH;
}
constantExpressions
.constantExpression(receiver, state)
.ifPresent(constantReceiver -> processSwitch(tree, constantReceiver, state));
return NO_MATCH;
}
private void processSwitch(
SwitchTree tree, ConstantExpression constantReceiver, VisitorState state) {
ImmutableSet<String> getters =
enumValues(getType(tree.getExpression()).tsym).stream()
.map(WrongOneof::getter)
.collect(toImmutableSet());
// Keep track of which getters might be set.
Set<String> allowableGetters = new HashSet<>();
for (CaseTree caseTree : tree.getCases()) {
// Break out once we reach a default.
if (caseTree.getExpression() == null) {
break;
}
allowableGetters.add(
getter(((IdentifierTree) caseTree.getExpression()).getName().toString()));
scanForInvalidGetters(getters, allowableGetters, caseTree, constantReceiver, state);
List<? extends StatementTree> statements = caseTree.getStatements();
if (statements != null
&& !statements.isEmpty()
&& !canCompleteNormally(getLast(statements))) {
allowableGetters.clear();
}
}
}
private void scanForInvalidGetters(
Set<String> getters,
Set<String> allowableGetters,
CaseTree caseTree,
ConstantExpression receiverSymbolChain,
VisitorState state) {
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitMethodInvocation(MethodInvocationTree methodInvocationTree, Void unused) {
ExpressionTree receiver = getReceiver(methodInvocationTree);
if (receiver == null) {
return super.visitMethodInvocation(methodInvocationTree, null);
}
if (!constantExpressions
.constantExpression(receiver, state)
.map(receiverSymbolChain::equals)
.orElse(false)) {
return super.visitMethodInvocation(methodInvocationTree, null);
}
String methodName =
((MemberSelectTree) methodInvocationTree.getMethodSelect()).getIdentifier().toString();
if (!allowableGetters.contains(methodName) && getters.contains(methodName)) {
state.reportMatch(
buildDescription(methodInvocationTree)
.setMessage(
String.format(
"%s is guaranteed to return the default instance, given this is"
+ " within a switch over a one_of.",
methodName))
.build());
}
return super.visitMethodInvocation(methodInvocationTree, null);
}
}.scan(new TreePath(state.getPath(), caseTree), null);
}
private static String getter(String enumCase) {
return "get" + CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, enumCase);
}
}
| 6,196
| 39.24026
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InjectOnBugCheckers.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.fixes.SuggestedFixes.qualifyType;
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.hasDirectAnnotationWithSimpleName;
import static com.google.errorprone.util.ASTHelpers.isGeneratedConstructor;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
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.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.MethodTree;
/** A BugPattern; see the summary. */
@BugPattern(severity = WARNING, summary = "BugChecker constructors should be marked @Inject.")
public final class InjectOnBugCheckers extends BugChecker implements MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
var symbol = getSymbol(tree);
if (!symbol.isConstructor()) {
return NO_MATCH;
}
if (isGeneratedConstructor(tree)) {
return NO_MATCH;
}
if (hasDirectAnnotationWithSimpleName(tree, "Inject")) {
return NO_MATCH;
}
if (!isSubtype(
symbol.owner.type, state.getTypeFromString(BugChecker.class.getCanonicalName()), state)
|| !hasAnnotation(symbol.owner, BugPattern.class, state)) {
return NO_MATCH;
}
if (tree.getParameters().isEmpty()
|| !tree.getParameters().stream()
.allMatch(
p ->
isSubtype(
getType(p),
state.getTypeFromString(ErrorProneFlags.class.getCanonicalName()),
state))) {
return NO_MATCH;
}
var fix = SuggestedFix.builder();
return describeMatch(
tree,
fix.prefixWith(tree, "@" + qualifyType(state, fix, "javax.inject.Inject") + " ").build());
}
}
| 2,929
| 39.136986
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NonApiType.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.predicates.TypePredicates.anyOf;
import static com.google.errorprone.predicates.TypePredicates.anything;
import static com.google.errorprone.predicates.TypePredicates.isDescendantOf;
import static com.google.errorprone.predicates.TypePredicates.isExactType;
import static com.google.errorprone.predicates.TypePredicates.not;
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.methodIsPublicAndNotAnOverride;
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.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.predicates.TypePredicate;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Type;
import java.util.ArrayDeque;
import java.util.Deque;
/** Flags instances of non-API types from being accepted or returned in APIs. */
@BugPattern(
summary = "Certain types should not be passed across API boundaries.",
// something about reducing build visibility
severity = WARNING)
public final class NonApiType extends BugChecker implements MethodTreeMatcher {
// TODO(kak): consider creating an annotation (e.g., `@NonApiType` or `@NotForPublicApi`) that
// users could apply to their own types.
private static final String FLOGGER_LINK = "";
private static final String TYPE_GENERALITY_LINK = "";
private static final String INTERFACES_NOT_IMPLS_LINK = "";
private static final String PRIMITIVE_ARRAYS_LINK = "";
private static final String PROTO_TIME_SERIALIZATION_LINK = "";
private static final String ITERATOR_LINK = "";
private static final String STREAM_LINK = "";
private static final String OPTIONAL_AS_PARAM_LINK = "";
private static final String PREFER_JDK_OPTIONAL_LINK = "";
private static final TypePredicate NON_GRAPH_WRAPPER =
not(isDescendantOf("com.google.apps.framework.producers.GraphWrapper"));
private static final ImmutableSet<TypeToCheck> NON_API_TYPES =
ImmutableSet.of(
// primitive arrays
withPublicVisibility(
anyOf(
(t, s) -> isSameType(t, s.getTypes().makeArrayType(s.getSymtab().intType), s),
(t, s) -> isSameType(t, makeArrayType("java.lang.Integer", s), s)),
"Prefer an ImmutableIntArray instead. " + PRIMITIVE_ARRAYS_LINK,
ApiElementType.ANY),
withPublicVisibility(
anyOf(
(t, s) -> isSameType(t, s.getTypes().makeArrayType(s.getSymtab().doubleType), s),
(t, s) -> isSameType(t, makeArrayType("java.lang.Double", s), s)),
"Prefer an ImmutableDoubleArray instead. " + PRIMITIVE_ARRAYS_LINK,
ApiElementType.ANY),
withPublicVisibility(
anyOf(
(t, s) -> isSameType(t, s.getTypes().makeArrayType(s.getSymtab().longType), s),
(t, s) -> isSameType(t, makeArrayType("java.lang.Long", s), s)),
"Prefer an ImmutableLongArray instead. " + PRIMITIVE_ARRAYS_LINK,
ApiElementType.ANY),
// Optionals
withPublicVisibility(
isExactType("java.util.Optional"),
"Avoid Optional parameters. " + OPTIONAL_AS_PARAM_LINK,
ApiElementType.PARAMETER),
withPublicVisibility(
isExactType("com.google.common.base.Optional"),
"Prefer a java.util.Optional instead. " + PREFER_JDK_OPTIONAL_LINK,
ApiElementType.ANY),
// ImmutableFoo as params
withPublicVisibility(
isExactType("com.google.common.collect.ImmutableCollection"),
NON_GRAPH_WRAPPER,
"Consider accepting a java.util.Collection or Iterable instead. "
+ TYPE_GENERALITY_LINK,
ApiElementType.PARAMETER),
withPublicVisibility(
isExactType("com.google.common.collect.ImmutableList"),
NON_GRAPH_WRAPPER,
"Consider accepting a java.util.List or Iterable instead. " + TYPE_GENERALITY_LINK,
ApiElementType.PARAMETER),
withPublicVisibility(
isExactType("com.google.common.collect.ImmutableSet"),
NON_GRAPH_WRAPPER,
"Consider accepting a java.util.Set or Iterable instead. " + TYPE_GENERALITY_LINK,
ApiElementType.PARAMETER),
withPublicVisibility(
isExactType("com.google.common.collect.ImmutableMap"),
NON_GRAPH_WRAPPER,
"Consider accepting a java.util.Map instead. " + TYPE_GENERALITY_LINK,
ApiElementType.PARAMETER),
// collection implementation classes
withAnyVisibility(
anyOf(isExactType("java.util.ArrayList"), isExactType("java.util.LinkedList")),
"Prefer a java.util.List instead. " + INTERFACES_NOT_IMPLS_LINK,
ApiElementType.ANY),
withAnyVisibility(
anyOf(
isExactType("java.util.HashSet"),
isExactType("java.util.LinkedHashSet"),
isExactType("java.util.TreeSet")),
"Prefer a java.util.Set instead. " + INTERFACES_NOT_IMPLS_LINK,
ApiElementType.ANY),
withAnyVisibility(
anyOf(
isExactType("java.util.HashMap"),
isExactType("java.util.LinkedHashMap"),
isExactType("java.util.TreeMap")),
"Prefer a java.util.Map instead. " + INTERFACES_NOT_IMPLS_LINK,
ApiElementType.ANY),
// Iterators
withPublicVisibility(
isDescendantOf("java.util.Iterator"),
"Prefer returning a Stream (or collecting to an ImmutableList/ImmutableSet) instead. "
+ ITERATOR_LINK,
ApiElementType.RETURN_TYPE),
// TODO(b/279464660): consider also warning on an Iterator as a ApiElementType.PARAMETER
// Streams
withPublicVisibility(
isDescendantOf("java.util.stream.Stream"),
"Prefer accepting an Iterable or Collection instead. " + STREAM_LINK,
ApiElementType.PARAMETER),
// ProtoTime
withPublicVisibility(
isExactType("com.google.protobuf.Duration"),
"Prefer a java.time.Duration instead. " + PROTO_TIME_SERIALIZATION_LINK,
ApiElementType.ANY),
withPublicVisibility(
isExactType("com.google.protobuf.Timestamp"),
"Prefer a java.time.Instant instead. " + PROTO_TIME_SERIALIZATION_LINK,
ApiElementType.ANY),
withPublicVisibility(
isExactType("com.google.type.Date"),
"Prefer a java.time.LocalDate instead. " + PROTO_TIME_SERIALIZATION_LINK,
ApiElementType.ANY),
withPublicVisibility(
isExactType("com.google.type.DateTime"),
"Prefer a java.time.LocalDateTime instead. " + PROTO_TIME_SERIALIZATION_LINK,
ApiElementType.ANY),
withPublicVisibility(
isExactType("com.google.type.DayOfWeek"),
"Prefer a java.time.DayOfWeek instead. " + PROTO_TIME_SERIALIZATION_LINK,
ApiElementType.ANY),
withPublicVisibility(
isExactType("com.google.type.Month"),
"Prefer a java.time.Month instead. " + PROTO_TIME_SERIALIZATION_LINK,
ApiElementType.ANY),
withPublicVisibility(
isExactType("com.google.type.TimeOfDay"),
"Prefer a java.time.LocalTime instead. " + PROTO_TIME_SERIALIZATION_LINK,
ApiElementType.ANY),
withPublicVisibility(
isExactType("com.google.type.TimeZone"),
"Prefer a java.time.ZoneId instead. " + PROTO_TIME_SERIALIZATION_LINK,
ApiElementType.ANY),
// TODO(kak): consider com.google.type.Interval -> Range<Instant>
// Flogger
withAnyVisibility(
anyOf(
isDescendantOf("com.google.common.flogger.FluentLogger"),
isDescendantOf("com.google.common.flogger.GoogleLogger"),
isDescendantOf("com.google.common.flogger.android.AndroidFluentLogger")),
"There is no advantage to passing around a logger rather than declaring one in the"
+ " class that needs it. "
+ FLOGGER_LINK,
ApiElementType.ANY));
private static Type makeArrayType(String typeName, VisitorState state) {
return state.getTypes().makeArrayType(state.getTypeFromString(typeName));
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
Type enclosingType = getSymbol(tree).owner.type;
boolean isPublicApi =
methodIsPublicAndNotAnOverride(getSymbol(tree), state)
&& state.errorProneOptions().isPubliclyVisibleTarget();
for (Tree parameter : tree.getParameters()) {
checkType(parameter, ApiElementType.PARAMETER, isPublicApi, enclosingType, state);
}
checkType(tree.getReturnType(), ApiElementType.RETURN_TYPE, isPublicApi, enclosingType, state);
// the accumulated matches (if any) are reported via state.reportMatch(...)
return NO_MATCH;
}
private void checkType(
Tree tree,
ApiElementType elementType,
boolean isPublicApi,
Type enclosingType,
VisitorState state) {
if (isSuppressed(tree, state)) {
return;
}
Type type = getType(tree);
if (type == null) {
return;
}
for (TypeToCheck typeToCheck : NON_API_TYPES) {
if (typeToCheck.matches(type, enclosingType, state)) {
if (typeToCheck.elementType() == ApiElementType.ANY
|| typeToCheck.elementType() == elementType) {
if (isPublicApi || typeToCheck.visibility() == ApiVisibility.ANY) {
state.reportMatch(
buildDescription(tree).setMessage(typeToCheck.failureMessage()).build());
}
}
}
}
}
enum ApiElementType {
PARAMETER,
RETURN_TYPE,
ANY
}
enum ApiVisibility {
PUBLIC,
ANY
}
private static TypeToCheck withPublicVisibility(
TypePredicate typePredicate, String failureMessage, ApiElementType elementType) {
return withPublicVisibility(typePredicate, anything(), failureMessage, elementType);
}
private static TypeToCheck withPublicVisibility(
TypePredicate typePredicate,
TypePredicate enclosingTypePredicate,
String failureMessage,
ApiElementType elementType) {
return new AutoValue_NonApiType_TypeToCheck(
typePredicate, enclosingTypePredicate, failureMessage, ApiVisibility.PUBLIC, elementType);
}
private static TypeToCheck withAnyVisibility(
TypePredicate typePredicate, String failureMessage, ApiElementType elementType) {
return new AutoValue_NonApiType_TypeToCheck(
typePredicate, anything(), failureMessage, ApiVisibility.ANY, elementType);
}
@AutoValue
abstract static class TypeToCheck {
final boolean matches(Type type, Type enclosingType, VisitorState state) {
// only fire this check inside certain subtypes
if (enclosingTypePredicate().apply(enclosingType, state)) {
Deque<Type> types = new ArrayDeque<>();
types.add(type);
while (!types.isEmpty()) {
Type head = types.poll();
if (typePredicate().apply(head, state)) {
return true;
}
types.addAll(head.getTypeArguments());
}
}
// TODO(kak): do we want to check var-args as well?
return false;
}
abstract TypePredicate typePredicate();
abstract TypePredicate enclosingTypePredicate();
abstract String failureMessage();
abstract ApiVisibility visibility();
abstract ApiElementType elementType();
}
}
| 13,065
| 41.148387
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ExpectedExceptionChecker.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.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.Matchers.anything;
import static com.google.errorprone.matchers.Matchers.expressionStatement;
import static com.google.errorprone.matchers.Matchers.receiverOfInvocation;
import static com.google.errorprone.matchers.Matchers.throwStatement;
import static com.google.errorprone.matchers.Matchers.toType;
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.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getUpperBound;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.PeekingIterator;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
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.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BlockTree;
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.Tree.Kind;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "Prefer assertThrows to ExpectedException", severity = WARNING)
public class ExpectedExceptionChecker extends BugChecker implements MethodTreeMatcher {
static final Matcher<StatementTree> MATCHER =
expressionStatement(
instanceMethod()
.onExactClass("org.junit.rules.ExpectedException")
.withNameMatching(Pattern.compile("expect.*")));
static final Matcher<ExpressionTree> IS_A =
staticMethod()
.onClassAny("org.hamcrest.Matchers", "org.hamcrest.CoreMatchers", "org.hamcrest.core.Is")
.withSignature("<T>isA(java.lang.Class<T>)");
static final Matcher<StatementTree> FAIL_MATCHER =
anyOf(
throwStatement(anything()), expressionStatement(staticMethod().anyClass().named("fail")));
private static final Matcher<StatementTree> TRUTH_ASSERT_THAT =
expressionStatement(
toType(
MethodInvocationTree.class,
receiverOfInvocation(
anyOf(
staticMethod()
.onClass("com.google.common.truth.Truth")
.namedAnyOf("assertThat"),
instanceMethod()
.onDescendantOf("com.google.common.truth.StandardSubjectBuilder")
.named("that")))));
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (tree.getBody() == null) {
return NO_MATCH;
}
tree.getBody()
.accept(
new TreeScanner<Void, Void>() {
@Override
public Void visitBlock(BlockTree block, Void unused) {
Description description = scanBlock(tree, block, state);
if (description != NO_MATCH) {
state.reportMatch(description);
}
return super.visitBlock(block, unused);
}
},
null);
return NO_MATCH;
}
Description scanBlock(MethodTree tree, BlockTree block, VisitorState state) {
PeekingIterator<? extends StatementTree> it =
Iterators.peekingIterator(block.getStatements().iterator());
while (it.hasNext() && !MATCHER.matches(it.peek(), state)) {
it.next();
}
List<Tree> expectations = new ArrayList<>();
while (it.hasNext() && MATCHER.matches(it.peek(), state)) {
expectations.add(it.next());
}
if (expectations.isEmpty()) {
return NO_MATCH;
}
Deque<StatementTree> suffix = new ArrayDeque<>();
StatementTree failure = null;
Iterators.addAll(suffix, it);
if (!suffix.isEmpty() && FAIL_MATCHER.matches(suffix.peekLast(), state)) {
failure = suffix.removeLast();
}
while (!suffix.isEmpty() && TRUTH_ASSERT_THAT.matches(suffix.peekLast(), state)) {
suffix.removeLast();
}
return handleMatch(tree, state, expectations, ImmutableList.copyOf(suffix), failure);
}
/**
* Handle a method that contains a use of {@code ExpectedException}.
*
* @param tree the method
* @param state the visitor state
* @param expectations the statements for the call to {@code thrown.except(...)}, and any
* additional assertions
* @param suffix the statements after the assertions, which are expected to throw
*/
private Description handleMatch(
MethodTree tree,
VisitorState state,
List<Tree> expectations,
List<StatementTree> suffix,
@Nullable StatementTree failure) {
return describeMatch(tree, buildFix(state, expectations, failure, suffix));
}
private static Fix buildFix(
VisitorState state,
List<Tree> expectations,
@Nullable StatementTree failure,
List<StatementTree> suffix) {
Type exceptionType = state.getSymtab().throwableType;
// additional assertions to perform on the captured exception (if any)
List<String> newAsserts = new ArrayList<>();
SuggestedFix.Builder fix = SuggestedFix.builder();
for (Tree expectation : expectations) {
MethodInvocationTree invocation =
(MethodInvocationTree) ((ExpressionStatementTree) expectation).getExpression();
MethodSymbol symbol = ASTHelpers.getSymbol(invocation);
Symtab symtab = state.getSymtab();
List<? extends ExpressionTree> args = invocation.getArguments();
switch (symbol.getSimpleName().toString()) {
case "expect":
Type type = ASTHelpers.getType(getOnlyElement(invocation.getArguments()));
if (isSubtype(type, symtab.classType, state)) {
// expect(Class<?>)
exceptionType =
getUpperBound(
Iterables.getFirst(
state.getTypes().asSuper(type, symtab.classType.tsym).getTypeArguments(),
symtab.throwableType),
state.getTypes());
} else if (isSubtype(type, ORG_HAMCREST_MATCHER_TYPE.get(state), state)) {
Type matcherType =
state.getTypes().asSuper(type, ORG_HAMCREST_MATCHER_SYMBOL.get(state));
if (!matcherType.getTypeArguments().isEmpty()) {
Type matchType = getOnlyElement(matcherType.getTypeArguments());
if (isSubtype(matchType, symtab.throwableType, state)) {
exceptionType = matchType;
}
}
// expect(Matcher)
fix.addStaticImport("org.hamcrest.MatcherAssert.assertThat");
newAsserts.add(
String.format(
"assertThat(thrown, %s);", state.getSourceForNode(getOnlyElement(args))));
}
break;
case "expectCause":
ExpressionTree matcher = getOnlyElement(invocation.getArguments());
if (IS_A.matches(matcher, state)) {
fix.addStaticImport("com.google.common.truth.Truth.assertThat");
newAsserts.add(
String.format(
"assertThat(thrown).hasCauseThat().isInstanceOf(%s);",
state.getSourceForNode(
getOnlyElement(((MethodInvocationTree) matcher).getArguments()))));
} else {
fix.addStaticImport("org.hamcrest.MatcherAssert.assertThat");
newAsserts.add(
String.format(
"assertThat(thrown.getCause(), %s);",
state.getSourceForNode(getOnlyElement(args))));
}
break;
case "expectMessage":
if (isSubtype(
getOnlyElement(symbol.getParameters()).asType(), symtab.stringType, state)) {
// expectedMessage(String)
fix.addStaticImport("com.google.common.truth.Truth.assertThat");
newAsserts.add(
String.format(
"assertThat(thrown).hasMessageThat().contains(%s);",
state.getSourceForNode(getOnlyElement(args))));
} else {
// expectedMessage(Matcher)
fix.addStaticImport("org.hamcrest.MatcherAssert.assertThat");
newAsserts.add(
String.format(
"assertThat(thrown.getMessage(), %s);",
state.getSourceForNode(getOnlyElement(args))));
}
break;
default:
throw new AssertionError("unknown expect method: " + symbol.getSimpleName());
}
}
// remove all interactions with the ExpectedException rule
fix.replace(
getStartPosition(expectations.get(0)), state.getEndPosition(getLast(expectations)), "");
if (failure != null) {
fix.delete(failure);
}
return finishFix(fix.build(), exceptionType, newAsserts, suffix, state);
}
private static Fix finishFix(
SuggestedFix baseFix,
Type exceptionType,
List<String> newAsserts,
List<StatementTree> throwingStatements,
VisitorState state) {
if (throwingStatements.isEmpty()) {
return baseFix;
}
SuggestedFix.Builder fix = SuggestedFix.builder().merge(baseFix);
fix.addStaticImport("org.junit.Assert.assertThrows");
StringBuilder fixPrefix = new StringBuilder();
String exceptionTypeName = SuggestedFixes.qualifyType(state, fix, exceptionType);
if (!newAsserts.isEmpty()) {
fixPrefix.append(String.format("%s thrown = ", exceptionTypeName));
}
fixPrefix.append("assertThrows");
fixPrefix.append(String.format("(%s.class, () -> ", exceptionTypeName));
boolean useExpressionLambda =
throwingStatements.size() == 1
&& getOnlyElement(throwingStatements).getKind() == Kind.EXPRESSION_STATEMENT;
if (!useExpressionLambda) {
fixPrefix.append("{");
}
fix.prefixWith(throwingStatements.get(0), fixPrefix.toString());
if (useExpressionLambda) {
fix.postfixWith(((ExpressionStatementTree) throwingStatements.get(0)).getExpression(), ")");
fix.postfixWith(getLast(throwingStatements), '\n' + Joiner.on('\n').join(newAsserts));
} else {
fix.postfixWith(getLast(throwingStatements), "});\n" + Joiner.on('\n').join(newAsserts));
}
return fix.build();
}
private static final Supplier<Symbol> ORG_HAMCREST_MATCHER_SYMBOL =
VisitorState.memoize(state -> state.getSymbolFromString("org.hamcrest.Matcher"));
private static final Supplier<Type> ORG_HAMCREST_MATCHER_TYPE =
VisitorState.memoize(state -> state.getTypeFromString("org.hamcrest.Matcher"));
}
| 12,635
| 41.689189
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DangerousLiteralNullChecker.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.Description.NO_MATCH;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableTable;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
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.matchers.Matchers;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.util.Name;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
name = "DangerousLiteralNull",
summary = "This method is null-hostile: passing a null literal to it is always wrong",
severity = SeverityLevel.ERROR)
public class DangerousLiteralNullChecker extends BugChecker implements LiteralTreeMatcher {
@AutoValue
abstract static class NullReplacementRule {
abstract Name klass();
abstract Name method();
abstract String replacementBody();
private static Builder builder() {
return new AutoValue_DangerousLiteralNullChecker_NullReplacementRule.Builder();
}
@AutoValue.Builder
abstract static class Builder {
abstract Builder setKlass(Name klass);
abstract Builder setMethod(Name method);
abstract Builder setReplacementBody(String body);
abstract NullReplacementRule build();
}
}
private static final Supplier<ImmutableList<NullReplacementRule>> RULES =
VisitorState.memoize(
state ->
ImmutableList.of(
NullReplacementRule.builder()
.setKlass(state.getName("java.util.Optional"))
.setMethod(state.getName("orElseGet"))
.setReplacementBody("orElse(null)")
.build(),
NullReplacementRule.builder()
.setKlass(state.getName("java.util.Optional"))
.setMethod(state.getName("orElseThrow"))
.setReplacementBody("orElseThrow(NullPointerException::new)")
.build()));
private static final Supplier<ImmutableTable<Name, Name, String>> RULE_LOOKUP =
VisitorState.memoize(
state -> {
ImmutableTable.Builder<Name, Name, String> builder = ImmutableTable.builder();
for (NullReplacementRule rule : RULES.get(state)) {
builder.put(rule.klass(), rule.method(), rule.replacementBody());
}
return builder.buildOrThrow();
});
@Override
public Description matchLiteral(LiteralTree tree, VisitorState state) {
if (!Matchers.nullLiteral().matches(tree, state)) {
return NO_MATCH;
}
Tree parent = state.getPath().getParentPath().getLeaf();
if (!(parent instanceof MethodInvocationTree)) {
return NO_MATCH;
}
MethodInvocationTree invocation = (MethodInvocationTree) parent;
if (invocation.getArguments().size() != 1) {
return NO_MATCH;
}
MethodSymbol sym = ASTHelpers.getSymbol(invocation);
String newBody = RULE_LOOKUP.get(state).get(sym.owner.getQualifiedName(), sym.name);
if (newBody == null) {
return NO_MATCH;
}
return describeMatch(
invocation,
SuggestedFix.replace(
invocation,
String.format(
"%s.%s", state.getSourceForNode(ASTHelpers.getReceiver(invocation)), newBody)));
}
}
| 4,491
| 36.123967
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JUnit3TestNotRun.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.common.base.Ascii.toUpperCase;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.fixes.SuggestedFixes.addModifiers;
import static com.google.errorprone.fixes.SuggestedFixes.removeModifiers;
import static com.google.errorprone.fixes.SuggestedFixes.renameMethod;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.JUnitMatchers.isJUnit3TestClass;
import static com.google.errorprone.matchers.JUnitMatchers.isJunit3TestCase;
import static com.google.errorprone.matchers.JUnitMatchers.wouldRunInJUnit4;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.enclosingClass;
import static com.google.errorprone.matchers.Matchers.hasModifier;
import static com.google.errorprone.matchers.Matchers.methodHasNoParameters;
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.findSuperMethods;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
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.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.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.Optional;
import java.util.regex.Pattern;
import javax.lang.model.element.Modifier;
/** A bugpattern; see the associated summary. */
@BugPattern(
summary =
"Test method will not be run; please correct method signature "
+ "(Should be public, non-static, and method name should begin with \"test\").",
severity = ERROR)
public final class JUnit3TestNotRun extends BugChecker implements CompilationUnitTreeMatcher {
/**
* Regular expression for test method name that is misspelled and should be replaced with "test".
* ".est" and "est" are omitted, because they catch real words like "restore", "destroy", "best",
* "establish". ".test" is omitted, because people use it on purpose, to disable the test.
* Otherwise, I haven't found any false positives; "tes" was most common typo. There are some
* ambiguities in this regex that lead to bad corrections (i.e. tets -> tests, tesst -> testst),
* but the error is still found (those could be improved with regex lookahead, but I prefer
* simpler regex). TODO(rburny): see if we can cleanup intentional ".test" misspellings
*/
private static final Pattern MISSPELLED_NAME =
Pattern.compile(
"t.est|te.st|"
+ // letter inserted
"tst|tet|tes|"
+ // letter removed
"etst|tset|tets|"
+ // letters swapped
"t.st|te.t|"
+ // letter changed
"[tT][eE][sS][tT]" // miscapitalized
);
private static final Matcher<MethodTree> LOOKS_LIKE_TEST_CASE =
allOf(
enclosingClass(isJUnit3TestClass),
not(isJunit3TestCase),
anyOf(methodHasNoParameters(), hasModifier(Modifier.PUBLIC)),
enclosingClass((t, s) -> !getSymbol(t).getSimpleName().toString().endsWith("Base")),
methodReturns(VOID_TYPE));
@Override
public Description matchCompilationUnit(CompilationUnitTree unused, VisitorState state) {
ImmutableSet<MethodSymbol> calledMethods = calledMethods(state);
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitMethod(MethodTree tree, Void unused) {
checkMethod(tree, calledMethods, state.withPath(getCurrentPath()))
.ifPresent(state::reportMatch);
return super.visitMethod(tree, null);
}
}.scan(state.getPath(), null);
return NO_MATCH;
}
private static ImmutableSet<MethodSymbol> calledMethods(VisitorState state) {
ImmutableSet.Builder<MethodSymbol> calledMethods = ImmutableSet.builder();
new TreeScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
calledMethods.add(getSymbol(tree));
return super.visitMethodInvocation(tree, null);
}
}.scan(state.getPath().getCompilationUnit(), null);
return calledMethods.build();
}
/**
* Matches iff:
*
* <ul>
* <li>Method's name begins with misspelled variation of "test".
* <li>Method is public, returns void, and has no parameters.
* <li>Enclosing class is JUnit3 test (extends TestCase, has no {@code @RunWith} annotation, no
* {@code @Test}-annotated methods, and is not abstract).
* </ul>
*/
public Optional<Description> checkMethod(
MethodTree methodTree, ImmutableSet<MethodSymbol> calledMethods, VisitorState state) {
if (calledMethods.contains(getSymbol(methodTree))) {
return Optional.empty();
}
if (!LOOKS_LIKE_TEST_CASE.matches(methodTree, state)) {
return Optional.empty();
}
if (!findSuperMethods(getSymbol(methodTree), state.getTypes()).isEmpty()) {
return Optional.empty();
}
SuggestedFix.Builder fix = SuggestedFix.builder();
String methodName = methodTree.getName().toString();
if (!methodName.startsWith("test")) {
var matcher = MISSPELLED_NAME.matcher(methodName);
String fixedName;
if (matcher.lookingAt()) {
fixedName = matcher.replaceFirst("test");
} else if (wouldRunInJUnit4.matches(methodTree, state)) {
fixedName = "test" + toUpperCase(methodName.substring(0, 1)) + methodName.substring(1);
} else {
return Optional.empty();
}
fix.merge(renameMethod(methodTree, fixedName, state));
}
addModifiers(methodTree, state, Modifier.PUBLIC).ifPresent(fix::merge);
removeModifiers(methodTree, state, Modifier.PRIVATE, Modifier.PROTECTED).ifPresent(fix::merge);
// N.B. must occur in separate step because removeModifiers only removes one modifier at a time.
removeModifiers(methodTree, state, Modifier.STATIC).ifPresent(fix::merge);
return Optional.of(describeMatch(methodTree, fix.build()));
}
}
| 7,310
| 43.309091
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LongLiteralLowerCaseSuffix.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 com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.LiteralTreeMatcher;
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.LiteralTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* Matcher for a <code>long</code> literal with a lower-case ell for a suffix (e.g. <code>234l
* </code>) rather than the more readable upper-case ell (e.g. <code>234L</code>).
*
* @author Simon Nickerson (sjnickerson@google.com)
*/
@BugPattern(summary = "Prefer 'L' to 'l' for the suffix to long literals", severity = ERROR)
public class LongLiteralLowerCaseSuffix extends BugChecker implements LiteralTreeMatcher {
private static final Matcher<LiteralTree> matcher =
new Matcher<LiteralTree>() {
@Override
public boolean matches(LiteralTree literalTree, VisitorState state) {
if (literalTree.getKind() == Kind.LONG_LITERAL) {
// The javac AST doesn't seem to record whether the suffix is present, or whether it's
// an 'l' or 'L'. We have to look at the original source
String longLiteral = getLongLiteral(literalTree, state);
return longLiteral != null && longLiteral.endsWith("l");
} else {
return false;
}
}
};
// Doesn't need to be strict, just shouldn't read past the end
// of the literal.
private static final Pattern LONG_LITERAL_PATTERN =
Pattern.compile("-? *(0[bBxX]?)?[0-9a-fA-F_]+[lL]?");
/**
* Extracts the long literal corresponding to a given {@link LiteralTree} node from the source
* code as a string. Returns null if the source code is not available.
*/
@Nullable
private static String getLongLiteral(LiteralTree literalTree, VisitorState state) {
JCLiteral longLiteral = (JCLiteral) literalTree;
CharSequence sourceFile = state.getSourceCode();
if (sourceFile == null) {
return null;
}
int start = longLiteral.getStartPosition();
java.util.regex.Matcher matcher =
LONG_LITERAL_PATTERN.matcher(sourceFile.subSequence(start, sourceFile.length()));
if (matcher.lookingAt()) {
return matcher.group();
}
return null;
}
@Override
public Description matchLiteral(LiteralTree literalTree, VisitorState state) {
if (!matcher.matches(literalTree, state)) {
return Description.NO_MATCH;
}
StringBuilder longLiteral = new StringBuilder(getLongLiteral(literalTree, state));
longLiteral.setCharAt(longLiteral.length() - 1, 'L');
Fix fix = SuggestedFix.replace(literalTree, longLiteral.toString());
return describeMatch(literalTree, fix);
}
}
| 3,671
| 38.06383
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/FutureReturnValueIgnored.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.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
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.annotations.CanIgnoreReturnValue;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions;
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.sun.source.tree.ExpressionTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import java.util.Optional;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ForkJoinTask;
import javax.inject.Inject;
/** See BugPattern annotation. */
@BugPattern(
summary =
"Return value of methods returning Future must be checked. Ignoring returned Futures "
+ "suppresses exceptions thrown from the code that completes the Future.",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE,
documentSuppression = false)
public final class FutureReturnValueIgnored extends AbstractReturnValueIgnored
implements ReturnTreeMatcher {
private static final Matcher<ExpressionTree> IGNORED_METHODS =
anyOf(
// ForkJoinTask#fork has side-effects and returns 'this', so it's reasonable to ignore
// the return value.
instanceMethod()
.onDescendantOf(ForkJoinTask.class.getName())
.named("fork")
.withNoParameters(),
// CompletionService is intended to be used in a way where the Future returned
// from submit is discarded, because the Futures are available later via e.g. take()
instanceMethod().onDescendantOf(CompletionService.class.getName()).named("submit"),
// IntelliJ's executeOnPooledThread wraps the Callable/Runnable in one that catches
// Throwable, so it can't fail (unless logging the Throwable also throws, but there's
// nothing much to be done at that point).
instanceMethod()
.onDescendantOf("com.intellij.openapi.application.Application")
.named("executeOnPooledThread"),
// ChannelFuture#addListener(s) returns itself for chaining. Any exception during the
// future execution should be dealt by the listener(s).
instanceMethod()
.onDescendantOf("io.netty.util.concurrent.Future")
.namedAnyOf(
"addListener",
"addListeners",
"removeListener",
"removeListeners",
"sync",
"syncUninterruptibly",
"await",
"awaitUninterruptibly"),
instanceMethod()
.onDescendantOf("io.netty.util.concurrent.Promise")
.namedAnyOf("setSuccess", "setFailure"),
instanceMethod()
.onExactClass("java.util.concurrent.CompletableFuture")
.namedAnyOf("exceptionally", "completeAsync", "orTimeout", "completeOnTimeout"));
private static final Matcher<ExpressionTree> MATCHER =
new Matcher<ExpressionTree>() {
@Override
public boolean matches(ExpressionTree tree, VisitorState state) {
Type futureType = JAVA_UTIL_CONCURRENT_FUTURE.get(state);
if (futureType == null) {
return false;
}
Symbol untypedSymbol = ASTHelpers.getSymbol(tree);
if (!(untypedSymbol instanceof MethodSymbol)) {
Type resultType = ASTHelpers.getResultType(tree);
return resultType != null
&& ASTHelpers.isSubtype(
ASTHelpers.getUpperBound(resultType, state.getTypes()), futureType, state);
}
MethodSymbol sym = (MethodSymbol) untypedSymbol;
if (hasAnnotation(sym, CanIgnoreReturnValue.class, state)) {
return false;
}
for (MethodSymbol superSym : ASTHelpers.findSuperMethods(sym, state.getTypes())) {
// There are interfaces annotated with @CanIgnoreReturnValue (like Guava's Function)
// whose return value really shouldn't be ignored - as a heuristic, check if the super's
// method is returning a future subtype.
if (hasAnnotation(superSym, CanIgnoreReturnValue.class, state)
&& ASTHelpers.isSubtype(
ASTHelpers.getUpperBound(superSym.getReturnType(), state.getTypes()),
futureType,
state)) {
return false;
}
}
if (IGNORED_METHODS.matches(tree, state)) {
return false;
}
Type returnType = sym.getReturnType();
return ASTHelpers.isSubtype(
ASTHelpers.getUpperBound(returnType, state.getTypes()), futureType, state);
}
};
@Inject
FutureReturnValueIgnored(ConstantExpressions constantExpressions) {
super(constantExpressions);
}
@Override
public Matcher<ExpressionTree> specializedMatcher() {
return MATCHER;
}
@Override
protected Optional<Type> lostType(VisitorState state) {
return Optional.ofNullable(futureType.get(state));
}
@Override
protected String lostTypeMessage(String returnedType, String declaredReturnType) {
return String.format(
"Returning %s from method that returns %s. Errors from the returned future may be ignored.",
returnedType, declaredReturnType);
}
private final Supplier<Type> futureType = Suppliers.typeFromString("java.util.concurrent.Future");
private static final Supplier<Type> JAVA_UTIL_CONCURRENT_FUTURE =
VisitorState.memoize(state -> state.getTypeFromString("java.util.concurrent.Future"));
}
| 6,874
| 42.512658
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/GetClassOnEnum.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.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.google.errorprone.util.ASTHelpers;
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 = "Calling getClass() on an enum may return a subclass of the enum type",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public class GetClassOnEnum extends BugChecker implements BugChecker.MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> ENUM_CLASS =
instanceMethod().onDescendantOf(Enum.class.getName()).named("getClass").withNoParameters();
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (ENUM_CLASS.matches(tree, state)) {
return describeMatch(
tree,
SuggestedFix.replace(
state.getEndPosition(ASTHelpers.getReceiver(tree)),
state.getEndPosition(tree),
".getDeclaringClass()"));
}
return Description.NO_MATCH;
}
}
| 2,158
| 38.254545
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MisusedWeekYear.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 java.util.Optional;
/**
* Ban use of YYYY in a SimpleDateFormat pattern, unless it is being used for a week date. Otherwise
* the user almost certainly meant yyyy instead. See the summary in the {@link BugPattern} below for
* more details.
*
* <p>This bug caused a Twitter outage in December 2014.
*/
@BugPattern(
summary =
"Use of \"YYYY\" (week year) in a date pattern without \"ww\" (week in year). "
+ "You probably meant to use \"yyyy\" (year) instead.",
severity = ERROR)
public final class MisusedWeekYear extends MisusedDateFormat {
@Override
Optional<String> rewriteTo(String pattern) {
boolean[] containsY = new boolean[1];
boolean[] containsW = new boolean[1];
parseDateFormat(
pattern,
new DateFormatConsumer() {
@Override
public void consumeLiteral(char literal) {}
@Override
public void consumeSpecial(char special) {
if (special == 'Y') {
containsY[0] = true;
}
if (special == 'w') {
containsW[0] = true;
}
}
});
if (containsY[0] && !containsW[0]) {
return Optional.of(replaceFormatChar(pattern, 'Y', 'y'));
}
return Optional.empty();
}
}
| 2,046
| 31.492063
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AlwaysThrows.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.ImmutableSet.toImmutableSet;
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.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.constValue;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static java.util.Arrays.stream;
import com.google.common.base.Throwables;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multiset;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.google.protobuf.ByteString;
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.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.lang.reflect.InvocationTargetException;
import java.util.UUID;
import java.util.function.Consumer;
import javax.inject.Inject;
import org.checkerframework.checker.nullness.qual.Nullable;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "Detects calls that will fail at runtime", severity = ERROR)
public class AlwaysThrows extends BugChecker implements MethodInvocationTreeMatcher {
@SuppressWarnings("UnnecessarilyFullyQualified")
private static final ImmutableMap<String, Consumer<CharSequence>> VALIDATORS =
ImmutableMap.<String, Consumer<CharSequence>>builder()
.put("java.time.Duration", java.time.Duration::parse)
.put("java.time.Instant", java.time.Instant::parse)
.put("java.time.LocalDate", java.time.LocalDate::parse)
.put("java.time.LocalDateTime", java.time.LocalDateTime::parse)
.put("java.time.LocalTime", java.time.LocalTime::parse)
.put("java.time.MonthDay", java.time.MonthDay::parse)
.put("java.time.OffsetDateTime", java.time.OffsetDateTime::parse)
.put("java.time.OffsetTime", java.time.OffsetTime::parse)
.put("java.time.Period", java.time.Period::parse)
.put("java.time.Year", java.time.Year::parse)
.put("java.time.YearMonth", java.time.YearMonth::parse)
.put("java.time.ZonedDateTime", java.time.ZonedDateTime::parse)
.buildOrThrow();
private static final Matcher<ExpressionTree> IMMUTABLE_MAP_OF =
staticMethod().onDescendantOf("com.google.common.collect.ImmutableMap").named("of");
private static final Matcher<ExpressionTree> IMMUTABLE_BI_MAP_OF =
staticMethod().onDescendantOf("com.google.common.collect.ImmutableBiMap").named("of");
private static final Matcher<ExpressionTree> IMMUTABLE_MAP_PUT =
instanceMethod()
.onDescendantOf("com.google.common.collect.ImmutableMap.Builder")
.namedAnyOf("put")
.withParameters("java.lang.Object", "java.lang.Object");
private static final Matcher<ExpressionTree> IMMUTABLE_BI_MAP_PUT =
instanceMethod()
.onDescendantOf("com.google.common.collect.ImmutableBiMap.Builder")
.namedAnyOf("put")
.withParameters("java.lang.Object", "java.lang.Object");
enum Api {
PARSE_TIME(
staticMethod()
.onClassAny(VALIDATORS.keySet())
.named("parse")
.withParameters("java.lang.CharSequence")) {
@Override
void validate(MethodInvocationTree tree, String argument) {
MethodSymbol sym = ASTHelpers.getSymbol(tree);
VALIDATORS.get(sym.owner.getQualifiedName().toString()).accept(argument);
}
},
BYTE_STRING(
staticMethod()
.onClass("com.google.protobuf.ByteString")
.named("fromHex")
.withParameters("java.lang.String")) {
@Override
void validate(MethodInvocationTree tree, String argument) {
try {
ByteString.class.getMethod("fromHex", String.class).invoke(null, argument);
} catch (NoSuchMethodException | IllegalAccessException e) {
return;
} catch (InvocationTargetException e) {
throw Throwables.getCauseAs(e.getCause(), NumberFormatException.class);
}
}
},
UUID_PARSE(staticMethod().onClass("java.util.UUID").named("fromString")) {
@Override
void validate(MethodInvocationTree tree, String argument) {
var unused = UUID.fromString(argument);
}
};
Api(Matcher<ExpressionTree> matcher) {
this.matcher = matcher;
}
@SuppressWarnings("ImmutableEnumChecker") // is immutable
private final Matcher<ExpressionTree> matcher;
abstract void validate(MethodInvocationTree tree, String argument) throws Exception;
}
private final ConstantExpressions constantExpressions;
@Inject
AlwaysThrows(ConstantExpressions constantExpressions) {
this.constantExpressions = constantExpressions;
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (IMMUTABLE_MAP_PUT.matches(tree, state)) {
if (state.getPath().getParentPath() != null
&& state.getPath().getParentPath().getParentPath() != null) {
Tree grandParent = state.getPath().getParentPath().getParentPath().getLeaf();
if (grandParent instanceof ExpressionTree
&& IMMUTABLE_MAP_PUT.matches((ExpressionTree) grandParent, state)) {
return NO_MATCH;
}
}
Description description = checkImmutableMapBuilder(tree, /* index= */ 0, state);
if (!description.equals(NO_MATCH)) {
return description;
}
if (IMMUTABLE_BI_MAP_PUT.matches(tree, state)) {
return checkImmutableMapBuilder(tree, /* index= */ 1, state);
}
}
if (IMMUTABLE_MAP_OF.matches(tree, state)) {
Description description = checkImmutableMapOf(tree, /* index= */ 0, state);
if (!description.equals(NO_MATCH)) {
return description;
}
if (IMMUTABLE_BI_MAP_OF.matches(tree, state)) {
return checkImmutableMapOf(tree, /* index= */ 1, state);
}
}
Api api =
stream(Api.values()).filter(m -> m.matcher.matches(tree, state)).findAny().orElse(null);
if (api == null) {
return NO_MATCH;
}
String argument = constValue(Iterables.getOnlyElement(tree.getArguments()), String.class);
if (argument == null) {
return NO_MATCH;
}
try {
api.validate(tree, argument);
} catch (Exception t) {
return buildDescription(tree)
.setMessage(
String.format(
"This call will fail at runtime with a %s: %s",
t.getClass().getSimpleName(), t.getMessage()))
.build();
}
return NO_MATCH;
}
private Description checkImmutableMapBuilder(
MethodInvocationTree tree, int index, VisitorState state) {
Multiset<Object> keys = HashMultiset.create();
ExpressionTree receiver = tree;
for (;
receiver instanceof MethodInvocationTree && IMMUTABLE_MAP_PUT.matches(receiver, state);
receiver = getReceiver(receiver)) {
Object constantKey =
getConstantKey(((MethodInvocationTree) receiver).getArguments().get(index), state);
if (constantKey == null) {
continue;
}
keys.add(constantKey);
}
return checkForRepeatedKeys(tree, keys);
}
private Description checkImmutableMapOf(
MethodInvocationTree tree, int index, VisitorState state) {
Multiset<Object> keys = HashMultiset.create();
for (int i = 0; i < tree.getArguments().size(); i += 2) {
Object constantKey = getConstantKey(tree.getArguments().get(i + index), state);
if (constantKey == null) {
continue;
}
keys.add(constantKey);
}
return checkForRepeatedKeys(tree, keys);
}
private @Nullable Object getConstantKey(ExpressionTree key, VisitorState state) {
return constantExpressions.constantExpression(key, state).orElse(null);
}
private Description checkForRepeatedKeys(MethodInvocationTree tree, Multiset<Object> keys) {
ImmutableSet<Object> repeatedKeys =
keys.entrySet().stream().filter(e -> e.getCount() > 1).collect(toImmutableSet());
if (repeatedKeys.isEmpty()) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage(
"This ImmutableMap construction will throw (or have known duplicates overwritten) due"
+ " to duplicates: "
+ repeatedKeys.stream()
.map(
k ->
k instanceof VarSymbol ? ((VarSymbol) k).getSimpleName() : k.toString())
.collect(toImmutableSet()))
.build();
}
}
| 9,980
| 39.573171
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UseEnumSwitch.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.SUGGESTION;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.tools.javac.code.Symbol;
import javax.lang.model.element.ElementKind;
import org.checkerframework.checker.nullness.qual.Nullable;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Prefer using a switch instead of a chained if-else for enums",
severity = SUGGESTION)
public class UseEnumSwitch extends AbstractUseSwitch {
@Override
protected @Nullable String getExpressionForCase(VisitorState state, ExpressionTree argument) {
Symbol sym = ASTHelpers.getSymbol(argument);
return sym != null && sym.getKind().equals(ElementKind.ENUM_CONSTANT)
? sym.getSimpleName().toString()
: null;
}
}
| 1,606
| 36.372093
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DepAnn.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.sun.tools.javac.code.Flags.DEPRECATED;
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.sun.source.tree.ClassTree;
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;
/**
* Matches the behaviour of the javac dep-ann Xlint warning.
*
* @author cushon@google.com (Liam Miller-Cushon)
*/
@BugPattern(
altNames = "dep-ann",
summary = "Item documented with a @deprecated javadoc note is not annotated with @Deprecated",
severity = ERROR)
public class DepAnn extends BugChecker
implements MethodTreeMatcher, ClassTreeMatcher, VariableTreeMatcher {
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
return checkDeprecatedAnnotation(methodTree, state);
}
@Override
public Description matchClass(ClassTree classTree, VisitorState state) {
return checkDeprecatedAnnotation(classTree, state);
}
@Override
public Description matchVariable(VariableTree variableTree, VisitorState state) {
return checkDeprecatedAnnotation(variableTree, state);
}
/**
* Reports a dep-ann error for a declaration if: (1) javadoc contains the deprecated javadoc tag
* (2) the declaration is not annotated with {@link java.lang.Deprecated}
*/
@SuppressWarnings("javadoc")
private Description checkDeprecatedAnnotation(Tree tree, VisitorState state) {
Symbol symbol = ASTHelpers.getSymbol(tree);
// (1)
// javac sets the DEPRECATED bit in flags if the Javadoc contains @deprecated
if ((symbol.flags() & DEPRECATED) == 0) {
return Description.NO_MATCH;
}
// (2)
if (symbol.attribute(state.getSymtab().deprecatedType.tsym) != null) {
return Description.NO_MATCH;
}
return describeMatch(tree, SuggestedFix.prefixWith(tree, "@Deprecated\n"));
}
}
| 3,014
| 34.470588
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MissingSuperCall.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.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.isType;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
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.Tree.Kind;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.Arrays;
import javax.lang.model.element.Modifier;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@BugPattern(
summary = "Overriding method is missing a call to overridden super method",
severity = ERROR)
// TODO(eaftan): Add support for JDK methods that cannot be annotated, such as
// java.lang.Object#finalize and java.lang.Object#clone.
public class MissingSuperCall extends BugChecker
implements AnnotationTreeMatcher, MethodTreeMatcher {
private enum AnnotationType {
ANDROID("android.support.annotation.CallSuper"),
ANDROIDX("androidx.annotation.CallSuper"),
ERROR_PRONE("com.google.errorprone.annotations.OverridingMethodsMustInvokeSuper"),
JSR305("javax.annotation.OverridingMethodsMustInvokeSuper"),
FINDBUGS("edu.umd.cs.findbugs.annotations.OverrideMustInvoke");
private final String fullyQualifiedName;
AnnotationType(String fullyQualifiedName) {
this.fullyQualifiedName = fullyQualifiedName;
}
public String fullyQualifiedName() {
return fullyQualifiedName;
}
public String simpleName() {
int index = fullyQualifiedName().lastIndexOf('.');
if (index >= 0) {
return fullyQualifiedName().substring(index + 1);
} else {
return fullyQualifiedName();
}
}
}
private static final Matcher<AnnotationTree> ANNOTATION_MATCHER =
anyOf(
Arrays.stream(AnnotationType.values())
.map(anno -> isType(anno.fullyQualifiedName()))
.collect(ImmutableList.toImmutableList()));
/**
* Prevents abstract methods from being annotated with {@code @CallSuper} et al. It doesn't make
* sense to require overriders to call a method with no implementation.
*/
@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
if (!ANNOTATION_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
MethodTree methodTree = ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class);
if (methodTree == null) {
return Description.NO_MATCH;
}
MethodSymbol methodSym = ASTHelpers.getSymbol(methodTree);
if (!methodSym.getModifiers().contains(Modifier.ABSTRACT)) {
return Description.NO_MATCH;
}
// Match, find the matched annotation to use for the error message.
Symbol annotationSym = ASTHelpers.getSymbol(tree);
if (annotationSym == null) {
return Description.NO_MATCH;
}
return buildDescription(tree)
.setMessage(
String.format(
"@%s cannot be applied to an abstract method", annotationSym.getSimpleName()))
.build();
}
/**
* Matches a method that overrides a method that has been annotated with {@code @CallSuper} et
* al., but does not call the super method.
*/
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
MethodSymbol methodSym = ASTHelpers.getSymbol(tree);
// Allow abstract methods.
if (methodSym.getModifiers().contains(Modifier.ABSTRACT)) {
return Description.NO_MATCH;
}
String annotatedSuperMethod = null;
String matchedAnnotationSimpleName = null;
for (MethodSymbol method : ASTHelpers.findSuperMethods(methodSym, state.getTypes())) {
for (AnnotationType annotationType : AnnotationType.values()) {
if (ASTHelpers.hasAnnotation(method, annotationType.fullyQualifiedName(), state)) {
annotatedSuperMethod = getMethodName(method);
matchedAnnotationSimpleName = annotationType.simpleName();
break;
}
}
}
if (annotatedSuperMethod == null || matchedAnnotationSimpleName == null) {
return Description.NO_MATCH;
}
TreeScanner<Boolean, Void> findSuper = new FindSuperTreeScanner(tree.getName().toString());
if (findSuper.scan(tree, null)) {
return Description.NO_MATCH;
}
return buildDescription(tree)
.setMessage(
String.format(
"This method overrides %s, which is annotated with @%s, but does not call the "
+ "super method",
annotatedSuperMethod, matchedAnnotationSimpleName))
.build();
}
/** Scans a tree looking for calls to a method that is overridden by the given one. */
private static class FindSuperTreeScanner extends TreeScanner<Boolean, Void> {
private final String overridingMethodName;
private FindSuperTreeScanner(String overridingMethodName) {
this.overridingMethodName = overridingMethodName;
}
@Override
public Boolean visitClass(ClassTree node, Void unused) {
// don't descend into classes
return false;
}
@Override
public Boolean visitLambdaExpression(LambdaExpressionTree node, Void unused) {
// don't descend into lambdas
return false;
}
@Override
public Boolean visitMethodInvocation(MethodInvocationTree tree, Void unused) {
boolean result = false;
ExpressionTree methodSelect = tree.getMethodSelect();
if (methodSelect.getKind() == Kind.MEMBER_SELECT) {
MemberSelectTree memberSelect = (MemberSelectTree) methodSelect;
result =
ASTHelpers.isSuper(memberSelect.getExpression())
&& memberSelect.getIdentifier().contentEquals(overridingMethodName);
}
return result || super.visitMethodInvocation(tree, unused);
}
@Override
public Boolean reduce(Boolean b1, Boolean b2) {
return firstNonNull(b1, false) || firstNonNull(b2, false);
}
}
/**
* Given a {@link MethodSymbol}, returns a method name in the form "owningClass#methodName", e.g.
* "java.util.function.Function#apply".
*/
private static String getMethodName(MethodSymbol methodSym) {
return String.format("%s#%s", methodSym.owner, methodSym.getSimpleName());
}
}
| 7,676
| 34.873832
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/RandomCast.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.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
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.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.ParenthesizedTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Type;
import javax.lang.model.type.TypeKind;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Casting a random number in the range [0.0, 1.0) to an integer or long always results"
+ " in 0.",
severity = ERROR)
public class RandomCast extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
anyOf(
instanceMethod().onExactClass("java.util.Random").namedAnyOf("nextFloat", "nextDouble"),
staticMethod().onClass("java.lang.Math").named("random"));
private static final ImmutableSet<TypeKind> INTEGRAL =
Sets.immutableEnumSet(TypeKind.LONG, TypeKind.INT);
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
TreePath parentPath = state.getPath().getParentPath();
while (parentPath.getLeaf() instanceof ParenthesizedTree) {
parentPath = parentPath.getParentPath();
}
Tree parent = parentPath.getLeaf();
if (!(parent instanceof TypeCastTree)) {
return NO_MATCH;
}
Type type = ASTHelpers.getType(parent);
if (type == null || !INTEGRAL.contains(type.getKind())) {
return NO_MATCH;
}
return describeMatch(tree);
}
}
| 3,059
| 38.230769
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CannotMockFinalClass.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.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.argument;
import static com.google.errorprone.matchers.Matchers.classLiteral;
import static com.google.errorprone.matchers.Matchers.enclosingClass;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.hasArgumentWithValue;
import static com.google.errorprone.matchers.Matchers.hasModifier;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.isType;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.matchers.Matchers.variableType;
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.bugpatterns.BugChecker.VariableTreeMatcher;
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.ClassTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import javax.lang.model.element.Modifier;
/**
* Bug pattern to recognize attempts to mock final types.
*
* @author Louis Wasserman
*/
@BugPattern(summary = "Mockito cannot mock final classes", severity = SeverityLevel.WARNING)
public class CannotMockFinalClass extends BugChecker
implements MethodInvocationTreeMatcher, VariableTreeMatcher {
// TODO(lowasser): consider stopping mocks of primitive types here or in its own checker
// Runners like GwtMockito allow mocking final types, so we conservatively stick to JUnit4.
private static final Matcher<AnnotationTree> runWithJunit4 =
allOf(
isType("org.junit.runner.RunWith"),
hasArgumentWithValue("value", classLiteral(isSameType("org.junit.runners.JUnit4"))));
private static final Matcher<Tree> enclosingClassIsJunit4Test =
enclosingClass(Matchers.<ClassTree>annotations(AT_LEAST_ONE, runWithJunit4));
private static final Matcher<VariableTree> variableOfFinalClassAnnotatedMock =
allOf(
variableType(hasModifier(Modifier.FINAL)),
hasAnnotation("org.mockito.Mock"),
enclosingClassIsJunit4Test);
private static final Matcher<MethodInvocationTree> creationOfMockForFinalClass =
allOf(
staticMethod().onClass("org.mockito.Mockito").named("mock"),
argument(0, classLiteral(hasModifier(Modifier.FINAL))),
enclosingClassIsJunit4Test);
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
return variableOfFinalClassAnnotatedMock.matches(tree, state)
? describeMatch(tree)
: Description.NO_MATCH;
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return creationOfMockForFinalClass.matches(tree, state)
? describeMatch(tree)
: Description.NO_MATCH;
}
}
| 3,978
| 43.211111
| 100
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.