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/CheckNotNullMultipleTimes.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.staticMethod;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;
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.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
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.LambdaExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.SwitchTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TryTree;
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.List;
import java.util.Map;
/** Checks for the same variable being checked against null twice in a method. */
@BugPattern(
severity = ERROR,
summary = "A variable was checkNotNulled multiple times. Did you mean to check something else?")
public final class CheckNotNullMultipleTimes extends BugChecker implements MethodTreeMatcher {
private static final Matcher<ExpressionTree> CHECK_NOT_NULL =
staticMethod().onClass("com.google.common.base.Preconditions").named("checkNotNull");
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
Multiset<VarSymbol> variables = HashMultiset.create();
Map<VarSymbol, Tree> lastCheck = new HashMap<>();
new TreePathScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
List<? extends ExpressionTree> arguments = tree.getArguments();
if (!arguments.isEmpty()
&& arguments.get(0) instanceof IdentifierTree
// Only consider side-effects-only calls to checkNotNull: it turns out people often
// intentionally write repeated null-checks for the same variable when using the result
// as a value, and we would have many false positives if we counted those.
&& getCurrentPath().getParentPath().getLeaf() instanceof StatementTree
&& CHECK_NOT_NULL.matches(tree, state)) {
Symbol symbol = getSymbol(arguments.get(0));
if (symbol instanceof VarSymbol && isConsideredFinal(symbol)) {
variables.add((VarSymbol) symbol);
lastCheck.put((VarSymbol) symbol, tree);
}
}
return super.visitMethodInvocation(tree, null);
}
// Don't descend into ifs and switches, given people often repeat the same checks within
// top-level conditional branches.
@Override
public Void visitSwitch(SwitchTree tree, Void unused) {
return null;
}
@Override
public Void visitIf(IfTree tree, Void unused) {
return null;
}
@Override
public Void visitLambdaExpression(LambdaExpressionTree tree, Void unused) {
return null;
}
@Override
public Void visitClass(ClassTree tree, Void unused) {
return null;
}
// Sometimes a variable is checked in the try and the catch blocks of a try statement; don't
// descend into the catch.
// try {
// <some code that might throw>
// checkNotNull(frobnicator);
// <more code>
// } catch (Exception e) {
// checkNotNull(frobnicator);
// }
@Override
public Void visitTry(TryTree tree, Void unused) {
return scan(tree.getBlock(), null);
}
}.scan(state.getPath(), null);
for (Multiset.Entry<VarSymbol> entry : variables.entrySet()) {
if (entry.getCount() > 1) {
state.reportMatch(
buildDescription(lastCheck.get(entry.getElement()))
.setMessage(
String.format(
"checkNotNull(%s) was called more than once. Did you mean to check"
+ " something else?",
entry.getElement()))
.build());
}
}
return NO_MATCH;
}
}
| 5,269
| 38.328358
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JUnit4ClassUsedInJUnit3.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.matchers.JUnitMatchers.isJUnit3TestClass;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.enclosingClass;
import static com.google.errorprone.matchers.Matchers.isType;
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.AnnotationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
/**
* @author jdesprez@google.com (Julien Desprez)
*/
@BugPattern(
summary =
"Some JUnit4 construct cannot be used in a JUnit3 context. Convert your class to JUnit4 "
+ "style to use them.",
severity = WARNING)
public class JUnit4ClassUsedInJUnit3 extends BugChecker
implements MethodInvocationTreeMatcher, AnnotationTreeMatcher {
private static final Matcher<ExpressionTree> ASSUME_CHECK =
allOf(
staticMethod().onClass("org.junit.Assume").withAnyName(),
enclosingClass(isJUnit3TestClass));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
// An Assume method has been called within a JUnit3 class
if (!ASSUME_CHECK.matches(tree, state)) {
return NO_MATCH;
}
return makeDescription("Assume", tree);
}
@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
if (!enclosingClass(isJUnit3TestClass).matches(tree, state)) {
return NO_MATCH;
}
// If we are inside a JUnit3 test class some annotation should not appear.
if (isType("org.junit.Ignore").matches(tree, state)) {
return makeDescription("@Ignore", tree);
}
if (isType("org.junit.Rule").matches(tree, state)) {
return makeDescription("@Rule", tree);
}
return NO_MATCH;
}
/**
* Returns a {@link Description} of the error based on the rejected JUnit4 construct in the JUnit3
* class.
*/
private Description makeDescription(String rejectedJUnit4, Tree tree) {
Description.Builder builder =
buildDescription(tree)
.setMessage(
String.format(
"%s cannot be used inside a JUnit3 class. Convert your class to JUnit4 style.",
rejectedJUnit4));
return builder.build();
}
}
| 3,503
| 36.276596
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DoNotMockChecker.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 com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.annotations.DoNotMock;
import com.sun.source.tree.VariableTree;
import java.util.stream.Stream;
/**
* Points out if a Mockito or EasyMock mock is mocking an object that would be better off being
* tested using an alternative instance.
*
* @author amalloy@google.com (Alan Malloy)
*/
@BugPattern(
name = "DoNotMock",
severity = SeverityLevel.ERROR,
summary = "Identifies undesirable mocks.",
documentSuppression = false)
public class DoNotMockChecker extends AbstractMockChecker<DoNotMock> {
private static final TypeExtractor<VariableTree> MOCKED_VAR =
fieldAnnotatedWithOneOf(Stream.of("org.mockito.Mock", "org.mockito.Spy"));
public DoNotMockChecker() {
super(MOCKED_VAR, MOCKING_METHOD, DoNotMock.class, DoNotMock::value);
}
}
| 1,548
| 33.422222
| 95
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CollectionToArraySafeParameter.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.getType;
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.suppliers.Supplier;
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;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import java.util.List;
/**
* @author mariasam@google.com (Maria Sam) on 6/27/17.
*/
@BugPattern(
summary =
"The type of the array parameter of Collection.toArray "
+ "needs to be compatible with the array type",
severity = ERROR)
public class CollectionToArraySafeParameter extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> TO_ARRAY_MATCHER =
instanceMethod().onDescendantOf("java.util.Collection").withSignature("<T>toArray(T[])");
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState visitorState) {
if (!TO_ARRAY_MATCHER.matches(methodInvocationTree, visitorState)) {
return NO_MATCH;
}
Types types = visitorState.getTypes();
Type variableType =
types.elemtype(getType(getOnlyElement(methodInvocationTree.getArguments())));
if (variableType == null) {
return NO_MATCH;
}
Type collectionType =
types.asSuper(
ASTHelpers.getReceiverType(methodInvocationTree),
JAVA_UTIL_COLLECTION.get(visitorState));
List<Type> typeArguments = collectionType.getTypeArguments();
if (!typeArguments.isEmpty()
&& !types.isCastable(
types.erasure(variableType), types.erasure(getOnlyElement(typeArguments)))) {
return describeMatch(methodInvocationTree);
}
return NO_MATCH;
}
private static final Supplier<Symbol> JAVA_UTIL_COLLECTION =
VisitorState.memoize(state -> state.getSymbolFromString("java.util.Collection"));
}
| 3,155
| 37.487805
| 95
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TypesWithUndefinedEquality.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.util.ASTHelpers.isSameType;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.VisitorState;
import com.sun.tools.javac.code.Type;
/** Enumerates types which have poorly-defined behaviour for equals. */
public enum TypesWithUndefinedEquality {
// keep-sorted start
CHAR_SEQUENCE("CharSequence", "java.lang.CharSequence"),
COLLECTION("Collection", "java.util.Collection"),
DATE("Date", "java.util.Date"),
IMMUTABLE_COLLECTION("ImmutableCollection", "com.google.common.collect.ImmutableCollection"),
IMMUTABLE_MULTIMAP("ImmutableMultimap", "com.google.common.collect.ImmutableMultimap"),
ITERABLE("Iterable", "com.google.common.collect.FluentIterable", "java.lang.Iterable"),
LONG_SPARSE_ARRAY(
"LongSparseArray",
"android.support.v4.util.LongSparseArrayCompat",
"android.util.LongSparseArray",
"androidx.collection.LongSparseArrayCompat",
"androidx.core.util.LongSparseArrayCompat"),
MULTIMAP("Multimap", "com.google.common.collect.Multimap"),
QUEUE("Queue", "java.util.Queue"),
SPARSE_ARRAY("SparseArray", "android.util.SparseArray", "androidx.collection.SparseArrayCompat");
// keep-sorted end
private final String shortName;
private final ImmutableSet<String> typeNames;
TypesWithUndefinedEquality(String shortName, String... typeNames) {
this.shortName = shortName;
this.typeNames = ImmutableSet.copyOf(typeNames);
}
public boolean matchesType(Type type, VisitorState state) {
return typeNames.stream()
.anyMatch(typeName -> isSameType(type, state.getTypeFromString(typeName), state));
}
public String shortName() {
return shortName;
}
}
| 2,355
| 37
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitch.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.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
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 static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.sun.source.tree.Tree.Kind.BREAK;
import static com.sun.source.tree.Tree.Kind.EXPRESSION_STATEMENT;
import static com.sun.source.tree.Tree.Kind.RETURN;
import static com.sun.source.tree.Tree.Kind.THROW;
import static java.util.stream.Collectors.joining;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Streams;
import com.google.errorprone.BugPattern;
import com.google.errorprone.ErrorProneFlags;
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.matchers.Matchers;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.Reachability;
import com.google.errorprone.util.RuntimeVersion;
import com.google.errorprone.util.SourceVersion;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.BreakTree;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.SwitchTree;
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.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAssign;
import com.sun.tools.javac.tree.JCTree.JCAssignOp;
import com.sun.tools.javac.tree.Pretty;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.lang.model.element.ElementKind;
/** Checks for statement switches that can be expressed as an equivalent expression switch. */
@BugPattern(
severity = WARNING,
summary = "This statement switch can be converted to an equivalent expression switch")
public final class StatementSwitchToExpressionSwitch extends BugChecker
implements SwitchTreeMatcher {
// Braces are not required if there is exactly one statement on the right hand of the arrow, and
// it's either an ExpressionStatement or a Throw. Refer to JLS 14 §14.11.1
private static final ImmutableSet<Kind> KINDS_CONVERTIBLE_WITHOUT_BRACES =
ImmutableSet.of(THROW, EXPRESSION_STATEMENT);
private static final ImmutableSet<Kind> KINDS_RETURN_OR_THROW = ImmutableSet.of(THROW, RETURN);
private static final Pattern FALL_THROUGH_PATTERN =
Pattern.compile("\\bfalls?.?through\\b", Pattern.CASE_INSENSITIVE);
// Default (negative) result for assignment switch conversion analysis. Note that the value is
// immutable.
private static final AssignmentSwitchAnalysisResult DEFAULT_ASSIGNMENT_SWITCH_ANALYSIS_RESULT =
AssignmentSwitchAnalysisResult.of(
/* canConvertToAssignmentSwitch= */ false,
/* assignmentTargetOptional= */ Optional.empty(),
/* assignmentKindOptional= */ Optional.empty(),
/* assignmentSourceCodeOptional= */ Optional.empty());
// Default (negative) result for overall analysis. Note that the value is immutable.
private static final AnalysisResult DEFAULT_ANALYSIS_RESULT =
AnalysisResult.of(
/* canConvertDirectlyToExpressionSwitch= */ false,
/* canConvertToReturnSwitch= */ false,
DEFAULT_ASSIGNMENT_SWITCH_ANALYSIS_RESULT,
/* groupedWithNextCase= */ ImmutableList.of());
private static final String EQUALS_STRING = "=";
// Tri-state to represent the fall-thru control flow of a particular case of a particular
// statement switch
private static enum CaseFallThru {
DEFINITELY_DOES_NOT_FALL_THRU,
MAYBE_FALLS_THRU,
DEFINITELY_DOES_FALL_THRU
};
// Tri-state to represent whether cases within a single switch statement meet an (unspecified)
// qualification predicate
static enum CaseQualifications {
NO_CASES_ASSESSED,
ALL_CASES_QUALIFY,
SOME_OR_ALL_CASES_DONT_QUALIFY
}
private final boolean enableDirectConversion;
private final boolean enableReturnSwitchConversion;
private final boolean enableAssignmentSwitchConversion;
@Inject
StatementSwitchToExpressionSwitch(ErrorProneFlags flags) {
this.enableDirectConversion =
flags.getBoolean("StatementSwitchToExpressionSwitch:EnableDirectConversion").orElse(false);
this.enableReturnSwitchConversion =
flags
.getBoolean("StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")
.orElse(false);
this.enableAssignmentSwitchConversion =
flags
.getBoolean("StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")
.orElse(false);
}
@Override
public Description matchSwitch(SwitchTree switchTree, VisitorState state) {
if (!SourceVersion.supportsSwitchExpressions(state.context)) {
return NO_MATCH;
}
AnalysisResult analysisResult = analyzeSwitchTree(switchTree, state);
List<SuggestedFix> suggestedFixes = new ArrayList<>();
if (enableReturnSwitchConversion && analysisResult.canConvertToReturnSwitch()) {
suggestedFixes.add(convertToReturnSwitch(switchTree, state, analysisResult));
}
if (enableAssignmentSwitchConversion
&& analysisResult.assignmentSwitchAnalysisResult().canConvertToAssignmentSwitch()) {
suggestedFixes.add(convertToAssignmentSwitch(switchTree, state, analysisResult));
}
if (enableDirectConversion && analysisResult.canConvertDirectlyToExpressionSwitch()) {
suggestedFixes.add(convertDirectlyToExpressionSwitch(switchTree, state, analysisResult));
}
return suggestedFixes.isEmpty()
? NO_MATCH
: buildDescription(switchTree).addAllFixes(suggestedFixes).build();
}
/**
* Analyzes a {@code SwitchTree}, and determines any possible findings and suggested fixes related
* to expression switches that can be made. Does not report any findings or suggested fixes up to
* the Error Prone framework.
*/
private static AnalysisResult analyzeSwitchTree(SwitchTree switchTree, VisitorState state) {
// Don't convert switch within switch
if (ASTHelpers.findEnclosingNode(state.getPath(), SwitchTree.class) != null) {
return DEFAULT_ANALYSIS_RESULT;
}
List<? extends CaseTree> cases = switchTree.getCases();
// A given case is said to have definite control flow if we are sure it always or never falls
// thru at the end of its statement block
boolean allCasesHaveDefiniteControlFlow = true;
// A case is said to be grouped with the next one if we are sure it can appear together with the
// next case on the left hand side of the arrow when converted to an expression switch. For
// example "case A,B -> ..."
List<Boolean> groupedWithNextCase = new ArrayList<>(Collections.nCopies(cases.size(), false));
// Set of all enum values (names) explicitly listed in a case tree
Set<String> handledEnumValues = new HashSet<>();
// Does each case consist solely of returning a (non-void) expression?
CaseQualifications returnSwitchCaseQualifications = CaseQualifications.NO_CASES_ASSESSED;
// Does each case consist solely of a throw or the same symbol assigned in the same way?
AssignmentSwitchAnalysisState assignmentSwitchAnalysisState =
AssignmentSwitchAnalysisState.of(
/* assignmentSwitchCaseQualifications= */ CaseQualifications.NO_CASES_ASSESSED,
/* assignmentTargetOptional= */ Optional.empty(),
/* assignmentKindOptional= */ Optional.empty(),
/* assignmentTreeOptional= */ Optional.empty());
boolean hasDefaultCase = false;
// One-pass scan through each case in switch
for (int caseIndex = 0; caseIndex < cases.size(); caseIndex++) {
CaseTree caseTree = cases.get(caseIndex);
boolean isDefaultCase = (getExpressions(caseTree).count() == 0);
hasDefaultCase |= isDefaultCase;
// Accumulate enum values included in this case
handledEnumValues.addAll(
getExpressions(caseTree)
.filter(IdentifierTree.class::isInstance)
.map(expressionTree -> ((IdentifierTree) expressionTree).getName().toString())
.collect(toImmutableSet()));
boolean isLastCaseInSwitch = caseIndex == cases.size() - 1;
List<? extends StatementTree> statements = caseTree.getStatements();
CaseFallThru caseFallThru = CaseFallThru.MAYBE_FALLS_THRU;
if (statements == null) {
// This case must be of kind CaseTree.CaseKind.RULE, and thus this is already an expression
// switch; no need to continue analysis.
return DEFAULT_ANALYSIS_RESULT;
} else if (statements.isEmpty()) {
// If the code for this case is just an empty block, then it must fall thru
caseFallThru = CaseFallThru.DEFINITELY_DOES_FALL_THRU;
// Can group with the next case (unless this is the last case)
groupedWithNextCase.set(caseIndex, !isLastCaseInSwitch);
} else {
groupedWithNextCase.set(caseIndex, false);
// Code for this case is non-empty
if (areStatementsConvertibleToExpressionSwitch(statements, isLastCaseInSwitch)) {
caseFallThru = CaseFallThru.DEFINITELY_DOES_NOT_FALL_THRU;
}
}
if (isDefaultCase) {
// The "default" case has distinct semantics; don't allow anything to fall into or out of
// default case. Exception: allowed to fall out of default case if it's the last case
boolean fallsIntoDefaultCase = (caseIndex > 0) && groupedWithNextCase.get(caseIndex - 1);
if (isLastCaseInSwitch) {
allCasesHaveDefiniteControlFlow &= !fallsIntoDefaultCase;
} else {
allCasesHaveDefiniteControlFlow &=
!fallsIntoDefaultCase
&& caseFallThru.equals(CaseFallThru.DEFINITELY_DOES_NOT_FALL_THRU);
}
} else {
// Cases other than default
allCasesHaveDefiniteControlFlow &= !caseFallThru.equals(CaseFallThru.MAYBE_FALLS_THRU);
}
// Analyze for return switch and assignment switch conversion
returnSwitchCaseQualifications =
analyzeCaseForReturnSwitch(
returnSwitchCaseQualifications, statements, isLastCaseInSwitch);
assignmentSwitchAnalysisState =
analyzeCaseForAssignmentSwitch(
assignmentSwitchAnalysisState, statements, isLastCaseInSwitch);
}
boolean exhaustive =
isSwitchExhaustive(
hasDefaultCase, handledEnumValues, ASTHelpers.getType(switchTree.getExpression()));
boolean canConvertToReturnSwitch =
// All restrictions for direct conversion apply
allCasesHaveDefiniteControlFlow
// Does each case consist solely of returning a (non-void) expression?
&& returnSwitchCaseQualifications.equals(CaseQualifications.ALL_CASES_QUALIFY)
// The switch must be exhaustive (at compile time)
&& exhaustive;
boolean canConvertToAssignmentSwitch =
// All restrictions for direct conversion apply
allCasesHaveDefiniteControlFlow
// Does each case consist solely of a throw or the same symbol assigned in the same way?
&& assignmentSwitchAnalysisState
.assignmentSwitchCaseQualifications()
.equals(CaseQualifications.ALL_CASES_QUALIFY)
// The switch must be exhaustive (at compile time)
&& exhaustive;
return AnalysisResult.of(
/* canConvertDirectlyToExpressionSwitch= */ allCasesHaveDefiniteControlFlow,
canConvertToReturnSwitch,
AssignmentSwitchAnalysisResult.of(
canConvertToAssignmentSwitch,
assignmentSwitchAnalysisState.assignmentTargetOptional(),
assignmentSwitchAnalysisState.assignmentExpressionKindOptional(),
assignmentSwitchAnalysisState
.assignmentTreeOptional()
.map(StatementSwitchToExpressionSwitch::renderJavaSourceOfAssignment)),
ImmutableList.copyOf(groupedWithNextCase));
}
/**
* Renders the Java source code for a [compound] assignment operator. The parameter must be either
* an {@code AssignmentTree} or a {@code CompoundAssignmentTree}.
*/
private static String renderJavaSourceOfAssignment(ExpressionTree tree) {
// Simple assignment tree?
if (tree instanceof JCAssign) {
return EQUALS_STRING;
}
// Invariant: must be a compound assignment tree
JCAssignOp jcAssignOp = (JCAssignOp) tree;
Pretty pretty = new Pretty(new StringWriter(), /* sourceOutput= */ true);
return pretty.operatorName(jcAssignOp.getTag().noAssignOp()) + EQUALS_STRING;
}
/**
* Analyze a single {@code case} of a single {@code switch} statement to determine whether it is
* convertible to a return switch. The supplied {@code previousCaseQualifications} is updated and
* returned based on this analysis.
*/
private static CaseQualifications analyzeCaseForReturnSwitch(
CaseQualifications previousCaseQualifications,
List<? extends StatementTree> statements,
boolean isLastCaseInSwitch) {
if (statements.isEmpty() && !isLastCaseInSwitch) {
// This case can be grouped with the next and further analyzed there
return previousCaseQualifications;
}
// Statement blocks on the RHS are not currently supported
if (!(statements.size() == 1 && KINDS_RETURN_OR_THROW.contains(statements.get(0).getKind()))) {
return CaseQualifications.SOME_OR_ALL_CASES_DONT_QUALIFY;
}
StatementTree onlyStatement = statements.get(0);
// For this analysis, cases that don't return something can be disregarded
if (!onlyStatement.getKind().equals(RETURN)) {
return previousCaseQualifications;
}
if (!previousCaseQualifications.equals(CaseQualifications.NO_CASES_ASSESSED)) {
// There is no need to inspect the type compatibility of the return values, because if they
// were incompatible then the compilation would have failed before reaching this point
return previousCaseQualifications;
}
// This is the first value-returning case that we are examining
Type returnType = ASTHelpers.getType(((ReturnTree) onlyStatement).getExpression());
return returnType == null
// Return of void does not qualify
? CaseQualifications.SOME_OR_ALL_CASES_DONT_QUALIFY
: CaseQualifications.ALL_CASES_QUALIFY;
}
/**
* Analyze a single {@code case} of a single {@code switch} statement to determine whether it is
* convertible to an assignment switch. The supplied {@code previousAssignmentSwitchAnalysisState}
* is updated and returned based on this analysis.
*/
private static AssignmentSwitchAnalysisState analyzeCaseForAssignmentSwitch(
AssignmentSwitchAnalysisState previousAssignmentSwitchAnalysisState,
List<? extends StatementTree> statements,
boolean isLastCaseInSwitch) {
CaseQualifications caseQualifications =
previousAssignmentSwitchAnalysisState.assignmentSwitchCaseQualifications();
Optional<Kind> assignmentExpressionKindOptional =
previousAssignmentSwitchAnalysisState.assignmentExpressionKindOptional();
Optional<ExpressionTree> assignmentTargetOptional =
previousAssignmentSwitchAnalysisState.assignmentTargetOptional();
Optional<ExpressionTree> assignmentTreeOptional =
previousAssignmentSwitchAnalysisState.assignmentTreeOptional();
if (statements.isEmpty()) {
return isLastCaseInSwitch
// An empty last case cannot be an assignment
? AssignmentSwitchAnalysisState.of(
CaseQualifications.SOME_OR_ALL_CASES_DONT_QUALIFY,
assignmentTargetOptional,
assignmentExpressionKindOptional,
assignmentTreeOptional)
// This case can be grouped with the next and further analyzed there
: previousAssignmentSwitchAnalysisState;
}
// Invariant: statements is never empty
StatementTree firstStatement = statements.get(0);
Kind firstStatementKind = firstStatement.getKind();
// Can convert one statement or two with the second being an unconditional break
boolean expressionOrExpressionBreak =
(statements.size() == 1 && KINDS_CONVERTIBLE_WITHOUT_BRACES.contains(firstStatementKind))
|| (KINDS_CONVERTIBLE_WITHOUT_BRACES.contains(firstStatementKind)
// If the second statement is a break, then there must be exactly two statements
&& statements.get(1).getKind().equals(BREAK)
&& ((BreakTree) statements.get(1)).getLabel() == null);
if (!expressionOrExpressionBreak) {
// Conversion of this block is not supported
return AssignmentSwitchAnalysisState.of(
CaseQualifications.SOME_OR_ALL_CASES_DONT_QUALIFY,
assignmentTargetOptional,
assignmentExpressionKindOptional,
assignmentTreeOptional);
}
if (!firstStatement.getKind().equals(EXPRESSION_STATEMENT)) {
// Throws don't affect the assignment analysis
return previousAssignmentSwitchAnalysisState;
}
ExpressionTree expression = ((ExpressionStatementTree) firstStatement).getExpression();
Optional<ExpressionTree> caseAssignmentTargetOptional = Optional.empty();
Optional<Tree.Kind> caseAssignmentKindOptional = Optional.empty();
Optional<ExpressionTree> caseAssignmentTreeOptional = Optional.empty();
// The assignment could be a normal assignment ("=") or a compound assignment (e.g. "+=")
if (expression instanceof CompoundAssignmentTree) {
CompoundAssignmentTree compoundAssignmentTree = (CompoundAssignmentTree) expression;
caseAssignmentTargetOptional = Optional.of(compoundAssignmentTree.getVariable());
caseAssignmentKindOptional = Optional.of(compoundAssignmentTree.getKind());
caseAssignmentTreeOptional = Optional.of(expression);
} else if (expression instanceof AssignmentTree) {
caseAssignmentTargetOptional = Optional.of(((AssignmentTree) expression).getVariable());
caseAssignmentKindOptional = Optional.of(Tree.Kind.ASSIGNMENT);
caseAssignmentTreeOptional = Optional.of(expression);
}
boolean compatibleOperator =
// First assignment seen?
(assignmentExpressionKindOptional.isEmpty() && caseAssignmentKindOptional.isPresent())
// Not first assignment, but compatible with the first?
|| (assignmentExpressionKindOptional.isPresent()
&& caseAssignmentKindOptional.isPresent()
&& assignmentExpressionKindOptional.get().equals(caseAssignmentKindOptional.get()));
boolean compatibleReference =
// First assignment seen?
(assignmentTargetOptional.isEmpty() && caseAssignmentTargetOptional.isPresent())
// Not first assignment, but assigning to same symbol as the first assignment?
|| (assignmentTargetOptional.isPresent()
&& caseAssignmentTargetOptional.isPresent()
&& getSymbol(assignmentTargetOptional.get())
.equals(getSymbol(caseAssignmentTargetOptional.get())));
if (compatibleOperator && compatibleReference) {
caseQualifications =
caseQualifications.equals(CaseQualifications.NO_CASES_ASSESSED)
? CaseQualifications.ALL_CASES_QUALIFY
: caseQualifications;
} else {
caseQualifications = CaseQualifications.SOME_OR_ALL_CASES_DONT_QUALIFY;
}
// Save the assignment target/kind in the state, but never overwrite existing target/kind
return AssignmentSwitchAnalysisState.of(
caseQualifications,
/* assignmentTargetOptional= */ assignmentTargetOptional.isEmpty()
? caseAssignmentTargetOptional
: assignmentTargetOptional,
/* assignmentKindOptional= */ assignmentExpressionKindOptional.isEmpty()
? caseAssignmentKindOptional
: assignmentExpressionKindOptional,
/* assignmentTreeOptional= */ assignmentTreeOptional.isEmpty()
? caseAssignmentTreeOptional
: assignmentTreeOptional);
}
/**
* Determines whether the supplied case's {@code statements} are capable of being mapped to an
* equivalent expression switch case (without repeating code), returning {@code true} if so.
* Detection is based on an ad-hoc algorithm that is not guaranteed to detect every convertible
* instance (whether a given block can fall-thru is an undecidable proposition in general).
*/
private static boolean areStatementsConvertibleToExpressionSwitch(
List<? extends StatementTree> statements, boolean isLastCaseInSwitch) {
// For the last case, we can always convert (fall through has no effect)
if (isLastCaseInSwitch) {
return true;
}
// Always falls-thru; can combine with next case (if present)
if (statements.isEmpty()) {
return true;
}
// We only look at whether the block can fall-thru; javac would have already reported an
// error if the last statement in the block weren't reachable (in the JLS sense). Since we know
// it is reachable, whether the block can complete normally is independent of any preceding
// statements. If the last statement cannot complete normally, then the block cannot, and thus
// the block cannot fall-thru
return !Reachability.canCompleteNormally(getLast(statements));
}
/**
* Transforms the supplied statement switch into an expression switch directly. In this
* conversion, each nontrivial statement block is mapped one-to-one to a new {@code Expression} or
* {@code StatementBlock} on the right-hand side. Comments are presevered where possible.
*/
private static SuggestedFix convertDirectlyToExpressionSwitch(
SwitchTree switchTree, VisitorState state, AnalysisResult analysisResult) {
List<? extends CaseTree> cases = switchTree.getCases();
StringBuilder replacementCodeBuilder = new StringBuilder();
replacementCodeBuilder
.append("switch ")
.append(state.getSourceForNode(switchTree.getExpression()))
.append(" {");
StringBuilder groupedCaseCommentsAccumulator = null;
boolean firstCaseInGroup = true;
for (int caseIndex = 0; caseIndex < cases.size(); caseIndex++) {
CaseTree caseTree = cases.get(caseIndex);
boolean isDefaultCase = caseTree.getExpression() == null;
// For readability, filter out trailing unlabelled break statement because these become a
// No-Op when used inside expression switches
ImmutableList<StatementTree> filteredStatements = filterOutRedundantBreak(caseTree);
String transformedBlockSource =
transformBlock(caseTree, state, cases, caseIndex, filteredStatements);
if (firstCaseInGroup) {
groupedCaseCommentsAccumulator = new StringBuilder();
replacementCodeBuilder.append("\n ");
if (!isDefaultCase) {
replacementCodeBuilder.append("case ");
}
}
replacementCodeBuilder.append(
isDefaultCase ? "default" : printCaseExpressions(caseTree, state));
if (analysisResult.groupedWithNextCase().get(caseIndex)) {
firstCaseInGroup = false;
replacementCodeBuilder.append(", ");
// Capture comments from this case so they can be added to the group's transformed case
if (!transformedBlockSource.trim().isEmpty()) {
groupedCaseCommentsAccumulator.append(removeFallThruLines(transformedBlockSource));
}
// Add additional cases to the list on the lhs of the arrow
continue;
} else {
// This case is the last case in its group, so insert the collected comments from the lhs of
// the colon here
transformedBlockSource = groupedCaseCommentsAccumulator + transformedBlockSource;
}
replacementCodeBuilder.append(" -> ");
if (filteredStatements.isEmpty()) {
// Transformed block has no code
String trimmedTransformedBlockSource = transformedBlockSource.trim();
// If block is just space or a single "break;" with no explanatory comments, then remove
// it to eliminate redundancy and improve readability
if (trimmedTransformedBlockSource.isEmpty()
|| trimmedTransformedBlockSource.equals("break;")) {
replacementCodeBuilder.append("{}");
} else {
replacementCodeBuilder.append("{").append(transformedBlockSource).append("\n}");
}
} else {
// Transformed block has code
// Extract comments (if any) for break that was removed as redundant
Optional<String> commentsBeforeRemovedBreak =
extractCommentsBeforeRemovedBreak(caseTree, state, filteredStatements);
if (commentsBeforeRemovedBreak.isPresent()) {
transformedBlockSource = transformedBlockSource + "\n" + commentsBeforeRemovedBreak.get();
}
// To improve readability, don't use braces on the rhs if not needed
if (shouldTransformCaseWithoutBraces(
filteredStatements, transformedBlockSource, filteredStatements.get(0), state)) {
// Single statement with no comments - no braces needed
replacementCodeBuilder.append(transformedBlockSource);
} else {
// Use braces on the rhs
replacementCodeBuilder.append("{").append(transformedBlockSource).append("\n}");
}
}
firstCaseInGroup = true;
} // case loop
// Close the switch statement
replacementCodeBuilder.append("\n}");
return SuggestedFix.builder().replace(switchTree, replacementCodeBuilder.toString()).build();
}
/**
* Transforms the supplied statement switch into a {@code return switch ...} style of expression
* switch. In this conversion, each nontrivial statement block is mapped one-to-one to a new
* expression on the right-hand side of the arrow. Comments are presevered where possible.
* Precondition: the {@code AnalysisResult} for the {@code SwitchTree} must have deduced that this
* conversion is possible.
*/
private static SuggestedFix convertToReturnSwitch(
SwitchTree switchTree, VisitorState state, AnalysisResult analysisResult) {
List<StatementTree> statementsToDelete = new ArrayList<>();
List<? extends CaseTree> cases = switchTree.getCases();
StringBuilder replacementCodeBuilder = new StringBuilder();
replacementCodeBuilder
.append("return switch ")
.append(state.getSourceForNode(switchTree.getExpression()))
.append(" {");
StringBuilder groupedCaseCommentsAccumulator = null;
boolean firstCaseInGroup = true;
for (int caseIndex = 0; caseIndex < cases.size(); caseIndex++) {
CaseTree caseTree = cases.get(caseIndex);
boolean isDefaultCase = caseTree.getExpression() == null;
String transformedBlockSource =
transformReturnOrThrowBlock(caseTree, state, cases, caseIndex, caseTree.getStatements());
if (firstCaseInGroup) {
groupedCaseCommentsAccumulator = new StringBuilder();
replacementCodeBuilder.append("\n ");
if (!isDefaultCase) {
replacementCodeBuilder.append("case ");
}
}
replacementCodeBuilder.append(
isDefaultCase ? "default" : printCaseExpressions(caseTree, state));
if (analysisResult.groupedWithNextCase().get(caseIndex)) {
firstCaseInGroup = false;
replacementCodeBuilder.append(", ");
// Capture comments from this case so they can be added to the group's transformed case
if (!transformedBlockSource.trim().isEmpty()) {
groupedCaseCommentsAccumulator.append(removeFallThruLines(transformedBlockSource));
}
// Add additional cases to the list on the lhs of the arrow
continue;
} else {
// This case is the last case in its group, so insert the collected comments from the lhs of
// the colon here
transformedBlockSource = groupedCaseCommentsAccumulator + transformedBlockSource;
}
replacementCodeBuilder.append(" -> ");
// Single statement with no comments - no braces needed
replacementCodeBuilder.append(transformedBlockSource);
firstCaseInGroup = true;
} // case loop
// Close the switch statement
replacementCodeBuilder.append("\n};");
// Statements in the same block following the switch are currently reachable but will become
// unreachable, which would lead to a compile-time error. Therefore, suggest that they be
// removed.
statementsToDelete.addAll(followingStatementsInBlock(switchTree, state));
SuggestedFix.Builder suggestedFixBuilder =
SuggestedFix.builder().replace(switchTree, replacementCodeBuilder.toString());
// Delete trailing statements, leaving comments where feasible
statementsToDelete.forEach(deleteMe -> suggestedFixBuilder.replace(deleteMe, ""));
return suggestedFixBuilder.build();
}
/**
* Retrieves a list of all statements (if any) following the supplied {@code SwitchTree} in its
* lowest-ancestor statement block (if any).
*/
private static List<StatementTree> followingStatementsInBlock(
SwitchTree switchTree, VisitorState state) {
List<StatementTree> followingStatements = new ArrayList<>();
// NOMUTANTS--for performance/early return only; correctness unchanged
if (!Matchers.nextStatement(Matchers.<StatementTree>anything()).matches(switchTree, state)) {
// No lowest-ancestor block or no following statements
return followingStatements;
}
// Fetch the lowest ancestor statement block
TreePath pathToEnclosing = state.findPathToEnclosing(BlockTree.class);
// NOMUTANTS--should early return above
if (pathToEnclosing != null) {
Tree enclosing = pathToEnclosing.getLeaf();
if (enclosing instanceof BlockTree) {
BlockTree blockTree = (BlockTree) enclosing;
// Path from root -> switchTree
TreePath rootToSwitchPath = TreePath.getPath(pathToEnclosing, switchTree);
for (int i = findBlockStatementIndex(rootToSwitchPath, blockTree) + 1;
(i >= 0) && (i < blockTree.getStatements().size());
i++) {
followingStatements.add(blockTree.getStatements().get(i));
}
}
}
return followingStatements;
}
/**
* Search through the provided {@code BlockTree} to find which statement in that block tree lies
* along the supplied {@code TreePath}. Returns the index (zero-based) of the matching statement
* in the block tree, or -1 if not found.
*/
private static int findBlockStatementIndex(TreePath treePath, BlockTree blockTree) {
for (int i = 0; i < blockTree.getStatements().size(); i++) {
StatementTree thisStatement = blockTree.getStatements().get(i);
// Look for thisStatement along the path from the root to the switch tree
TreePath pathFromRootToThisStatement = TreePath.getPath(treePath, thisStatement);
if (pathFromRootToThisStatement != null) {
return i;
}
}
return -1;
}
/**
* Transforms the supplied statement switch into an assignment switch style of expression switch.
* In this conversion, each nontrivial statement block is mapped one-to-one to a new expression on
* the right-hand side of the arrow. Comments are presevered where possible. Precondition: the
* {@code AnalysisResult} for the {@code SwitchTree} must have deduced that this conversion is
* possible.
*/
private static SuggestedFix convertToAssignmentSwitch(
SwitchTree switchTree, VisitorState state, AnalysisResult analysisResult) {
List<? extends CaseTree> cases = switchTree.getCases();
StringBuilder replacementCodeBuilder =
new StringBuilder(
state.getSourceForNode(
analysisResult
.assignmentSwitchAnalysisResult()
.assignmentTargetOptional()
.get()))
.append(" ")
// Invariant: always present when a finding exists
.append(
analysisResult
.assignmentSwitchAnalysisResult()
.assignmentSourceCodeOptional()
.get())
.append(" ")
.append("switch ")
.append(state.getSourceForNode(switchTree.getExpression()))
.append(" {");
StringBuilder groupedCaseCommentsAccumulator = null;
boolean firstCaseInGroup = true;
for (int caseIndex = 0; caseIndex < cases.size(); caseIndex++) {
CaseTree caseTree = cases.get(caseIndex);
boolean isDefaultCase = caseTree.getExpression() == null;
ImmutableList<StatementTree> filteredStatements = filterOutRedundantBreak(caseTree);
String transformedBlockSource =
transformAssignOrThrowBlock(caseTree, state, cases, caseIndex, filteredStatements);
if (firstCaseInGroup) {
groupedCaseCommentsAccumulator = new StringBuilder();
replacementCodeBuilder.append("\n ");
if (!isDefaultCase) {
replacementCodeBuilder.append("case ");
}
}
replacementCodeBuilder.append(
isDefaultCase ? "default" : printCaseExpressions(caseTree, state));
if (analysisResult.groupedWithNextCase().get(caseIndex)) {
firstCaseInGroup = false;
replacementCodeBuilder.append(", ");
// Capture comments from this case so they can be added to the group's transformed case
if (!transformedBlockSource.trim().isEmpty()) {
groupedCaseCommentsAccumulator.append(removeFallThruLines(transformedBlockSource));
}
// Add additional cases to the list on the lhs of the arrow
continue;
} else {
// This case is the last case in its group, so insert the collected comments from the lhs of
// the colon here
transformedBlockSource = groupedCaseCommentsAccumulator + transformedBlockSource;
}
replacementCodeBuilder.append(" -> ");
// Extract comments (if any) for break that was removed as redundant
Optional<String> commentsBeforeRemovedBreak =
extractCommentsBeforeRemovedBreak(caseTree, state, filteredStatements);
if (commentsBeforeRemovedBreak.isPresent()) {
transformedBlockSource = transformedBlockSource + "\n" + commentsBeforeRemovedBreak.get();
}
// Single statement with no comments - no braces needed
replacementCodeBuilder.append(transformedBlockSource);
firstCaseInGroup = true;
} // case loop
// Close the switch statement
replacementCodeBuilder.append("\n};");
return SuggestedFix.builder().replace(switchTree, replacementCodeBuilder.toString()).build();
}
/**
* Extracts comments after the last filtered statement but before a removed trailing break
* statement, if present.
*/
private static Optional<String> extractCommentsBeforeRemovedBreak(
CaseTree caseTree, VisitorState state, ImmutableList<StatementTree> filteredStatements) {
// Was a trailing break removed and some expressions remain?
if (caseTree.getStatements().size() > filteredStatements.size()
&& !filteredStatements.isEmpty()) {
// Extract any comments after what is now the last statement and before the removed
// break
String commentsAfterNewLastStatement =
state
.getSourceCode()
.subSequence(
state.getEndPosition(Iterables.getLast(filteredStatements)),
getStartPosition(
caseTree.getStatements().get(caseTree.getStatements().size() - 1)))
.toString()
.trim();
if (!commentsAfterNewLastStatement.isEmpty()) {
return Optional.of(commentsAfterNewLastStatement);
}
}
return Optional.empty();
}
/**
* If the block for this {@code CaseTree} ends with a {@code break} statement that would be
* redundant after transformation, then filter out the relevant {@code break} statement.
*/
private static ImmutableList<StatementTree> filterOutRedundantBreak(CaseTree caseTree) {
boolean caseEndsWithUnlabelledBreak =
Streams.findLast(caseTree.getStatements().stream())
.filter(statement -> statement.getKind().equals(BREAK))
.filter(breakTree -> ((BreakTree) breakTree).getLabel() == null)
.isPresent();
return caseEndsWithUnlabelledBreak
? caseTree.getStatements().stream()
.limit(caseTree.getStatements().size() - 1)
.collect(toImmutableList())
: ImmutableList.copyOf(caseTree.getStatements());
}
/** Transforms code for this case into the code under an expression switch. */
private static String transformBlock(
CaseTree caseTree,
VisitorState state,
List<? extends CaseTree> cases,
int caseIndex,
ImmutableList<StatementTree> filteredStatements) {
StringBuilder transformedBlockBuilder = new StringBuilder();
int codeBlockStart = extractLhsComments(caseTree, state, transformedBlockBuilder);
int codeBlockEnd =
filteredStatements.isEmpty()
? getBlockEnd(state, caseTree, cases, caseIndex)
: state.getEndPosition(Streams.findLast(filteredStatements.stream()).get());
transformedBlockBuilder.append(state.getSourceCode(), codeBlockStart, codeBlockEnd);
return transformedBlockBuilder.toString();
}
/**
* Extracts comments to the left side of the colon for the provided {@code CaseTree} into the
* {@code StringBuilder}. Note that any whitespace between distinct comments is not necessarily
* preserved exactly.
*/
private static int extractLhsComments(
CaseTree caseTree, VisitorState state, StringBuilder stringBuilder) {
int lhsStart = getStartPosition(caseTree);
int lhsEnd =
caseTree.getStatements().isEmpty()
? state.getEndPosition(caseTree)
: getStartPosition(caseTree.getStatements().get(0));
// Accumulate comments into transformed block
state.getOffsetTokens(lhsStart, lhsEnd).stream()
.flatMap(errorProneToken -> errorProneToken.comments().stream())
.forEach(comment -> stringBuilder.append(comment.getText()).append("\n"));
return lhsEnd;
}
/**
* Finds the position in source corresponding to the end of the code block of the supplied {@code
* caseIndex} within all {@code cases}.
*/
private static int getBlockEnd(
VisitorState state, CaseTree caseTree, List<? extends CaseTree> cases, int caseIndex) {
if (caseIndex == cases.size() - 1) {
return state.getEndPosition(caseTree);
}
return ((JCTree) cases.get(caseIndex + 1)).getStartPosition();
}
/**
* Determines whether the supplied {@code case}'s logic should be expressed on the right of the
* arrow symbol without braces, incorporating both language and readabilitiy considerations.
*/
private static boolean shouldTransformCaseWithoutBraces(
ImmutableList<StatementTree> statementTrees,
String transformedBlockSource,
StatementTree firstStatement,
VisitorState state) {
if (statementTrees.isEmpty()) {
// Instead, express as "-> {}"
return false;
}
if (statementTrees.size() > 1) {
// Instead, express as a code block "-> { ... }"
return false;
}
// If code has comments, use braces for readability
if (!transformedBlockSource.trim().equals(state.getSourceForNode(firstStatement).trim())) {
return false;
}
StatementTree onlyStatementTree = statementTrees.get(0);
return KINDS_CONVERTIBLE_WITHOUT_BRACES.contains(onlyStatementTree.getKind());
}
/**
* Removes any comment lines containing language similar to "fall thru". Intermediate line
* delimiters are also changed to newline.
*/
private static String removeFallThruLines(String comments) {
StringBuilder output = new StringBuilder();
try (BufferedReader br = new BufferedReader(new CharArrayReader(comments.toCharArray()))) {
String line;
while ((line = br.readLine()) != null) {
if (!FALL_THROUGH_PATTERN.matcher(line).find()) {
output.append(line).append("\n");
}
}
// Remove trailing \n, if present
return output.length() > 0 ? output.substring(0, output.length() - 1) : "";
} catch (IOException e) {
return comments;
}
}
/** Prints source for all expressions in a given {@code case}, separated by commas. */
private static String printCaseExpressions(CaseTree caseTree, VisitorState state) {
return getExpressions(caseTree).map(state::getSourceForNode).collect(joining(", "));
}
/**
* Retrieves a stream containing all case expressions, in order, for a given {@code CaseTree}.
* This method acts as a facade to the {@code CaseTree.getExpressions()} API, falling back to
* legacy APIs when necessary.
*/
@SuppressWarnings("unchecked")
private static Stream<? extends ExpressionTree> getExpressions(CaseTree caseTree) {
try {
if (RuntimeVersion.isAtLeast12()) {
return ((List<? extends ExpressionTree>)
CaseTree.class.getMethod("getExpressions").invoke(caseTree))
.stream();
} else {
// "default" case gives an empty stream
return caseTree.getExpression() == null
? Stream.empty()
: Stream.of(caseTree.getExpression());
}
} catch (ReflectiveOperationException e) {
throw new LinkageError(e.getMessage(), e);
}
}
/**
* Ad-hoc algorithm to search for a surjective map from (non-null) values of a {@code switch}'s
* expression to a {@code CaseTree}. Note that this algorithm does not compute whether such a map
* exists, but rather only whether it can find such a map.
*/
private static boolean isSwitchExhaustive(
boolean hasDefaultCase, Set<String> handledEnumValues, Type switchType) {
if (hasDefaultCase) {
// Anything not included in a case can be mapped to the default CaseTree
return true;
}
// Handles switching on enum (map is bijective)
if (switchType.asElement().getKind() != ElementKind.ENUM) {
// Give up on search
return false;
}
return handledEnumValues.containsAll(ASTHelpers.enumValues(switchType.asElement()));
}
/**
* Transforms a return or throw block into an expression statement suitable for use on the
* right-hand-side of the arrow of a return switch. For example, {@code return x+1;} would be
* transformed to {@code x+1;}.
*/
private static String transformReturnOrThrowBlock(
CaseTree caseTree,
VisitorState state,
List<? extends CaseTree> cases,
int caseIndex,
List<? extends StatementTree> statements) {
StringBuilder transformedBlockBuilder = new StringBuilder();
int codeBlockStart;
int codeBlockEnd =
statements.isEmpty()
? getBlockEnd(state, caseTree, cases, caseIndex)
: state.getEndPosition(Streams.findLast(statements.stream()).get());
if (statements.size() == 1 && statements.get(0).getKind().equals(RETURN)) {
// For "return x;", we want to take source starting after the "return"
int unused = extractLhsComments(caseTree, state, transformedBlockBuilder);
ReturnTree returnTree = (ReturnTree) statements.get(0);
codeBlockStart = getStartPosition(returnTree.getExpression());
} else {
codeBlockStart = extractLhsComments(caseTree, state, transformedBlockBuilder);
}
transformedBlockBuilder.append(state.getSourceCode(), codeBlockStart, codeBlockEnd);
return transformedBlockBuilder.toString();
}
/**
* Transforms a assignment or throw into an expression statement suitable for use on the
* right-hand-side of the arrow of an assignment switch. For example, {@code x >>= 2;} would be
* transformed to {@code 2;}. Note that this method does not return the assignment operator (e.g.
* {@code >>=}).
*/
private static String transformAssignOrThrowBlock(
CaseTree caseTree,
VisitorState state,
List<? extends CaseTree> cases,
int caseIndex,
List<? extends StatementTree> statements) {
StringBuilder transformedBlockBuilder = new StringBuilder();
int codeBlockStart;
int codeBlockEnd =
statements.isEmpty()
? getBlockEnd(state, caseTree, cases, caseIndex)
: state.getEndPosition(Streams.findLast(statements.stream()).get());
if (!statements.isEmpty() && statements.get(0).getKind().equals(EXPRESSION_STATEMENT)) {
// For "x = foo", we want to take source starting after the "x ="
int unused = extractLhsComments(caseTree, state, transformedBlockBuilder);
ExpressionTree expression = ((ExpressionStatementTree) statements.get(0)).getExpression();
Optional<ExpressionTree> rhs = Optional.empty();
if (expression instanceof CompoundAssignmentTree) {
rhs = Optional.of(((CompoundAssignmentTree) expression).getExpression());
} else if (expression instanceof AssignmentTree) {
rhs = Optional.of(((AssignmentTree) expression).getExpression());
}
codeBlockStart = getStartPosition(rhs.get());
} else {
codeBlockStart = extractLhsComments(caseTree, state, transformedBlockBuilder);
}
transformedBlockBuilder.append(state.getSourceCode(), codeBlockStart, codeBlockEnd);
return transformedBlockBuilder.toString();
}
@AutoValue
abstract static class AnalysisResult {
// Whether the statement switch can be directly converted to an expression switch
abstract boolean canConvertDirectlyToExpressionSwitch();
// Whether the statement switch can be converted to a return switch
abstract boolean canConvertToReturnSwitch();
// Results of the analysis for conversion to an assignment switch
abstract AssignmentSwitchAnalysisResult assignmentSwitchAnalysisResult();
// List of whether each case tree can be grouped with its successor in transformed source code
abstract ImmutableList<Boolean> groupedWithNextCase();
static AnalysisResult of(
boolean canConvertDirectlyToExpressionSwitch,
boolean canConvertToReturnSwitch,
AssignmentSwitchAnalysisResult assignmentSwitchAnalysisResult,
ImmutableList<Boolean> groupedWithNextCase) {
return new AutoValue_StatementSwitchToExpressionSwitch_AnalysisResult(
canConvertDirectlyToExpressionSwitch,
canConvertToReturnSwitch,
assignmentSwitchAnalysisResult,
groupedWithNextCase);
}
}
@AutoValue
abstract static class AssignmentSwitchAnalysisResult {
// Whether the statement switch can be converted to an assignment switch
abstract boolean canConvertToAssignmentSwitch();
// Target of the assignment switch, if any
abstract Optional<ExpressionTree> assignmentTargetOptional();
// Kind of assignment made by the assignment switch, if any
abstract Optional<Tree.Kind> assignmentKindOptional();
// Java source code of the assignment switch's operator, e.g. "+="
abstract Optional<String> assignmentSourceCodeOptional();
static AssignmentSwitchAnalysisResult of(
boolean canConvertToAssignmentSwitch,
Optional<ExpressionTree> assignmentTargetOptional,
Optional<Tree.Kind> assignmentKindOptional,
Optional<String> assignmentSourceCodeOptional) {
return new AutoValue_StatementSwitchToExpressionSwitch_AssignmentSwitchAnalysisResult(
canConvertToAssignmentSwitch,
assignmentTargetOptional,
assignmentKindOptional,
assignmentSourceCodeOptional);
}
}
@AutoValue
abstract static class AssignmentSwitchAnalysisState {
// Overall qualification of the switch statement for conversion to an assignment switch
abstract CaseQualifications assignmentSwitchCaseQualifications();
// Target of the first assignment seen, if any
abstract Optional<ExpressionTree> assignmentTargetOptional();
// Kind of the first assignment seen, if any
abstract Optional<Tree.Kind> assignmentExpressionKindOptional();
// ExpressionTree of the first assignment seen, if any
abstract Optional<ExpressionTree> assignmentTreeOptional();
static AssignmentSwitchAnalysisState of(
CaseQualifications assignmentSwitchCaseQualifications,
Optional<ExpressionTree> assignmentTargetOptional,
Optional<Tree.Kind> assignmentKindOptional,
Optional<ExpressionTree> assignmentTreeOptional) {
return new AutoValue_StatementSwitchToExpressionSwitch_AssignmentSwitchAnalysisState(
assignmentSwitchCaseQualifications,
assignmentTargetOptional,
assignmentKindOptional,
assignmentTreeOptional);
}
}
}
| 50,663
| 43.520211
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/PrivateConstructorForUtilityClass.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Streams.stream;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.fixes.SuggestedFixes.addMembers;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.createPrivateConstructor;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import static com.google.errorprone.util.ASTHelpers.isGeneratedConstructor;
import static com.sun.source.tree.Tree.Kind.CLASS;
import static com.sun.source.tree.Tree.Kind.METHOD;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.STATIC;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.BlockTree;
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.ClassSymbol;
import javax.lang.model.element.Modifier;
/**
* @author gak@google.com (Gregory Kick)
*/
@BugPattern(
summary =
"Classes which are not intended to be instantiated should be made non-instantiable with a"
+ " private constructor. This includes utility classes (classes with only static"
+ " members), and the main class.",
severity = SUGGESTION)
public final class PrivateConstructorForUtilityClass extends BugChecker
implements ClassTreeMatcher {
private static final ImmutableSet<String> ANNOTATIONS_TO_IGNORE =
ImmutableSet.of(
"org.junit.runner.RunWith",
"org.robolectric.annotation.Implements",
"com.google.auto.value.AutoValue");
@Override
public Description matchClass(ClassTree classTree, VisitorState state) {
if (!classTree.getKind().equals(CLASS)
|| classTree.getModifiers().getFlags().contains(Modifier.ABSTRACT)
|| classTree.getExtendsClause() != null
|| !classTree.getImplementsClause().isEmpty()
|| isInPrivateScope(state)) {
return NO_MATCH;
}
ClassSymbol sym = getSymbol(classTree);
for (String annotation : ANNOTATIONS_TO_IGNORE) {
if (hasAnnotation(sym, annotation, state)) {
return NO_MATCH;
}
}
ImmutableList<Tree> nonSyntheticMembers =
classTree.getMembers().stream()
.filter(
tree ->
!(tree.getKind().equals(METHOD) && isGeneratedConstructor((MethodTree) tree)))
.collect(toImmutableList());
if (nonSyntheticMembers.isEmpty()
|| nonSyntheticMembers.stream().anyMatch(PrivateConstructorForUtilityClass::isInstance)) {
return NO_MATCH;
}
SuggestedFix.Builder fix =
SuggestedFix.builder()
.merge(addMembers(classTree, state, createPrivateConstructor(classTree)));
SuggestedFixes.addModifiers(classTree, state, Modifier.FINAL).ifPresent(fix::merge);
return describeMatch(classTree, fix.build());
}
private static boolean isInPrivateScope(VisitorState state) {
return stream(state.getPath())
.anyMatch(
currentLeaf ->
// Checking instanceof rather than Kind given (e.g.) enums are ClassTrees.
currentLeaf instanceof ClassTree
&& ((ClassTree) currentLeaf).getModifiers().getFlags().contains(PRIVATE));
}
private static boolean isInstance(Tree tree) {
switch (tree.getKind()) {
case CLASS:
return !((ClassTree) tree).getModifiers().getFlags().contains(STATIC);
case METHOD:
return !((MethodTree) tree).getModifiers().getFlags().contains(STATIC);
case VARIABLE:
return !((VariableTree) tree).getModifiers().getFlags().contains(STATIC);
case BLOCK:
return !((BlockTree) tree).isStatic();
case ENUM:
case ANNOTATION_TYPE:
case INTERFACE:
return false;
default:
if (tree.getKind().name().equals("RECORD")) {
return false;
}
throw new AssertionError("unknown member type:" + tree.getKind());
}
}
}
| 5,251
| 39.4
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/FuzzyEqualsShouldNotBeUsedInEqualsMethod.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.enclosingMethod;
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.matchers.Matchers;
import com.sun.source.tree.MethodInvocationTree;
/**
* @author sulku@google.com (Marsela Sulku)
*/
@BugPattern(
summary = "DoubleMath.fuzzyEquals should never be used in an Object.equals() method",
severity = ERROR)
public class FuzzyEqualsShouldNotBeUsedInEqualsMethod extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Matcher<MethodInvocationTree> CALL_TO_FUZZY_IN_EQUALS =
allOf(
staticMethod().onClass("com.google.common.math.DoubleMath").named("fuzzyEquals"),
enclosingMethod(Matchers.equalsMethodDeclaration()));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (CALL_TO_FUZZY_IN_EQUALS.matches(tree, state)) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
}
| 2,067
| 37.296296
| 91
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BadInstanceof.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.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.isNonNullUsingDataflow;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.InstanceOfTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.InstanceOfTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
/**
* Matches instanceof checks where the expression is a subtype of the checked type.
*
* @author ghm@google.com (Graeme Morgan)
*/
@BugPattern(
summary = "instanceof used in a way that is equivalent to a null check.",
severity = WARNING,
tags = SIMPLIFICATION)
public final class BadInstanceof extends BugChecker implements InstanceOfTreeMatcher {
@Override
public Description matchInstanceOf(InstanceOfTree tree, VisitorState state) {
if (!isSubtype(getType(tree.getExpression()), getType(tree.getType()), state)) {
return NO_MATCH;
}
String subType = SuggestedFixes.prettyType(getType(tree.getExpression()), state);
String expression = state.getSourceForNode(tree.getExpression());
String superType = state.getSourceForNode(tree.getType());
if (isNonNullUsingDataflow().matches(tree.getExpression(), state)) {
return buildDescription(tree)
.setMessage(
String.format(
"`%s` is a non-null instance of %s which is a subtype of %s, so this check is"
+ " always true.",
expression, subType, superType))
.build();
}
return buildDescription(tree)
.setMessage(
String.format(
"`%s` is an instance of %s which is a subtype of %s, so this is equivalent to a"
+ " null check.",
expression, subType, superType))
.addFix(getFix(tree, state))
.build();
}
private static SuggestedFix getFix(InstanceOfTree tree, VisitorState state) {
Tree parent = state.getPath().getParentPath().getLeaf();
Tree grandParent = state.getPath().getParentPath().getParentPath().getLeaf();
if (parent.getKind() == Kind.PARENTHESIZED
&& grandParent.getKind() == Kind.LOGICAL_COMPLEMENT) {
return SuggestedFix.replace(
grandParent, state.getSourceForNode(tree.getExpression()) + " == null");
}
return SuggestedFix.replace(tree, state.getSourceForNode(tree.getExpression()) + " != null");
}
}
| 3,549
| 40.764706
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MethodCanBeStatic.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.Sets.immutableEnumSet;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.fixes.SuggestedFixes.addModifiers;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.SERIALIZATION_METHODS;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static java.util.Collections.disjoint;
import static javax.lang.model.element.Modifier.ABSTRACT;
import static javax.lang.model.element.Modifier.DEFAULT;
import static javax.lang.model.element.Modifier.NATIVE;
import static javax.lang.model.element.Modifier.SYNCHRONIZED;
import com.google.common.collect.ImmutableSet;
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.bugpatterns.CanBeStaticAnalyzer.CanBeStaticResult;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePathScanner;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import javax.lang.model.element.Modifier;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
altNames = "static-method",
summary = "A private method that does not reference the enclosing instance can be static",
severity = SUGGESTION,
documentSuppression = false)
public class MethodCanBeStatic extends BugChecker implements CompilationUnitTreeMatcher {
private final FindingOutputStyle findingOutputStyle;
@Inject
MethodCanBeStatic(ErrorProneFlags flags) {
boolean findingPerSite = flags.getBoolean("MethodCanBeStatic:FindingPerSite").orElse(false);
this.findingOutputStyle =
findingPerSite ? FindingOutputStyle.FINDING_PER_SITE : FindingOutputStyle.ONE_FINDING;
}
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
Map<MethodSymbol, MethodDetails> nodes = new HashMap<>();
new TreePathScanner<Void, Void>() {
private int suppressions = 0;
@Override
public Void visitClass(ClassTree classTree, Void unused) {
if (isSuppressed(classTree, state)) {
suppressions++;
super.visitClass(classTree, null);
suppressions--;
} else {
super.visitClass(classTree, null);
}
return null;
}
@Override
public Void visitMethod(MethodTree tree, Void unused) {
if (isSuppressed(tree, state)) {
suppressions++;
matchMethod(tree);
super.visitMethod(tree, null);
suppressions--;
} else {
matchMethod(tree);
super.visitMethod(tree, null);
}
return null;
}
@Override
public Void visitVariable(VariableTree variableTree, Void unused) {
if (isSuppressed(variableTree, state)) {
suppressions++;
super.visitVariable(variableTree, null);
suppressions--;
} else {
super.visitVariable(variableTree, null);
}
return null;
}
private void matchMethod(MethodTree tree) {
MethodSymbol sym = ASTHelpers.getSymbol(tree);
if (sym.isStatic()) {
nodes.put(sym, new MethodDetails(tree, true, ImmutableSet.of()));
} else {
CanBeStaticResult result = CanBeStaticAnalyzer.canBeStaticResult(tree, sym, state);
boolean isExcluded = isExcluded(tree, state);
nodes.put(
sym,
new MethodDetails(
tree,
result.canPossiblyBeStatic() && !isExcluded && suppressions == 0,
result.methodsReferenced()));
}
}
}.scan(state.getPath(), null);
propagateNonStaticness(nodes);
nodes
.entrySet()
.removeIf(
entry -> entry.getValue().tree.getModifiers().getFlags().contains(Modifier.STATIC));
return generateDescription(nodes, state);
}
private static void propagateNonStaticness(Map<MethodSymbol, MethodDetails> nodes) {
for (Map.Entry<MethodSymbol, MethodDetails> entry : nodes.entrySet()) {
MethodSymbol sym = entry.getKey();
MethodDetails methodDetails = entry.getValue();
for (MethodSymbol use : methodDetails.methodsReferenced) {
if (nodes.containsKey(use)) {
nodes.get(use).referencedBy.add(sym);
}
}
if (referencesExternalMethods(methodDetails, nodes.keySet())) {
methodDetails.couldPossiblyBeStatic = false;
}
}
Set<MethodSymbol> toVisit = new HashSet<>(nodes.keySet());
while (!toVisit.isEmpty()) {
Set<MethodSymbol> nextVisit = new HashSet<>();
for (MethodSymbol sym : toVisit) {
MethodDetails methodDetails = nodes.get(sym);
if (methodDetails.couldPossiblyBeStatic) {
continue;
}
for (MethodSymbol user : methodDetails.referencedBy) {
if (!nodes.get(user).couldPossiblyBeStatic) {
continue;
}
nodes.get(user).couldPossiblyBeStatic = false;
nodes.get(user).methodsReferenced.remove(sym);
nextVisit.add(user);
}
}
toVisit = nextVisit;
}
}
private Description generateDescription(
Map<MethodSymbol, MethodDetails> nodes, VisitorState state) {
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
fixBuilder.setShortDescription("Make static");
Set<MethodTree> affectedTrees = new HashSet<>();
for (Map.Entry<MethodSymbol, MethodDetails> entry : nodes.entrySet()) {
MethodSymbol sym = entry.getKey();
MethodDetails methodDetails = entry.getValue();
boolean noExternalMethods = !referencesExternalMethods(methodDetails, nodes.keySet());
if (methodDetails.couldPossiblyBeStatic && noExternalMethods) {
addModifiers(methodDetails.tree, state, Modifier.STATIC)
.map(f -> fixQualifiers(state, sym, f))
.ifPresent(fixBuilder::merge);
affectedTrees.add(methodDetails.tree);
}
}
return findingOutputStyle.report(affectedTrees, fixBuilder.build(), state, this);
}
private static boolean referencesExternalMethods(
MethodDetails methodDetails, Set<MethodSymbol> localMethods) {
return !Sets.difference(methodDetails.methodsReferenced, localMethods).isEmpty();
}
/**
* Replace instance references to the method with static access (e.g. `this.foo(...)` ->
* `EnclosingClass.foo(...)` and `this::foo` to `EnclosingClass::foo`).
*/
private SuggestedFix fixQualifiers(VisitorState state, MethodSymbol sym, SuggestedFix f) {
SuggestedFix.Builder builder = SuggestedFix.builder().merge(f);
new TreeScanner<Void, Void>() {
@Override
public Void visitMemberSelect(MemberSelectTree tree, Void unused) {
fixQualifier(tree, tree.getExpression());
return super.visitMemberSelect(tree, unused);
}
@Override
public Void visitMemberReference(MemberReferenceTree tree, Void unused) {
fixQualifier(tree, tree.getQualifierExpression());
return super.visitMemberReference(tree, unused);
}
private void fixQualifier(Tree tree, ExpressionTree qualifierExpression) {
if (sym.equals(ASTHelpers.getSymbol(tree))) {
builder.replace(qualifierExpression, sym.owner.enclClass().getSimpleName().toString());
}
}
}.scan(state.getPath().getCompilationUnit(), null);
return builder.build();
}
private static boolean isExcluded(MethodTree tree, VisitorState state) {
MethodSymbol sym = ASTHelpers.getSymbol(tree);
if (sym.isConstructor() || !disjoint(EXCLUDED_MODIFIERS, sym.getModifiers())) {
return true;
}
if (!ASTHelpers.canBeRemoved(sym, state) || ASTHelpers.shouldKeep(tree)) {
return true;
}
switch (sym.owner.enclClass().getNestingKind()) {
case TOP_LEVEL:
break;
case MEMBER:
if (sym.owner.enclClass().hasOuterInstance()) {
return true;
}
break;
case LOCAL:
case ANONYMOUS:
return true;
}
return SERIALIZATION_METHODS.matches(tree, state);
}
private static final ImmutableSet<Modifier> EXCLUDED_MODIFIERS =
immutableEnumSet(NATIVE, SYNCHRONIZED, ABSTRACT, DEFAULT);
/** Information about a {@link MethodSymbol} and whether it can be made static. */
private static final class MethodDetails {
private final MethodTree tree;
private boolean couldPossiblyBeStatic;
private final Set<MethodSymbol> methodsReferenced;
private final Set<MethodSymbol> referencedBy = new HashSet<>();
private MethodDetails(
MethodTree tree, boolean couldPossiblyBeStatic, Set<MethodSymbol> methodsReferenced) {
this.tree = tree;
this.couldPossiblyBeStatic = couldPossiblyBeStatic;
this.methodsReferenced = new HashSet<>(methodsReferenced);
}
}
/**
* Encapsulates how we should report findings. We support reporting a finding on either every
* affected (can be static) method, or just the first one in the file.
*/
private enum FindingOutputStyle {
ONE_FINDING {
@Override
public Description report(
Set<MethodTree> affectedTrees, SuggestedFix fix, VisitorState state, BugChecker checker) {
return affectedTrees.stream()
.min(Comparator.comparingInt(t -> getStartPosition(t)))
.map(t -> checker.describeMatch(t.getModifiers(), fix))
.orElse(NO_MATCH);
}
},
FINDING_PER_SITE {
@Override
public Description report(
Set<MethodTree> affectedTrees, SuggestedFix fix, VisitorState state, BugChecker checker) {
for (MethodTree tree : affectedTrees) {
state.reportMatch(checker.describeMatch(tree.getModifiers(), fix));
}
return NO_MATCH;
}
};
public abstract Description report(
Set<MethodTree> affectedTrees, SuggestedFix fix, VisitorState state, BugChecker checker);
}
}
| 11,483
| 36.776316
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DoubleBraceInitialization.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.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.expressionStatement;
import static com.google.errorprone.matchers.method.MethodMatchers.constructor;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.predicates.TypePredicates.isDescendantOf;
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.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.matchers.Matchers;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ClassTree;
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.NewClassTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Prefer collection factory methods or builders to the double-brace initialization"
+ " pattern.",
severity = ERROR)
public class DoubleBraceInitialization extends BugChecker implements NewClassTreeMatcher {
@SuppressWarnings("ImmutableEnumChecker") // Matcher is immutable in practice
enum CollectionTypes {
MAP("Map", "put", "ImmutableMap"),
SET("Set", "add", "ImmutableSet"),
LIST("List", "add", "ImmutableList"),
COLLECTION("Collection", "add", "ImmutableList");
final Matcher<ExpressionTree> constructorMatcher;
final Matcher<StatementTree> mutateMatcher;
final Matcher<Tree> unmodifiableMatcher;
final String factoryMethod;
final String factoryImport;
final String immutableType;
final String immutableImport;
CollectionTypes(String type, String mutator, String factory) {
this.immutableType = "Immutable" + type;
this.immutableImport = "com.google.common.collect.Immutable" + type;
this.factoryMethod = factory + ".of";
this.factoryImport = "com.google.common.collect." + factory;
this.constructorMatcher = constructor().forClass(isDescendantOf("java.util." + type));
this.mutateMatcher =
expressionStatement(instanceMethod().onDescendantOf("java.util." + type).named(mutator));
this.unmodifiableMatcher =
Matchers.toType(
ExpressionTree.class,
MethodMatchers.staticMethod()
.onClass("java.util.Collections")
.named("unmodifiable" + type));
}
Optional<Fix> maybeFix(NewClassTree tree, VisitorState state, BlockTree block) {
// scan the body for mutator methods (add, put) and record their arguments for rewriting as
// a static factory method
List<List<? extends ExpressionTree>> arguments = new ArrayList<>();
for (StatementTree statement : block.getStatements()) {
if (!mutateMatcher.matches(statement, state)) {
return Optional.empty();
}
arguments.add(
((MethodInvocationTree) ((ExpressionStatementTree) statement).getExpression())
.getArguments());
}
if (arguments.stream()
.flatMap(Collection::stream)
.anyMatch(a -> a.getKind() == Kind.NULL_LITERAL)) {
return Optional.empty();
}
ImmutableList<String> args =
arguments.stream()
.map(
arg ->
arg.stream()
.map(ASTHelpers::stripParentheses)
.map(state::getSourceForNode)
.collect(joining(", ", "\n", "")))
.collect(toImmutableList());
// check the enclosing context: calls to Collections.unmodifiable* are now redundant, and
// if there's an enclosing constant variable declaration we can rewrite its type to Immutable*
Tree unmodifiable = null;
boolean constant = false;
Tree typeTree = null;
Tree toReplace = null;
for (TreePath path = state.getPath().getParentPath();
path != null;
path = path.getParentPath()) {
Tree enclosing = path.getLeaf();
if (unmodifiableMatcher.matches(enclosing, state)) {
unmodifiable = enclosing;
continue;
}
if (enclosing instanceof ParenthesizedTree) {
continue;
}
if (enclosing instanceof VariableTree) {
VariableTree enclosingVariable = (VariableTree) enclosing;
toReplace = enclosingVariable.getInitializer();
typeTree = enclosingVariable.getType();
VarSymbol symbol = ASTHelpers.getSymbol(enclosingVariable);
constant =
symbol.isStatic()
&& symbol.getModifiers().contains(Modifier.FINAL)
&& symbol.getKind() == ElementKind.FIELD;
}
if (enclosing instanceof ReturnTree) {
toReplace = ((ReturnTree) enclosing).getExpression();
MethodTree enclosingMethod = ASTHelpers.findEnclosingNode(path, MethodTree.class);
typeTree = enclosingMethod == null ? null : enclosingMethod.getReturnType();
}
break;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
String replacement;
if (immutableType.equals("ImmutableMap") && args.size() > 5) {
String typeArguments =
tree.getIdentifier() instanceof ParameterizedTypeTree
? ((ParameterizedTypeTree) tree.getIdentifier())
.getTypeArguments().stream()
.map(state::getSourceForNode)
.collect(joining(", ", "<", ">"))
: "";
replacement =
"ImmutableMap."
+ typeArguments
+ "builder()"
+ args.stream().map(a -> ".put(" + a + ")").collect(joining(""))
+ ".buildOrThrow()";
} else {
replacement = args.stream().collect(joining(", ", factoryMethod + "(", ")"));
}
fix.addImport(factoryImport);
fix.addImport(immutableImport);
if (unmodifiable != null || constant) {
// there's an enclosing unmodifiable* call, or we're in the initializer of a constant,
// so rewrite the variable's type to be immutable and drop the unmodifiable* method
if (typeTree instanceof ParameterizedTypeTree) {
typeTree = ((ParameterizedTypeTree) typeTree).getType();
}
if (typeTree != null) {
fix.replace(typeTree, immutableType);
}
fix.replace(unmodifiable == null ? toReplace : unmodifiable, replacement);
} else {
// the result may need to be mutable, so rewrite e.g.
// `new ArrayList<>() {{ add(1); }}` -> `new ArrayList<>(ImmutableList.of(1));`
fix.replace(
state.getEndPosition(tree.getIdentifier()),
state.getEndPosition(tree),
"(" + replacement + ")");
}
return Optional.of(fix.build());
}
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
ClassTree body = tree.getClassBody();
if (body == null) {
return NO_MATCH;
}
ImmutableList<? extends Tree> members =
body.getMembers().stream()
.filter(
m ->
!(m instanceof MethodTree && ASTHelpers.isGeneratedConstructor((MethodTree) m)))
.collect(toImmutableList());
if (members.size() != 1) {
return NO_MATCH;
}
Tree member = Iterables.getOnlyElement(members);
if (!(member instanceof BlockTree)) {
return NO_MATCH;
}
BlockTree block = (BlockTree) member;
Optional<CollectionTypes> collectionType =
Arrays.stream(CollectionTypes.values())
.filter(type -> type.constructorMatcher.matches(tree, state))
.findFirst();
if (!collectionType.isPresent()) {
return NO_MATCH;
}
Description.Builder description = buildDescription(tree);
collectionType.get().maybeFix(tree, state, block).ifPresent(description::addFix);
return description.build();
}
}
| 9,995
| 40.305785
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AbstractMethodReturnsNull.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.sun.source.tree.Tree.Kind.NULL_LITERAL;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.util.TreePath;
import java.util.Optional;
/** Superclass for checks that method implementations that directly {@code return null}. */
abstract class AbstractMethodReturnsNull extends BugChecker implements ReturnTreeMatcher {
private final Matcher<MethodTree> methodTreeMatcher;
AbstractMethodReturnsNull(Matcher<MethodTree> methodTreeMatcher) {
this.methodTreeMatcher = methodTreeMatcher;
}
protected abstract Optional<Fix> provideFix(ReturnTree tree);
@Override
public final Description matchReturn(ReturnTree tree, VisitorState state) {
if (tree.getExpression() == null || tree.getExpression().getKind() != NULL_LITERAL) {
return NO_MATCH;
}
TreePath path = state.getPath();
while (path != null && path.getLeaf() instanceof StatementTree) {
path = path.getParentPath();
}
if (path == null || !(path.getLeaf() instanceof MethodTree)) {
return NO_MATCH;
}
if (!methodTreeMatcher.matches((MethodTree) path.getLeaf(), state)) {
return NO_MATCH;
}
return provideFix(tree)
.map(fix -> describeMatch(tree, fix))
.orElseGet(() -> describeMatch(tree));
}
}
| 2,325
| 35.920635
| 91
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MisusedDateFormat.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.constructor;
import static com.google.errorprone.matchers.Matchers.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.getSymbol;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
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.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 java.util.Optional;
import javax.lang.model.element.ElementKind;
/** Base class for checks which find common errors in date format patterns. */
public abstract class MisusedDateFormat extends BugChecker
implements MethodInvocationTreeMatcher, NewClassTreeMatcher {
private static final String JAVA_SIMPLE_DATE_FORMAT = "java.text.SimpleDateFormat";
private static final String ICU_SIMPLE_DATE_FORMAT = "com.ibm.icu.text.SimpleDateFormat";
private static final Matcher<NewClassTree> PATTERN_CTOR_MATCHER =
anyOf(
constructor().forClass(JAVA_SIMPLE_DATE_FORMAT).withParameters("java.lang.String"),
constructor()
.forClass(JAVA_SIMPLE_DATE_FORMAT)
.withParameters("java.lang.String", "java.text.DateFormatSymbols"),
constructor()
.forClass(JAVA_SIMPLE_DATE_FORMAT)
.withParameters("java.lang.String", "java.util.Locale"),
constructor().forClass(ICU_SIMPLE_DATE_FORMAT).withParameters("java.lang.String"),
constructor()
.forClass(ICU_SIMPLE_DATE_FORMAT)
.withParameters("java.lang.String", "com.ibm.icu.text.DateFormatSymbols"),
constructor()
.forClass(ICU_SIMPLE_DATE_FORMAT)
.withParameters(
"java.lang.String",
"com.ibm.icu.text.DateFormatSymbols",
"com.ibm.icu.util.ULocale"),
constructor()
.forClass(ICU_SIMPLE_DATE_FORMAT)
.withParameters("java.lang.String", "java.util.Locale"),
constructor()
.forClass(ICU_SIMPLE_DATE_FORMAT)
.withParameters("java.lang.String", "java.lang.String", "com.ibm.icu.util.ULocale"),
constructor()
.forClass(ICU_SIMPLE_DATE_FORMAT)
.withParameters("java.lang.String", "com.ibm.icu.util.ULocale"));
/** Matches methods that take a pattern as the first argument. */
private static final Matcher<ExpressionTree> PATTERN_MATCHER =
anyOf(
instanceMethod().onExactClass(JAVA_SIMPLE_DATE_FORMAT).named("applyPattern"),
instanceMethod().onExactClass(JAVA_SIMPLE_DATE_FORMAT).named("applyLocalizedPattern"),
instanceMethod().onExactClass(ICU_SIMPLE_DATE_FORMAT).named("applyPattern"),
instanceMethod().onExactClass(ICU_SIMPLE_DATE_FORMAT).named("applyLocalizedPattern"),
staticMethod().onClass("java.time.format.DateTimeFormatter").named("ofPattern"));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!PATTERN_MATCHER.matches(tree, state)) {
return NO_MATCH;
}
String argument = constValue(tree.getArguments().get(0), String.class);
if (argument == null) {
return NO_MATCH;
}
return constructDescription(tree, tree.getArguments().get(0), state);
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (!PATTERN_CTOR_MATCHER.matches(tree, state)) {
return NO_MATCH;
}
return constructDescription(tree, tree.getArguments().get(0), state);
}
/**
* Override this method to provide a rewritten date format pattern from {@code pattern}. An empty
* optional indicates that {@code pattern} does not need rewriting.
*/
abstract Optional<String> rewriteTo(String pattern);
private Description constructDescription(
Tree tree, ExpressionTree patternArg, VisitorState state) {
return Optional.ofNullable(constValue(patternArg, String.class))
.flatMap(this::rewriteTo)
.map(replacement -> describeMatch(tree, replaceArgument(patternArg, replacement, state)))
.orElse(NO_MATCH);
}
private static SuggestedFix replaceArgument(
ExpressionTree patternArg, String replacement, VisitorState state) {
String quotedReplacement = String.format("\"%s\"", replacement);
if (patternArg.getKind() == Kind.STRING_LITERAL) {
return SuggestedFix.replace(patternArg, quotedReplacement);
}
Symbol sym = getSymbol(patternArg);
if (!(sym instanceof VarSymbol) || sym.getKind() != ElementKind.FIELD) {
return SuggestedFix.emptyFix();
}
SuggestedFix.Builder fix = SuggestedFix.builder();
new TreeScanner<Void, Void>() {
@Override
public Void visitVariable(VariableTree node, Void unused) {
if (sym.equals(getSymbol(node))
&& node.getInitializer() != null
&& node.getInitializer().getKind() == Kind.STRING_LITERAL) {
fix.replace(node.getInitializer(), quotedReplacement);
return null;
}
return super.visitVariable(node, null);
}
}.scan(state.getPath().getCompilationUnit(), null);
return fix.build();
}
static String replaceFormatChar(String format, char from, char to) {
StringBuilder builder = new StringBuilder();
parseDateFormat(
format,
new DateFormatConsumer() {
@Override
public void consumeLiteral(char literal) {
builder.append(literal);
}
@Override
public void consumeSpecial(char special) {
builder.append(special == from ? to : special);
}
});
return builder.toString();
}
static void parseDateFormat(String format, DateFormatConsumer consumer) {
for (int pos = 0; pos < format.length(); ++pos) {
char c = format.charAt(pos);
if (c == '\'') {
consumer.consumeSpecial('\'');
pos++;
for (; pos < format.length(); ++pos) {
consumer.consumeLiteral(format.charAt(pos));
if (format.charAt(pos) == '\'') {
if (pos + 1 < format.length() && format.charAt(pos + 1) == '\'') {
consumer.consumeSpecial('\'');
pos++; // Increment another to skip the escaped '
} else {
break;
}
}
}
} else {
consumer.consumeSpecial(c);
}
}
}
interface DateFormatConsumer {
/** Consumes a literal (escaped) character. */
void consumeLiteral(char literal);
/** Consumes a special (format) character. */
void consumeSpecial(char special);
}
}
| 8,075
| 39.38
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/OptionalOfRedundantMethod.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.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.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.util.Name;
/**
* Checks if {@code Optional#of} is chained with a redundant method.
*
* <p>{@code Optional#of} will always return a non-empty optional. Using any of the following
* methods:
*
* <ul>
* <li>{@code isPresent}
* <li>{@code ifPresent}
* <li>{@code orElse}
* <li>{@code orElseGet}
* <li>{@code orElseThrow}
* <li>{@code or} (only for Guava optionals)
* <li>{@code orNull} (only for Guava optionals)
* </ul>
*
* on it is unnecessary and a potential source of bugs.
*/
@BugPattern(
summary =
"Optional.of() always returns a non-empty optional. Using"
+ " ifPresent/isPresent/orElse/orElseGet/orElseThrow/isPresent/or/orNull method on it"
+ " is unnecessary and most probably a bug.",
severity = ERROR)
public class OptionalOfRedundantMethod extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> GUAVA_OPTIONAL_OF_MATCHER =
staticMethod().onClass("com.google.common.base.Optional").named("of");
private static final Matcher<ExpressionTree> OPTIONAL_OF_MATCHER =
anyOf(staticMethod().onClass("java.util.Optional").named("of"), GUAVA_OPTIONAL_OF_MATCHER);
private static final Matcher<ExpressionTree> REDUNDANT_METHOD_MATCHER =
anyOf(
instanceMethod()
.onExactClass("java.util.Optional")
.namedAnyOf("ifPresent", "isPresent", "orElse", "orElseGet", "orElseThrow"),
instanceMethod()
.onExactClass("com.google.common.base.Optional")
.namedAnyOf("isPresent", "or", "orNull"));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
ExpressionTree childMethodInvocationTree = ASTHelpers.getReceiver(tree);
if (!(childMethodInvocationTree instanceof MethodInvocationTree)) {
return NO_MATCH;
}
if (!OPTIONAL_OF_MATCHER.matches(childMethodInvocationTree, state)
|| !REDUNDANT_METHOD_MATCHER.matches(tree, state)) {
return NO_MATCH;
}
String methodName = ASTHelpers.getSymbol(tree).getSimpleName().toString();
return buildDescription(tree)
.setMessage(
String.format(
"Optional.of() always returns a non-empty Optional. Using '%s' method on it is"
+ " unnecessary and most probably a bug.",
methodName))
.addAllFixes(getSuggestedFixes(tree, state))
.build();
}
private ImmutableList<SuggestedFix> getSuggestedFixes(
MethodInvocationTree tree, VisitorState state) {
MethodInvocationTree optionalOfInvocationTree =
(MethodInvocationTree) ASTHelpers.getReceiver(tree);
String nullableMethodName =
GUAVA_OPTIONAL_OF_MATCHER.matches(optionalOfInvocationTree, state)
? "fromNullable"
: "ofNullable";
ImmutableList.Builder<SuggestedFix> fixesBuilder = ImmutableList.builder();
fixesBuilder.add(
SuggestedFixes.renameMethodInvocation(optionalOfInvocationTree, nullableMethodName, state));
if (state.getPath().getParentPath().getLeaf() instanceof ExpressionStatementTree) {
return fixesBuilder.build();
}
Name methodSimpleName = ASTHelpers.getSymbol(tree).getSimpleName();
if (methodSimpleName.contentEquals("orElse")
|| methodSimpleName.contentEquals("orElseGet")
|| methodSimpleName.contentEquals("orElseThrow")
|| methodSimpleName.contentEquals("or")
|| methodSimpleName.contentEquals("orNull")) {
Tree argument = optionalOfInvocationTree.getArguments().get(0);
SuggestedFix.Builder fixBuilder =
SuggestedFix.builder().replace(tree, state.getSourceForNode(argument));
fixBuilder.setShortDescription("Simplify expression.");
if (methodSimpleName.contentEquals("orElse")) {
fixBuilder.setShortDescription(
"Simplify expression. Note that this may change semantics if arguments have side"
+ " effects");
}
fixesBuilder.add(fixBuilder.build());
} else if (methodSimpleName.contentEquals("isPresent")) {
fixesBuilder.add(SuggestedFix.builder().replace(tree, "true").build());
}
// TODO(b/192550897): Add suggested fix for ifpresent
return fixesBuilder.build();
}
}
| 5,952
| 40.629371
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnusedLabel.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.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.BreakTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ContinueTree;
import com.sun.source.tree.LabeledStatementTree;
import com.sun.source.util.TreeScanner;
import java.util.HashMap;
import java.util.Map;
import javax.lang.model.element.Name;
/** A BugPattern; see the summary. */
@BugPattern(summary = "This label is unused.", severity = SeverityLevel.WARNING)
public final class UnusedLabel extends BugChecker implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
Map<Name, LabeledStatementTree> labels = new HashMap<>();
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitLabeledStatement(LabeledStatementTree tree, Void unused) {
labels.put(tree.getLabel(), tree);
return super.visitLabeledStatement(tree, null);
}
}.scan(state.getPath(), null);
new TreeScanner<Void, Void>() {
@Override
public Void visitBreak(BreakTree tree, Void unused) {
labels.remove(tree.getLabel());
return super.visitBreak(tree, null);
}
@Override
public Void visitContinue(ContinueTree tree, Void unused) {
labels.remove(tree.getLabel());
return super.visitContinue(tree, null);
}
}.scan(tree, null);
for (LabeledStatementTree label : labels.values()) {
state.reportMatch(
describeMatch(
label,
SuggestedFix.replace(
getStartPosition(label), getStartPosition(label.getStatement()), "")));
}
return NO_MATCH;
}
}
| 2,780
| 36.08
| 89
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryBoxedVariable.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.Preconditions.checkArgument;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.findEnclosingMethod;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.ASTHelpers.TargetType;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTag;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.lang.model.element.ElementKind;
/**
* Finds and fixes unnecessarily boxed variables.
*
* @author awturner@google.com (Andy Turner)
*/
@BugPattern(
summary = "It is unnecessary for this variable to be boxed. Use the primitive instead.",
explanation =
"This variable is of boxed type, but equivalent semantics can be achieved using the"
+ " corresponding primitive type, which avoids the cost of constructing an unnecessary"
+ " object.",
severity = SeverityLevel.SUGGESTION)
public class UnnecessaryBoxedVariable extends BugChecker implements CompilationUnitTreeMatcher {
private static final Matcher<ExpressionTree> VALUE_OF_MATCHER =
staticMethod().onClass(UnnecessaryBoxedVariable::isBoxableType).named("valueOf");
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
FindBoxedUsagesScanner usages = new FindBoxedUsagesScanner(state);
usages.scan(tree, null);
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitVariable(VariableTree tree, Void unused) {
VisitorState innerState = state.withPath(getCurrentPath());
unboxed(tree, innerState)
.flatMap(u -> handleVariable(u, usages, tree, innerState))
.ifPresent(state::reportMatch);
return super.visitVariable(tree, null);
}
}.scan(tree, null);
return NO_MATCH;
}
private Optional<Description> handleVariable(
Type unboxed, FindBoxedUsagesScanner usages, VariableTree tree, VisitorState state) {
VarSymbol varSymbol = getSymbol(tree);
switch (varSymbol.getKind()) {
case PARAMETER:
if (!canChangeMethodSignature(state, (MethodSymbol) varSymbol.getEnclosingElement())
|| state.getPath().getParentPath().getLeaf() instanceof LambdaExpressionTree) {
return Optional.empty();
}
// Fall through.
case LOCAL_VARIABLE:
if (!variableMatches(tree, state)) {
return Optional.empty();
}
break;
default:
return Optional.empty();
}
return fixVariable(unboxed, usages, tree, state);
}
private Optional<Description> fixVariable(
Type unboxed, FindBoxedUsagesScanner usages, VariableTree tree, VisitorState state) {
VarSymbol varSymbol = getSymbol(tree);
if (usages.boxedUsageFound.contains(varSymbol)) {
return Optional.empty();
}
if (!usages.dereferenced.contains(varSymbol) && varSymbol.getKind() == ElementKind.PARAMETER) {
// If it isn't used and it is a parameter, don't fix it, because this could introduce a new
// NPE.
return Optional.empty();
}
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
fixBuilder.replace(tree.getType(), unboxed.tsym.getSimpleName().toString());
fixMethodInvocations(usages.fixableSimpleMethodInvocations.get(varSymbol), fixBuilder, state);
fixNullCheckInvocations(usages.fixableNullCheckInvocations.get(varSymbol), fixBuilder, state);
fixCastingInvocations(usages.fixableCastMethodInvocations.get(varSymbol), fixBuilder, state);
// Remove @Nullable annotation, if present.
AnnotationTree nullableAnnotation =
ASTHelpers.getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "Nullable");
if (nullableAnnotation == null) {
return Optional.of(describeMatch(tree, fixBuilder.build()));
}
fixBuilder.replace(nullableAnnotation, "");
return Optional.of(
buildDescription(tree)
.setMessage(
"All usages of this @Nullable variable would result in a NullPointerException when"
+ " it actually is null. Use the primitive type if this variable should never"
+ " be null, or else fix the code to avoid unboxing or invoking its instance"
+ " methods.")
.addFix(fixBuilder.build())
.build());
}
private static Optional<Type> unboxed(Tree tree, VisitorState state) {
Type type = ASTHelpers.getType(tree);
if (type == null || !type.isReference()) {
return Optional.empty();
}
Type unboxed = state.getTypes().unboxedType(type);
if (unboxed == null
|| unboxed.getTag() == TypeTag.NONE
// Don't match java.lang.Void.
|| unboxed.getTag() == TypeTag.VOID) {
return Optional.empty();
}
return Optional.of(unboxed);
}
private static void fixNullCheckInvocations(
List<TreePath> nullCheckInvocations, SuggestedFix.Builder fixBuilder, VisitorState state) {
for (TreePath pathForTree : nullCheckInvocations) {
checkArgument(pathForTree.getLeaf() instanceof MethodInvocationTree);
MethodInvocationTree methodInvocation = (MethodInvocationTree) pathForTree.getLeaf();
TargetType targetType = ASTHelpers.targetType(state.withPath(pathForTree));
if (targetType == null) {
// If the check is the only thing in a statement, remove the statement.
StatementTree statementTree =
ASTHelpers.findEnclosingNode(pathForTree, StatementTree.class);
if (statementTree != null) {
fixBuilder.delete(statementTree);
}
} else {
// If it's an expression, we can replace simply with the first argument.
fixBuilder.replace(
methodInvocation, state.getSourceForNode(methodInvocation.getArguments().get(0)));
}
}
}
private static void fixMethodInvocations(
List<MethodInvocationTree> simpleMethodInvocations,
SuggestedFix.Builder fixBuilder,
VisitorState state) {
for (MethodInvocationTree methodInvocation : simpleMethodInvocations) {
ExpressionTree receiver = ASTHelpers.getReceiver(methodInvocation);
Type receiverType = ASTHelpers.getType(receiver);
MemberSelectTree methodSelect = (MemberSelectTree) methodInvocation.getMethodSelect();
fixBuilder.replace(
methodInvocation,
String.format(
"%s.%s(%s)",
receiverType.tsym.getSimpleName(),
methodSelect.getIdentifier(),
state.getSourceForNode(receiver)));
}
}
private static void fixCastingInvocations(
List<TreePath> castMethodInvocations, SuggestedFix.Builder fixBuilder, VisitorState state) {
for (TreePath castPath : castMethodInvocations) {
MethodInvocationTree castInvocation = (MethodInvocationTree) castPath.getLeaf();
ExpressionTree receiver = ASTHelpers.getReceiver(castInvocation);
Type expressionType = ASTHelpers.getType(castInvocation);
if (castPath.getParentPath() != null
&& castPath.getParentPath().getLeaf().getKind() == Kind.EXPRESSION_STATEMENT) {
// If we were to replace X.intValue(); with (int) x;, the code wouldn't compile because
// that's not a statement. Instead, just delete.
fixBuilder.delete(castPath.getParentPath().getLeaf());
} else {
Type unboxedReceiverType = state.getTypes().unboxedType(ASTHelpers.getType(receiver));
if (unboxedReceiverType.getTag() == expressionType.getTag()) {
// someInteger.intValue() can just become someInt.
fixBuilder.replace(castInvocation, state.getSourceForNode(receiver));
} else {
// someInteger.otherPrimitiveValue() can become (otherPrimitive) someInt.
fixBuilder.replace(
castInvocation,
String.format(
"(%s) %s",
expressionType.tsym.getSimpleName(), state.getSourceForNode(receiver)));
}
}
}
}
/**
* Check to see if the variable should be considered for replacement, i.e.
*
* <ul>
* <li>A variable without an initializer
* <li>Enhanced for loop variables can be replaced if they are loops over primitive arrays
* <li>A variable initialized with a primitive value (which is then auto-boxed)
* <li>A variable initialized with an invocation of {@code Boxed.valueOf}, since that can be
* replaced with {@code Boxed.parseBoxed}.
* </ul>
*/
private static boolean variableMatches(VariableTree tree, VisitorState state) {
ExpressionTree expression = tree.getInitializer();
if (expression == null) {
Tree leaf = state.getPath().getParentPath().getLeaf();
if (!(leaf instanceof EnhancedForLoopTree)) {
return true;
}
EnhancedForLoopTree node = (EnhancedForLoopTree) leaf;
Type expressionType = ASTHelpers.getType(node.getExpression());
if (expressionType == null) {
return false;
}
Type elemtype = state.getTypes().elemtype(expressionType);
// Be conservative - if elemtype is null, treat it as if it is a loop over a wrapped type.
return elemtype != null && elemtype.isPrimitive();
}
Type initializerType = ASTHelpers.getType(expression);
if (initializerType == null) {
return false;
}
if (initializerType.isPrimitive()) {
return true;
}
// Don't count X.valueOf(...) as a boxed usage, since it can be replaced with X.parseX.
return VALUE_OF_MATCHER.matches(expression, state);
}
private static boolean isBoxableType(Type type, VisitorState state) {
Type unboxedType = state.getTypes().unboxedType(type);
return unboxedType != null && unboxedType.getTag() != TypeTag.NONE;
}
private static boolean canChangeMethodSignature(VisitorState state, MethodSymbol methodSymbol) {
return !ASTHelpers.methodCanBeOverridden(methodSymbol)
&& ASTHelpers.findSuperMethods(methodSymbol, state.getTypes()).isEmpty();
}
private static class FindBoxedUsagesScanner extends TreePathScanner<Void, Void> {
// Method invocations like V.hashCode() can be replaced with TypeOfV.hashCode(v).
private static final Matcher<ExpressionTree> SIMPLE_METHOD_MATCH =
instanceMethod().anyClass().namedAnyOf("hashCode", "toString");
// Method invocations like V.intValue() can be replaced with (int) v.
private static final Matcher<ExpressionTree> CAST_METHOD_MATCH =
instanceMethod()
.onClass(UnnecessaryBoxedVariable::isBoxableType)
.namedAnyOf(
"byteValue",
"shortValue",
"intValue",
"longValue",
"floatValue",
"doubleValue",
"booleanValue");
// Method invocations that check (and throw) if the value is potentially null.
private static final Matcher<ExpressionTree> NULL_CHECK_MATCH =
anyOf(
staticMethod().onClass("com.google.common.base.Preconditions").named("checkNotNull"),
staticMethod().onClass("com.google.common.base.Verify").named("verifyNonNull"),
staticMethod().onClass("java.util.Objects").named("requireNonNull"));
private final VisitorState state;
private final ListMultimap<VarSymbol, MethodInvocationTree> fixableSimpleMethodInvocations =
ArrayListMultimap.create();
private final ListMultimap<VarSymbol, TreePath> fixableNullCheckInvocations =
ArrayListMultimap.create();
private final ListMultimap<VarSymbol, TreePath> fixableCastMethodInvocations =
ArrayListMultimap.create();
private final Set<VarSymbol> boxedUsageFound = new HashSet<>();
private final Set<VarSymbol> dereferenced = new HashSet<>();
FindBoxedUsagesScanner(VisitorState state) {
this.state = state;
}
@Override
public Void scan(Tree tree, Void unused) {
var symbol = getSymbol(tree);
if (boxedUsageFound.contains(symbol)) {
return null;
}
return super.scan(tree, unused);
}
@Override
public Void visitAssignment(AssignmentTree node, Void unused) {
Symbol nodeSymbol = getSymbol(node.getVariable());
if (!isBoxed(nodeSymbol, state)) {
return super.visitAssignment(node, unused);
}
// The variable of interest is being assigned. Check if the expression is non-primitive,
// and go on to scan the expression.
if (!checkAssignmentExpression(node.getExpression())) {
return scan(node.getExpression(), unused);
}
boxedUsageFound.add((VarSymbol) nodeSymbol);
return null;
}
private boolean checkAssignmentExpression(ExpressionTree expression) {
Type expressionType = ASTHelpers.getType(expression);
if (expressionType.isPrimitive()) {
return false;
}
// If the value is assigned a non-primitive value, we need to keep it non-primitive.
// Unless it's an invocation of Boxed.valueOf or new Boxed, in which case it doesn't need to
// be kept boxed since we know the result of valueOf is non-null.
return !VALUE_OF_MATCHER.matches(expression, state.withPath(getCurrentPath()))
&& expression.getKind() != Kind.NEW_CLASS;
}
@Override
public Void visitIdentifier(IdentifierTree node, Void unused) {
Symbol nodeSymbol = getSymbol(node);
if (isBoxed(nodeSymbol, state)) {
dereferenced.add((VarSymbol) nodeSymbol);
VisitorState identifierState = state.withPath(getCurrentPath());
TargetType targetType = ASTHelpers.targetType(identifierState);
if (targetType != null && !targetType.type().isPrimitive()) {
boxedUsageFound.add((VarSymbol) nodeSymbol);
return null;
}
}
return super.visitIdentifier(node, unused);
}
@Override
public Void visitCompoundAssignment(CompoundAssignmentTree node, Void unused) {
// Don't count the LHS of compound assignments as boxed usages, because they have to be
// unboxed. Just visit the expression.
return scan(node.getExpression(), unused);
}
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void unused) {
if (NULL_CHECK_MATCH.matches(node, state)) {
Symbol firstArgSymbol = getSymbol(ASTHelpers.stripParentheses(node.getArguments().get(0)));
if (isBoxed(firstArgSymbol, state)) {
dereferenced.add((VarSymbol) firstArgSymbol);
fixableNullCheckInvocations.put((VarSymbol) firstArgSymbol, getCurrentPath());
return null;
}
}
Tree receiver = ASTHelpers.getReceiver(node);
Symbol receiverSymbol = getSymbol(receiver);
if (receiver != null && isBoxed(receiverSymbol, state)) {
if (SIMPLE_METHOD_MATCH.matches(node, state)) {
fixableSimpleMethodInvocations.put((VarSymbol) receiverSymbol, node);
return null;
}
if (CAST_METHOD_MATCH.matches(node, state)) {
fixableCastMethodInvocations.put((VarSymbol) receiverSymbol, getCurrentPath());
return null;
}
boxedUsageFound.add((VarSymbol) receiverSymbol);
return null;
}
return super.visitMethodInvocation(node, unused);
}
@Override
public Void visitReturn(ReturnTree node, Void unused) {
Symbol nodeSymbol = getSymbol(ASTHelpers.stripParentheses(node.getExpression()));
if (!isBoxed(nodeSymbol, state)) {
return super.visitReturn(node, unused);
}
dereferenced.add((VarSymbol) nodeSymbol);
// Don't count a return value as a boxed usage, except if we are returning a parameter, and
// the method's return type is boxed.
if (nodeSymbol.getKind() == ElementKind.PARAMETER) {
MethodTree enclosingMethod = findEnclosingMethod(state.withPath(getCurrentPath()));
if (enclosingMethod != null) {
Type returnType = ASTHelpers.getType(enclosingMethod.getReturnType());
if (!returnType.isPrimitive()) {
boxedUsageFound.add((VarSymbol) nodeSymbol);
}
}
}
return null;
}
@Override
public Void visitMemberReference(MemberReferenceTree node, Void unused) {
ExpressionTree qualifierExpression = node.getQualifierExpression();
if (qualifierExpression.getKind() == Kind.IDENTIFIER) {
Symbol symbol = getSymbol(qualifierExpression);
if (isBoxed(symbol, state)) {
boxedUsageFound.add((VarSymbol) symbol);
dereferenced.add((VarSymbol) symbol);
return null;
}
}
return super.visitMemberReference(node, unused);
}
}
private static boolean isBoxed(Symbol symbol, VisitorState state) {
return symbol instanceof VarSymbol
&& !state.getTypes().isSameType(state.getTypes().unboxedType(symbol.type), Type.noType);
}
}
| 19,388
| 40.786638
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NullTernary.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 com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ConditionalExpressionTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.Tree.Kind;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"This conditional expression may evaluate to null, which will result in an NPE when the"
+ " result is unboxed.",
severity = ERROR)
public class NullTernary extends BugChecker implements ConditionalExpressionTreeMatcher {
@Override
public Description matchConditionalExpression(
ConditionalExpressionTree conditionalExpression, VisitorState state) {
if (conditionalExpression.getFalseExpression().getKind() != Kind.NULL_LITERAL
&& conditionalExpression.getTrueExpression().getKind() != Kind.NULL_LITERAL) {
return NO_MATCH;
}
ASTHelpers.TargetType targetType = ASTHelpers.targetType(state);
if (targetType == null || !targetType.type().isPrimitive()) {
return NO_MATCH;
}
return describeMatch(conditionalExpression);
}
}
| 2,069
| 38.807692
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SameNameButDifferent.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.util.ASTHelpers.findPathFromEnclosingNodeToTopLevel;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.FindIdentifiers.findIdent;
import static java.util.stream.Collectors.joining;
import com.google.common.base.Joiner;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.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.tools.javac.code.Kinds.KindSelector;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.util.Position;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Name;
import org.checkerframework.checker.nullness.qual.Nullable;
/** Looks for types being shadowed by other types in a way that may be confusing. */
@BugPattern(
summary = "This type name shadows another in a way that may be confusing.",
severity = WARNING)
public final class SameNameButDifferent extends BugChecker implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
Table<String, TypeSymbol, List<TreePath>> table = HashBasedTable.create();
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void unused) {
if (!shouldIgnore()) {
handle(memberSelectTree);
}
return super.visitMemberSelect(memberSelectTree, null);
}
@Override
public Void visitIdentifier(IdentifierTree identifierTree, Void unused) {
if (shouldIgnore()) {
return null;
}
if (!(getSymbol(identifierTree) instanceof ClassSymbol)) {
return null;
}
TreePath enclosingClass =
findPathFromEnclosingNodeToTopLevel(getCurrentPath(), ClassTree.class);
if (enclosingClass != null
&& getSymbol(enclosingClass.getLeaf()) == getSymbol(identifierTree)) {
return null;
}
handle(identifierTree);
return null;
}
private boolean shouldIgnore() {
// Don't report duplicate hits if we're not at the tail of a series of member selects on
// classes.
Tree parentTree = getCurrentPath().getParentPath().getLeaf();
return parentTree instanceof MemberSelectTree
&& getSymbol(parentTree) instanceof ClassSymbol;
}
private @Nullable String qualifiedName(Tree tree) {
if (state.getEndPosition(tree) == Position.NOPOS) {
return null;
}
ArrayDeque<Name> parts = new ArrayDeque<>();
while (tree instanceof MemberSelectTree) {
MemberSelectTree select = (MemberSelectTree) tree;
parts.addFirst(select.getIdentifier());
tree = select.getExpression();
}
if (!(tree instanceof IdentifierTree)) {
return null;
}
parts.addFirst(((IdentifierTree) tree).getName());
return Joiner.on('.').join(parts);
}
private void handle(Tree tree) {
if (tree instanceof IdentifierTree
&& ((IdentifierTree) tree).getName().contentEquals("Builder")) {
return;
}
String qualifiedName = qualifiedName(tree);
if (qualifiedName == null) {
return;
}
Symbol symbol = getSymbol(tree);
if (symbol instanceof ClassSymbol) {
List<TreePath> treePaths = table.get(qualifiedName, symbol.type.tsym);
if (treePaths == null) {
treePaths = new ArrayList<>();
table.put(qualifiedName, symbol.type.tsym, treePaths);
}
treePaths.add(getCurrentPath());
}
}
}.scan(state.getPath(), null);
// Keep any (simpleName, typeSymbol) entries which shadow a class name outside the enclosing
// class.
Table<String, TypeSymbol, List<TreePath>> trimmedTable = HashBasedTable.create();
for (Map.Entry<String, Map<TypeSymbol, List<TreePath>>> row : table.rowMap().entrySet()) {
Map<TypeSymbol, List<TreePath>> columns = row.getValue();
if (columns.size() <= 1) {
continue;
}
for (Map.Entry<TypeSymbol, List<TreePath>> cell : columns.entrySet()) {
if (cell.getValue().stream().anyMatch(treePath -> shadowsClass(state, treePath))) {
trimmedTable.put(row.getKey(), cell.getKey(), cell.getValue());
}
}
}
for (Map.Entry<String, Map<TypeSymbol, List<TreePath>>> row :
trimmedTable.rowMap().entrySet()) {
String simpleName = row.getKey();
Map<TypeSymbol, List<TreePath>> columns = row.getValue();
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
if (columns.size() > 1) {
for (Map.Entry<TypeSymbol, List<TreePath>> cell : columns.entrySet()) {
for (TreePath treePath : cell.getValue()) {
TypeSymbol typeSymbol = cell.getKey();
getBetterImport(typeSymbol, simpleName)
.ifPresent(
imp -> {
String qualifiedName = qualifyType(state.withPath(treePath), fixBuilder, imp);
String newSimpleName = qualifiedName + "." + simpleName;
fixBuilder.replace(treePath.getLeaf(), newSimpleName);
});
}
}
String message =
String.format(
"The name `%s` refers to %s within this file. It may be confusing to have the same"
+ " name refer to multiple types. Consider qualifying them for clarity.",
simpleName,
columns.keySet().stream()
.map(t -> t.getQualifiedName().toString())
.collect(joining(", ", "[", "]")));
SuggestedFix fix = fixBuilder.build();
for (List<TreePath> treePaths : trimmedTable.row(simpleName).values()) {
for (TreePath treePath : treePaths) {
state.reportMatch(
buildDescription(treePath.getLeaf()).setMessage(message).addFix(fix).build());
}
}
}
}
return NO_MATCH;
}
private static boolean shadowsClass(VisitorState state, TreePath treePath) {
if (!(treePath.getLeaf() instanceof IdentifierTree)) {
return true;
}
TreePath enclosingClass = findPathFromEnclosingNodeToTopLevel(treePath, ClassTree.class);
String name = ((IdentifierTree) treePath.getLeaf()).getName().toString();
return findIdent(name, state.withPath(enclosingClass), KindSelector.VAL_TYP) != null;
}
private static Optional<Symbol> getBetterImport(TypeSymbol classSymbol, String simpleName) {
Symbol owner = classSymbol;
long dots = simpleName.chars().filter(c -> c == '.').count();
for (long i = 0; i < dots + 1; ++i) {
if (owner == null) {
return Optional.empty();
}
owner = owner.owner;
}
if (owner instanceof ClassSymbol) {
return Optional.of(owner);
}
return Optional.empty();
}
/** Try to qualify the type, or return the full name. */
public static String qualifyType(VisitorState state, SuggestedFix.Builder fix, Symbol sym) {
Deque<String> names = new ArrayDeque<>();
for (Symbol curr = sym; curr != null; curr = curr.owner) {
names.addFirst(curr.getSimpleName().toString());
Symbol found = findIdent(curr.getSimpleName().toString(), state, KindSelector.VAL_TYP);
if (found == curr) {
break;
}
if (curr.getKind() == ElementKind.PACKAGE) {
return sym.getQualifiedName().toString();
}
if (found == null) {
fix.addImport(curr.getQualifiedName().toString());
break;
}
}
return Joiner.on('.').join(names);
}
}
| 9,299
| 38.574468
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ReachabilityFenceUsage.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.matchers.method.MethodMatchers.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.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TryTree;
import java.util.Objects;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "reachabilityFence should always be called inside a finally block",
severity = WARNING)
public class ReachabilityFenceUsage extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> FENCE_MATCHER =
staticMethod().onClass("java.lang.ref.Reference").named("reachabilityFence");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!FENCE_MATCHER.matches(tree, state)) {
return NO_MATCH;
}
Tree previous = null;
OUTER:
for (Tree enclosing : state.getPath().getParentPath()) {
switch (enclosing.getKind()) {
case TRY:
if (Objects.equals(((TryTree) enclosing).getFinallyBlock(), previous)) {
return NO_MATCH;
}
break;
case CLASS:
case METHOD:
case LAMBDA_EXPRESSION:
break OUTER;
default: // fall out
}
previous = enclosing;
}
return describeMatch(tree);
}
}
| 2,457
| 35.147059
| 95
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NoAllocationChecker.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.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.anything;
import static com.google.errorprone.matchers.Matchers.assignment;
import static com.google.errorprone.matchers.Matchers.binaryTree;
import static com.google.errorprone.matchers.Matchers.compoundAssignment;
import static com.google.errorprone.matchers.Matchers.enclosingMethod;
import static com.google.errorprone.matchers.Matchers.enhancedForLoop;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.isArrayType;
import static com.google.errorprone.matchers.Matchers.isPrimitiveArrayType;
import static com.google.errorprone.matchers.Matchers.isPrimitiveType;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.kindIs;
import static com.google.errorprone.matchers.Matchers.methodReturnsNonPrimitiveType;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.Matchers.symbolHasAnnotation;
import static com.google.errorprone.matchers.Matchers.typeCast;
import static com.google.errorprone.matchers.Matchers.variableInitializer;
import static com.google.errorprone.matchers.Matchers.variableType;
import static com.google.errorprone.util.ASTHelpers.streamSuperMethods;
import static com.sun.source.tree.Tree.Kind.AND_ASSIGNMENT;
import static com.sun.source.tree.Tree.Kind.DIVIDE_ASSIGNMENT;
import static com.sun.source.tree.Tree.Kind.LEFT_SHIFT_ASSIGNMENT;
import static com.sun.source.tree.Tree.Kind.MINUS_ASSIGNMENT;
import static com.sun.source.tree.Tree.Kind.MULTIPLY_ASSIGNMENT;
import static com.sun.source.tree.Tree.Kind.OR_ASSIGNMENT;
import static com.sun.source.tree.Tree.Kind.PLUS;
import static com.sun.source.tree.Tree.Kind.PLUS_ASSIGNMENT;
import static com.sun.source.tree.Tree.Kind.POSTFIX_DECREMENT;
import static com.sun.source.tree.Tree.Kind.POSTFIX_INCREMENT;
import static com.sun.source.tree.Tree.Kind.PREFIX_DECREMENT;
import static com.sun.source.tree.Tree.Kind.PREFIX_INCREMENT;
import static com.sun.source.tree.Tree.Kind.REMAINDER_ASSIGNMENT;
import static com.sun.source.tree.Tree.Kind.RIGHT_SHIFT_ASSIGNMENT;
import static com.sun.source.tree.Tree.Kind.UNSIGNED_RIGHT_SHIFT_ASSIGNMENT;
import static com.sun.source.tree.Tree.Kind.XOR_ASSIGNMENT;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.NoAllocation;
import com.google.errorprone.bugpatterns.BugChecker.AssignmentTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.CompoundAssignmentTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.EnhancedForLoopTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewArrayTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.TypeCastTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.UnaryTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.StatementTree;
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.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type.ArrayType;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
/**
* Checks methods annotated with {@code @NoAllocation} to ensure they really do not allocate.
*
* <ol>
* <li>Calls to new are disallowed.
* <li>Methods statically determined to be reachable from this method must also be annotated with
* {@code @NoAllocation}.
* <li>Autoboxing is disallowed.
* <li>String concatenation and conversions are disallowed.
* <li>To make it easier to use exceptions, allocations are always allowed within a throw
* statement. (But not in the methods of nested classes if they are annotated with {@code
* NoAllocation}.)
* <li>The check is done at the source level. The compiler or runtime may perform optimizations or
* transformations that add or remove allocations in a way not visible to this check.
* </ol>
*/
@BugPattern(
name = "NoAllocation",
summary =
"@NoAllocation was specified on this method, but something was found that would"
+ " trigger an allocation",
severity = ERROR)
public class NoAllocationChecker extends BugChecker
implements AssignmentTreeMatcher,
BinaryTreeMatcher,
CompoundAssignmentTreeMatcher,
EnhancedForLoopTreeMatcher,
MethodTreeMatcher,
MethodInvocationTreeMatcher,
NewArrayTreeMatcher,
NewClassTreeMatcher,
ReturnTreeMatcher,
TypeCastTreeMatcher,
UnaryTreeMatcher,
VariableTreeMatcher {
private static final String COMMON_MESSAGE_SUFFIX =
"is disallowed in methods annotated with @NoAllocation";
private static final Matcher<MethodTree> noAllocationMethodMatcher =
hasAnnotation(NoAllocation.class.getName());
private static final Matcher<MethodInvocationTree> noAllocationMethodInvocationMatcher =
symbolHasAnnotation(NoAllocation.class.getName());
private static final Matcher<ExpressionTree> anyExpression = anything();
private static final Matcher<StatementTree> anyStatement = anything();
private static final Matcher<VariableTree> anyVariable = anything();
private static final Matcher<ExpressionTree> isString = isSameType("java.lang.String");
private static final Matcher<ExpressionTree> arrayExpression = isArrayType();
private static final Matcher<ExpressionTree> primitiveExpression = isPrimitiveType();
private static final Matcher<ExpressionTree> primitiveArrayExpression = isPrimitiveArrayType();
private static final ImmutableSet<Kind> ALL_COMPOUND_OPERATORS =
ImmutableSet.copyOf(
EnumSet.of(
AND_ASSIGNMENT,
DIVIDE_ASSIGNMENT,
LEFT_SHIFT_ASSIGNMENT,
MINUS_ASSIGNMENT,
MULTIPLY_ASSIGNMENT,
OR_ASSIGNMENT,
PLUS_ASSIGNMENT,
REMAINDER_ASSIGNMENT,
RIGHT_SHIFT_ASSIGNMENT,
UNSIGNED_RIGHT_SHIFT_ASSIGNMENT,
XOR_ASSIGNMENT));
/**
* Matches if a Tree has a ThrowTree or an AnnotationTree before any MethodTree in its hierarchy.
* We don't want the throw to nullify any {@code @NoAnnotation} in a method in an anonymous class
* below it.
*/
private static final Matcher<Tree> withinThrowOrAnnotation =
new Matcher<Tree>() {
@Override
public boolean matches(Tree tree, VisitorState state) {
// TODO(agoode): Make this accept statements in a block that definitely will lead to a
// throw.
TreePath path = state.getPath().getParentPath();
while (path != null) {
Tree node = path.getLeaf();
state = state.withPath(path);
switch (node.getKind()) {
case METHOD:
// We've gotten to the top of the method without finding a throw.
return false;
case THROW:
case ANNOTATION:
return true;
default:
path = path.getParentPath();
}
}
return false;
}
};
/**
* Matches a new array statement if the enclosing method is annotated with {@code @NoAllocation}.
*/
private static final Matcher<NewArrayTree> newArrayMatcher =
allOf(not(withinThrowOrAnnotation), enclosingMethod(noAllocationMethodMatcher));
/** Matches a new statement if the enclosing method is annotated with {@code @NoAllocation}. */
private static final Matcher<NewClassTree> newClassMatcher =
allOf(not(withinThrowOrAnnotation), enclosingMethod(noAllocationMethodMatcher));
/**
* Matches if a method without {@code @NoAllocation} is invoked from a method with
* {@code @NoAllocation}.
*/
private static final Matcher<MethodInvocationTree> methodMatcher =
allOf(
not(withinThrowOrAnnotation),
enclosingMethod(noAllocationMethodMatcher),
not(noAllocationMethodInvocationMatcher));
/** Matches string concatenation. Includes all string conversions. */
private static final Matcher<BinaryTree> stringConcatenationMatcher =
allOf(
not(withinThrowOrAnnotation),
enclosingMethod(noAllocationMethodMatcher),
kindIs(PLUS),
binaryTree(anyExpression, isString));
/** Matches string and boxing compound assignment. */
private static final Matcher<CompoundAssignmentTree> compoundAssignmentMatcher =
allOf(
not(withinThrowOrAnnotation),
enclosingMethod(noAllocationMethodMatcher),
anyOf(
compoundAssignment(PLUS_ASSIGNMENT, isString, anyExpression),
compoundAssignment(ALL_COMPOUND_OPERATORS, not(primitiveExpression), anyExpression)));
/** Matches if foreach is used on a non-array or if boxing occurs with an array. */
private static final Matcher<EnhancedForLoopTree> foreachMatcher =
allOf(
not(withinThrowOrAnnotation),
enclosingMethod(noAllocationMethodMatcher),
anyOf(
not(enhancedForLoop(anyVariable, arrayExpression, anyStatement)),
enhancedForLoop(
variableType(not(isPrimitiveType())), primitiveArrayExpression, anyStatement)));
/** Matches boxing assignment. */
private static final Matcher<AssignmentTree> boxingAssignment =
allOf(
not(withinThrowOrAnnotation),
enclosingMethod(noAllocationMethodMatcher),
assignment(not(primitiveExpression), primitiveExpression));
/** Matches boxing during variable initialization. */
private static final Matcher<VariableTree> boxingInitialization =
allOf(
not(withinThrowOrAnnotation),
enclosingMethod(noAllocationMethodMatcher),
variableInitializer(primitiveExpression),
variableType(not(isPrimitiveType())));
/** Matches boxing by explicit cast. */
private static final Matcher<TypeCastTree> boxingCast =
allOf(
not(withinThrowOrAnnotation),
enclosingMethod(noAllocationMethodMatcher),
typeCast(not(isPrimitiveType()), primitiveExpression));
/** Matches boxing by return. */
private static final Matcher<StatementTree> boxingReturn =
Matchers.matchExpressionReturn(
allOf(
not(withinThrowOrAnnotation),
enclosingMethod(allOf(noAllocationMethodMatcher, methodReturnsNonPrimitiveType())),
isPrimitiveType()));
/** Matches boxing by method invocation, including varargs. */
private static final Matcher<MethodInvocationTree> boxingInvocation =
new Matcher<MethodInvocationTree>() {
@Override
public boolean matches(MethodInvocationTree tree, VisitorState state) {
if (!enclosingMethod(noAllocationMethodMatcher).matches(tree, state)) {
return false;
}
// Get the arguments.
JCMethodInvocation methodInvocation = (JCMethodInvocation) tree;
List<JCExpression> arguments = methodInvocation.getArguments();
// Get the parameters.
MethodSymbol methodSymbol = ASTHelpers.getSymbol(tree);
List<VarSymbol> params = methodSymbol.getParameters();
// If there is a length mismatch, this implies varargs boxing.
if (arguments.size() != params.size()) {
return true;
}
// Check for boxing at each argument.
int numArgs = arguments.size();
int i = 0;
Iterator<JCExpression> argument = arguments.iterator();
Iterator<VarSymbol> param = params.iterator();
while (param.hasNext() && argument.hasNext()) {
JCExpression a = argument.next();
VarSymbol p = param.next();
if (a.type.isPrimitive() && !p.type.isPrimitive()) {
// Boxing occurs here.
return true;
}
// Check last parameter. If it's a varargs parameter, ensure no boxing by making sure
// it's assignable.
if (i == numArgs - 1
&& methodSymbol.isVarArgs()
&& p.type instanceof ArrayType
&& !state.getTypes().isAssignable(a.type, p.type)) {
return true;
}
i++;
}
return false;
}
};
/** Matches boxing by unary operator. */
private static final Matcher<UnaryTree> boxingUnary =
new Matcher<UnaryTree>() {
@Override
public boolean matches(UnaryTree tree, VisitorState state) {
return allOf(
not(withinThrowOrAnnotation),
enclosingMethod(noAllocationMethodMatcher),
anyOf(
kindIs(POSTFIX_DECREMENT),
kindIs(POSTFIX_INCREMENT),
kindIs(PREFIX_DECREMENT),
kindIs(PREFIX_INCREMENT)))
.matches(tree, state)
&& not(isPrimitiveType()).matches(tree, state);
}
};
@Override
public Description matchNewArray(NewArrayTree tree, VisitorState state) {
if (!newArrayMatcher.matches(tree, state)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage("Allocating a new array with \"new\" or \"{ ... }\" " + COMMON_MESSAGE_SUFFIX)
.build();
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (!newClassMatcher.matches(tree, state)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage("Constructing a new object " + COMMON_MESSAGE_SUFFIX)
.build();
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!methodMatcher.matches(tree, state) && !boxingInvocation.matches(tree, state)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage(
"Calling a method that is not annotated with @NoAllocation, calling a varargs"
+ " method without exactly matching the signature, or passing a primitive value as"
+ " non-primitive method argument "
+ COMMON_MESSAGE_SUFFIX)
.build();
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (hasAnnotation(NoAllocation.class).matches(tree, state)) {
return NO_MATCH;
}
MethodSymbol symbol = ASTHelpers.getSymbol(tree);
return streamSuperMethods(symbol, state.getTypes())
.filter(s -> ASTHelpers.hasAnnotation(s, NoAllocation.class.getName(), state))
.findAny()
.map(
s -> {
String message =
String.format(
"Method overrides %s in %s which is annotated @NoAllocation,"
+ " it should also be annotated.",
s.getSimpleName(), s.owner.getSimpleName());
return buildDescription(tree)
.setMessage(message)
.addFix(
SuggestedFix.builder()
.addImport(NoAllocation.class.getName())
.prefixWith(tree, "@NoAllocation ")
.build())
.build();
})
.orElse(NO_MATCH);
}
@Override
public Description matchBinary(BinaryTree tree, VisitorState state) {
if (!stringConcatenationMatcher.matches(tree, state)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage("String concatenation allocates a new String, which " + COMMON_MESSAGE_SUFFIX)
.build();
}
@Override
public Description matchCompoundAssignment(CompoundAssignmentTree tree, VisitorState state) {
if (!compoundAssignmentMatcher.matches(tree, state)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage(
"Compound assignment to a String or boxed primitive allocates a new object,"
+ " which "
+ COMMON_MESSAGE_SUFFIX)
.build();
}
@Override
public Description matchEnhancedForLoop(EnhancedForLoopTree tree, VisitorState state) {
if (!foreachMatcher.matches(tree, state)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage(
"Iterating over a Collection or iterating over a primitive array using a"
+ " non-primitive element type will trigger allocation, which "
+ COMMON_MESSAGE_SUFFIX)
.build();
}
@Override
public Description matchAssignment(AssignmentTree tree, VisitorState state) {
if (!boxingAssignment.matches(tree, state)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage(
"Assigning a primitive value to a non-primitive variable or array element"
+ " will autobox the value, which "
+ COMMON_MESSAGE_SUFFIX)
.build();
}
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
if (!boxingInitialization.matches(tree, state)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage(
"Initializing a non-primitive variable with a primitive value will autobox the"
+ " value, which "
+ COMMON_MESSAGE_SUFFIX)
.build();
}
@Override
public Description matchTypeCast(TypeCastTree tree, VisitorState state) {
if (!boxingCast.matches(tree, state)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage(
"Casting a primitive value to a non-primitive type will autobox the value,"
+ " which "
+ COMMON_MESSAGE_SUFFIX)
.build();
}
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
if (!boxingReturn.matches(tree, state)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage(
"Returning a primitive value from a method with a non-primitive return type"
+ " will autobox the value, which "
+ COMMON_MESSAGE_SUFFIX)
.build();
}
@Override
public Description matchUnary(UnaryTree tree, VisitorState state) {
if (!boxingUnary.matches(tree, state)) {
return NO_MATCH;
}
return buildDescription(tree)
.setMessage(
"Pre- and post- increment/decrement operations on a non-primitive variable or"
+ " array element will autobox the result, which "
+ COMMON_MESSAGE_SUFFIX)
.build();
}
}
| 21,145
| 39.743738
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BadImport.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.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import com.google.common.collect.ImmutableSet;
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.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.suppliers.Supplier;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.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.PackageSymbol;
import com.sun.tools.javac.code.Type;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.Name;
/**
* @author awturner@google.com (Andy Turner)
*/
@BugPattern(
summary =
"Importing nested classes/static methods/static fields with commonly-used names can make "
+ "code harder to read, because it may not be clear from the context exactly which "
+ "type is being referred to. Qualifying the name with that of the containing class "
+ "can make the code clearer.",
severity = WARNING)
public class BadImport extends BugChecker implements ImportTreeMatcher {
/**
* Class names which are bad as a direct import if they have an enclosing class.
*
* <p>The common factor for these names isn't just that they may be vague class names; there are
* many more examples of that. What's important is that they are vague <em>and</em> generally
* clarified by the name of the outer class (that is, {@code Foo.Builder} is clearer than {@code
* Builder}).
*/
static final ImmutableSet<String> BAD_NESTED_CLASSES =
ImmutableSet.of(
"Builder",
"BuilderFactory",
"Callback",
"Class",
"Enum",
"Factory",
"Type",
"Key",
"Id",
"Provider");
private static final ImmutableSet<String> BAD_STATIC_IDENTIFIERS =
ImmutableSet.of(
"builder",
"create",
"copyOf",
"from",
"getDefaultInstance",
"INSTANCE",
"newBuilder",
"newInstance",
"of",
"valueOf");
private static final MultiMatcher<Tree, AnnotationTree> HAS_TYPE_USE_ANNOTATION =
annotations(AT_LEAST_ONE, (t, state) -> isTypeAnnotation(t));
private static final String MESSAGE_LITE = "com.google.protobuf.MessageLite";
@Override
public Description matchImport(ImportTree tree, VisitorState state) {
Symbol symbol;
ImmutableSet<Symbol> symbols;
if (!tree.isStatic()) {
symbol = getSymbol(tree.getQualifiedIdentifier());
if (symbol == null || isAcceptableImport(symbol, BAD_NESTED_CLASSES)) {
return Description.NO_MATCH;
}
symbols = ImmutableSet.of(symbol);
} else {
StaticImportInfo staticImportInfo = StaticImports.tryCreate(tree, state);
if (staticImportInfo == null || staticImportInfo.members().isEmpty()) {
return Description.NO_MATCH;
}
symbols = staticImportInfo.members();
// Pick an arbitrary symbol. They've all got the same simple name, so it doesn't matter which.
symbol = symbols.iterator().next();
if (isAcceptableImport(symbol, BAD_STATIC_IDENTIFIERS)) {
return Description.NO_MATCH;
}
}
if (state.getPath().getCompilationUnit().getTypeDecls().stream()
.anyMatch(c -> symbol.outermostClass().equals(getSymbol(c)))) {
return Description.NO_MATCH;
}
if (symbol.getEnclosingElement() instanceof PackageSymbol) {
return Description.NO_MATCH;
}
if (isSubtype(symbol.type, COM_GOOGLE_PROTOBUF_MESSAGELITE.get(state), state)) {
return Description.NO_MATCH;
}
SuggestedFix.Builder builder =
SuggestedFix.builder().removeImport(symbol.getQualifiedName().toString());
// Have to start at the symbol's enclosing element because otherwise we find the symbol again
// immediately.
String replacement =
SuggestedFixes.qualifyType(getCheckState(state), builder, symbol.getEnclosingElement())
+ ".";
return buildDescription(builder, symbols, replacement, state);
}
private static VisitorState getCheckState(VisitorState state) {
// Gets the VisitorState to start from when checking how to qualify the name. This won't work
// correctly in all cases 1) it assumes there is only 1 top level type; 2) it doesn't look for
// all of the locations where the symbol-to-be-replaced is used in the compilation unit.
// Really, we should gather all of the usages first, and check them all.
// It is assumed that this will work sufficiently until proven otherwise.
CompilationUnitTree compilationUnit = state.getPath().getCompilationUnit();
if (compilationUnit.getTypeDecls().isEmpty()) {
return state;
}
Tree tree = compilationUnit.getTypeDecls().get(0);
if (!(tree instanceof ClassTree) || ((ClassTree) tree).getMembers().isEmpty()) {
return state;
}
return state.withPath(
TreePath.getPath(compilationUnit, ((ClassTree) tree).getMembers().get(0)));
}
private static boolean isAcceptableImport(Symbol symbol, Set<String> badNames) {
Name simpleName = symbol.getSimpleName();
return badNames.stream().noneMatch(simpleName::contentEquals);
}
private Description buildDescription(
SuggestedFix.Builder builder,
Set<Symbol> symbols,
String enclosingReplacement,
VisitorState state) {
CompilationUnitTree compilationUnit = state.getPath().getCompilationUnit();
TreePath path = TreePath.getPath(compilationUnit, compilationUnit);
IdentifierTree firstFound =
new SuppressibleTreePathScanner<IdentifierTree, Void>(state) {
@Override
public IdentifierTree reduce(IdentifierTree r1, IdentifierTree r2) {
return (r2 != null) ? r2 : r1;
}
@Override
public IdentifierTree visitIdentifier(IdentifierTree node, Void unused) {
Symbol nodeSymbol = getSymbol(node);
if (symbols.contains(nodeSymbol) && !isSuppressed(node, state)) {
if (getCurrentPath().getParentPath().getLeaf().getKind() != Kind.CASE) {
builder.prefixWith(node, enclosingReplacement);
moveTypeAnnotations(node);
return node;
}
}
return super.visitIdentifier(node, unused);
}
// We need to move any type annotation inside the qualified usage to preserve semantics,
// e.g. @Nullable Builder -> SomeClass.@Nullable Builder.
private void moveTypeAnnotations(IdentifierTree node) {
Tree parent = getCurrentPath().getParentPath().getLeaf();
switch (parent.getKind()) {
case METHOD:
case VARIABLE:
case ANNOTATED_TYPE:
moveTypeAnnotations(node, parent, state, builder);
break;
case PARAMETERIZED_TYPE:
Tree grandParent = getCurrentPath().getParentPath().getParentPath().getLeaf();
if (grandParent.getKind() == Kind.VARIABLE
|| grandParent.getKind() == Kind.METHOD) {
moveTypeAnnotations(node, grandParent, state, builder);
}
break;
default:
// Do nothing.
}
}
private void moveTypeAnnotations(
IdentifierTree node,
Tree annotationHolder,
VisitorState state,
SuggestedFix.Builder builder) {
for (AnnotationTree annotation :
HAS_TYPE_USE_ANNOTATION.multiMatchResult(annotationHolder, state).matchingNodes()) {
builder.delete(annotation);
builder.prefixWith(node, state.getSourceForNode(annotation) + " ");
}
}
}.scan(path, null);
if (firstFound == null) {
// If no usage of the symbol was found, just leave the import to be cleaned up by the unused
// import fix.
return Description.NO_MATCH;
}
return buildDescription(firstFound)
.setMessage(
String.format(
"Importing nested classes/static methods/static fields with commonly-used names can"
+ " make code harder to read, because it may not be clear from the context"
+ " exactly which type is being referred to. Qualifying the name with that of"
+ " the containing class can make the code clearer. Here we recommend using"
+ " qualified class: %s",
enclosingReplacement))
.addFix(builder.build())
.build();
}
private static boolean isTypeAnnotation(AnnotationTree t) {
Symbol annotationSymbol = getSymbol(t.getAnnotationType());
if (annotationSymbol == null) {
return false;
}
Target target = annotationSymbol.getAnnotation(Target.class);
if (target == null) {
return false;
}
List<ElementType> value = Arrays.asList(target.value());
return value.contains(ElementType.TYPE_USE) || value.contains(ElementType.TYPE_PARAMETER);
}
private static final Supplier<Type> COM_GOOGLE_PROTOBUF_MESSAGELITE =
VisitorState.memoize(state -> state.getTypeFromString(MESSAGE_LITE));
}
| 10,905
| 39.243542
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/FloatingPointAssertionWithinEpsilon.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
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.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTag;
import java.util.Optional;
/**
* Detects usages of {@code Float,DoubleSubject.isWithin(TOLERANCE).of(EXPECTED)} where there are no
* other floating point values other than {@code EXPECTED} with satisfy the assertion, but {@code
* TOLERANCE} is not zero. Likewise for older-style JUnit assertions ({@code assertEquals(double,
* double, double)}).
*
* @author ghm@google.com (Graeme Morgan)
*/
@BugPattern(
summary =
"This fuzzy equality check is using a tolerance less than the gap to the next number. "
+ "You may want a less restrictive tolerance, or to assert equality.",
severity = WARNING,
tags = StandardTags.SIMPLIFICATION)
public final class FloatingPointAssertionWithinEpsilon extends BugChecker
implements MethodInvocationTreeMatcher {
private static final String DESCRIPTION =
"This fuzzy equality check is using a tolerance less than the gap to the next number "
+ "(which is ~%.2g). You may want a less restrictive tolerance, or to assert equality.";
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
for (FloatingPointType floatingPointType : FloatingPointType.values()) {
Optional<Description> description = floatingPointType.match(this, tree, state);
if (description.isPresent()) {
return description.get();
}
}
return Description.NO_MATCH;
}
@SuppressWarnings("ImmutableEnumChecker")
private enum FloatingPointType {
FLOAT(
TypeTag.FLOAT, "float", "com.google.common.truth.FloatSubject", "TolerantFloatComparison") {
@Override
Float nextNumber(Number actual) {
float number = actual.floatValue();
return Math.min(Math.nextUp(number) - number, number - Math.nextDown(number));
}
@Override
boolean isIntolerantComparison(Number tolerance, Number actual) {
return tolerance.floatValue() != 0 && tolerance.floatValue() < nextNumber(actual);
}
@Override
Optional<String> suffixLiteralIfPossible(LiteralTree literal, VisitorState state) {
// If the value passed to #of was being converted to a float, we can make that explicit with
// an "f" qualifier.
return Optional.of(removeSuffixes(state.getSourceForNode(literal)) + "f");
}
},
DOUBLE(
TypeTag.DOUBLE,
"double",
"com.google.common.truth.DoubleSubject",
"TolerantDoubleComparison") {
@Override
Double nextNumber(Number actual) {
double number = actual.doubleValue();
return Math.min(Math.nextUp(number) - number, number - Math.nextDown(number));
}
@Override
boolean isIntolerantComparison(Number tolerance, Number actual) {
return tolerance.doubleValue() != 0 && tolerance.doubleValue() < nextNumber(actual);
}
@Override
Optional<String> suffixLiteralIfPossible(LiteralTree literal, VisitorState state) {
String literalString = removeSuffixes(state.getSourceForNode(literal));
double asDouble;
try {
asDouble = Double.parseDouble(literalString);
} catch (NumberFormatException nfe) {
return Optional.empty();
}
// We need to double-check that the value with a "d" suffix has the same value. For example,
// 0.1f != 0.1d, so must be replaced with (double) 0.1f
if (asDouble == ASTHelpers.constValue(literal, Number.class).doubleValue()) {
return Optional.of(literalString.contains(".") ? literalString : literalString + "d");
}
return Optional.empty();
}
};
private final TypeTag typeTag;
private final String typeName;
private final Matcher<MethodInvocationTree> truthOfCall;
private final Matcher<ExpressionTree> junitWithoutMessage;
private final Matcher<ExpressionTree> junitWithMessage;
FloatingPointType(
TypeTag typeTag, String typeName, String subjectClass, String tolerantSubclass) {
this.typeTag = typeTag;
this.typeName = typeName;
String tolerantClass = subjectClass + "." + tolerantSubclass;
truthOfCall =
allOf(
instanceMethod().onDescendantOf(tolerantClass).named("of").withParameters(typeName),
Matchers.receiverOfInvocation(
instanceMethod()
.onDescendantOf(subjectClass)
.namedAnyOf("isWithin", "isNotWithin")
.withParameters(typeName)));
junitWithoutMessage =
staticMethod()
.onClass("org.junit.Assert")
.named("assertEquals")
.withParameters(typeName, typeName, typeName);
junitWithMessage =
staticMethod()
.onClass("org.junit.Assert")
.named("assertEquals")
.withParameters("java.lang.String", typeName, typeName, typeName);
}
abstract Number nextNumber(Number actual);
abstract boolean isIntolerantComparison(Number tolerance, Number actual);
abstract Optional<String> suffixLiteralIfPossible(LiteralTree literal, VisitorState state);
private Optional<Description> match(
BugChecker bugChecker, MethodInvocationTree tree, VisitorState state) {
if (junitWithoutMessage.matches(tree, state)) {
return check(tree.getArguments().get(2), tree.getArguments().get(0))
.map(
tolerance ->
suggestJunitFix(bugChecker, tree)
.setMessage(String.format(DESCRIPTION, tolerance))
.build());
}
if (junitWithMessage.matches(tree, state)) {
return check(tree.getArguments().get(3), tree.getArguments().get(1))
.map(
tolerance ->
suggestJunitFix(bugChecker, tree)
.setMessage(String.format(DESCRIPTION, tolerance))
.build());
}
if (truthOfCall.matches(tree, state)) {
return check(getReceiverArgument(tree), getOnlyElement(tree.getArguments()))
.map(
tolerance ->
suggestTruthFix(bugChecker, tree, state)
.setMessage(String.format(DESCRIPTION, tolerance))
.build());
}
return Optional.empty();
}
/**
* Checks whether the provided {@code toleranceArgument} and {@code actualArgument} will lead to
* an equality check. If so, returns the smallest tolerance that wouldn't for diagnostic
* purposes.
*/
private Optional<Double> check(
ExpressionTree toleranceArgument, ExpressionTree actualArgument) {
Number actual = ASTHelpers.constValue(actualArgument, Number.class);
Number tolerance = ASTHelpers.constValue(toleranceArgument, Number.class);
if (actual == null || tolerance == null) {
return Optional.empty();
}
return isIntolerantComparison(tolerance, actual)
? Optional.of(nextNumber(actual).doubleValue())
: Optional.empty();
}
private static ExpressionTree getReceiverArgument(MethodInvocationTree tree) {
ExpressionTree receiver = ASTHelpers.getReceiver(tree);
return getOnlyElement(((MethodInvocationTree) receiver).getArguments());
}
/** Suggest replacing the tolerance with {@code 0} for JUnit assertions. */
private static Description.Builder suggestJunitFix(
BugChecker bugChecker, MethodInvocationTree tree) {
SuggestedFix fix = SuggestedFix.replace(getLast(tree.getArguments()), "0");
return bugChecker.buildDescription(tree).addFix(fix);
}
/** Suggest replacing {@code isWithin(..).of(foo)} with {@code isEqualTo(foo)} for Truth. */
private Description.Builder suggestTruthFix(
BugChecker bugChecker, MethodInvocationTree tree, VisitorState state) {
ExpressionTree within = ASTHelpers.getReceiver(tree);
ExpressionTree assertion = ASTHelpers.getReceiver(within);
String replacementMethod =
ASTHelpers.getSymbol(within).getSimpleName().toString().contains("Not")
? "isNotEqualTo"
: "isEqualTo";
ExpressionTree argument = getOnlyElement(tree.getArguments());
SuggestedFix fix =
SuggestedFix.replace(
tree,
String.format(
"%s.%s(%s)",
state.getSourceForNode(assertion),
replacementMethod,
castArgumentIfNecessary(argument, state)));
return bugChecker.buildDescription(tree).addFix(fix);
}
private String castArgumentIfNecessary(ExpressionTree tree, VisitorState state) {
String source = state.getSourceForNode(tree);
Type type = ASTHelpers.getType(tree);
if (state.getTypes().unboxedTypeOrType(type).getTag() == typeTag) {
return source;
}
if (tree instanceof LiteralTree) {
Optional<String> suffixed = suffixLiteralIfPossible((LiteralTree) tree, state);
if (suffixed.isPresent()) {
return suffixed.get();
}
}
if (ASTHelpers.requiresParentheses(tree, state)) {
return String.format("(%s) (%s)", typeName, source);
}
return String.format("(%s) %s", typeName, source);
}
static String removeSuffixes(String source) {
return source.replaceAll("[fFdDlL]$", "");
}
}
}
| 11,172
| 40.535316
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MultipleUnaryOperatorsInMethodCall.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 java.util.stream.Collectors.groupingBy;
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.util.ASTHelpers;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.UnaryTree;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author sulku@google.com (Marsela Sulku)
*/
@BugPattern(
summary = "Avoid having multiple unary operators acting on the same variable in a method call",
severity = WARNING)
public class MultipleUnaryOperatorsInMethodCall extends BugChecker
implements MethodInvocationTreeMatcher {
private static final ImmutableSet<Kind> UNARY_OPERATORS =
Sets.immutableEnumSet(
Kind.POSTFIX_DECREMENT,
Kind.POSTFIX_INCREMENT,
Kind.PREFIX_DECREMENT,
Kind.PREFIX_INCREMENT);
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState visitorState) {
if (methodInvocationTree.getArguments().stream()
.filter(arg -> UNARY_OPERATORS.contains(arg.getKind()))
.map(arg -> ASTHelpers.getSymbol(((UnaryTree) arg).getExpression()))
.filter(sym -> sym != null)
.collect(groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.anyMatch(e -> e.getValue() > 1)) {
return describeMatch(methodInvocationTree);
}
return NO_MATCH;
}
}
| 2,519
| 36.61194
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CacheLoaderNull.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 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.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "The result of CacheLoader#load must be non-null.", severity = WARNING)
public class CacheLoaderNull extends BugChecker implements MethodTreeMatcher {
private static final Supplier<Type> CACHE_LOADER_TYPE =
Suppliers.typeFromString("com.google.common.cache.CacheLoader");
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!tree.getName().contentEquals("load")) {
return NO_MATCH;
}
MethodSymbol sym = ASTHelpers.getSymbol(tree);
if (!ASTHelpers.isSubtype(sym.owner.asType(), CACHE_LOADER_TYPE.get(state), state)) {
return NO_MATCH;
}
new TreeScanner<Void, Void>() {
@Override
public Void visitLambdaExpression(LambdaExpressionTree tree, Void unused) {
return null;
}
@Override
public Void visitClass(ClassTree tree, Void unused) {
return null;
}
@Override
public Void visitReturn(ReturnTree tree, Void unused) {
ExpressionTree expression = tree.getExpression();
if (expression != null && expression.getKind() == Tree.Kind.NULL_LITERAL) {
state.reportMatch(describeMatch(tree));
}
return super.visitReturn(tree, null);
}
}.scan(tree.getBody(), null);
return NO_MATCH;
}
}
| 2,907
| 36.282051
| 93
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JUnit4TestsNotRunWithinEnclosed.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.fixes.SuggestedFixes.updateAnnotationArgumentValues;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.JUnitMatchers.TEST_CASE;
import static com.google.errorprone.matchers.JUnitMatchers.isJUnit4TestRunnerOfType;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.matchers.Matchers.hasArgumentWithValue;
import static com.google.errorprone.matchers.Matchers.isType;
import static com.google.errorprone.util.ASTHelpers.getAnnotationWithSimpleName;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
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.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ClassType;
/** Finds tests that won't run due to the enclosing runner. */
@BugPattern(
summary =
"This test is annotated @Test, but given it's within a class using the Enclosed runner,"
+ " will not run.",
severity = ERROR)
public final class JUnit4TestsNotRunWithinEnclosed extends BugChecker
implements CompilationUnitTreeMatcher {
private static final MultiMatcher<ClassTree, AnnotationTree> ENCLOSED =
annotations(
AT_LEAST_ONE,
allOf(
isType("org.junit.runner.RunWith"),
hasArgumentWithValue(
"value",
isJUnit4TestRunnerOfType(
ImmutableSet.of("org.junit.experimental.runners.Enclosed")))));
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
ImmutableSet<Type> extendedTypes = getExtendedTypes(state);
new TreePathScanner<Void, Void>() {
@Override
public Void visitClass(ClassTree classTree, Void unused) {
if (!ENCLOSED.matches(classTree, state)) {
return super.visitClass(classTree, null);
}
ClassType classType = getType(classTree);
if (extendedTypes.stream().anyMatch(t -> isSameType(t, classType, state))) {
return super.visitClass(classTree, null);
}
for (Tree member : classTree.getMembers()) {
if (member instanceof MethodTree && TEST_CASE.matches((MethodTree) member, state)) {
SuggestedFix.Builder fix = SuggestedFix.builder();
String junit4 = SuggestedFixes.qualifyType(state, fix, "org.junit.runners.JUnit4");
state.reportMatch(
describeMatch(
member,
fix.merge(
updateAnnotationArgumentValues(
getAnnotationWithSimpleName(
classTree.getModifiers().getAnnotations(), "RunWith"),
state,
"value",
ImmutableList.of(junit4 + ".class")))
.build()));
}
}
return super.visitClass(classTree, unused);
}
}.scan(tree, null);
return Description.NO_MATCH;
}
private static ImmutableSet<Type> getExtendedTypes(VisitorState state) {
ImmutableSet.Builder<Type> extendedTypes = ImmutableSet.builder();
new TreePathScanner<Void, Void>() {
@Override
public Void visitClass(ClassTree classTree, Void unused) {
if (classTree.getExtendsClause() != null) {
extendedTypes.add(getType(classTree.getExtendsClause()));
}
return super.visitClass(classTree, null);
}
}.scan(state.getPath().getCompilationUnit(), null);
return extendedTypes.build();
}
}
| 5,172
| 42.108333
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MultiVariableDeclaration.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.SUGGESTION;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static java.util.stream.Collectors.joining;
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.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.BlockTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.Pretty;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.List;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Variable declarations should declare only one variable",
severity = SUGGESTION,
linkType = CUSTOM,
tags = StandardTags.STYLE,
link = "https://google.github.io/styleguide/javaguide.html#s4.8.2.1-variables-per-declaration")
public class MultiVariableDeclaration extends BugChecker
implements ClassTreeMatcher, BlockTreeMatcher {
@Override
public Description matchBlock(BlockTree tree, VisitorState state) {
return checkDeclarations(tree.getStatements(), state);
}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
return checkDeclarations(tree.getMembers(), state);
}
private Description checkDeclarations(List<? extends Tree> children, VisitorState state) {
PeekingIterator<Tree> it = Iterators.<Tree>peekingIterator(children.iterator());
while (it.hasNext()) {
if (it.peek().getKind() != Tree.Kind.VARIABLE) {
it.next();
continue;
}
VariableTree variableTree = (VariableTree) it.next();
ArrayList<JCVariableDecl> fragments = new ArrayList<>();
fragments.add((JCVariableDecl) variableTree);
// Javac handles multi-variable declarations by lowering them in the parser into a series of
// individual declarations, all of which have the same start position. We search for the first
// declaration in the group, which is either the first variable declared in this scope or has
// a distinct end position from the previous declaration.
while (it.hasNext()
&& it.peek().getKind() == Tree.Kind.VARIABLE
&& getStartPosition(variableTree) == getStartPosition(it.peek())) {
fragments.add((JCVariableDecl) it.next());
}
if (fragments.size() == 1) {
continue;
}
Fix fix =
SuggestedFix.replace(
fragments.get(0).getStartPosition(),
state.getEndPosition(Iterables.getLast(fragments)),
fragments.stream().map(this::pretty).collect(joining("")));
state.reportMatch(describeMatch(fragments.get(0), fix));
}
return NO_MATCH;
}
private String pretty(JCVariableDecl variableDecl) {
StringWriter sw = new StringWriter();
try {
new Pretty(sw, true) {
@Override
public void visitAnnotation(JCAnnotation anno) {
if (anno.getArguments().isEmpty()) {
try {
print("@");
printExpr(anno.annotationType);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
} else {
super.visitAnnotation(anno);
}
}
}.printStat(variableDecl);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return sw.toString();
}
}
| 4,865
| 37.928
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ConditionalExpressionNumericPromotion.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.Preconditions.checkNotNull;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ConditionalExpressionTreeMatcher;
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.google.errorprone.util.ASTHelpers.TargetType;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.tools.javac.code.Type;
/**
* @author awturner@google.com (Andy Turner)
*/
@BugPattern(
summary =
"A conditional expression with numeric operands of differing types will perform binary "
+ "numeric promotion of the operands; when these operands are of reference types, "
+ "the expression's result may not be of the expected type.",
severity = ERROR)
public class ConditionalExpressionNumericPromotion extends BugChecker
implements ConditionalExpressionTreeMatcher {
@Override
public Description matchConditionalExpression(
ConditionalExpressionTree conditionalExpression, VisitorState state) {
Type expressionType = checkNotNull(ASTHelpers.getType(conditionalExpression));
if (!expressionType.isPrimitive()) {
return NO_MATCH;
}
ExpressionTree trueExpression = conditionalExpression.getTrueExpression();
ExpressionTree falseExpression = conditionalExpression.getFalseExpression();
Type trueType = checkNotNull(ASTHelpers.getType(trueExpression));
Type falseType = checkNotNull(ASTHelpers.getType(falseExpression));
if (trueType.isPrimitive() || falseType.isPrimitive()) {
return NO_MATCH;
}
if (ASTHelpers.isSameType(trueType, falseType, state)) {
return NO_MATCH;
}
TargetType targetType = ASTHelpers.targetType(state);
if (targetType == null) {
return NO_MATCH;
}
if (targetType.type().isPrimitive()) {
return NO_MATCH;
}
Type numberType = JAVA_LANG_NUMBER.get(state);
if (ASTHelpers.isSubtype(targetType.type(), numberType, state)
&& !ASTHelpers.isSameType(targetType.type(), numberType, state)) {
return NO_MATCH;
}
SuggestedFix.Builder builder = SuggestedFix.builder();
String numberName = SuggestedFixes.qualifyType(state, builder, numberType);
String prefix = "((" + numberName + ") ";
builder.prefixWith(trueExpression, prefix).postfixWith(trueExpression, ")");
builder.prefixWith(falseExpression, prefix).postfixWith(falseExpression, ")");
return describeMatch(conditionalExpression, builder.build());
}
private static final Supplier<Type> JAVA_LANG_NUMBER =
VisitorState.memoize(state -> state.getTypeFromString("java.lang.Number"));
}
| 3,704
| 38.414894
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NarrowingCompoundAssignment.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.util.ASTHelpers.getType;
import static com.google.errorprone.util.Signatures.prettyType;
import com.google.common.base.Optional;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompoundAssignmentTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.OperatorPrecedence;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.tree.JCTree.JCBinary;
import javax.annotation.Nullable;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Compound assignments may hide dangerous casts",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public class NarrowingCompoundAssignment extends BugChecker
implements CompoundAssignmentTreeMatcher {
static String assignmentToString(Tree.Kind kind) {
switch (kind) {
case MULTIPLY:
return "*";
case DIVIDE:
return "/";
case REMAINDER:
return "%";
case PLUS:
return "+";
case MINUS:
return "-";
case LEFT_SHIFT:
return "<<";
case AND:
return "&";
case XOR:
return "^";
case OR:
return "|";
case RIGHT_SHIFT:
return ">>";
case UNSIGNED_RIGHT_SHIFT:
return ">>>";
default:
throw new IllegalArgumentException("Unexpected operator assignment kind: " + kind);
}
}
static Kind regularAssignmentFromCompound(Kind kind) {
switch (kind) {
case MULTIPLY_ASSIGNMENT:
return Kind.MULTIPLY;
case DIVIDE_ASSIGNMENT:
return Kind.DIVIDE;
case REMAINDER_ASSIGNMENT:
return Kind.REMAINDER;
case PLUS_ASSIGNMENT:
return Kind.PLUS;
case MINUS_ASSIGNMENT:
return Kind.MINUS;
case LEFT_SHIFT_ASSIGNMENT:
return Kind.LEFT_SHIFT;
case AND_ASSIGNMENT:
return Kind.AND;
case XOR_ASSIGNMENT:
return Kind.XOR;
case OR_ASSIGNMENT:
return Kind.OR;
case RIGHT_SHIFT_ASSIGNMENT:
return Kind.RIGHT_SHIFT;
case UNSIGNED_RIGHT_SHIFT_ASSIGNMENT:
return Kind.UNSIGNED_RIGHT_SHIFT;
default:
throw new IllegalArgumentException("Unexpected compound assignment kind: " + kind);
}
}
@Override
public Description matchCompoundAssignment(CompoundAssignmentTree tree, VisitorState state) {
String message =
identifyBadCast(
getType(tree.getVariable()), getType(tree.getExpression()), state.getTypes());
if (message == null) {
return Description.NO_MATCH;
}
Optional<Fix> fix = rewriteCompoundAssignment(tree, state);
if (!fix.isPresent()) {
return Description.NO_MATCH;
}
return buildDescription(tree).addFix(fix.get()).setMessage(message).build();
}
/** Classifies bad casts. */
@Nullable
private static String identifyBadCast(Type lhs, Type rhs, Types types) {
if (!lhs.isPrimitive()) {
return null;
}
if (types.isConvertible(rhs, lhs)) {
// Exemption if the rhs is convertible to the lhs.
// This allows, e.g.: <byte> &= <byte> since the narrowing conversion can never be
// detected.
// This also allows, for example, char += char, which could overflow, but this is no
// different than any other integral addition.
return null;
}
return String.format(
"Compound assignments from %s to %s hide lossy casts", prettyType(rhs), prettyType(lhs));
}
/** Desugars a compound assignment, making the cast explicit. */
private static Optional<Fix> rewriteCompoundAssignment(
CompoundAssignmentTree tree, VisitorState state) {
CharSequence var = state.getSourceForNode(tree.getVariable());
CharSequence expr = state.getSourceForNode(tree.getExpression());
if (var == null || expr == null) {
return Optional.absent();
}
switch (tree.getKind()) {
case RIGHT_SHIFT_ASSIGNMENT:
// narrowing the result of a signed right shift does not lose information
return Optional.absent();
case AND_ASSIGNMENT:
case XOR_ASSIGNMENT:
case OR_ASSIGNMENT:
if (twiddlingConstantBitsOk(tree)) {
return Optional.absent();
}
break;
default:
break;
}
Kind regularAssignmentKind = regularAssignmentFromCompound(tree.getKind());
String op = assignmentToString(regularAssignmentKind);
// Add parens to the rhs if necessary to preserve the current precedence
// e.g. 's -= 1 - 2' -> 's = s - (1 - 2)'
OperatorPrecedence rhsPrecedence =
tree.getExpression() instanceof JCBinary
? OperatorPrecedence.from(tree.getExpression().getKind())
: tree.getExpression() instanceof ConditionalExpressionTree
? OperatorPrecedence.TERNARY
: null;
if (rhsPrecedence != null) {
if (!rhsPrecedence.isHigher(OperatorPrecedence.from(regularAssignmentKind))) {
expr = String.format("(%s)", expr);
}
}
// e.g. 's *= 42' -> 's = (short) (s * 42)'
String castType = getType(tree.getVariable()).toString();
String replacement = String.format("%s = (%s) (%s %s %s)", var, castType, var, op, expr);
return Optional.of(SuggestedFix.replace(tree, replacement));
}
private static boolean twiddlingConstantBitsOk(CompoundAssignmentTree tree) {
int shift;
switch (ASTHelpers.getType(tree.getVariable()).getKind()) {
case BYTE:
shift = 8;
break;
case SHORT:
shift = 16;
break;
default:
return false;
}
Object constValue = ASTHelpers.constValue(tree.getExpression());
if (!(constValue instanceof Integer || constValue instanceof Long)) {
return false;
}
long constLong = ((Number) constValue).longValue();
long shifted = constLong >> shift;
return shifted == 0 || shifted == ~0;
}
}
| 7,166
| 33.456731
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CanonicalDuration.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.constValue;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static java.util.stream.Collectors.toList;
import com.google.common.base.Converter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableTable;
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.LiteralTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Duration can be expressed more clearly with different units",
severity = WARNING)
public class CanonicalDuration extends BugChecker implements MethodInvocationTreeMatcher {
enum Api {
JAVA("java.time.Duration"),
JODA("org.joda.time.Duration");
private final String durationFullyQualifiedName;
Api(String durationFullyQualifiedName) {
this.durationFullyQualifiedName = durationFullyQualifiedName;
}
String getDurationFullyQualifiedName() {
return durationFullyQualifiedName;
}
}
private static final Matcher<ExpressionTree> JAVA_TIME_MATCHER =
staticMethod().onClass(Api.JAVA.getDurationFullyQualifiedName());
private static final Matcher<ExpressionTree> JODA_MATCHER =
staticMethod().onClass(Api.JODA.getDurationFullyQualifiedName());
private static final ImmutableTable<Api, ChronoUnit, String> FACTORIES =
ImmutableTable.<Api, ChronoUnit, String>builder()
.put(Api.JAVA, ChronoUnit.DAYS, "ofDays")
.put(Api.JAVA, ChronoUnit.HOURS, "ofHours")
.put(Api.JAVA, ChronoUnit.MINUTES, "ofMinutes")
.put(Api.JAVA, ChronoUnit.SECONDS, "ofSeconds")
.put(Api.JAVA, ChronoUnit.MILLIS, "ofMillis")
.put(Api.JAVA, ChronoUnit.NANOS, "ofNanos")
.put(Api.JODA, ChronoUnit.DAYS, "standardDays")
.put(Api.JODA, ChronoUnit.HOURS, "standardHours")
.put(Api.JODA, ChronoUnit.MINUTES, "standardMinutes")
.put(Api.JODA, ChronoUnit.SECONDS, "standardSeconds")
.buildOrThrow();
private static final ImmutableMap<String, TemporalUnit> METHOD_NAME_TO_UNIT =
FACTORIES.rowMap().values().stream()
.flatMap(x -> x.entrySet().stream())
.collect(toImmutableMap(x -> x.getValue(), x -> x.getKey()));
private static final ImmutableMap<ChronoUnit, Converter<Duration, Long>> CONVERTERS =
ImmutableMap.<ChronoUnit, Converter<Duration, Long>>builder()
.put(ChronoUnit.DAYS, Converter.from(Duration::toDays, Duration::ofDays))
.put(ChronoUnit.HOURS, Converter.from(Duration::toHours, Duration::ofHours))
.put(ChronoUnit.MINUTES, Converter.from(Duration::toMinutes, Duration::ofMinutes))
.put(ChronoUnit.SECONDS, Converter.from(Duration::getSeconds, Duration::ofSeconds))
.put(ChronoUnit.MILLIS, Converter.from(Duration::toMillis, Duration::ofMillis))
.put(ChronoUnit.NANOS, Converter.from(Duration::toNanos, Duration::ofNanos))
.buildOrThrow();
// Represent a single day/hour/minute as hours/minutes/seconds is sometimes used to allow a block
// of durations to have consistent units.
private static final ImmutableMap<TemporalUnit, Long> BANLIST =
ImmutableMap.of(
ChronoUnit.HOURS, 24L,
ChronoUnit.MINUTES, 60L,
ChronoUnit.SECONDS, 60L);
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
Api api;
if (JAVA_TIME_MATCHER.matches(tree, state)) {
api = Api.JAVA;
} else if (JODA_MATCHER.matches(tree, state)) {
api = Api.JODA;
} else {
return NO_MATCH;
}
if (tree.getArguments().size() != 1) {
// TODO(cushon): ofSeconds w/ nano adjustment?
return NO_MATCH;
}
List<MethodInvocationTree> allInvocationsInParentExpression =
getAllInvocationsInParentExpression(state);
if (allInvocationsInParentExpression.isEmpty()) {
return NO_MATCH;
}
List<Number> constValues =
allInvocationsInParentExpression.stream()
.map(t -> getOnlyElement(t.getArguments()))
.map(arg -> entirelyLiterals(arg) ? arg : null)
.map(arg -> constValue(arg, Number.class))
.collect(toList());
if (constValues.stream().anyMatch(Objects::isNull)) {
return NO_MATCH;
}
if (constValues.stream().mapToLong(Number::longValue).allMatch(v -> v == 0L)) {
return handleAllZeros(state, api, allInvocationsInParentExpression);
}
MethodSymbol sym = getSymbol(tree);
if (!METHOD_NAME_TO_UNIT.containsKey(sym.getSimpleName().toString())) {
return NO_MATCH;
}
TemporalUnit unit = METHOD_NAME_TO_UNIT.get(sym.getSimpleName().toString());
Long banListValue = BANLIST.get(unit);
if (banListValue != null
&& constValues.stream()
.anyMatch(value -> Objects.equals(banListValue, value.longValue()))) {
return NO_MATCH;
}
List<Duration> durations =
constValues.stream().map(value -> Duration.of(value.longValue(), unit)).collect(toList());
// Iterate over all possible units from largest to smallest (days to nanos) until we find the
// largest unit that can be used to exactly express the duration.
for (Map.Entry<ChronoUnit, Converter<Duration, Long>> entry : CONVERTERS.entrySet()) {
ChronoUnit nextUnit = entry.getKey();
if (unit.equals(nextUnit)) {
// We reached the original unit, no simplification is possible.
break;
}
Converter<Duration, Long> converter = entry.getValue();
List<Duration> roundTripped =
durations.stream()
.map(converter::convert)
.map(converter.reverse()::convert)
.collect(toList());
if (roundTripped.equals(durations)) {
// We reached a larger than original unit that precisely expresses the duration, rewrite to
// use it instead.
for (int i = 0; i < allInvocationsInParentExpression.size(); i++) {
MethodInvocationTree m = allInvocationsInParentExpression.get(i);
long nextValue = converter.convert(durations.get(i));
String name = FACTORIES.get(api, nextUnit);
String replacement =
String.format("%s(%d%s)", name, nextValue, nextValue == ((int) nextValue) ? "" : "L");
ExpressionTree receiver = getReceiver(m);
if (receiver == null) { // static import of the method
SuggestedFix fix =
SuggestedFix.builder()
.addStaticImport(api.getDurationFullyQualifiedName() + "." + name)
.replace(m, replacement)
.build();
state.reportMatch(describeMatch(m, fix));
} else {
state.reportMatch(
describeMatch(
m,
SuggestedFix.replace(
state.getEndPosition(receiver),
state.getEndPosition(m),
"." + replacement)));
}
}
return Description.NO_MATCH;
}
}
return NO_MATCH;
}
private static boolean entirelyLiterals(ExpressionTree arg) {
AtomicBoolean anyNonLiterals = new AtomicBoolean();
new TreeScanner<Void, Void>() {
@Override
public Void scan(Tree tree, Void unused) {
if (!(tree instanceof LiteralTree) && !(tree instanceof BinaryTree)) {
anyNonLiterals.set(true);
}
return super.scan(tree, null);
}
}.scan(arg, null);
return !anyNonLiterals.get();
}
private Description handleAllZeros(
VisitorState state, Api api, List<MethodInvocationTree> allInvocationsInParentExpression) {
switch (api) {
case JODA:
for (MethodInvocationTree tree : allInvocationsInParentExpression) {
ExpressionTree receiver = getReceiver(tree);
SuggestedFix fix;
if (receiver == null) { // static import of the method
fix =
SuggestedFix.builder()
.addImport(api.getDurationFullyQualifiedName())
.replace(tree, "Duration.ZERO")
.build();
} else {
fix =
SuggestedFix.replace(
state.getEndPosition(getReceiver(tree)), state.getEndPosition(tree), ".ZERO");
}
state.reportMatch(
buildDescription(tree)
.setMessage(
"Duration can be expressed more clearly without units, as Duration.ZERO")
.addFix(fix)
.build());
}
return NO_MATCH;
case JAVA:
// don't rewrite e.g. `ofMillis(0)` to `ofDays(0)`
return NO_MATCH;
}
throw new AssertionError(api);
}
private static List<MethodInvocationTree> getAllInvocationsInParentExpression(
VisitorState state) {
// Walk up the tree path until the parent tree is no longer an expression.
TreePath expressionPath = state.getPath();
while (true) {
TreePath parentPath = expressionPath.getParentPath();
if (parentPath == null) {
break;
}
if (!(expressionPath.getParentPath().getLeaf() instanceof ExpressionTree)) {
break;
}
expressionPath = parentPath;
}
// This check gets run on all invocations of the duration methods, but we propose fixes for
// all things in the same expression. As such, we detect if we are the first invocation of the
// method, and if not, we don't check any further, because all trees will be checked when the
// first invocation is checked.
AtomicBoolean notFirst = new AtomicBoolean();
// Scan the tree for invocations of the same method.
MethodInvocationTree tree = (MethodInvocationTree) state.getPath().getLeaf();
MethodSymbol methodSymbol = getSymbol(tree);
List<MethodInvocationTree> sameMethodInvocations = new ArrayList<>();
new TreeScanner<Void, Void>() {
@Override
public Void scan(Tree node, Void unused) {
if (notFirst.get()) {
return null;
}
return super.scan(node, unused);
}
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void unused) {
if (Objects.equals(methodSymbol, ASTHelpers.getSymbol(node))) {
if (sameMethodInvocations.isEmpty()) {
if (!Objects.equals(node, tree)) {
notFirst.set(true);
return null;
}
}
sameMethodInvocations.add(node);
return super.visitMethodInvocation(node, unused);
}
return super.visitMethodInvocation(node, unused);
}
}.scan(expressionPath.getLeaf(), null);
if (notFirst.get()) {
sameMethodInvocations.clear();
}
return sameMethodInvocations;
}
}
| 12,836
| 38.743034
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JUnit4TearDownNotRun.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.JUnitMatchers.JUNIT_AFTER_ANNOTATION;
import static com.google.errorprone.matchers.JUnitMatchers.JUNIT_AFTER_CLASS_ANNOTATION;
import static com.google.errorprone.matchers.JUnitMatchers.JUNIT_BEFORE_ANNOTATION;
import static com.google.errorprone.matchers.JUnitMatchers.JUNIT_BEFORE_CLASS_ANNOTATION;
import static com.google.errorprone.matchers.JUnitMatchers.hasJUnit4AfterAnnotations;
import static com.google.errorprone.matchers.JUnitMatchers.looksLikeJUnit3TearDown;
import static com.google.errorprone.matchers.JUnitMatchers.looksLikeJUnit4After;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.not;
import com.google.errorprone.BugPattern;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.MethodTree;
import java.util.Arrays;
import java.util.List;
/**
* Checks for the existence of a JUnit3 style tearDown() method in a JUnit4 test class or methods
* annotated with a non-JUnit4 @After annotation.
*
* @author glorioso@google.com (Nick Glorioso)
*/
@BugPattern(
summary = "tearDown() method will not be run; please add JUnit's @After annotation",
severity = ERROR)
public class JUnit4TearDownNotRun extends AbstractJUnit4InitMethodNotRun {
@Override
protected Matcher<MethodTree> methodMatcher() {
return allOf(
anyOf(looksLikeJUnit3TearDown, looksLikeJUnit4After), not(hasJUnit4AfterAnnotations));
}
@Override
protected String correctAnnotation() {
return JUNIT_AFTER_ANNOTATION;
}
@Override
protected List<AnnotationReplacements> annotationReplacements() {
return Arrays.asList(
new AnnotationReplacements(JUNIT_BEFORE_ANNOTATION, JUNIT_AFTER_ANNOTATION),
new AnnotationReplacements(JUNIT_BEFORE_CLASS_ANNOTATION, JUNIT_AFTER_CLASS_ANNOTATION));
}
}
| 2,649
| 39.769231
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/WildcardImport.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.SUGGESTION;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Scope.StarImportScope;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.TreeScanner;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.lang.model.element.ElementKind;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Wildcard imports, static or otherwise, should not be used",
severity = SUGGESTION,
linkType = CUSTOM,
documentSuppression = false,
tags = StandardTags.STYLE,
link = "https://google.github.io/styleguide/javaguide.html?cl=head#s3.3.1-wildcard-imports")
public class WildcardImport extends BugChecker implements CompilationUnitTreeMatcher {
private static final Logger logger = Logger.getLogger(WildcardImport.class.getName());
/** Maximum number of members to import before switching to qualified names. */
public static final int MAX_MEMBER_IMPORTS = 20;
/** A type or member that needs to be imported. */
@AutoValue
abstract static class TypeToImport {
/** Returns the simple name of the import. */
abstract String name();
/** Returns the owner of the imported type or member. */
abstract Symbol owner();
/** Returns true if the import needs to be static (i.e. the import is for a field or method). */
abstract boolean isStatic();
static TypeToImport create(String name, Symbol owner, boolean stat) {
return new AutoValue_WildcardImport_TypeToImport(name, owner, stat);
}
private void addFix(SuggestedFix.Builder fix) {
String qualifiedName = owner().getQualifiedName() + "." + name();
if (isStatic()) {
fix.addStaticImport(qualifiedName);
} else {
fix.addImport(qualifiedName);
}
}
}
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
ImmutableList<ImportTree> wildcardImports = getWildcardImports(tree.getImports());
if (wildcardImports.isEmpty()) {
return NO_MATCH;
}
// Find all of the types that need to be imported.
Set<TypeToImport> typesToImport = ImportCollector.collect((JCCompilationUnit) tree);
Fix fix = createFix(wildcardImports, typesToImport, state);
if (fix.isEmpty()) {
return NO_MATCH;
}
return describeMatch(wildcardImports.get(0), fix);
}
/** Collect all on demand imports. */
private static ImmutableList<ImportTree> getWildcardImports(List<? extends ImportTree> imports) {
ImmutableList.Builder<ImportTree> result = ImmutableList.builder();
for (ImportTree tree : imports) {
// javac represents on-demand imports as a member select where the selected name is '*'.
Tree ident = tree.getQualifiedIdentifier();
if (!(ident instanceof MemberSelectTree)) {
continue;
}
MemberSelectTree select = (MemberSelectTree) ident;
if (select.getIdentifier().contentEquals("*")) {
result.add(tree);
}
}
return result.build();
}
/** Collects all uses of on demand-imported types and static members in a compilation unit. */
static class ImportCollector extends TreeScanner {
private final StarImportScope wildcardScope;
private final Set<TypeToImport> seen = new LinkedHashSet<>();
ImportCollector(StarImportScope wildcardScope) {
this.wildcardScope = wildcardScope;
}
public static Set<TypeToImport> collect(JCCompilationUnit tree) {
ImportCollector collector = new ImportCollector(tree.starImportScope);
collector.scan(tree);
return collector.seen;
}
@Override
public void visitImport(JCTree.JCImport tree) {
// skip imports
}
@Override
public void visitMethodDef(JCTree.JCMethodDecl method) {
if (ASTHelpers.isGeneratedConstructor(method)) {
// Skip types in the signatures of synthetic constructors
scan(method.body);
} else {
super.visitMethodDef(method);
}
}
@Override
public void visitIdent(JCIdent tree) {
Symbol sym = tree.sym;
if (sym == null) {
return;
}
sym = sym.baseSymbol();
if (wildcardScope.includes(sym)) {
if (sym.owner.getQualifiedName().contentEquals("java.lang")) {
return;
}
switch (sym.kind) {
case TYP:
seen.add(
TypeToImport.create(sym.getSimpleName().toString(), sym.owner, /* stat= */ false));
break;
case VAR:
case MTH:
seen.add(
TypeToImport.create(sym.getSimpleName().toString(), sym.owner, /* stat= */ true));
break;
default:
return;
}
}
}
}
/** Creates a {@link Fix} that replaces wildcard imports. */
static Fix createFix(
ImmutableList<ImportTree> wildcardImports,
Set<TypeToImport> typesToImport,
VisitorState state) {
Map<Symbol, List<TypeToImport>> toFix =
typesToImport.stream().collect(Collectors.groupingBy(TypeToImport::owner));
SuggestedFix.Builder fix = SuggestedFix.builder();
for (ImportTree importToDelete : wildcardImports) {
String importSpecification = state.getSourceForNode(importToDelete.getQualifiedIdentifier());
if (importToDelete.isStatic()) {
fix.removeStaticImport(importSpecification);
} else {
fix.removeImport(importSpecification);
}
}
for (Map.Entry<Symbol, List<TypeToImport>> entry : toFix.entrySet()) {
Symbol owner = entry.getKey();
if (entry.getKey().getKind() != ElementKind.PACKAGE
&& entry.getValue().size() > MAX_MEMBER_IMPORTS) {
qualifiedNameFix(fix, owner, state);
} else {
for (TypeToImport toImport : entry.getValue()) {
toImport.addFix(fix);
}
}
}
return fix.build();
}
private static final MethodHandle CONSTANT_CASE_LABEL_TREE_GET_EXPRESSION;
static {
MethodHandle h;
try {
Class<?> constantCaseLabelTree = Class.forName("com.sun.source.tree.ConstantCaseLabelTree");
h =
MethodHandles.lookup()
.findVirtual(
constantCaseLabelTree,
"getConstantExpression",
MethodType.methodType(ExpressionTree.class));
} catch (ReflectiveOperationException e) {
h = null;
}
CONSTANT_CASE_LABEL_TREE_GET_EXPRESSION = h;
}
/**
* Add an import for {@code owner}, and qualify all on demand imported references to members of
* owner by owner's simple name.
*/
private static void qualifiedNameFix(SuggestedFix.Builder fix, Symbol owner, VisitorState state) {
fix.addImport(owner.getQualifiedName().toString());
JCCompilationUnit unit = (JCCompilationUnit) state.getPath().getCompilationUnit();
new TreePathScanner<Void, Void>() {
@Override
public Void visitIdentifier(IdentifierTree tree, Void unused) {
Symbol sym = ASTHelpers.getSymbol(tree);
if (sym == null) {
return null;
}
Tree parent = getCurrentPath().getParentPath().getLeaf();
if (sym.owner.getKind() == ElementKind.ENUM) {
if (parent.getKind() == Tree.Kind.CASE
&& ((CaseTree) parent).getExpression().equals(tree)) {
// switch cases can refer to enum constants by simple name without importing them
return null;
}
// In JDK 19, the tree representation of enum case-labels changes. We can't reference the
// relevant API directly because then this code wouldn't compile on earlier JDK versions.
// So instead we use method handles. The straightforward code would be:
// if (parent.getKind() == Tree.Kind.CONSTANT_CASE_LABEL
// && tree.equals(((ConstantCaseLabelTree) parent).getConstantExpression())) {...}
if (parent.getKind().name().equals("CONSTANT_CASE_LABEL")) {
try {
if (tree.equals(CONSTANT_CASE_LABEL_TREE_GET_EXPRESSION.invoke(parent))) {
return null;
}
} catch (Throwable e) {
// MethodHandle.invoke obliges us to catch Throwable here.
logger.log(Level.SEVERE, "Could not compare trees", e);
}
}
}
if (sym.owner.equals(owner) && unit.starImportScope.includes(sym)) {
fix.prefixWith(tree, owner.getSimpleName() + ".");
}
return null;
}
}.scan(unit, null);
}
}
| 10,594
| 36.045455
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ConstantPatternCompile.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.base.CaseFormat.LOWER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFixes.renameVariableUsages;
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.google.errorprone.util.ASTHelpers.canBeRemoved;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isInStaticInitializer;
import static com.google.errorprone.util.ASTHelpers.isStatic;
import static java.lang.String.format;
import com.google.common.base.Ascii;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multiset;
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.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.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.Flags;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.util.Optional;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Flags variables initialized with {@link java.util.regex.Pattern#compile(String)} calls that could
* be constants.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary = "Variables initialized with Pattern#compile calls on constants can be constants",
severity = WARNING)
public final class ConstantPatternCompile extends BugChecker implements ClassTreeMatcher {
private static final ImmutableList<String> PATTERN_CLASSES =
ImmutableList.of("java.util.regex.Pattern", "com.google.re2j.Pattern");
private static final Matcher<ExpressionTree> PATTERN_COMPILE_CHECK =
staticMethod().onClassAny(PATTERN_CLASSES).named("compile");
private static final Matcher<ExpressionTree> MATCHER_MATCHER =
instanceMethod().onExactClassAny(PATTERN_CLASSES).named("matcher");
@Override
public Description matchClass(ClassTree classTree, VisitorState state) {
NameUniquifier nameUniquifier = new NameUniquifier();
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
Tree[] firstHit = new Tree[1];
for (Tree member : classTree.getMembers()) {
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitClass(ClassTree node, Void unused) {
// Don't descend into nested classes - we'll visit them later
return null;
}
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
tryFix(tree, state.withPath(getCurrentPath()), nameUniquifier)
.ifPresent(
other -> {
fixBuilder.merge(other);
if (firstHit[0] == null) {
firstHit[0] = tree;
}
});
return super.visitMethodInvocation(tree, unused);
}
private Optional<SuggestedFix> tryFix(
MethodInvocationTree tree, VisitorState state, NameUniquifier nameUniquifier) {
if (!PATTERN_COMPILE_CHECK.matches(tree, state)) {
return Optional.empty();
}
if (!tree.getArguments().stream()
.allMatch(ConstantPatternCompile::isArgStaticAndConstant)) {
return Optional.empty();
}
if (state.errorProneOptions().isTestOnlyTarget()) {
return Optional.empty();
}
if (isInStaticInitializer(state)) {
return Optional.empty();
}
Tree parent = state.getPath().getParentPath().getLeaf();
if (parent instanceof VariableTree) {
return handleVariable((VariableTree) parent, state);
}
return Optional.of(handleInlineExpression(tree, state, nameUniquifier));
}
}.scan(new TreePath(state.getPath(), member), null);
}
if (firstHit[0] == null) {
return NO_MATCH;
}
return describeMatch(firstHit[0], fixBuilder.build());
}
private static SuggestedFix handleInlineExpression(
MethodInvocationTree tree, VisitorState state, NameUniquifier nameUniquifier) {
String nameSuggestion =
nameUniquifier.uniquify(
Optional.ofNullable(findNameFromMatcherArgument(state, state.getPath()))
.orElse("PATTERN"));
SuggestedFix.Builder fix = SuggestedFix.builder();
return fix.replace(tree, nameSuggestion)
.merge(
SuggestedFixes.addMembers(
state.findEnclosing(ClassTree.class),
state,
format(
"private static final %s %s = %s;",
SuggestedFixes.qualifyType(state, fix, getSymbol(tree).getReturnType().tsym),
nameSuggestion,
state.getSourceForNode(tree))))
.build();
}
private static Optional<SuggestedFix> handleVariable(VariableTree tree, VisitorState state) {
MethodTree outerMethodTree = ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class);
if (outerMethodTree == null) {
return Optional.empty();
}
VarSymbol sym = getSymbol(tree);
switch (sym.getKind()) {
case RESOURCE_VARIABLE:
return Optional.of(SuggestedFix.emptyFix());
case LOCAL_VARIABLE:
return Optional.of(fixLocal(tree, outerMethodTree, state));
default:
return Optional.empty();
}
}
private static SuggestedFix fixLocal(
VariableTree tree, MethodTree outerMethodTree, VisitorState state) {
SuggestedFix fix = replaceRegexConstant(tree, state);
if (!fix.isEmpty()) {
return fix;
}
String name = inferName(tree, state);
if (name == null) {
return SuggestedFix.emptyFix();
}
MethodSymbol methodSymbol = getSymbol(outerMethodTree);
boolean canUseStatic =
methodSymbol.owner.enclClass().getNestingKind() == NestingKind.TOP_LEVEL
|| outerMethodTree.getModifiers().getFlags().contains(Modifier.STATIC);
String replacement =
String.format(
"private %s final %s %s = %s;",
canUseStatic ? "static " : "",
state.getSourceForNode(tree.getType()),
name,
state.getSourceForNode(tree.getInitializer()));
return SuggestedFix.builder()
.merge(renameVariableUsages(tree, name, state))
.postfixWith(outerMethodTree, replacement)
.delete(tree)
.build();
}
/**
* If the pattern variable is initialized with a regex from a {@code private static final String}
* constant, and the constant is only used once, store the {@code Pattern} in the existing
* constant.
*
* <p>Before:
*
* <pre>{@code
* private static final String MY_REGEX = "a+";
* ...
* Pattern p = Pattern.compile(MY_REGEX);
* p.matcher(...);
* }</pre>
*
* <p>After:
*
* <pre>{@code
* private static final Pattern MY_REGEX = Pattern.compile("a+");
* ...
* MY_REGEX.matcher(...);
* }</pre>
*/
private static SuggestedFix replaceRegexConstant(VariableTree tree, VisitorState state) {
ExpressionTree regex = ((MethodInvocationTree) tree.getInitializer()).getArguments().get(0);
Symbol regexSym = getSymbol(regex);
if (regexSym == null
|| !regexSym.getKind().equals(ElementKind.FIELD)
|| !isStatic(regexSym)
|| !regexSym.getModifiers().contains(Modifier.FINAL)
|| !canBeRemoved((VarSymbol) regexSym)) {
return SuggestedFix.emptyFix();
}
VariableTree[] defs = {null};
int[] uses = {0};
new TreeScanner<Void, Void>() {
@Override
public Void visitVariable(VariableTree tree, Void unused) {
if (regexSym.equals(getSymbol(tree))) {
defs[0] = tree;
}
return super.visitVariable(tree, null);
}
@Override
public Void visitIdentifier(IdentifierTree tree, Void unused) {
if (regexSym.equals(getSymbol(tree))) {
uses[0]++;
}
return super.visitIdentifier(tree, null);
}
@Override
public Void visitMemberSelect(MemberSelectTree tree, Void unused) {
if (regexSym.equals(getSymbol(tree))) {
uses[0]++;
}
return super.visitMemberSelect(tree, null);
}
}.scan(state.getPath().getCompilationUnit(), null);
if (uses[0] != 1) {
return SuggestedFix.emptyFix();
}
VariableTree def = defs[0];
return SuggestedFix.builder()
.replace(def.getType(), state.getSourceForNode(tree.getType()))
.prefixWith(
def.getInitializer(),
state
.getSourceCode()
.subSequence(getStartPosition(tree.getInitializer()), getStartPosition(regex))
.toString())
.postfixWith(def.getInitializer(), ")")
.merge(renameVariableUsages(tree, def.getName().toString(), state))
.delete(tree)
.build();
}
/** Infer a name when upgrading the {@code Pattern} local to a constant. */
private static @Nullable String inferName(VariableTree tree, VisitorState state) {
String name;
if ((name = fromName(tree)) != null) {
return name;
}
if ((name = fromInitializer(tree)) != null) {
return name;
}
if ((name = fromUse(tree, state)) != null) {
return name;
}
return null;
}
/** Use the existing local variable's name, unless it's terrible. */
private static @Nullable String fromName(VariableTree tree) {
String name = LOWER_CAMEL.to(UPPER_UNDERSCORE, tree.getName().toString());
if (name.length() > 1 && !name.equals("PATTERN")) {
return name;
}
return null;
}
/**
* If the pattern is initialized from an existing constant, re-use its name.
*
* <p>e.g. use {@code FOO_PATTERN} for {@code Pattern.compile(FOO)} and {@code
* Pattern.compile(FOO_REGEX)}.
*/
private static @Nullable String fromInitializer(VariableTree tree) {
ExpressionTree regex = ((MethodInvocationTree) tree.getInitializer()).getArguments().get(0);
if (!(regex instanceof IdentifierTree)) {
return null;
}
String name = ((IdentifierTree) regex).getName().toString();
if (name.endsWith("_REGEX")) {
name = name.substring(0, name.length() - "_REGEX".length());
}
if (name.endsWith("_PATTERN")) {
// Give up if we have something like Pattern.compile(FOO_PATTERN),
// we don't want to name the regex FOO_PATTERN_PATTERN.
return null;
}
return name + "_PATTERN";
}
/**
* If the pattern is only used once in a call to {@code matcher}, and the argument is a variable,
* use that variable's name. For example, infer {@code FOO_PATTERN} from {@code
* pattern.matcher(foo)}. If the argument to the call is a method call, use the method's name.
*/
private static @Nullable String fromUse(VariableTree tree, VisitorState state) {
VarSymbol sym = getSymbol(tree);
ImmutableList.Builder<TreePath> usesBuilder = ImmutableList.builder();
new TreePathScanner<Void, Void>() {
@Override
public Void visitIdentifier(IdentifierTree tree, Void unused) {
if (sym.equals(getSymbol(tree))) {
usesBuilder.add(getCurrentPath());
}
return null;
}
}.scan(state.getPath().getCompilationUnit(), null);
ImmutableList<TreePath> uses = usesBuilder.build();
if (uses.size() != 1) {
return null;
}
TreePath use = getOnlyElement(uses);
return findNameFromMatcherArgument(state, use);
}
/**
* If the path at {@code use} is a Pattern object whose .matcher method is being called on a
* variable CharSequence, returns the name of that variable.
*/
private static @Nullable String findNameFromMatcherArgument(VisitorState state, TreePath use) {
Tree grandParent = use.getParentPath().getParentPath().getLeaf();
if (!(grandParent instanceof ExpressionTree)) {
return null;
}
if (!MATCHER_MATCHER.matches((ExpressionTree) grandParent, state)) {
return null;
}
ExpressionTree matchTree = ((MethodInvocationTree) grandParent).getArguments().get(0);
if (matchTree instanceof IdentifierTree) {
return convertToConstantName(((IdentifierTree) matchTree).getName().toString());
}
if (matchTree instanceof MethodInvocationTree) {
return convertToConstantName(
getSymbol((MethodInvocationTree) matchTree).getSimpleName().toString());
}
return null;
}
private static String convertToConstantName(String variableName) {
String root =
variableName.equals(Ascii.toUpperCase(variableName))
? variableName
: LOWER_CAMEL.to(UPPER_UNDERSCORE, variableName);
return root + "_PATTERN";
}
private static boolean isArgStaticAndConstant(ExpressionTree arg) {
if (ASTHelpers.constValue(arg) == null) {
return false;
}
Symbol argSymbol = getSymbol(arg);
if (argSymbol == null) {
return true;
}
return (argSymbol.flags() & Flags.STATIC) != 0;
}
// TODO(b/250568455): Make this more widely available.
private static final class NameUniquifier {
final Multiset<String> assignmentCounts = HashMultiset.create();
String uniquify(String name) {
int numPreviousUses = assignmentCounts.add(name, 1);
if (numPreviousUses == 0) {
return name;
}
return name + (numPreviousUses + 1);
}
}
}
| 15,359
| 36.463415
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ThreadJoinLoop.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.matchers.Matchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
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.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.AssignmentTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.EmptyStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TryTree;
import com.sun.source.tree.WhileLoopTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Type;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author mariasam@google.com (Maria Sam)
*/
@BugPattern(
summary =
"Thread.join needs to be immediately surrounded by a loop until it succeeds. "
+ "Consider using Uninterruptibles.joinUninterruptibly.",
severity = SeverityLevel.WARNING)
public class ThreadJoinLoop extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MATCH_THREAD_JOIN =
instanceMethod().onDescendantOf("java.lang.Thread").named("join");
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState state) {
String threadString;
if (methodInvocationTree.getMethodSelect() instanceof MemberSelectTree) {
threadString =
state.getSourceForNode(
((MemberSelectTree) methodInvocationTree.getMethodSelect()).getExpression());
} else {
threadString = "this";
}
// if it is thread.join with a timeout, ignore (too many special cases in codebase
// with calculating time with declared variables)
if (!methodInvocationTree.getArguments().isEmpty()) {
return Description.NO_MATCH;
}
if (!MATCH_THREAD_JOIN.matches(methodInvocationTree, state)) {
return Description.NO_MATCH;
}
TreePath tryTreePath =
ASTHelpers.findPathFromEnclosingNodeToTopLevel(state.getPath(), TryTree.class);
if (tryTreePath == null) {
return Description.NO_MATCH;
}
WhileLoopTree pathToLoop = ASTHelpers.findEnclosingNode(tryTreePath, WhileLoopTree.class);
// checks to make sure that if there is a while loop with only one statement (the try catch
// block)
boolean hasWhileLoopOneStatement = false;
if (pathToLoop != null) {
Tree statements = pathToLoop.getStatement();
if (statements instanceof BlockTree && ((BlockTree) statements).getStatements().size() == 1) {
hasWhileLoopOneStatement = true;
}
}
// Scans the try tree block for any other method invocations so that we do not accidentally
// delete important actions when replacing.
TryTree tryTree = (TryTree) tryTreePath.getLeaf();
if (hasOtherInvocationsOrAssignments(methodInvocationTree, tryTree, state)) {
return Description.NO_MATCH;
}
if (tryTree.getFinallyBlock() != null) {
return Description.NO_MATCH;
}
Type interruptedType = state.getSymtab().interruptedExceptionType;
for (CatchTree tree : tryTree.getCatches()) {
Type typeSym = getType(tree.getParameter().getType());
if (ASTHelpers.isCastable(typeSym, interruptedType, state)) {
// replaces the while loop with the try block or replaces just the try block
if (tree.getBlock().getStatements().stream()
.allMatch(s -> s instanceof EmptyStatementTree)) {
SuggestedFix.Builder fix = SuggestedFix.builder();
String uninterruptibles =
SuggestedFixes.qualifyType(
state, fix, "com.google.common.util.concurrent.Uninterruptibles");
fix.replace(
hasWhileLoopOneStatement ? pathToLoop : tryTree,
String.format("%s.joinUninterruptibly(%s);", uninterruptibles, threadString));
return describeMatch(methodInvocationTree, fix.build());
}
}
}
return Description.NO_MATCH;
}
private static boolean hasOtherInvocationsOrAssignments(
MethodInvocationTree methodInvocationTree, TryTree tryTree, VisitorState state) {
AtomicInteger count = new AtomicInteger(0);
Type threadType = JAVA_LANG_THREAD.get(state);
new TreeScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
if (!tree.equals(methodInvocationTree)) {
count.incrementAndGet();
}
return super.visitMethodInvocation(tree, null);
}
@Override
public Void visitAssignment(AssignmentTree tree, Void unused) {
if (isSubtype(getType(tree.getVariable()), threadType, state)) {
count.incrementAndGet();
}
return super.visitAssignment(tree, null);
}
}.scan(tryTree.getBlock(), null);
return count.get() > 0;
}
private static final Supplier<Type> JAVA_LANG_THREAD =
VisitorState.memoize(state -> state.getTypeFromString("java.lang.Thread"));
}
| 6,298
| 40.169935
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/FloatCast.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.Sets.immutableEnumSet;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.TypeCastTreeMatcher;
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.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Symtab;
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 = "Use parentheses to make the precedence explicit", severity = WARNING)
public class FloatCast extends BugChecker implements TypeCastTreeMatcher {
private static final ImmutableSet<TypeKind> INTEGRAL =
immutableEnumSet(TypeKind.LONG, TypeKind.INT);
private static final Matcher<ExpressionTree> IGNORED_METHODS =
staticMethod().onClass("java.lang.Math").namedAnyOf("floor", "ceil", "signum", "rint");
private static final Matcher<ExpressionTree> POW =
staticMethod().onClass("java.lang.Math").named("pow");
@Override
public Description matchTypeCast(TypeCastTree tree, VisitorState state) {
Tree parent = state.getPath().getParentPath().getLeaf();
if (!(parent instanceof BinaryTree)) {
return NO_MATCH;
}
BinaryTree binop = (BinaryTree) parent;
if (!binop.getLeftOperand().equals(tree)) {
// the precedence is unambiguous for e.g. `i + (int) f`
return NO_MATCH;
}
if (binop.getKind() != Kind.MULTIPLY) {
// there's a bound on the imprecision for +, -, /
return NO_MATCH;
}
Type castType = ASTHelpers.getType(tree.getType());
Type operandType = ASTHelpers.getType(tree.getExpression());
if (castType == null || operandType == null) {
return NO_MATCH;
}
Symtab symtab = state.getSymtab();
if (isSameType(ASTHelpers.getType(parent), symtab.stringType, state)) {
// string concatenation doesn't count
return NO_MATCH;
}
switch (castType.getKind()) {
case LONG:
case INT:
case SHORT:
case CHAR:
case BYTE:
break;
default:
return NO_MATCH;
}
switch (operandType.getKind()) {
case FLOAT:
case DOUBLE:
break;
default:
return NO_MATCH;
}
if (IGNORED_METHODS.matches(tree.getExpression(), state)) {
return NO_MATCH;
}
if (POW.matches(tree.getExpression(), state)) {
MethodInvocationTree pow = (MethodInvocationTree) tree.getExpression();
if (pow.getArguments().stream()
.map(ASTHelpers::getType)
.filter(x -> x != null)
.map(state.getTypes()::unboxedTypeOrType)
.map(Type::getKind)
.allMatch(INTEGRAL::contains)) {
return NO_MATCH;
}
}
// Find the outermost enclosing binop, to suggest e.g. `(long) (f * a * b)` instead of
// `(long) (f * a) * b`.
Tree enclosing = binop;
TreePath path = state.getPath().getParentPath().getParentPath();
while (path != null) {
if (!(path.getLeaf() instanceof BinaryTree)) {
break;
}
BinaryTree enclosingBinop = (BinaryTree) path.getLeaf();
if (!enclosingBinop.getLeftOperand().equals(enclosing)) {
break;
}
enclosing = enclosingBinop;
path = path.getParentPath();
}
return buildDescription(tree)
.addFix(
SuggestedFix.builder()
.prefixWith(tree.getExpression(), "(")
.postfixWith(enclosing, ")")
.build())
.addFix(SuggestedFix.builder().prefixWith(tree, "(").postfixWith(tree, ")").build())
.build();
}
}
| 5,046
| 35.572464
| 93
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AbstractAsKeyOfSetOrMap.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.matchers.Matchers.anyOf;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
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 com.sun.source.tree.NewClassTree;
import com.sun.tools.javac.code.Type;
import java.util.List;
/**
* Check for usage of {@code Set<T>} or {@code Map<T, E>}.
*
* @author seibelsabrina@google.com (Sabrina Seibel)
*/
public abstract class AbstractAsKeyOfSetOrMap extends BugChecker
implements MethodInvocationTreeMatcher, NewClassTreeMatcher {
private static final Matcher<ExpressionTree> CONSTRUCTS_SET =
anyOf(
MethodMatchers.staticMethod()
.onClass("com.google.common.collect.Sets")
.named("newHashSet"),
Matchers.constructor().forClass("java.util.HashSet"));
private static final Matcher<ExpressionTree> CONSTRUCTS_MULTISET =
anyOf(
MethodMatchers.staticMethod()
.onClass("com.google.common.collect.HashMultiset")
.named("create")
.withNoParameters(),
MethodMatchers.staticMethod()
.onClass("com.google.common.collect.LinkedHashMultiset")
.named("create"));
private static final Matcher<ExpressionTree> CONSTRUCTS_MAP =
anyOf(
MethodMatchers.staticMethod()
.onClass("com.google.common.collect.Maps")
.named("newHashMap"),
Matchers.constructor().forClass("java.util.HashMap"),
MethodMatchers.staticMethod()
.onClass("com.google.common.collect.Maps")
.named("newLinkedHashMap"),
Matchers.constructor().forClass("java.util.LinkedHashMap"),
Matchers.constructor().forClass("java.util.concurrent.ConcurrentHashMap"),
MethodMatchers.staticMethod()
.onClass("com.google.common.collect.HashBiMap")
.named("create"));
private static final Matcher<ExpressionTree> CONSTRUCTS_MULTIMAP =
anyOf(
MethodMatchers.staticMethod()
.onClass("com.google.common.collect.HashMultimap")
.named("create"),
MethodMatchers.staticMethod()
.onClass("com.google.common.collect.LinkedHashMultimap")
.named("create"),
MethodMatchers.staticMethod()
.onClass("com.google.common.collect.ArrayListMultimap")
.named("create"),
MethodMatchers.staticMethod()
.onClass("com.google.common.collect.LinkedListMultimap")
.named("create"));
private static final Matcher<ExpressionTree> CONSTRUCTS_SET_OR_MAP =
anyOf(CONSTRUCTS_SET, CONSTRUCTS_MAP, CONSTRUCTS_MULTIMAP, CONSTRUCTS_MULTISET);
protected abstract boolean isBadType(Type type, VisitorState state);
private Description matchType(ExpressionTree tree, VisitorState state) {
if (CONSTRUCTS_SET_OR_MAP.matches(tree, state)) {
List<Type> argumentTypes = ASTHelpers.getResultType(tree).getTypeArguments();
if (argumentTypes.isEmpty()) {
return Description.NO_MATCH;
}
Type typeArg = argumentTypes.get(0);
if (isBadType(typeArg, state)) {
return describeMatch(tree);
}
}
return Description.NO_MATCH;
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return matchType(tree, state);
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
return matchType(tree, state);
}
}
| 4,611
| 37.756303
| 91
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NewFileSystem.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 com.google.errorprone.BugPattern;
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.matchers.method.MethodMatchers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Starting in JDK 13, this call is ambiguous with FileSystem.newFileSystem(Path,Map)",
severity = WARNING)
public class NewFileSystem extends BugChecker implements BugChecker.MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
MethodMatchers.staticMethod()
.onClass("java.nio.file.FileSystems")
.named("newFileSystem")
.withParameters("java.nio.file.Path", "java.lang.ClassLoader");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
ExpressionTree expressionTree = tree.getArguments().get(1);
if (!expressionTree.getKind().equals(Tree.Kind.NULL_LITERAL)) {
return NO_MATCH;
}
return describeMatch(tree, SuggestedFix.prefixWith(expressionTree, "(ClassLoader) "));
}
}
| 2,218
| 38.625
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SymbolToString.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 static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.toType;
import static com.google.errorprone.predicates.TypePredicates.isDescendantOf;
import static com.google.errorprone.util.ASTHelpers.isBugCheckerCode;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.predicates.TypePredicate;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Type;
import java.util.Optional;
/**
* Flags {@code com.sun.tools.javac.code.Symbol#toString} usage in {@link BugChecker}s.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary = "Symbol#toString shouldn't be used for comparison as it is expensive and fragile.",
severity = SUGGESTION)
public class SymbolToString extends AbstractToString {
private static final TypePredicate IS_SYMBOL = isDescendantOf("com.sun.tools.javac.code.Symbol");
private static final Matcher<Tree> STRING_EQUALS =
toType(
MemberSelectTree.class,
instanceMethod().onExactClass("java.lang.String").named("equals"));
private static boolean symbolToStringInBugChecker(Type type, VisitorState state) {
if (!isBugCheckerCode(state)) {
return false;
}
Tree parentTree = state.getPath().getParentPath().getLeaf();
return IS_SYMBOL.apply(type, state) && STRING_EQUALS.matches(parentTree, state);
}
@Override
protected TypePredicate typePredicate() {
return SymbolToString::symbolToStringInBugChecker;
}
@Override
protected Optional<String> descriptionMessageForDefaultMatch(Type type, VisitorState state) {
return Optional.of("Symbol#toString shouldn't be used as it is expensive and fragile.");
}
@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();
}
}
| 2,942
| 35.333333
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InfiniteRecursion.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.methodCanBeOverridden;
import static com.sun.source.tree.Tree.Kind.CONDITIONAL_AND;
import static com.sun.source.tree.Tree.Kind.CONDITIONAL_OR;
import static com.sun.source.tree.Tree.Kind.IDENTIFIER;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.IfTree;
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.ParenthesizedTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.tree.WhileLoopTree;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "This method always recurses, and will cause a StackOverflowError",
severity = ERROR)
public class InfiniteRecursion extends BugChecker implements MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree declaration, VisitorState state) {
if (declaration.getBody() == null) {
return NO_MATCH;
}
MethodSymbol declaredSymbol = getSymbol(declaration);
new SuppressibleTreePathScanner<Void, Boolean>(state) {
/*
* Once we hit a `return`, we know that any code afterward is not necessarily always executed.
* So we track that and stop reporting infinite recursion afterward.
*/
boolean mayHaveReturned;
@Override
public Void visitReturn(ReturnTree tree, Boolean underConditional) {
super.visitReturn(tree, underConditional);
mayHaveReturned = true;
return null;
}
/*
* Some other code is executed only conditionally. We need to scan such code to look for
* `return` statements, but we don't report infinite recursion for any self-calls there. We
* track this sort of conditional-ness through the scanner's Boolean parameter.
*
* Since we're scanning such code only for `return` statements, there's no need to scan any
* code that contains only expressions (e.g., for a ternary, getTrueExpression()
* and getFalseExpression()).
*/
@Override
public Void visitBinary(BinaryTree tree, Boolean underConditional) {
scan(tree.getLeftOperand(), underConditional);
if (tree.getKind() != CONDITIONAL_AND && tree.getKind() != CONDITIONAL_OR) {
scan(tree.getRightOperand(), underConditional);
} // otherwise, no need to conditionally visit getRightOperand() expression
return null;
}
@Override
public Void visitCase(CaseTree tree, Boolean underConditional) {
return super.visitCase(tree, /*underConditional*/ true);
}
@Override
public Void visitCatch(CatchTree tree, Boolean underConditional) {
/*
* We mostly ignore exceptions. Notably, if a loop would be infinite *except* that it throws
* an exception, we still report it as an infinite loop. But we do want to consider `catch`
* blocks to be conditionally executed, since it would be reasonable for a method to
* delegate to itself (on another object or with a different argument) in case of an
* exception. For example, `toString(COMPLEX)` might fall back to `toString(SIMPLE)`.
*/
return super.visitCatch(tree, /*underConditional*/ true);
}
@Override
public Void visitConditionalExpression(
ConditionalExpressionTree tree, Boolean underConditional) {
scan(tree.getCondition(), underConditional);
// no need to conditionally visit getTrueExpression() and getFalseExpression() expressions
return null;
}
@Override
public Void visitEnhancedForLoop(EnhancedForLoopTree tree, Boolean underConditional) {
scan(tree.getExpression(), underConditional);
scan(tree.getStatement(), /*underConditional*/ true);
return null;
}
@Override
public Void visitForLoop(ForLoopTree tree, Boolean underConditional) {
scan(tree.getInitializer(), underConditional);
scan(tree.getCondition(), underConditional);
scan(tree.getStatement(), /*underConditional*/ true);
// no need to conditionally visit getUpdate() expressions
return null;
}
@Override
public Void visitIf(IfTree tree, Boolean underConditional) {
scan(tree.getCondition(), underConditional);
scan(tree.getThenStatement(), /*underConditional*/ true);
scan(tree.getElseStatement(), /*underConditional*/ true);
return null;
}
@Override
public Void visitWhileLoop(WhileLoopTree tree, Boolean underConditional) {
scan(tree.getCondition(), underConditional);
scan(tree.getStatement(), /*underConditional*/ true);
return null;
}
/*
* Don't descend into classes and lambdas at all, but resume checking afterward.
*
* We neither want to report supposedly "recursive" calls inside them nor scan them for
* `return` (which would cause us to stop scanning entirely).
*/
@Override
public Void visitClass(ClassTree tree, Boolean underConditional) {
return null;
}
@Override
public Void visitLambdaExpression(LambdaExpressionTree tree, Boolean underConditional) {
return null;
}
// Finally, the thing we're actually looking for:
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, Boolean underConditional) {
checkInvocation(tree, underConditional);
return super.visitMethodInvocation(tree, underConditional);
}
// Handling constructors doesn't appear worthwhile: See b/264529494#comment11 and afterward.
void checkInvocation(MethodInvocationTree invocation, boolean underConditional) {
if (mayHaveReturned || underConditional) {
return;
}
if (!declaredSymbol.equals(getSymbol(invocation))) {
return;
}
/*
* We have provably infinite recursion if the call goes to the same implementation code that
* we're analyzing. We already know that we're looking at the same MethodSymbol, so now we
* just need to make sure that the call isn't a virtual call that may resolve to a different
* implementation. Specifically, we can resolve the call as triggering infinite recursion in
* the case of any non-overridable method (including a static method) and of any call on
* this object.
*/
if (!methodCanBeOverridden(declaredSymbol) || isCallOnThisObject(invocation)) {
state.reportMatch(describeMatch(invocation));
}
}
}.scan(new TreePath(state.getPath(), declaration.getBody()), /*underConditional*/ false);
return NO_MATCH; // We reported any matches through state.reportMatch.
}
private static boolean isCallOnThisObject(MethodInvocationTree invocation) {
ExpressionTree select = invocation.getMethodSelect();
return select.getKind() == IDENTIFIER || isThis(((MemberSelectTree) select).getExpression());
}
// TODO(b/236055787): Share code with various checks that look for "return this."
private static boolean isThis(ExpressionTree input) {
return new SimpleTreeVisitor<Boolean, Void>() {
@Override
public Boolean visitParenthesized(ParenthesizedTree tree, Void unused) {
return visit(tree.getExpression(), null);
}
@Override
public Boolean visitTypeCast(TypeCastTree tree, Void unused) {
return visit(tree.getExpression(), null);
}
@Override
public Boolean visitMemberSelect(MemberSelectTree tree, Void unused) {
/*
* The caller has already checked that the MethodSymbol is from this class, so we don't need
* to disambiguate between ThisClass.this and SomeOtherEnclosingClass.this.
*/
return tree.getIdentifier().contentEquals("this");
}
@Override
public Boolean visitIdentifier(IdentifierTree tree, Void unused) {
return tree.getName().contentEquals("this");
}
@Override
protected Boolean defaultAction(Tree tree, Void unused) {
return false;
}
}.visit(input, null);
}
}
| 9,937
| 39.563265
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SystemExitOutsideMain.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.MAIN_METHOD;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.enclosingMethod;
import static com.google.errorprone.matchers.Matchers.not;
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.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import java.util.Optional;
/**
* Check for calls to {@code System.exit()} outside of a main method.
*
* @author seibelsabrina@google.com (Sabrina Seibel)
*/
@BugPattern(summary = "Code that contains System.exit() is untestable.", severity = ERROR)
public class SystemExitOutsideMain extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> CALLS_TO_SYSTEM_EXIT =
staticMethod().onClass("java.lang.System").named("exit");
private static final Matcher<ExpressionTree> CALLS_TO_SYSTEM_EXIT_OUTSIDE_MAIN =
allOf(CALLS_TO_SYSTEM_EXIT, not(enclosingMethod(MAIN_METHOD)));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (CALLS_TO_SYSTEM_EXIT_OUTSIDE_MAIN.matches(tree, state)) {
Optional<? extends Tree> mainMethodInThisClass =
ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class).getMembers().stream()
.filter(t -> t instanceof MethodTree)
.filter(t -> MAIN_METHOD.matches((MethodTree) t, state))
.findAny();
return mainMethodInThisClass.isPresent() ? Description.NO_MATCH : describeMatch(tree);
}
return Description.NO_MATCH;
}
}
| 2,802
| 42.796875
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DuplicateMapKeys.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 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.util.HashSet;
import java.util.Set;
/**
* Flags duplicate keys used in ImmutableMap construction.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary =
"Map#ofEntries will throw an IllegalArgumentException if there are any duplicate keys",
severity = ERROR)
public class DuplicateMapKeys extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> METHOD_MATCHER =
MethodMatchers.staticMethod().onClass("java.util.Map").named("ofEntries");
private static final Matcher<ExpressionTree> ENTRY_MATCHER =
MethodMatchers.staticMethod().onClass("java.util.Map").named("entry");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!METHOD_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
Set<Object> keySet = new HashSet<>();
for (ExpressionTree expr : tree.getArguments()) {
if (!(expr instanceof MethodInvocationTree)) {
continue;
}
if (!ENTRY_MATCHER.matches(expr, state)) {
continue;
}
MethodInvocationTree entryInvocation = (MethodInvocationTree) expr;
Object key = ASTHelpers.constValue(entryInvocation.getArguments().get(0));
if (key == null) {
continue;
}
if (!keySet.add(key)) {
return buildDescription(tree)
.setMessage(
String.format(
"duplicate key '%s'; Map#ofEntries will throw an IllegalArgumentException",
key))
.build();
}
}
return Description.NO_MATCH;
}
}
| 2,844
| 34.5625
| 95
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/WithSignatureDiscouraged.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.instanceMethod;
import static java.util.stream.Collectors.joining;
import com.google.common.base.Ascii;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.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.MethodInvocationTree;
import com.sun.tools.javac.tree.JCTree;
/**
* {@link
* com.google.errorprone.matchers.method.MethodMatchers.MethodClassMatcher#withSignature(String)} is
* discouraged: most usages should use .named and/or .withParameters instead.
*
* @author amalloy@google.com (Alan Malloy)
*/
@BugPattern(
summary = "withSignature is discouraged. Prefer .named and/or .withParameters where possible.",
severity = WARNING)
public class WithSignatureDiscouraged extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> WITH_SIGNATURE =
instanceMethod()
.onExactClass("com.google.errorprone.matchers.method.MethodMatchers.MethodClassMatcher")
.named("withSignature")
.withParameters("java.lang.String");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!WITH_SIGNATURE.matches(tree, state)) {
return NO_MATCH;
}
ExpressionTree argument = tree.getArguments().get(0);
String sig = ASTHelpers.constValue(argument, String.class);
if (sig == null) {
// Non-const arguments to withSignature are a bit weird but there's not much we can do.
return NO_MATCH;
}
if (sig.contains("...") || sig.contains("<")) {
// We don't have a migration strategy to suggest for varargs or generics.
return NO_MATCH;
}
int firstParenIndex = sig.indexOf('(');
if (firstParenIndex == -1) {
// .withSignature("toString") => .named("toString")
return describeMatch(tree, SuggestedFixes.renameMethodInvocation(tree, "named", state));
}
// .withSignature("valueOf(java.lang.String,int)")
// =>
// .named("valueOf").withParameters("java.lang.String", "int")
if (!(tree instanceof JCTree)) {
// We can't easily compute offsets to replace a whole method chain based on just the public
// Tree API.
return NO_MATCH;
}
String methodName = sig.substring(0, firstParenIndex);
String paramList = sig.substring(firstParenIndex + 1, sig.length() - 1);
return fixWithParameters((JCTree) tree, state, methodName, paramList);
}
private Description fixWithParameters(
JCTree tree, VisitorState state, String methodName, String paramList) {
ImmutableList<String> paramTypes =
ImmutableList.copyOf(Splitter.on(',').omitEmptyStrings().split(paramList));
if (paramTypes.stream().anyMatch(type -> isProbableTypeParameter(type) || isArrayType(type))) {
// We can't migrate references to type parameters or arrays, because withParameters doesn't
// handle those.
return NO_MATCH;
}
int treeStart = tree.getStartPosition();
String source = state.getSourceForNode(tree);
if (source == null) {
// Not clear how this could happen, but if it does we may as well give up.
return NO_MATCH;
}
// Technically too restrictive, but will handle google-java-format'ed code okay.
int offset = source.indexOf(".withSignature");
if (offset == -1) {
return NO_MATCH;
}
int startPosition = treeStart + offset;
int endPosition = state.getEndPosition(tree);
String withParameters =
paramTypes.isEmpty()
? "withNoParameters()"
: paramTypes.stream()
.map(type -> String.format("\"%s\"", type))
.collect(joining(", ", "withParameters(", ")"));
String replacementText = String.format(".named(\"%s\").%s", methodName, withParameters);
return describeMatch(tree, SuggestedFix.replace(startPosition, endPosition, replacementText));
}
private static boolean isArrayType(String type) {
return type.contains("[");
}
private static boolean isProbableTypeParameter(String type) {
// This is a reasonable heuristic for references to type parameters:
// they have no . in them, and are not all-lowercase.
return !type.contains(".") && !type.equals(Ascii.toLowerCase(type));
}
}
| 5,517
| 40.80303
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ArrayHashCode.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.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.argument;
import static com.google.errorprone.matchers.Matchers.hasArguments;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.predicates.TypePredicates.isArray;
import com.google.common.base.Preconditions;
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.ChildMultiMatcher.MatchType;
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.Types;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@BugPattern(summary = "hashcode method on array does not hash array contents", severity = ERROR)
public class ArrayHashCode extends BugChecker implements MethodInvocationTreeMatcher {
/**
* Matches calls to varargs hashcode methods {@link com.google.common.base.Objects#hashCode} and
* {@link java.util.Objects#hash} in which at least one argument is of array type.
*/
private static final Matcher<MethodInvocationTree> varargsHashCodeMethodMatcher =
allOf(
Matchers.anyOf(
staticMethod().onClass("com.google.common.base.Objects").named("hashCode"),
staticMethod().onClass("java.util.Objects").named("hash")),
hasArguments(MatchType.AT_LEAST_ONE, Matchers.<ExpressionTree>isArrayType()));
/**
* Matches calls to the JDK7 method {@link java.util.Objects#hashCode} with an argument of array
* type. This method is not varargs, so we don't need to check the number of arguments.
*/
private static final Matcher<MethodInvocationTree> jdk7HashCodeMethodMatcher =
allOf(
staticMethod().onClass("java.util.Objects").named("hashCode"),
argument(0, Matchers.<ExpressionTree>isArrayType()));
/** Matches calls to the hashCode instance method on an array. */
private static final Matcher<ExpressionTree> instanceHashCodeMethodMatcher =
instanceMethod().onClass(isArray()).named("hashCode");
/**
* Wraps identity hashcode computations in calls to {@link java.util.Arrays#hashCode} if the array
* is single dimensional or {@link java.util.Arrays#deepHashCode} if the array is
* multidimensional.
*
* <p>If there is only one argument to the hashcode method or the instance hashcode method is
* used, replaces the whole method invocation. If there are multiple arguments, wraps any that are
* of array type with the appropriate {@link java.util.Arrays} hashcode method.
*/
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
SuggestedFix.Builder fix = null;
Types types = state.getTypes();
if (jdk7HashCodeMethodMatcher.matches(tree, state)) {
// java.util.Objects#hashCode takes a single argument, so rewrite the whole method call
// to use Arrays.hashCode/deepHashCode instead.
fix =
SuggestedFix.builder()
.replace(tree, rewriteArrayArgument(tree.getArguments().get(0), state));
} else if (instanceHashCodeMethodMatcher.matches(tree, state)) {
// Rewrite call to instance hashCode method to use Arrays.hashCode/deepHashCode instead.
fix =
SuggestedFix.builder()
.replace(
tree,
rewriteArrayArgument(
((JCFieldAccess) tree.getMethodSelect()).getExpression(), state));
} else if (varargsHashCodeMethodMatcher.matches(tree, state)) {
// Varargs hash code methods, java.util.Objects#hash and
// com.google.common.base.Objects#hashCode
if (tree.getArguments().size() == 1) {
// If only one argument, type must be either primitive array or multidimensional array.
// Types like Object[], String[], etc. are not an error because they don't get boxed
// in this single-argument varargs call.
ExpressionTree arg = tree.getArguments().get(0);
Type elemType = types.elemtype(ASTHelpers.getType(arg));
if (elemType.isPrimitive() || types.isArray(elemType)) {
fix = SuggestedFix.builder().replace(tree, rewriteArrayArgument(arg, state));
}
} else {
// If more than one argument, wrap each argument in a call to Arrays#hashCode/deepHashCode.
fix = SuggestedFix.builder();
for (ExpressionTree arg : tree.getArguments()) {
if (types.isArray(ASTHelpers.getType(arg))) {
fix.replace(arg, rewriteArrayArgument(arg, state));
}
}
}
}
if (fix != null) {
fix.addImport("java.util.Arrays");
return describeMatch(tree, fix.build());
}
return Description.NO_MATCH;
}
/**
* Given an {@link ExpressionTree} that represents an argument of array type, rewrites it to wrap
* it in a call to either {@link java.util.Arrays#hashCode} if it is single dimensional, or {@link
* java.util.Arrays#deepHashCode} if it is multidimensional.
*/
private static String rewriteArrayArgument(ExpressionTree arg, VisitorState state) {
Types types = state.getTypes();
Type argType = ASTHelpers.getType(arg);
Preconditions.checkState(types.isArray(argType), "arg must be of array type");
if (types.isArray(types.elemtype(argType))) {
return "Arrays.deepHashCode(" + state.getSourceForNode(arg) + ")";
} else {
return "Arrays.hashCode(" + state.getSourceForNode(arg) + ")";
}
}
}
| 6,742
| 44.870748
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AnnotationMirrorToString.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 =
"AnnotationMirror#toString doesn't use fully qualified type names, prefer auto-common's"
+ " AnnotationMirrors#toString",
severity = SUGGESTION)
public class AnnotationMirrorToString extends AbstractToString {
private static final TypePredicate TYPE_PREDICATE =
TypePredicates.isExactType("javax.lang.model.element.AnnotationMirror");
@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.AnnotationMirrors"),
state.getSourceForNode(with)))
.build());
}
}
| 2,495
| 34.657143
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AbstractReferenceEquality.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.dataflow.nullnesspropagation.Nullness.NONNULL;
import static com.google.errorprone.dataflow.nullnesspropagation.Nullness.NULL;
import static com.google.errorprone.matchers.Matchers.instanceEqualsInvocation;
import static com.google.errorprone.matchers.Matchers.staticEqualsInvocation;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher;
import com.google.errorprone.dataflow.nullnesspropagation.Nullness;
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.google.errorprone.util.FindIdentifiers;
import com.sun.source.tree.BinaryTree;
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.Kinds.KindSelector;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.util.Name;
import java.util.List;
import java.util.Optional;
/**
* Abstract implementation of a BugPattern that detects the use of reference equality to compare
* classes with value semantics.
*
* <p>See e.g. {@link OptionalEquality}, {@link ProtoStringFieldReferenceEquality}.
*
* @author cushon@google.com (Liam Miller-Cushon)
*/
public abstract class AbstractReferenceEquality extends BugChecker implements BinaryTreeMatcher {
private static final Matcher<MethodInvocationTree> EQUALS_STATIC_METHODS =
staticEqualsInvocation();
private static final Matcher<ExpressionTree> OBJECT_INSTANCE_EQUALS = instanceEqualsInvocation();
protected abstract boolean matchArgument(ExpressionTree tree, VisitorState state);
@Override
public final Description matchBinary(BinaryTree tree, VisitorState state) {
switch (tree.getKind()) {
case EQUAL_TO:
case NOT_EQUAL_TO:
break;
default:
return Description.NO_MATCH;
}
if (tree.getLeftOperand().getKind() == Kind.NULL_LITERAL
|| !matchArgument(tree.getLeftOperand(), state)) {
return Description.NO_MATCH;
}
if (tree.getRightOperand().getKind() == Kind.NULL_LITERAL
|| !matchArgument(tree.getRightOperand(), state)) {
return Description.NO_MATCH;
}
Description.Builder builder = buildDescription(tree);
addFixes(builder, tree, state);
return builder.build();
}
private static boolean symbolsTypeHasName(Symbol sym, String name) {
if (sym == null) {
return false;
}
Type type = sym.type;
if (type == null) {
return false;
}
TypeSymbol tsym = type.tsym;
if (tsym == null) {
return false;
}
Name typeName = tsym.getQualifiedName();
if (typeName == null) {
// Probably shouldn't happen, but might as well check
return false;
}
return typeName.contentEquals(name);
}
protected void addFixes(Description.Builder builder, BinaryTree tree, VisitorState state) {
ExpressionTree lhs = tree.getLeftOperand();
ExpressionTree rhs = tree.getRightOperand();
Optional<Fix> fixToReplaceOrStatement = inOrStatementWithEqualsCheck(state, tree);
if (fixToReplaceOrStatement.isPresent()) {
builder.addFix(fixToReplaceOrStatement.get());
return;
}
// Swap the order (e.g. rhs.equals(lhs) if the rhs is a non-null constant, and the lhs is not
if (ASTHelpers.constValue(lhs) == null && ASTHelpers.constValue(rhs) != null) {
ExpressionTree tmp = lhs;
lhs = rhs;
rhs = tmp;
}
String prefix = tree.getKind() == Kind.NOT_EQUAL_TO ? "!" : "";
String lhsSource = state.getSourceForNode(lhs);
String rhsSource = state.getSourceForNode(rhs);
Nullness nullness = getNullness(lhs, state);
// If the lhs is possibly-null, provide both options.
if (nullness != NONNULL) {
Symbol existingObjects = FindIdentifiers.findIdent("Objects", state, KindSelector.TYP);
ObjectsFix preferredFix;
if (symbolsTypeHasName(existingObjects, ObjectsFix.GUAVA.className)) {
preferredFix = ObjectsFix.GUAVA;
} else if (symbolsTypeHasName(existingObjects, ObjectsFix.JAVA_UTIL.className)) {
preferredFix = ObjectsFix.JAVA_UTIL;
} else if (state.isAndroidCompatible()) {
preferredFix = ObjectsFix.GUAVA;
} else {
preferredFix = ObjectsFix.JAVA_UTIL;
}
builder.addFix(preferredFix.fix(tree, prefix, lhsSource, rhsSource));
}
if (nullness != NULL) {
builder.addFix(
SuggestedFix.replace(
tree,
String.format(
"%s%s.equals(%s)",
prefix,
lhs instanceof BinaryTree ? String.format("(%s)", lhsSource) : lhsSource,
rhsSource)));
}
}
private enum ObjectsFix {
JAVA_UTIL("java.util.Objects", "Objects.equals"),
GUAVA("com.google.common.base.Objects", "Objects.equal");
private final String className;
private final String methodName;
ObjectsFix(String className, String methodName) {
this.className = className;
this.methodName = methodName;
}
SuggestedFix fix(BinaryTree tree, String prefix, String lhsSource, String rhsSource) {
return SuggestedFix.builder()
.replace(tree, String.format("%s%s(%s, %s)", prefix, methodName, lhsSource, rhsSource))
.addImport(className)
.build();
}
}
private static Optional<Fix> inOrStatementWithEqualsCheck(VisitorState state, BinaryTree tree) {
// Only attempt to handle a == b || a.equals(b);
if (tree.getKind() == Kind.NOT_EQUAL_TO) {
return Optional.empty();
}
ExpressionTree lhs = tree.getLeftOperand();
ExpressionTree rhs = tree.getRightOperand();
Tree parent = state.getPath().getParentPath().getLeaf();
if (parent.getKind() != Kind.CONDITIONAL_OR) {
return Optional.empty();
}
BinaryTree p = (BinaryTree) parent;
if (p.getLeftOperand() != tree) {
// a == b is on the RHS, ignore this construction
return Optional.empty();
}
// If the other half of this or statement is foo.equals(bar) or Objects.equals(foo, bar)
// replace the or statement with the other half as already written.
ExpressionTree otherExpression = ASTHelpers.stripParentheses(p.getRightOperand());
if (!(otherExpression instanceof MethodInvocationTree)) {
return Optional.empty();
}
MethodInvocationTree other = (MethodInvocationTree) otherExpression;
// a == b || Objects.equals(a, b) => Objects.equals(a, b)
if (EQUALS_STATIC_METHODS.matches(other, state)) {
List<? extends ExpressionTree> arguments = other.getArguments();
if (treesMatch(arguments.get(0), arguments.get(1), lhs, rhs)) {
return Optional.of(SuggestedFix.replace(parent, state.getSourceForNode(otherExpression)));
}
}
// a == b || a.equals(b) => a.equals(b)
if (OBJECT_INSTANCE_EQUALS.matches(otherExpression, state)) {
if (treesMatch(ASTHelpers.getReceiver(other), other.getArguments().get(0), lhs, rhs)) {
return Optional.of(SuggestedFix.replace(parent, state.getSourceForNode(otherExpression)));
}
}
return Optional.empty();
}
private static Nullness getNullness(ExpressionTree expr, VisitorState state) {
TreePath pathToExpr = new TreePath(state.getPath(), expr);
return state.getNullnessAnalysis().getNullness(pathToExpr, state.context);
}
private static boolean treesMatch(
ExpressionTree lhs1, ExpressionTree rhs1, ExpressionTree lhs2, ExpressionTree rhs2) {
return (ASTHelpers.sameVariable(lhs1, lhs2) && ASTHelpers.sameVariable(rhs1, rhs2))
|| (ASTHelpers.sameVariable(lhs1, rhs2) && ASTHelpers.sameVariable(rhs1, lhs2));
}
}
| 8,693
| 36.313305
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MemberName.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.base.Ascii.isUpperCase;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFix.emptyFix;
import static com.google.errorprone.fixes.SuggestedFixes.renameMethodWithInvocations;
import static com.google.errorprone.fixes.SuggestedFixes.renameVariable;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.JUnitMatchers.TEST_CASE;
import static com.google.errorprone.util.ASTHelpers.annotationsAmong;
import static com.google.errorprone.util.ASTHelpers.canBeRemoved;
import static com.google.errorprone.util.ASTHelpers.findSuperMethods;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import static com.google.errorprone.util.ASTHelpers.isStatic;
import static java.util.stream.Collectors.joining;
import static javax.lang.model.element.ElementKind.EXCEPTION_PARAMETER;
import static javax.lang.model.element.ElementKind.LOCAL_VARIABLE;
import static javax.lang.model.element.ElementKind.RESOURCE_VARIABLE;
import com.google.common.base.Ascii;
import com.google.common.base.CaseFormat;
import com.google.common.base.Splitter;
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.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.bugpatterns.argumentselectiondefects.NamedParameterComment;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
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.util.Name;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
/** Flags a few ways in which member names may violate the style guide. */
@BugPattern(
severity = WARNING,
summary = "Methods and non-static variables should be named in lowerCamelCase.",
linkType = CUSTOM,
link = "https://google.github.io/styleguide/javaguide.html#s5.2-specific-identifier-names")
public final class MemberName extends BugChecker implements MethodTreeMatcher, VariableTreeMatcher {
private static final Supplier<ImmutableSet<Name>> EXEMPTED_CLASS_ANNOTATIONS =
VisitorState.memoize(
s ->
Stream.of("org.robolectric.annotation.Implements")
.map(s::getName)
.collect(toImmutableSet()));
private static final Supplier<ImmutableSet<Name>> EXEMPTED_METHOD_ANNOTATIONS =
VisitorState.memoize(
s ->
Stream.of(
"com.pholser.junit.quickcheck.Property",
"com.google.caliper.Benchmark",
"com.google.caliper.api.Macrobenchmark",
"com.google.caliper.api.Footprint")
.map(s::getName)
.collect(toImmutableSet()));
private static final String STATIC_VARIABLE_FINDING =
"Static variables should be named in UPPER_SNAKE_CASE if deeply immutable or lowerCamelCase"
+ " if not.";
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
MethodSymbol symbol = getSymbol(tree);
if (!annotationsAmong(symbol.owner, EXEMPTED_CLASS_ANNOTATIONS.get(state), state).isEmpty()) {
return NO_MATCH;
}
if (!annotationsAmong(symbol, EXEMPTED_METHOD_ANNOTATIONS.get(state), state).isEmpty()) {
return NO_MATCH;
}
if (hasTestAnnotation(symbol)) {
return NO_MATCH;
}
// It is a surprisingly common error to replace @Test with @Ignore to ignore a test.
if (hasAnnotation(symbol, "org.junit.Ignore", state)) {
return NO_MATCH;
}
if (!findSuperMethods(symbol, state.getTypes()).isEmpty()) {
return NO_MATCH;
}
if (tree.getModifiers().getFlags().contains(Modifier.NATIVE)) {
return NO_MATCH;
}
// JUnitParams reflectively accesses methods starting with "parametersFor" to provide parameters
// for tests (which may then contain underscores).
if (symbol.getSimpleName().toString().startsWith("parametersFor")) {
return NO_MATCH;
}
if (TEST_CASE.matches(tree, state)) {
return NO_MATCH;
}
String name = tree.getName().toString();
if (isConformant(symbol, name)) {
return NO_MATCH;
}
String suggested = fixInitialisms(suggestedRename(symbol, name));
return suggested.equals(name) || !canBeRemoved(symbol, state)
? buildDescription(tree)
.setMessage(
String.format(
"Methods and non-static variables should be named in lowerCamelCase; did you"
+ " mean '%s'?",
suggested))
.build()
: describeMatch(tree, renameMethodWithInvocations(tree, suggested, state));
}
private static boolean hasTestAnnotation(MethodSymbol symbol) {
return symbol.getRawAttributes().stream()
.anyMatch(c -> c.type.tsym.getSimpleName().toString().contains("Test"));
}
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
VarSymbol symbol = getSymbol(tree);
String name = tree.getName().toString();
if (symbol.owner instanceof MethodSymbol
&& symbol.getKind() == ElementKind.PARAMETER
&& state.getPath().getParentPath().getLeaf().getKind() != Kind.LAMBDA_EXPRESSION) {
var methodSymbol = (MethodSymbol) symbol.owner;
int index = methodSymbol.getParameters().indexOf(symbol);
var maybeSuper = ASTHelpers.streamSuperMethods(methodSymbol, state.getTypes()).findFirst();
if (maybeSuper.isPresent()) {
var superMethod = maybeSuper.get();
if (NamedParameterComment.containsSyntheticParameterName(superMethod)) {
return NO_MATCH;
}
if (index < superMethod.getParameters().size()
&& superMethod.getParameters().get(index).getSimpleName().contentEquals(name)) {
return NO_MATCH;
}
}
}
// Try to avoid dual-matching with ConstantCaseForConstants.
if (isConformantStaticVariableName(name) && !symbol.isStatic()) {
return NO_MATCH;
}
if (isConformant(symbol, name)) {
return NO_MATCH;
}
if (EXEMPTED_VARIABLE_NAMES.contains(name)) {
return NO_MATCH;
}
String suggested = fixInitialisms(suggestedRename(symbol, name));
boolean fixable = !suggested.equals(name) && canBeRenamed(symbol);
return buildDescription(tree)
.addFix(fixable ? renameVariable(tree, suggested, state) : emptyFix())
.setMessage(
isStaticVariable(symbol)
? STATIC_VARIABLE_FINDING
: message()
+ (fixable || suggested.equals(name)
? ""
: (" Did you mean " + suggested + "?")))
.build();
}
private static final ImmutableSet<String> EXEMPTED_VARIABLE_NAMES =
ImmutableSet.of("serialVersionUID");
private static String suggestedRename(Symbol symbol, String name) {
if (!isStaticVariable(symbol) && isConformantStaticVariableName(name)) {
return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name);
}
if (LOWER_UNDERSCORE_PATTERN.matcher(name).matches()) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name);
}
// If we get this far, it's likely a mixture of lower camelcase and underscores.
return CaseFormat.UPPER_CAMEL.to(
CaseFormat.LOWER_CAMEL,
UNDERSCORE_SPLITTER
.splitToStream(name)
.map(c -> CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, c))
.collect(joining("")));
}
private static boolean canBeRenamed(Symbol symbol) {
return symbol.isPrivate() || LOCAL_VARIABLE_KINDS.contains(symbol.getKind());
}
private static final ImmutableSet<ElementKind> LOCAL_VARIABLE_KINDS =
ImmutableSet.of(LOCAL_VARIABLE, RESOURCE_VARIABLE, EXCEPTION_PARAMETER);
private static boolean isConformant(Symbol symbol, String name) {
if (isStaticVariable(symbol) && isConformantStaticVariableName(name)) {
return true;
}
return isConformantLowerCamelName(name);
}
private static boolean isConformantStaticVariableName(String name) {
return UPPER_UNDERSCORE_PATTERN.matcher(name).matches();
}
private static boolean isConformantLowerCamelName(String name) {
return !name.contains("_")
&& !isUpperCase(name.charAt(0))
&& !PROBABLE_INITIALISM.matcher(name).find();
}
private static boolean isStaticVariable(Symbol symbol) {
return symbol instanceof VarSymbol && isStatic(symbol);
}
private static String fixInitialisms(String input) {
return PROBABLE_INITIALISM.matcher(input).replaceAll(r -> titleCase(r.group(1)) + r.group(2));
}
private static String titleCase(String input) {
var lower = Ascii.toLowerCase(input);
return Ascii.toUpperCase(lower.charAt(0)) + lower.substring(1);
}
private static final Pattern LOWER_UNDERSCORE_PATTERN = Pattern.compile("[a-z0-9_]+");
private static final Pattern UPPER_UNDERSCORE_PATTERN = Pattern.compile("[A-Z0-9_]+");
private static final java.util.regex.Pattern PROBABLE_INITIALISM =
java.util.regex.Pattern.compile("([A-Z]{2,})([A-Z][^A-Z]|$)");
private static final Splitter UNDERSCORE_SPLITTER = Splitter.on('_');
}
| 10,653
| 41.616
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JavaUtilDateChecker.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.anyOf;
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.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.tools.javac.code.Type;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
name = "JavaUtilDate",
summary = "Date has a bad API that leads to bugs; prefer java.time.Instant or LocalDate.",
severity = WARNING)
public class JavaUtilDateChecker extends BugChecker
implements MethodInvocationTreeMatcher, NewClassTreeMatcher {
private static final Matcher<ExpressionTree> EXEMPTIONS =
anyOf(
instanceMethod().onExactClass("java.util.Date").named("toInstant"),
staticMethod()
.onClass("java.util.Date")
.named("from")
.withParameters("java.time.Instant"));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!isDate(state, ASTHelpers.getReceiverType(tree))) {
return NO_MATCH;
}
if (EXEMPTIONS.matches(tree, state)) {
return NO_MATCH;
}
return describeMatch(tree);
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
return isDate(state, ASTHelpers.getType(tree.getIdentifier())) ? describeMatch(tree) : NO_MATCH;
}
private static boolean isDate(VisitorState state, Type type) {
return ASTHelpers.isSameType(type, JAVA_UTIL_DATE.get(state), state);
}
private static final Supplier<Type> JAVA_UTIL_DATE =
VisitorState.memoize(state -> state.getTypeFromString("java.util.Date"));
}
| 3,065
| 38.818182
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SubstringOfZero.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.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 java.util.Objects;
/** Check for calls to String's {@code foo.substring(0)}. */
@BugPattern(
summary = "String.substring(0) returns the original String",
explanation =
"String.substring(int) gives you the substring from the index to the end, inclusive."
+ " Calling that method with an index of 0 will return the same String.",
severity = ERROR)
public final class SubstringOfZero extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> SUBSTRING_CALLS =
Matchers.instanceMethod()
.onExactClass("java.lang.String")
.named("substring")
.withParameters("int");
private static final Matcher<MethodInvocationTree> ARGUMENT_IS_ZERO =
Matchers.argument(0, (tree, state) -> Objects.equals(ASTHelpers.constValue(tree), 0));
private static final Matcher<MethodInvocationTree> SUBSTRING_CALLS_WITH_ZERO_ARG =
Matchers.allOf(SUBSTRING_CALLS, ARGUMENT_IS_ZERO);
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!SUBSTRING_CALLS_WITH_ZERO_ARG.matches(tree, state)) {
return Description.NO_MATCH;
}
return describeMatch(tree, removeSubstringCall(tree, state));
}
private static Fix removeSubstringCall(MethodInvocationTree tree, VisitorState state) {
ExpressionTree originalString = ASTHelpers.getReceiver(tree);
return SuggestedFix.replace(tree, state.getSourceForNode(originalString));
}
}
| 2,776
| 40.447761
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnusedTypeParameter.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getLast;
import static com.google.errorprone.fixes.SuggestedFixes.removeElement;
import static com.google.errorprone.util.ASTHelpers.findSuperMethods;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.methodCanBeOverridden;
import com.google.common.collect.ImmutableMultiset;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ErrorProneTokens;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TypeParameterTree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol.TypeVariableSymbol;
import com.sun.tools.javac.parser.Tokens.TokenKind;
import java.util.List;
/** A BugPattern; see the summary. */
@BugPattern(
severity = SeverityLevel.WARNING,
summary = "This type parameter is unused and can be removed.")
public final class UnusedTypeParameter extends BugChecker implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
var usedIdentifiers = findUsedIdentifiers(tree);
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitClass(ClassTree node, Void unused) {
if ((getSymbol(node).flags() & Flags.FINAL) != 0) {
handle(node, node.getTypeParameters());
}
return super.visitClass(node, null);
}
@Override
public Void visitMethod(MethodTree node, Void unused) {
var symbol = getSymbol(node);
if (methodCanBeOverridden(symbol)
|| !findSuperMethods(symbol, state.getTypes()).isEmpty()) {
return null;
}
handle(node, node.getTypeParameters());
return super.visitMethod(node, null);
}
private void handle(Tree tree, List<? extends TypeParameterTree> typeParameters) {
for (TypeParameterTree typeParameter : typeParameters) {
if (usedIdentifiers.count(getSymbol(typeParameter)) == 1) {
state.reportMatch(
describeMatch(
typeParameter,
removeTypeParameter(tree, typeParameter, typeParameters, state)));
}
}
}
}.scan(state.getPath(), null);
return Description.NO_MATCH;
}
private static ImmutableMultiset<TypeVariableSymbol> findUsedIdentifiers(
CompilationUnitTree tree) {
ImmutableMultiset.Builder<TypeVariableSymbol> identifiers = ImmutableMultiset.builder();
new TreeScanner<Void, Void>() {
@Override
public Void scan(Tree tree, Void unused) {
var symbol = getSymbol(tree);
if (symbol instanceof TypeVariableSymbol) {
identifiers.add((TypeVariableSymbol) symbol);
}
return super.scan(tree, unused);
}
}.scan(tree, null);
return identifiers.build();
}
private static SuggestedFix removeTypeParameter(
Tree tree,
TypeParameterTree typeParameter,
List<? extends TypeParameterTree> typeParameters,
VisitorState state) {
if (typeParameters.size() > 1) {
return removeElement(typeParameter, typeParameters, state);
}
var tokens =
ErrorProneTokens.getTokens(
state.getSourceForNode(tree), getStartPosition(tree), state.context);
int startPos =
tokens.reverse().stream()
.filter(
t -> t.pos() <= getStartPosition(typeParameter) && t.kind().equals(TokenKind.LT))
.findFirst()
.get()
.pos();
int endPos =
tokens.stream()
.filter(
t ->
t.endPos() >= state.getEndPosition(getLast(typeParameters))
&& (t.kind().equals(TokenKind.GT) || t.kind().equals(TokenKind.GTGT)))
.findFirst()
.get()
.endPos();
return SuggestedFix.replace(startPos, endPos, "");
}
}
| 5,124
| 37.533835
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AbstractMustBeClosedChecker.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.fixes.SuggestedFixes.qualifyType;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.symbolHasAnnotation;
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 static com.google.errorprone.util.ASTHelpers.getReturnType;
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.hasAnnotation;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import com.google.auto.value.AutoValue;
import com.google.common.base.CaseFormat;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.ForOverride;
import com.google.errorprone.annotations.MustBeClosed;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.UnusedReturnValueMatcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.ExpressionStatementTree;
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.NewClassTree;
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.util.TreePath;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.util.Position;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.lang.model.element.ElementKind;
/**
* An abstract check for resources that must be closed; used by {@link StreamResourceLeak} and
* {@link MustBeClosedChecker}.
*/
public abstract class AbstractMustBeClosedChecker extends BugChecker {
private static final String MUST_BE_CLOSED_ANNOTATION_NAME =
MustBeClosed.class.getCanonicalName();
/** Matches trees annotated with {@link MustBeClosed}. */
protected static final Matcher<Tree> HAS_MUST_BE_CLOSED_ANNOTATION =
symbolHasAnnotation(MUST_BE_CLOSED_ANNOTATION_NAME);
private static final Matcher<ExpressionTree> CLOSE_METHOD =
instanceMethod().onDescendantOf("java.lang.AutoCloseable").named("close");
private static final Matcher<Tree> MOCKITO_MATCHER =
toType(
MethodInvocationTree.class, staticMethod().onClass("org.mockito.Mockito").named("when"));
static final class NameSuggester {
private final Multiset<String> assignedNamesInThisMethod = HashMultiset.create();
/** Returns basename if there are no conflicts, then basename + "2", then basename + "3"... */
String uniquifyName(String basename) {
int numPreviousConflicts = assignedNamesInThisMethod.add(basename, 1);
if (numPreviousConflicts == 0) {
// First time using this name.
return basename;
}
// If we already have `var foo`, then `var foo2` seems like a good next choice.
return basename + (numPreviousConflicts + 1);
}
/**
* @param tree must be either MethodInvocationTree or NewClassTree
*/
String suggestName(ExpressionTree tree) {
String symbolName;
switch (tree.getKind()) {
case NEW_CLASS:
symbolName = getSymbol(((NewClassTree) tree).getIdentifier()).getSimpleName().toString();
break;
case METHOD_INVOCATION:
symbolName = getReturnType(tree).asElement().getSimpleName().toString();
break;
default:
throw new AssertionError(tree.getKind());
}
return uniquifyName(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, symbolName));
}
}
/**
* Scans a method body for invocations matching {@code matcher}, emitting them as a single fix.
*/
protected Description scanEntireMethodFor(
Matcher<? super ExpressionTree> matcher, MethodTree tree, VisitorState state) {
BlockTree body = tree.getBody();
if (body == null) {
return NO_MATCH;
}
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
NameSuggester suggester = new NameSuggester();
Multiset<Tree> closeBraceLocations = HashMultiset.create();
Tree[] firstIssuedFixLocation = new Tree[1];
new SuppressibleTreePathScanner<Void, Void>(state) {
@Override
public Void visitMethod(MethodTree methodTree, Void aVoid) {
// Don't descend into sub-methods - we will scanEntireMethod on each later
return null;
}
private void visitNewClassOrMethodInvocation(ExpressionTree tree) {
VisitorState localState = state.withPath(getCurrentPath());
if (matcher.matches(tree, localState)) {
matchNewClassOrMethodInvocation(tree, localState, suggester)
.ifPresent(
change -> {
fixBuilder.merge(change.otherFixes());
change.closeBraceAfter().ifPresent(closeBraceLocations::add);
if (firstIssuedFixLocation[0] == null) {
// Attach the finding to the first invocation that broke the rules.
firstIssuedFixLocation[0] = tree;
}
});
}
}
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
visitNewClassOrMethodInvocation(tree);
return super.visitMethodInvocation(tree, unused);
}
@Override
public Void visitNewClass(NewClassTree tree, Void unused) {
visitNewClassOrMethodInvocation(tree);
return super.visitNewClass(tree, unused);
}
}.scan(new TreePath(state.getPath(), body), null);
if (firstIssuedFixLocation[0] == null) {
// No findings fired, even with empty fixes
return NO_MATCH;
}
closeBraceLocations.forEachEntry((t, count) -> fixBuilder.postfixWith(t, "}".repeat(count)));
return describeMatch(firstIssuedFixLocation[0], fixBuilder.build());
}
/**
* Error Prone's fix application logic doesn't like it when a fix suggests multiple identical
* insertions at the same position. This Change class breaks up a SuggestedFix into two parts: a
* position at which to insert a close brace, and a SuggestedFix of other related changes. We use
* this to aggregate all the suggested changes within a method, so that we can handle adding
* multiple try blocks with the same scope. Instead of emitting N fixes that each add a new
* close-brace at the end of that scope, we emit a single fix that adds N close braces.
*/
@AutoValue
protected abstract static class Change {
abstract SuggestedFix otherFixes();
abstract Optional<Tree> closeBraceAfter();
@AutoValue.Builder
abstract static class Builder {
abstract Builder otherFixes(SuggestedFix value);
abstract Builder closeBraceAfter(Tree value);
abstract Change build();
/**
* A shortcut for {@code Optional.of(build())}. Many operations taking a Change expect an
* {@code Optional<Change>}, and if you have a Builder already, you're clearly not planning to
* return empty(), so this is a convenient way to make the Optional implicit.
*/
Optional<Change> wrapped() {
return Optional.of(build());
}
}
static Builder builder(SuggestedFix otherFixes) {
return new AutoValue_AbstractMustBeClosedChecker_Change.Builder().otherFixes(otherFixes);
}
static Optional<Change> of(SuggestedFix fix) {
return builder(fix).wrapped();
}
}
/**
* Check that the expression {@code tree} occurs within the resource variable initializer of a
* try-with-resources statement.
*/
private final Optional<Change> matchNewClassOrMethodInvocation(
ExpressionTree tree, VisitorState state, NameSuggester suggester) {
if (ASTHelpers.isInStaticInitializer(state)) {
return Optional.empty();
}
return checkClosed(tree, state, suggester)
.filter(
unusedFix ->
!(UnusedReturnValueMatcher.expectedExceptionTest(state)
|| UnusedReturnValueMatcher.mockitoInvocation(tree, state)
|| MOCKITO_MATCHER.matches(state.getPath().getParentPath().getLeaf(), state)
|| exemptChange(tree, state)));
}
@ForOverride
protected boolean exemptChange(ExpressionTree tree, VisitorState state) {
return false;
}
private Optional<Change> checkClosed(
ExpressionTree tree, VisitorState state, NameSuggester suggester) {
MethodTree callerMethodTree = enclosingMethod(state);
TreePath path = state.getPath();
OUTER:
while (true) {
TreePath prev = path;
path = path.getParentPath();
switch (path.getLeaf().getKind()) {
case RETURN:
if (callerMethodTree != null) {
// The invocation occurs within a return statement of a method, instead of a lambda
// expression or anonymous class.
if (HAS_MUST_BE_CLOSED_ANNOTATION.matches(callerMethodTree, state)) {
// Ignore invocations of annotated methods and constructors that occur in the return
// statement of an annotated caller method, since invocations of the caller are
// enforced.
return Optional.empty();
}
// The caller method is not annotated, so the closing of the returned resource is not
// enforced. Suggest fixing this by annotating the caller method.
return Change.of(
SuggestedFix.builder()
.prefixWith(callerMethodTree, "@MustBeClosed\n")
.addImport(MustBeClosed.class.getCanonicalName())
.build());
}
// If enclosingMethod returned null, we must be returning from a statement lambda.
return handleTailPositionInLambda(state);
case LAMBDA_EXPRESSION:
// The method invocation is the body of an expression lambda.
return handleTailPositionInLambda(state);
case CONDITIONAL_EXPRESSION:
ConditionalExpressionTree conditionalExpressionTree =
(ConditionalExpressionTree) path.getLeaf();
if (conditionalExpressionTree.getTrueExpression().equals(prev.getLeaf())
|| conditionalExpressionTree.getFalseExpression().equals(prev.getLeaf())) {
continue OUTER;
}
break;
case MEMBER_SELECT:
MemberSelectTree memberSelectTree = (MemberSelectTree) path.getLeaf();
if (memberSelectTree.getExpression().equals(prev.getLeaf())) {
Type type = getType(memberSelectTree);
Symbol sym = getSymbol(memberSelectTree);
Type streamType = state.getTypeFromString(Stream.class.getName());
if (isSubtype(sym.enclClass().asType(), streamType, state)
&& isSameType(type.getReturnType(), streamType, state)) {
// skip enclosing method invocation
path = path.getParentPath();
continue OUTER;
}
}
break;
case VARIABLE:
Symbol sym = getSymbol(path.getLeaf());
if (sym instanceof VarSymbol) {
VarSymbol var = (VarSymbol) sym;
if (var.getKind() == ElementKind.RESOURCE_VARIABLE
|| isClosedInFinallyClause(var, path, state)
|| ASTHelpers.variableIsStaticFinal(var)) {
return Optional.empty();
}
}
break;
case ASSIGNMENT:
// We shouldn't suggest a try/finally fix when we know the variable is going to be saved
// for later.
return findingWithNoFix();
default:
break;
}
// The constructor or method invocation does not occur within the resource variable
// initializer of a try-with-resources statement.
return fix(tree, state, suggester);
}
}
protected Optional<Change> fix(ExpressionTree tree, VisitorState state, NameSuggester suggester) {
return chooseFixType(tree, state, suggester);
}
private static Optional<Change> handleTailPositionInLambda(VisitorState state) {
LambdaExpressionTree lambda =
ASTHelpers.findEnclosingNode(state.getPath(), LambdaExpressionTree.class);
if (lambda == null) {
// Apparently we're not inside a lambda?!
return findingWithNoFix();
}
if (hasAnnotation(
state.getTypes().findDescriptorSymbol(getType(lambda).tsym),
MUST_BE_CLOSED_ANNOTATION_NAME,
state)) {
return Optional.empty();
}
return findingWithNoFix();
}
private static Optional<Change> findingWithNoFix() {
return Change.of(SuggestedFix.emptyFix());
}
/**
* Returns the enclosing method of the given visitor state. Returns null if the state is within a
* lambda expression or anonymous class.
*/
@Nullable
private static MethodTree enclosingMethod(VisitorState state) {
for (Tree node : state.getPath().getParentPath()) {
switch (node.getKind()) {
case LAMBDA_EXPRESSION:
case NEW_CLASS:
return null;
case METHOD:
return (MethodTree) node;
default:
break;
}
}
return null;
}
private static boolean isClosedInFinallyClause(VarSymbol var, TreePath path, VisitorState state) {
if (!isConsideredFinal(var)) {
return false;
}
Tree parent = path.getParentPath().getLeaf();
if (parent.getKind() != Tree.Kind.BLOCK) {
return false;
}
BlockTree block = (BlockTree) parent;
int idx = block.getStatements().indexOf(path.getLeaf());
if (idx == -1 || idx == block.getStatements().size() - 1) {
return false;
}
StatementTree next = block.getStatements().get(idx + 1);
if (!(next instanceof TryTree)) {
return false;
}
TryTree tryTree = (TryTree) next;
if (tryTree.getFinallyBlock() == null) {
return false;
}
boolean[] closed = {false};
tryTree
.getFinallyBlock()
.accept(
new TreeScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
if (CLOSE_METHOD.matches(tree, state)
&& Objects.equals(getSymbol(getReceiver(tree)), var)) {
closed[0] = true;
}
return null;
}
},
null);
return closed[0];
}
private static Optional<Change> chooseFixType(
ExpressionTree tree, VisitorState state, NameSuggester suggester) {
TreePath path = state.getPath();
Tree parent = path.getParentPath().getLeaf();
if (parent instanceof VariableTree) {
return wrapTryFinallyAroundVariableScope((VariableTree) parent, state);
}
StatementTree stmt = state.findEnclosing(StatementTree.class);
if (stmt == null) {
return Optional.empty();
}
if (!(stmt instanceof VariableTree)) {
return introduceSingleStatementTry(tree, stmt, state, suggester);
}
VarSymbol varSym = getSymbol((VariableTree) stmt);
if (varSym.getKind() == ElementKind.RESOURCE_VARIABLE) {
return extractToResourceInCurrentTry(tree, stmt, state, suggester);
}
return splitVariableDeclarationAroundTry(tree, (VariableTree) stmt, state, suggester);
}
private static Optional<Change> introduceSingleStatementTry(
ExpressionTree tree, StatementTree stmt, VisitorState state, NameSuggester suggester) {
SuggestedFix.Builder fix = SuggestedFix.builder();
String name = suggester.suggestName(tree);
if (state.getPath().getParentPath().getLeaf() instanceof ExpressionStatementTree) {
fix.delete(stmt);
} else {
fix.replace(tree, name);
}
return Change.builder(
fix.prefixWith(
stmt, String.format("try (var %s = %s) {", name, state.getSourceForNode(tree)))
.build())
.closeBraceAfter(stmt)
.wrapped();
}
private static Optional<Change> extractToResourceInCurrentTry(
ExpressionTree tree,
StatementTree declaringStatement,
VisitorState state,
NameSuggester suggester) {
Type type = getType(tree);
if (type == null) {
return Optional.empty();
}
String name = suggester.suggestName(tree);
SuggestedFix.Builder fix = SuggestedFix.builder();
return Change.of(
SuggestedFix.builder()
.prefixWith(
declaringStatement,
String.format(
"%s %s = %s;",
qualifyType(state, fix, type), name, state.getSourceForNode(tree)))
.replace(tree, name)
.build());
}
private static Optional<Change> splitVariableDeclarationAroundTry(
ExpressionTree tree, VariableTree var, VisitorState state, NameSuggester suggester) {
int initPos = getStartPosition(var.getInitializer());
int afterTypePos = state.getEndPosition(var.getType());
String name = suggester.suggestName(tree);
return Change.builder(
SuggestedFix.builder()
.replace(
afterTypePos,
initPos,
String.format(
" %s;\ntry (var %s = %s) {\n%s =",
var.getName(), name, state.getSourceForNode(tree), var.getName()))
.replace(tree, name)
.build())
.closeBraceAfter(var)
.wrapped();
}
private static Optional<Change> wrapTryFinallyAroundVariableScope(
VariableTree decl, VisitorState state) {
BlockTree enclosingBlock = state.findEnclosing(BlockTree.class);
if (enclosingBlock == null) {
return Optional.empty();
}
Tree declTree = decl.getType();
String declType =
state.getEndPosition(declTree) == Position.NOPOS ? "var" : state.getSourceForNode(declTree);
return Change.builder(
SuggestedFix.builder()
.delete(decl)
.prefixWith(
decl,
String.format(
"try (%s %s = %s) {",
declType, decl.getName(), state.getSourceForNode(decl.getInitializer())))
.build())
.closeBraceAfter(enclosingBlock)
.wrapped();
}
}
| 20,024
| 38.264706
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CompileTimeConstantChecker.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.LinkType.NONE;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.CompileTimeConstantExpressionMatcher.hasCompileTimeConstantAnnotation;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.AssignmentTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.LambdaExpressionTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.matchers.CompileTimeConstantExpressionMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
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.VariableTree;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.lang.model.element.ElementKind;
/** A Bugpattern; see the accompanying Markdown documentation. */
@BugPattern(
name = "CompileTimeConstant",
summary =
"Non-compile-time constant expression passed to parameter with "
+ "@CompileTimeConstant type annotation.",
linkType = NONE,
severity = ERROR)
public class CompileTimeConstantChecker extends BugChecker
implements LambdaExpressionTreeMatcher,
MemberReferenceTreeMatcher,
MethodInvocationTreeMatcher,
MethodTreeMatcher,
NewClassTreeMatcher,
VariableTreeMatcher,
AssignmentTreeMatcher {
private static final String DID_YOU_MEAN_FINAL_FMT_MESSAGE = " Did you mean to make '%s' final?";
private final Matcher<ExpressionTree> compileTimeConstExpressionMatcher =
CompileTimeConstantExpressionMatcher.instance();
/**
* Matches formal parameters with {@link com.google.errorprone.annotations.CompileTimeConstant}
* annotations against corresponding actual parameters.
*
* @param state the visitor state
* @param calleeSymbol the method whose formal parameters to consider
* @param actualParams the list of actual parameters
* @return a {@code Description} of the match <i>iff</i> for any of the actual parameters that is
* annotated with {@link com.google.errorprone.annotations.CompileTimeConstant}, the
* corresponding formal parameter is not a compile-time-constant expression in the sense of
* {@link CompileTimeConstantExpressionMatcher}. Otherwise returns {@code
* Description.NO_MATCH}.
*/
private Description matchArguments(
VisitorState state,
Symbol.MethodSymbol calleeSymbol,
Iterator<? extends ExpressionTree> actualParams) {
Symbol.VarSymbol lastFormalParam = null;
for (Symbol.VarSymbol formalParam : calleeSymbol.getParameters()) {
lastFormalParam = formalParam;
// It appears that for some reason, the Tree for implicit Enum constructors
// includes an invocation of super(), but the target symbol has the signature
// Enum(String, int). This resulted in NoSuchElementExceptions.
// It is safe to return no match in this case, since even if this could happen
// in another scenario, a non-existent actual parameter can't possibly
// be a non-constant parameter for a @CompileTimeConstant formal.
if (!actualParams.hasNext()) {
return Description.NO_MATCH;
}
ExpressionTree actualParam = actualParams.next();
if (hasCompileTimeConstantAnnotation(state, formalParam)) {
if (!compileTimeConstExpressionMatcher.matches(actualParam, state)) {
return handleMatch(actualParam, state);
}
}
}
// If the last formal parameter is a vararg and has the @CompileTimeConstant annotation,
// we need to check the remaining args as well.
if (lastFormalParam == null) {
return Description.NO_MATCH;
}
if (!calleeSymbol.isVarArgs()) {
return Description.NO_MATCH;
}
if (!hasCompileTimeConstantAnnotation(state, lastFormalParam)) {
return Description.NO_MATCH;
}
while (actualParams.hasNext()) {
ExpressionTree actualParam = actualParams.next();
if (!compileTimeConstExpressionMatcher.matches(actualParam, state)) {
return handleMatch(actualParam, state);
}
}
return Description.NO_MATCH;
}
/**
* If the non-constant variable is annotated with @CompileTimeConstant, it must have been
* non-final. Suggest making it final in the error message.
*/
private Description handleMatch(ExpressionTree actualParam, VisitorState state) {
Symbol sym = ASTHelpers.getSymbol(actualParam);
if (!(sym instanceof VarSymbol)) {
return describeMatch(actualParam);
}
VarSymbol var = (VarSymbol) sym;
if (!hasCompileTimeConstantAnnotation(state, var)) {
return describeMatch(actualParam);
}
return buildDescription(actualParam)
.setMessage(
this.message() + String.format(DID_YOU_MEAN_FINAL_FMT_MESSAGE, var.getSimpleName()))
.build();
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
Symbol.MethodSymbol sym = ASTHelpers.getSymbol(tree);
return matchArguments(state, sym, tree.getArguments().iterator());
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
Symbol.MethodSymbol sym = ASTHelpers.getSymbol(tree);
return matchArguments(state, sym, tree.getArguments().iterator());
}
@Override
public Description matchMethod(MethodTree node, VisitorState state) {
Symbol.MethodSymbol method = ASTHelpers.getSymbol(node);
List<Integer> compileTimeConstantAnnotationIndexes =
getAnnotatedParams(method.getParameters(), state);
if (compileTimeConstantAnnotationIndexes.isEmpty()) {
return Description.NO_MATCH;
}
return checkSuperMethods(
node,
state,
compileTimeConstantAnnotationIndexes,
ASTHelpers.findSuperMethods(method, state.getTypes()));
}
@Override
public Description matchMemberReference(MemberReferenceTree node, VisitorState state) {
Symbol.MethodSymbol sym = ASTHelpers.getSymbol(node);
List<Integer> compileTimeConstantAnnotationIndexes =
getAnnotatedParams(sym.getParameters(), state);
if (compileTimeConstantAnnotationIndexes.isEmpty()) {
return Description.NO_MATCH;
}
return checkLambda(node, state, compileTimeConstantAnnotationIndexes);
}
@Override
public Description matchLambdaExpression(LambdaExpressionTree node, VisitorState state) {
List<Integer> compileTimeConstantAnnotationIndexes =
getAnnotatedParams(
node.getParameters().stream().map(ASTHelpers::getSymbol).collect(toImmutableList()),
state);
if (compileTimeConstantAnnotationIndexes.isEmpty()) {
return Description.NO_MATCH;
}
return checkLambda(node, state, compileTimeConstantAnnotationIndexes);
}
@Override
public Description matchVariable(VariableTree node, VisitorState state) {
Symbol symbol = ASTHelpers.getSymbol(node);
if (!hasCompileTimeConstantAnnotation(state, symbol)) {
return Description.NO_MATCH;
}
switch (symbol.getKind()) {
case PARAMETER:
return Description.NO_MATCH;
case FIELD:
break; // continue below
case LOCAL_VARIABLE: // disallowed by @Target meta-annotation
default: // impossible
throw new AssertionError(symbol.getKind());
}
if ((symbol.flags() & Flags.FINAL) == 0) {
return buildDescription(node)
.setMessage(
this.message()
+ String.format(DID_YOU_MEAN_FINAL_FMT_MESSAGE, symbol.getSimpleName()))
.build();
}
if (node.getInitializer() != null
&& !compileTimeConstExpressionMatcher.matches(node.getInitializer(), state)) {
return describeMatch(node.getInitializer());
}
return Description.NO_MATCH;
}
@Override
public Description matchAssignment(AssignmentTree node, VisitorState state) {
ExpressionTree variable = node.getVariable();
ExpressionTree expression = node.getExpression();
Symbol assignedSymbol = ASTHelpers.getSymbol(variable);
if (assignedSymbol == null || assignedSymbol.owner == null) {
return Description.NO_MATCH;
}
if (assignedSymbol.owner.getKind() != ElementKind.CLASS
&& assignedSymbol.owner.getKind() != ElementKind.ENUM) {
return Description.NO_MATCH;
}
if (!hasCompileTimeConstantAnnotation(state, assignedSymbol)) {
return Description.NO_MATCH;
}
if (compileTimeConstExpressionMatcher.matches(expression, state)) {
return Description.NO_MATCH;
}
return describeMatch(expression);
}
private Description checkLambda(
ExpressionTree node, VisitorState state, List<Integer> compileTimeConstantAnnotationIndexes) {
MethodSymbol descriptorSymbol =
(MethodSymbol) state.getTypes().findDescriptorSymbol(ASTHelpers.getType(node).tsym);
ImmutableSet.Builder<Symbol.MethodSymbol> methods = ImmutableSet.builder();
methods.add(descriptorSymbol);
methods.addAll(ASTHelpers.findSuperMethods(descriptorSymbol, state.getTypes()));
return checkSuperMethods(node, state, compileTimeConstantAnnotationIndexes, methods.build());
}
private static List<Integer> getAnnotatedParams(List<VarSymbol> params, VisitorState state) {
List<Integer> compileTimeConstantAnnotationIndexes = new ArrayList<>();
for (int i = 0; i < params.size(); i++) {
if (hasCompileTimeConstantAnnotation(state, params.get(i))) {
compileTimeConstantAnnotationIndexes.add(i);
}
}
return compileTimeConstantAnnotationIndexes;
}
private Description checkSuperMethods(
Tree node,
VisitorState state,
List<Integer> compileTimeConstantAnnotationIndexes,
Iterable<MethodSymbol> superMethods) {
for (Symbol.MethodSymbol superMethod : superMethods) {
for (Integer index : compileTimeConstantAnnotationIndexes) {
if (!hasCompileTimeConstantAnnotation(state, superMethod.getParameters().get(index))) {
return buildDescription(node)
.setMessage(
"Method with @CompileTimeConstant parameter can't override method without it.")
.build();
}
}
}
return Description.NO_MATCH;
}
}
| 12,008
| 40.126712
| 115
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SelfEquals.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.instanceEqualsInvocation;
import static com.google.errorprone.matchers.Matchers.receiverSameAsArgument;
import static com.google.errorprone.matchers.Matchers.sameArgument;
import static com.google.errorprone.matchers.Matchers.staticEqualsInvocation;
import static com.google.errorprone.matchers.Matchers.toType;
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.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;
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.TypeSymbol;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import java.util.List;
import javax.annotation.Nullable;
/**
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary = "Testing an object for equality with itself will always be true.",
severity = ERROR)
public class SelfEquals extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<Tree> ASSERTION =
toType(
MethodInvocationTree.class,
staticMethod().anyClass().namedAnyOf("assertTrue", "assertThat"));
private static final Matcher<MethodInvocationTree> INSTANCE_MATCHER =
allOf(instanceEqualsInvocation(), receiverSameAsArgument(0));
private static final Matcher<MethodInvocationTree> STATIC_MATCHER =
allOf(staticEqualsInvocation(), sameArgument(0, 1));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (ASSERTION.matches(state.getPath().getParentPath().getLeaf(), state)) {
return NO_MATCH;
}
List<? extends ExpressionTree> args = tree.getArguments();
ExpressionTree toReplace;
if (INSTANCE_MATCHER.matches(tree, state)) {
toReplace = args.get(0);
} else if (STATIC_MATCHER.matches(tree, state)) {
if (args.get(0).getKind() == Kind.IDENTIFIER && args.get(1).getKind() != Kind.IDENTIFIER) {
toReplace = args.get(0);
} else {
toReplace = args.get(1);
}
} else {
return NO_MATCH;
}
Description.Builder description = buildDescription(tree);
Fix fix = fieldFix(toReplace, state);
if (fix != null) {
description.addFix(fix);
}
return description.build();
}
@Nullable
protected static Fix fieldFix(Tree toReplace, VisitorState state) {
TreePath path = state.getPath();
while (path != null
&& path.getLeaf().getKind() != Kind.CLASS
&& path.getLeaf().getKind() != Kind.BLOCK) {
path = path.getParentPath();
}
if (path == null) {
return null;
}
List<? extends JCTree> members;
// Must be block or class
if (path.getLeaf().getKind() == Kind.CLASS) {
members = ((JCClassDecl) path.getLeaf()).getMembers();
} else {
members = ((JCBlock) path.getLeaf()).getStatements();
}
for (JCTree jcTree : members) {
if (jcTree.getKind() == Kind.VARIABLE) {
JCVariableDecl declaration = (JCVariableDecl) jcTree;
TypeSymbol variableTypeSymbol =
state.getTypes().erasure(ASTHelpers.getType(declaration)).tsym;
if (ASTHelpers.getSymbol(toReplace).isMemberOf(variableTypeSymbol, state.getTypes())) {
if (toReplace.getKind() == Kind.IDENTIFIER) {
return SuggestedFix.prefixWith(toReplace, declaration.getName() + ".");
} else {
return SuggestedFix.replace(
((JCFieldAccess) toReplace).getExpression(), declaration.getName().toString());
}
}
}
}
return null;
}
}
| 5,134
| 37.609023
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ComparableType.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.getType;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.Signatures;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ClassType;
/**
* @author amesbah@google.com (Ali Mesbah)
*/
@BugPattern(
summary =
"Implementing 'Comparable<T>' where T is not the same as the implementing class is"
+ " incorrect, since it violates the symmetry contract of compareTo.",
severity = ERROR)
public class ComparableType extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
Type comparableType = state.getSymtab().comparableType;
return tree.getImplementsClause().stream()
.filter(impl -> isSameType(getType(impl), comparableType, state))
.findAny()
.map(impl -> match(tree, impl, state))
.orElse(NO_MATCH);
}
Description match(ClassTree tree, Tree impl, VisitorState state) {
Type implType = getType(impl);
ClassType type = getType(tree);
if (implType.getTypeArguments().isEmpty()) {
return buildDescription(tree).setMessage("Comparable should not be raw").build();
}
Type comparableTypeArgument = getOnlyElement(implType.getTypeArguments());
if (!isSameType(type, comparableTypeArgument, state)) {
return buildDescription(tree)
.setMessage(
String.format(
"Type of Comparable (%s) is not the same as implementing class (%s).",
Signatures.prettyType(comparableTypeArgument), Signatures.prettyType(type)))
.build();
}
return NO_MATCH;
}
}
| 2,846
| 39.098592
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CheckedExceptionNotThrown.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
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 static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getThrownExceptions;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isCheckedExceptionType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static com.google.errorprone.util.ASTHelpers.methodCanBeOverridden;
import static java.util.stream.Collectors.joining;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Streams;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.ErrorProneToken;
import com.google.errorprone.util.ErrorProneTokens;
import com.sun.source.doctree.DocCommentTree;
import com.sun.source.doctree.ReferenceTree;
import com.sun.source.doctree.ThrowsTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.DocSourcePositions;
import com.sun.source.util.DocTreePath;
import com.sun.source.util.DocTreePathScanner;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.parser.Tokens.TokenKind;
import java.util.Objects;
import java.util.stream.Stream;
import javax.lang.model.element.Element;
/** Flags checked exceptions which are claimed to be thrown, but are not. */
@BugPattern(
summary =
"This method cannot throw a checked exception that it claims to. This may cause consumers"
+ " of the API to incorrectly attempt to handle, or propagate, this exception.",
severity = WARNING)
public final class CheckedExceptionNotThrown extends BugChecker implements MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (tree.getThrows().isEmpty()) {
return NO_MATCH;
}
// Don't match test methods: that's rather noisy.
MethodSymbol symbol = getSymbol(tree);
if (methodCanBeOverridden(symbol)
|| state.errorProneOptions().isTestOnlyTarget()
|| tree.getBody() == null) {
return NO_MATCH;
}
ImmutableSet<Type> thrownExceptions =
treesToScanForCheckedExceptions(tree, state)
.flatMap(t -> getThrownExceptions(t, state).stream())
.filter(t -> isCheckedExceptionType(t, state))
.collect(toImmutableSet());
ImmutableList<ExpressionTree> canActuallyBeThrown =
tree.getThrows().stream()
.filter(
et -> {
Type type = getType(et);
return !isCheckedExceptionType(type, state)
|| thrownExceptions.stream().anyMatch(t -> isSubtype(t, type, state));
})
.collect(toImmutableList());
if (tree.getThrows().equals(canActuallyBeThrown)) {
return NO_MATCH;
}
ImmutableSet<Type> thrownTypes =
canActuallyBeThrown.stream()
.map(ASTHelpers::getType)
.filter(Objects::nonNull)
.collect(toImmutableSet());
String unthrown =
tree.getThrows().stream()
.filter(et -> !canActuallyBeThrown.contains(et))
.map(state::getSourceForNode)
.sorted()
.collect(joining(", ", "(", ")"));
String description =
String.format(
"This method does not throw checked exceptions %s despite claiming to. This may cause"
+ " consumers of the API to incorrectly attempt to handle, or propagate, this"
+ " exception.",
unthrown);
SuggestedFix throwsFix =
canActuallyBeThrown.isEmpty()
? deleteEntireThrowsClause(tree, state)
: SuggestedFix.replace(
getStartPosition(tree.getThrows().get(0)),
state.getEndPosition(getLast(tree.getThrows())),
canActuallyBeThrown.stream().map(state::getSourceForNode).collect(joining(", ")));
SuggestedFix fix =
SuggestedFix.builder().merge(fixJavadoc(thrownTypes, state)).merge(throwsFix).build();
return buildDescription(tree.getThrows().get(0)).setMessage(description).addFix(fix).build();
}
private static Stream<Tree> treesToScanForCheckedExceptions(MethodTree tree, VisitorState state) {
if (getSymbol(tree).isStatic()) {
return Stream.of(tree.getBody());
}
return Streams.concat(
Stream.of(tree.getBody()), fieldInitializers(state.findEnclosing(ClassTree.class)));
}
private static Stream<ExpressionTree> fieldInitializers(ClassTree tree) {
return tree.getMembers().stream()
.filter(VariableTree.class::isInstance)
.map(VariableTree.class::cast)
.filter(v -> !getSymbol(v).isStatic())
.map(VariableTree::getInitializer)
.filter(i -> i != null);
}
private SuggestedFix fixJavadoc(ImmutableSet<Type> actuallyThrownTypes, VisitorState state) {
DocCommentTree docCommentTree =
JavacTrees.instance(state.context).getDocCommentTree(state.getPath());
if (docCommentTree == null) {
return SuggestedFix.emptyFix();
}
SuggestedFix.Builder fix = SuggestedFix.builder();
DocTreePath docTreePath = new DocTreePath(state.getPath(), docCommentTree);
new DocTreePathScanner<Void, Void>() {
@Override
public Void visitThrows(ThrowsTree throwsTree, Void unused) {
ReferenceTree exName = throwsTree.getExceptionName();
Element element =
JavacTrees.instance(state.context)
.getElement(new DocTreePath(getCurrentPath(), exName));
if (element != null) {
Type type = (Type) element.asType();
if (!actuallyThrownTypes.contains(type)) {
DocSourcePositions positions = JavacTrees.instance(state.context).getSourcePositions();
CompilationUnitTree compilationUnitTree = state.getPath().getCompilationUnit();
fix.replace(
(int) positions.getStartPosition(compilationUnitTree, docCommentTree, throwsTree),
(int) positions.getEndPosition(compilationUnitTree, docCommentTree, throwsTree),
"");
}
}
return super.visitThrows(throwsTree, null);
}
}.scan(docTreePath, null);
return fix.build();
}
private static SuggestedFix deleteEntireThrowsClause(MethodTree tree, VisitorState state) {
int endPos = state.getEndPosition(getLast(tree.getThrows()));
int methodStartPos = getStartPosition(tree);
int startPos =
ErrorProneTokens.getTokens(
state.getSourceCode().subSequence(methodStartPos, endPos).toString(),
methodStartPos,
state.context)
.stream()
.filter(token -> token.kind().equals(TokenKind.THROWS))
.findFirst()
.map(ErrorProneToken::pos)
.get();
return SuggestedFix.replace(startPos, endPos, "");
}
}
| 8,493
| 41.258706
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LabelledBreakTarget.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 com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.LabeledStatementTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.LabeledStatementTree;
/** A BugPattern; see the summary. */
@BugPattern(summary = "Labels should only be used on loops.", severity = WARNING)
public class LabelledBreakTarget extends BugChecker implements LabeledStatementTreeMatcher {
@Override
public Description matchLabeledStatement(LabeledStatementTree tree, VisitorState state) {
switch (tree.getStatement().getKind()) {
case DO_WHILE_LOOP:
case ENHANCED_FOR_LOOP:
case FOR_LOOP:
case WHILE_LOOP:
return NO_MATCH;
default:
break;
}
return describeMatch(tree);
}
}
| 1,618
| 34.977778
| 92
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/IsInstanceOfClass.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.argument;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import com.google.auto.value.AutoValue;
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.matchers.Matchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.tree.JCTree;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "The argument to Class#isInstance(Object) should not be a Class",
severity = ERROR)
public class IsInstanceOfClass extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<MethodInvocationTree> INSTANCE_OF_CLASS =
Matchers.allOf(
instanceMethod().onExactClass("java.lang.Class").named("isInstance"),
argument(
0,
// Class is final so we could just use isSameType, but we want to
// test for the same _erased_ type.
Matchers.<ExpressionTree>isSubtypeOf("java.lang.Class")));
/** Suggests removing getClass() or changing to Class.class. */
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!INSTANCE_OF_CLASS.matches(tree, state)) {
return Description.NO_MATCH;
}
return describeMatch(tree, SuggestedFix.replace(tree, buildReplacement(tree, state)));
}
static String buildReplacement(MethodInvocationTree tree, VisitorState state) {
Operand lhs = classify((JCTree) ASTHelpers.getReceiver(tree.getMethodSelect()), state);
Operand rhs = classify((JCTree) Iterables.getOnlyElement(tree.getArguments()), state);
// expr.getClass().isInstance(Bar.class) -> expr instanceof Bar
if (lhs.kind() == Kind.GET_CLASS && rhs.kind() == Kind.LITERAL) {
return String.format("%s instanceof %s", lhs.value(), rhs.value());
}
// expr1.getClass().isInstance(expr2.getClass()) -> expr2.getClass().isInstance(expr1)
if (lhs.kind() == Kind.GET_CLASS && rhs.kind() == Kind.GET_CLASS) {
return String.format("%s.getClass().isInstance(%s)", rhs.value(), lhs.value());
}
// Foo.class.isInstance(Bar.class) -> Bar.class == Class.class
if (lhs.kind() == Kind.LITERAL && rhs.kind() == Kind.LITERAL) {
return String.format("%s.class == Class.class", rhs.value()); // !!
}
// Foo.class.isInstance(expr.getClass()) -> expr instanceof Foo
if (lhs.kind() == Kind.LITERAL && rhs.kind() == Kind.GET_CLASS) {
return String.format("%s instanceof %s", rhs.value(), lhs.value());
}
// clazz.isInstance(expr.getClass()) -> clazz.isInstance(expr)
if (rhs.kind() == Kind.GET_CLASS) {
return String.format("%s.isInstance(%s)", lhs.source(), rhs.value());
}
// expr.getClass().isInstance(clazz) -> clazz.isInstance(expr)
if (lhs.kind() == Kind.GET_CLASS) {
return String.format("%s.isInstance(%s)", rhs.source(), lhs.value());
}
// clazz1.isInstance(clazz2) -> clazz2.isAssignableFrom(clazz1)
// clazz.isInstance(Bar.class) -> Bar.class.isAssignableFrom(clazz)
// Foo.class.isInstance(clazz) -> clazz.isAssignableFrom(Foo.class)
return String.format("%s.isAssignableFrom(%s)", rhs.source(), lhs.source());
}
enum Kind {
LITERAL,
GET_CLASS,
EXPR
}
@AutoValue
abstract static class Operand {
abstract Kind kind();
abstract CharSequence value();
abstract CharSequence source();
static Operand create(Kind kind, CharSequence value, CharSequence source) {
return new AutoValue_IsInstanceOfClass_Operand(kind, value, source);
}
}
static Operand classify(JCTree tree, VisitorState state) {
CharSequence source = state.getSourceForNode(tree);
if (tree instanceof MethodInvocationTree) {
// expr.getClass() -> "expr"
MethodInvocationTree receiverInvocation = (MethodInvocationTree) tree;
MethodSymbol sym = ASTHelpers.getSymbol(receiverInvocation);
if (sym.getSimpleName().contentEquals("getClass") && sym.params().isEmpty()) {
if (receiverInvocation.getMethodSelect() instanceof IdentifierTree) {
// unqualified `getClass()`
return Operand.create(Kind.EXPR, state.getSourceForNode(tree), source);
}
return Operand.create(
Kind.GET_CLASS,
state.getSourceForNode(ASTHelpers.getReceiver(receiverInvocation)),
source);
}
} else if (tree instanceof MemberSelectTree) {
// Foo.class -> "Foo"
MemberSelectTree select = (MemberSelectTree) tree;
if (select.getIdentifier().contentEquals("class")) {
return Operand.create(Kind.LITERAL, state.getSourceForNode(select.getExpression()), source);
}
}
return Operand.create(Kind.EXPR, source, source);
}
}
| 6,091
| 39.613333
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AssertThrowsMultipleStatements.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.matchers.Description.NO_MATCH;
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.SeverityLevel;
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.BlockTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import java.util.List;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "The lambda passed to assertThrows should contain exactly one statement",
severity = SeverityLevel.WARNING)
public class AssertThrowsMultipleStatements extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
staticMethod().onClass("org.junit.Assert").named("assertThrows");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
ExpressionTree arg = getLast(tree.getArguments());
if (!(arg instanceof LambdaExpressionTree)) {
return NO_MATCH;
}
Tree body = ((LambdaExpressionTree) arg).getBody();
if (!(body instanceof BlockTree)) {
return NO_MATCH;
}
List<? extends StatementTree> statements = ((BlockTree) body).getStatements();
if (statements.size() <= 1) {
return NO_MATCH;
}
StatementTree last = getLast(statements);
int startPosition = getStartPosition(statements.get(0));
int endPosition = state.getEndPosition(statements.get(statements.size() - 2));
SuggestedFix.Builder fix = SuggestedFix.builder();
// if the last statement is an expression, convert from a block to expression lambda
if (last instanceof ExpressionStatementTree) {
fix.replace(body, state.getSourceForNode(((ExpressionStatementTree) last).getExpression()));
} else {
fix.replace(startPosition, endPosition, "");
}
fix.prefixWith(
state.findEnclosing(StatementTree.class),
state.getSourceCode().subSequence(startPosition, endPosition).toString());
return describeMatch(last, fix.build());
}
}
| 3,434
| 40.385542
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnusedCollectionModifiedInPlace.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.anyOf;
import static com.google.errorprone.matchers.Matchers.argument;
import static com.google.errorprone.matchers.Matchers.kindIs;
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;
import com.sun.source.tree.Tree.Kind;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@BugPattern(
summary = "Collection is modified in place, but the result is not used",
severity = ERROR)
public class UnusedCollectionModifiedInPlace extends BugChecker
implements MethodInvocationTreeMatcher {
/**
* Matches "destructive" methods in java.util.Collections, which modify their first argument in
* place and return void.
*/
private static final Matcher<MethodInvocationTree> COLLECTIONS_DESTRUCTIVE =
anyOf(
staticMethod().onClass("java.util.Collections").named("copy"),
staticMethod().onClass("java.util.Collections").named("fill"),
staticMethod().onClass("java.util.Collections").named("reverse"),
staticMethod().onClass("java.util.Collections").named("rotate"),
staticMethod().onClass("java.util.Collections").named("shuffle"),
staticMethod().onClass("java.util.Collections").named("sort"),
staticMethod().onClass("java.util.Collections").named("swap"));
/**
* Matches cases where the first argument to the method call constructs a new list, but the result
* is not assigned.
*/
private static final Matcher<MethodInvocationTree> FIRST_ARG_CONSTRUCTS_NEW_LIST =
argument(
0,
anyOf(
staticMethod().onClass("com.google.common.collect.Lists").named("newArrayList"),
staticMethod().onClass("com.google.common.collect.Lists").named("newLinkedList"),
kindIs(Kind.NEW_CLASS)));
private static final Matcher<MethodInvocationTree> MATCHER =
allOf(COLLECTIONS_DESTRUCTIVE, FIRST_ARG_CONSTRUCTS_NEW_LIST);
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
return describeMatch(tree);
}
}
| 3,274
| 39.9375
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InterruptedExceptionSwallowed.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getLast;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFixes.qualifyType;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.MAIN_METHOD;
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.isSameType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static java.lang.Boolean.TRUE;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.TryTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.ASTHelpers.ScanThrownTypes;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.InstanceOfTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.ThrowTree;
import com.sun.source.tree.TryTree;
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.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.UnionClassType;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import javax.annotation.Nullable;
/**
* Checks for cases where an {@link InterruptedException} is caught as part of a catch block
* catching a supertype, and not specially handled.
*/
@BugPattern(
summary =
"This catch block appears to be catching an explicitly declared InterruptedException as an"
+ " Exception/Throwable and not handling the interruption separately.",
severity = WARNING,
documentSuppression = false)
public final class InterruptedExceptionSwallowed extends BugChecker
implements MethodTreeMatcher, TryTreeMatcher {
private static final String METHOD_DESCRIPTION =
"This method can throw InterruptedException but declares that it throws Exception/Throwable."
+ " This makes it difficult for callers to recognize the need to handle interruption"
+ " properly.";
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (state.errorProneOptions().isTestOnlyTarget()) {
return NO_MATCH;
}
if (MAIN_METHOD.matches(tree, state)) {
return NO_MATCH;
}
Type interrupted = state.getSymtab().interruptedExceptionType;
if (tree.getThrows().stream().anyMatch(t -> isSubtype(getType(t), interrupted, state))) {
return NO_MATCH;
}
ImmutableSet<Type> thrownExceptions = ASTHelpers.getThrownExceptions(tree.getBody(), state);
// Bail out if none of the exceptions thrown are subtypes of InterruptedException.
if (thrownExceptions.stream().noneMatch(t -> isSubtype(t, interrupted, state))) {
return NO_MATCH;
}
// Bail if any of the thrown exceptions are masking InterruptedException: that is, we don't want
// to suggest updating with `throws Exception, InterruptedException`.
if (thrownExceptions.stream()
.anyMatch(t -> !isSameType(t, interrupted, state) && isSubtype(interrupted, t, state))) {
return NO_MATCH;
}
Set<Type> exceptions =
Stream.concat(
thrownExceptions.stream()
.filter(t -> !isSubtype(t, state.getSymtab().runtimeExceptionType, state)),
tree.getThrows().stream()
.filter(t -> !isSubtype(interrupted, getType(t), state))
.map(ASTHelpers::getType))
.collect(toCollection(HashSet::new));
for (Type type : ImmutableSet.copyOf(exceptions)) {
exceptions.removeIf(t -> !isSameType(t, type, state) && isSubtype(t, type, state));
}
// Don't suggest adding more than five exceptions to the method signature.
if (exceptions.size() > 5) {
return NO_MATCH;
}
SuggestedFix fix = narrowExceptionTypes(tree, exceptions, state);
return buildDescription(tree).setMessage(METHOD_DESCRIPTION).addFix(fix).build();
}
private static SuggestedFix narrowExceptionTypes(
MethodTree tree, Set<Type> exceptions, VisitorState state) {
SuggestedFix.Builder fix = SuggestedFix.builder();
fix.replace(
getStartPosition(tree.getThrows().get(0)),
state.getEndPosition(getLast(tree.getThrows())),
exceptions.stream().map(t -> qualifyType(state, fix, t)).sorted().collect(joining(", ")));
return fix.build();
}
@Override
public Description matchTry(TryTree tree, VisitorState state) {
for (CatchTree catchTree : tree.getCatches()) {
Type type = getType(catchTree.getParameter());
Type interrupted = state.getSymtab().interruptedExceptionType;
ImmutableList<Type> caughtTypes = extractTypes(type);
if (caughtTypes.stream().anyMatch(t -> isSubtype(t, interrupted, state))) {
return NO_MATCH;
}
if (caughtTypes.stream().anyMatch(t -> isSubtype(interrupted, t, state))) {
ImmutableSet<Type> thrownExceptions = getThrownExceptions(tree, state);
if (thrownExceptions.stream().anyMatch(t -> isSubtype(t, interrupted, state))
&& !blockChecksForInterruptedException(catchTree.getBlock(), state)
&& !(exceptionIsRethrown(catchTree, catchTree.getParameter(), state)
&& methodDeclaresInterruptedException(state.findEnclosing(MethodTree.class), state))
&& !isSuppressed(catchTree.getParameter(), state)) {
return describeMatch(catchTree, createFix(catchTree));
}
}
}
return NO_MATCH;
}
private boolean exceptionIsRethrown(
CatchTree catchTree, VariableTree parameter, VisitorState state) {
AtomicBoolean rethrown = new AtomicBoolean();
new TreePathScanner<Void, Void>() {
@Override
public Void visitThrow(ThrowTree throwTree, Void unused) {
VarSymbol parameterSymbol = getSymbol(parameter);
if (parameterSymbol.equals(getSymbol(throwTree.getExpression()))) {
rethrown.set(true);
}
return super.visitThrow(throwTree, null);
}
}.scan(new TreePath(state.getPath(), catchTree), null);
return rethrown.get();
}
private boolean methodDeclaresInterruptedException(MethodTree enclosing, VisitorState state) {
if (enclosing == null) {
return false;
}
return enclosing.getThrows().stream()
.anyMatch(t -> isSameType(getType(t), state.getSymtab().interruptedExceptionType, state));
}
private static SuggestedFix createFix(CatchTree catchTree) {
List<? extends StatementTree> block = catchTree.getBlock().getStatements();
String fix =
String.format(
"if (%s instanceof InterruptedException) {\nThread.currentThread().interrupt();\n}\n",
catchTree.getParameter().getName());
if (block.isEmpty()) {
return SuggestedFix.replace(catchTree.getBlock(), String.format("{%s}", fix));
}
return SuggestedFix.prefixWith(block.get(0), fix);
}
private static boolean blockChecksForInterruptedException(BlockTree block, VisitorState state) {
return TRUE.equals(
new TreeScanner<Boolean, Void>() {
@Override
public Boolean reduce(Boolean a, Boolean b) {
return TRUE.equals(a) || TRUE.equals(b);
}
@Override
public Boolean visitInstanceOf(InstanceOfTree instanceOfTree, Void unused) {
return isSubtype(
getType(instanceOfTree.getType()),
state.getSymtab().interruptedExceptionType,
state);
}
}.scan(block, null));
}
/**
* Returns the exceptions that need to be handled by {@code tryTree}'s catch blocks, or be
* propagated out.
*/
private static ImmutableSet<Type> getThrownExceptions(TryTree tryTree, VisitorState state) {
ScanThrownTypes scanner = new ScanThrownTypes(state);
scanner.scanResources(tryTree);
scanner.scan(tryTree.getBlock(), null);
return ImmutableSet.copyOf(scanner.getThrownTypes());
}
private static ImmutableList<Type> extractTypes(@Nullable Type type) {
if (type == null) {
return ImmutableList.of();
}
if (type.isUnion()) {
UnionClassType unionType = (UnionClassType) type;
return ImmutableList.copyOf(unionType.getAlternativeTypes());
}
return ImmutableList.of(type);
}
}
| 9,825
| 40.991453
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/GetClassOnAnnotation.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.method.MethodMatchers.instanceMethod;
import com.google.errorprone.BugPattern;
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;
import java.lang.annotation.Annotation;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Calling getClass() on an annotation may return a proxy class",
severity = ERROR)
public class GetClassOnAnnotation extends BugChecker
implements BugChecker.MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> ANNOTATION_CLASS =
instanceMethod()
.onDescendantOf(Annotation.class.getName())
.named("getClass")
.withNoParameters();
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (ANNOTATION_CLASS.matches(tree, state)) {
return describeMatch(
tree,
SuggestedFix.replace(
state.getEndPosition(ASTHelpers.getReceiver(tree)),
state.getEndPosition(tree),
".annotationType()"));
}
return Description.NO_MATCH;
}
}
| 2,152
| 36.12069
| 91
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/OperatorPrecedence.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.getStartPosition;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.tree.JCTree.JCBinary;
import com.sun.tools.javac.tree.TreeInfo;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Use grouping parenthesis to make the operator precedence explicit",
severity = WARNING,
tags = StandardTags.STYLE)
public class OperatorPrecedence extends BugChecker implements BinaryTreeMatcher {
private static final ImmutableSet<Kind> CONDITIONAL =
Sets.immutableEnumSet(Kind.AND, Kind.OR, Kind.XOR, Kind.CONDITIONAL_AND, Kind.CONDITIONAL_OR);
private static final ImmutableSet<Kind> SHIFT =
Sets.immutableEnumSet(Kind.LEFT_SHIFT, Kind.RIGHT_SHIFT, Kind.UNSIGNED_RIGHT_SHIFT);
private static final ImmutableSet<Kind> ARITHMETIC =
Sets.immutableEnumSet(Kind.PLUS, Kind.MULTIPLY, Kind.DIVIDE, Kind.MINUS);
private static final ImmutableSet<Kind> SAFE_ASSOCIATIVE_OPERATORS =
Sets.immutableEnumSet(Kind.CONDITIONAL_AND, Kind.CONDITIONAL_OR, Kind.PLUS);
@Override
public Description matchBinary(BinaryTree tree, VisitorState state) {
Tree parent = state.getPath().getParentPath().getLeaf();
if (!(parent instanceof BinaryTree)) {
return NO_MATCH;
}
if (TreeInfo.opPrec(((JCBinary) tree).getTag())
== TreeInfo.opPrec(((JCBinary) parent).getTag())) {
return NO_MATCH;
}
if (!isConfusing(tree.getKind(), parent.getKind())) {
return NO_MATCH;
}
return createAppropriateFix(tree, state);
}
private static boolean isConfusing(Kind thisKind, Kind parentKind) {
if (CONDITIONAL.contains(thisKind) && CONDITIONAL.contains(parentKind)) {
return true;
}
return (SHIFT.contains(thisKind) && ARITHMETIC.contains(parentKind))
|| (SHIFT.contains(parentKind) && ARITHMETIC.contains(thisKind));
}
private Description createAppropriateFix(BinaryTree tree, VisitorState state) {
// If our expression is like: (A && B) && C, replace it with (A && B && C) instead of
// ((A && B) && C)
return SAFE_ASSOCIATIVE_OPERATORS.contains(tree.getKind())
&& tree.getLeftOperand() instanceof ParenthesizedTree
!= tree.getRightOperand() instanceof ParenthesizedTree
&& parenthesizedChildHasKind(tree, tree.getKind())
? leftOrRightFix(tree, state)
: basicFix(tree);
}
private Description leftOrRightFix(BinaryTree tree, VisitorState state) {
int startPos;
int endPos;
String prefix = "(";
String postfix = ")";
if (tree.getRightOperand() instanceof ParenthesizedTree) {
startPos = getStartPosition(tree.getRightOperand());
endPos = getStartPosition(tree.getRightOperand()) + 1;
postfix = "";
} else {
startPos = state.getEndPosition(tree.getLeftOperand()) - 1;
endPos = state.getEndPosition(tree.getLeftOperand());
prefix = "";
}
return describeMatch(
tree,
SuggestedFix.builder()
.prefixWith(tree, prefix)
.replace(startPos, endPos, "")
.postfixWith(tree, postfix)
.build());
}
private Description basicFix(BinaryTree tree) {
return describeMatch(
tree, SuggestedFix.builder().prefixWith(tree, "(").postfixWith(tree, ")").build());
}
private static boolean parenthesizedChildHasKind(BinaryTree tree, Kind kind) {
Kind childKind =
ASTHelpers.stripParentheses(
tree.getLeftOperand() instanceof ParenthesizedTree
? tree.getLeftOperand()
: tree.getRightOperand())
.getKind();
return childKind == kind;
}
}
| 5,092
| 37.877863
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ArrayEquals.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.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.argument;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.isArrayType;
import static com.google.errorprone.matchers.Matchers.staticEqualsInvocation;
import static com.google.errorprone.predicates.TypePredicates.isArray;
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.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@BugPattern(summary = "Reference equality used to compare arrays", severity = ERROR)
public class ArrayEquals extends BugChecker implements MethodInvocationTreeMatcher {
/** Matches when the equals instance method is used to compare two arrays. */
private static final Matcher<MethodInvocationTree> instanceEqualsMatcher =
allOf(instanceMethod().onClass(isArray()).named("equals"), argument(0, isArrayType()));
/** Matches when {@link java.util.Objects#equals}-like methods compare two arrays. */
private static final Matcher<MethodInvocationTree> staticEqualsMatcher =
allOf(staticEqualsInvocation(), argument(0, isArrayType()), argument(1, isArrayType()));
/**
* Suggests replacing with Arrays.equals(a, b). Also adds the necessary import statement for
* java.util.Arrays.
*/
@Override
public Description matchMethodInvocation(MethodInvocationTree t, VisitorState state) {
String arg1;
String arg2;
if (instanceEqualsMatcher.matches(t, state)) {
arg1 = state.getSourceForNode(((JCFieldAccess) t.getMethodSelect()).getExpression());
arg2 = state.getSourceForNode(t.getArguments().get(0));
} else if (staticEqualsMatcher.matches(t, state)) {
arg1 = state.getSourceForNode(t.getArguments().get(0));
arg2 = state.getSourceForNode(t.getArguments().get(1));
} else {
return NO_MATCH;
}
Fix fix =
SuggestedFix.builder()
.replace(t, "Arrays.equals(" + arg1 + ", " + arg2 + ")")
.addImport("java.util.Arrays")
.build();
return describeMatch(t, fix);
}
}
| 3,306
| 41.948052
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TruthSelfEquals.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import com.google.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;
import java.util.regex.Pattern;
/**
* Points out if an object is tested for equality/inequality to itself using Truth Libraries.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary =
"isEqualTo should not be used to test an object for equality with itself; the"
+ " assertion will never fail.",
severity = ERROR)
public class TruthSelfEquals extends BugChecker implements MethodInvocationTreeMatcher {
/**
* Matches calls to any Truth method called "isEqualTo"/"isNotEqualTo" with exactly one argument
* in which the receiver is the same reference as the argument.
*
* <p>Examples:
*
* <ul>
* <li>assertThat(a).isEqualTo(a)
* <li>assertThat(a).isNotEqualTo(a)
* <li>assertThat(a).isNotSameInstanceAs(a)
* <li>assertThat(a).isSameInstanceAs(a)
* <li>assertWithMessage(msg).that(a).isEqualTo(a)
* <li>assertWithMessage(msg).that(a).isNotEqualTo(a)
* <li>assertWithMessage(msg).that(a).isNotSameInstanceAs(a)
* <li>assertWithMessage(msg).that(a).isSameInstanceAs(a)
* </ul>
*/
private static final Pattern EQUALS_SAME = Pattern.compile("(isEqualTo|isSameInstanceAs)");
private static final Pattern NOT_EQUALS_NOT_SAME =
Pattern.compile("(isNotEqualTo|isNotSameInstanceAs)");
private static final Matcher<MethodInvocationTree> EQUALS_MATCHER =
allOf(
instanceMethod()
.onDescendantOf("com.google.common.truth.Subject")
.withNameMatching(EQUALS_SAME)
.withParameters("java.lang.Object"),
receiverSameAsParentsArgument());
private static final Matcher<MethodInvocationTree> NOT_EQUALS_MATCHER =
allOf(
instanceMethod()
.onDescendantOf("com.google.common.truth.Subject")
.withNameMatching(NOT_EQUALS_NOT_SAME)
.withParameters("java.lang.Object"),
receiverSameAsParentsArgument());
private static final Matcher<ExpressionTree> ASSERT_THAT =
anyOf(
staticMethod().onClass("com.google.common.truth.Truth").named("assertThat"),
instanceMethod().onDescendantOf("com.google.common.truth.TestVerb").named("that"),
instanceMethod()
.onDescendantOf("com.google.common.truth.StandardSubjectBuilder")
.named("that"));
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState state) {
if (methodInvocationTree.getArguments().isEmpty()) {
return Description.NO_MATCH;
}
Description.Builder description = buildDescription(methodInvocationTree);
ExpressionTree toReplace = methodInvocationTree.getArguments().get(0);
if (EQUALS_MATCHER.matches(methodInvocationTree, state)) {
description
.setMessage(
generateSummary(
ASTHelpers.getSymbol(methodInvocationTree).getSimpleName().toString(), "passes"))
.addFix(suggestEqualsTesterFix(methodInvocationTree, toReplace, state));
} else if (NOT_EQUALS_MATCHER.matches(methodInvocationTree, state)) {
description.setMessage(
generateSummary(
ASTHelpers.getSymbol(methodInvocationTree).getSimpleName().toString(), "fails"));
} else {
return Description.NO_MATCH;
}
Fix fix = SelfEquals.fieldFix(toReplace, state);
if (fix != null) {
description.addFix(fix);
}
return description.build();
}
private static String generateSummary(String methodName, String constantOutput) {
return "The arguments to the "
+ methodName
+ " method are the same object, so it always "
+ constantOutput
+ ". Please change the arguments to point to different objects or "
+ "consider using EqualsTester.";
}
private static Matcher<? super MethodInvocationTree> receiverSameAsParentsArgument() {
return new Matcher<MethodInvocationTree>() {
@Override
public boolean matches(MethodInvocationTree t, VisitorState state) {
ExpressionTree rec = ASTHelpers.getReceiver(t);
if (rec == null) {
return false;
}
if (!ASSERT_THAT.matches(rec, state)) {
return false;
}
if (!ASTHelpers.sameVariable(
getOnlyElement(((MethodInvocationTree) rec).getArguments()),
getOnlyElement(t.getArguments()))) {
return false;
}
return true;
}
};
}
private static Fix suggestEqualsTesterFix(
MethodInvocationTree methodInvocationTree, ExpressionTree toReplace, VisitorState state) {
String equalsTesterSuggest =
"new EqualsTester().addEqualityGroup("
+ state.getSourceForNode(toReplace)
+ ").testEquals()";
return SuggestedFix.builder()
.replace(methodInvocationTree, equalsTesterSuggest)
.addImport("com.google.common.testing.EqualsTester")
.build();
}
}
| 6,520
| 38.283133
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DiscardedPostfixExpression.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.matchers.Description.NO_MATCH;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.UnaryTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.UnaryTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.tree.JCTree.JCLambda;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "The result of this unary operation on a lambda parameter is discarded",
severity = SeverityLevel.ERROR)
public class DiscardedPostfixExpression extends BugChecker implements UnaryTreeMatcher {
@Override
public Description matchUnary(UnaryTree tree, VisitorState state) {
switch (tree.getKind()) {
case POSTFIX_INCREMENT:
case POSTFIX_DECREMENT:
break;
default:
return NO_MATCH;
}
Tree parent = state.getPath().getParentPath().getLeaf();
if (parent.getKind() != Kind.LAMBDA_EXPRESSION) {
return NO_MATCH;
}
JCLambda lambda = (JCLambda) parent;
Symbol sym = ASTHelpers.getSymbol(tree.getExpression());
if (lambda.getParameters().stream().noneMatch(p -> ASTHelpers.getSymbol(p) == sym)) {
return NO_MATCH;
}
return describeMatch(
tree,
SuggestedFix.replace(
tree,
String.format(
"%s %s 1",
state.getSourceForNode(tree.getExpression()),
tree.getKind() == Kind.POSTFIX_INCREMENT ? "+" : "-")));
}
}
| 2,473
| 35.382353
| 90
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/Varifier.java
|
/*
* Copyright 2022 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.hasNoExplicitType;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static com.google.errorprone.util.ASTHelpers.streamReceivers;
import static javax.lang.model.element.ElementKind.LOCAL_VARIABLE;
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.matchers.Matcher;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.regex.Pattern;
/** Converts some local variables to use {@code var}. */
@BugPattern(severity = WARNING, summary = "Consider using `var` here to avoid boilerplate.")
public final class Varifier extends BugChecker implements VariableTreeMatcher {
private static final Matcher<ExpressionTree> BUILD_METHOD =
instanceMethod().anyClass().withNameMatching(Pattern.compile("build.*"));
private static final Matcher<ExpressionTree> BUILDER_FACTORY =
anyOf(
staticMethod().anyClass().withNameMatching(Pattern.compile("(builder|newBuilder).*")),
MethodMatchers.constructor()
.forClass(
(type, state) -> type.tsym.getSimpleName().toString().startsWith("Builder")));
private static final Matcher<ExpressionTree> FACTORY_METHOD =
allOf(
staticMethod().anyClass().withNameMatching(Pattern.compile("(new|create|of).*")),
(t, s) -> {
var symbol = getSymbol(t);
return symbol instanceof MethodSymbol
&& isSameType(((MethodSymbol) symbol).getReturnType(), symbol.owner.type, s);
});
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
var symbol = getSymbol(tree);
ExpressionTree initializer = tree.getInitializer();
if (!symbol.getKind().equals(LOCAL_VARIABLE)
|| !isConsideredFinal(symbol)
|| initializer == null
|| hasNoExplicitType(tree, state)) {
return NO_MATCH;
}
// Foo foo = (Foo) bar;
if (initializer instanceof TypeCastTree
&& isSameType(
getType(((TypeCastTree) initializer).getType()), getType(tree.getType()), state)) {
return fix(tree);
}
// Foo foo = new Foo(...);
if (initializer instanceof NewClassTree
&& isSameType(
getType(((NewClassTree) initializer).getIdentifier()),
getType(tree.getType()),
state)) {
var identifier = ((NewClassTree) initializer).getIdentifier();
if (identifier instanceof ParameterizedTypeTree
&& ((ParameterizedTypeTree) identifier).getTypeArguments().isEmpty()) {
return NO_MATCH;
}
return fix(tree);
}
// Foo foo = Foo.builder()...build();
if (BUILD_METHOD.matches(initializer, state)
&& streamReceivers(initializer).anyMatch(t -> BUILDER_FACTORY.matches(t, state))) {
return fix(tree);
}
// Foo foo = Foo.createFoo(..);
if (FACTORY_METHOD.matches(initializer, state)) {
return fix(tree);
}
return NO_MATCH;
}
private Description fix(VariableTree tree) {
return describeMatch(tree, SuggestedFix.replace(tree.getType(), "var"));
}
}
| 4,889
| 41.521739
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StreamResourceLeak.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.util.ASTHelpers.getStartPosition;
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.Matcher;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.EnhancedForLoopTree;
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.MethodTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreeScanner;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
altNames = "FilesLinesLeak",
summary =
"Streams that encapsulate a closeable resource should be closed using"
+ " try-with-resources",
severity = WARNING)
public class StreamResourceLeak extends AbstractMustBeClosedChecker implements MethodTreeMatcher {
public static final Matcher<ExpressionTree> MATCHER =
MethodMatchers.staticMethod()
.onClass("java.nio.file.Files")
.namedAnyOf("lines", "newDirectoryStream", "list", "walk", "find");
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
return scanEntireMethodFor(MATCHER, tree, state);
}
@Override
protected Optional<Change> fix(ExpressionTree tree, VisitorState state, NameSuggester suggester) {
return Change.of(definiteFix(tree, state));
}
private static SuggestedFix definiteFix(ExpressionTree tree, VisitorState state) {
TreePath parentPath = state.getPath().getParentPath();
Tree parent = parentPath.getLeaf();
SuggestedFix.Builder fix = SuggestedFix.builder();
String streamType = SuggestedFixes.prettyType(state, fix, ASTHelpers.getReturnType(tree));
if (parent instanceof MemberSelectTree) {
StatementTree statement = state.findEnclosing(StatementTree.class);
if (statement instanceof VariableTree) {
// Variables need to be declared outside the try-with-resources:
// e.g. `int count = Files.lines(p).count();`
// -> `int count; try (Stream<String> stream = Files.lines(p)) { count = stream.count(); }`
VariableTree var = (VariableTree) statement;
int pos = getStartPosition(var);
int initPos = getStartPosition(var.getInitializer());
int eqPos = pos + state.getSourceForNode(var).substring(0, initPos - pos).lastIndexOf('=');
fix.replace(
eqPos,
initPos,
String.format(
";\ntry (%s stream = %s) {\n%s =",
streamType, state.getSourceForNode(tree), var.getName()));
} else {
// the non-variable case, e.g. `return Files.lines(p).count()`
// -> try (Stream<Stream> stream = Files.lines(p)) { return stream.count(); }`
fix.prefixWith(
statement,
String.format("try (%s stream = %s) {\n", streamType, state.getSourceForNode(tree)));
}
fix.replace(tree, "stream");
fix.postfixWith(statement, "}");
return fix.build();
} else if (parent instanceof VariableTree) {
// If the stream is assigned to a variable, wrap the variable in a try-with-resources
// that includes all statements in the same block that reference the variable.
Tree grandParent = parentPath.getParentPath().getLeaf();
if (!(grandParent instanceof BlockTree)) {
return SuggestedFix.emptyFix();
}
List<? extends StatementTree> statements = ((BlockTree) grandParent).getStatements();
int idx = statements.indexOf(parent);
int lastUse = idx;
for (int i = idx + 1; i < statements.size(); i++) {
boolean[] found = {false};
statements
.get(i)
.accept(
new TreeScanner<Void, Void>() {
@Override
public Void visitIdentifier(IdentifierTree tree, Void unused) {
if (Objects.equals(ASTHelpers.getSymbol(tree), ASTHelpers.getSymbol(parent))) {
found[0] = true;
}
return null;
}
},
null);
if (found[0]) {
lastUse = i;
}
}
fix.prefixWith(parent, "try (");
fix.replace(
state.getEndPosition(((VariableTree) parent).getInitializer()),
state.getEndPosition(parent),
") {");
fix.postfixWith(statements.get(lastUse), "}");
return fix.build();
} else if (parent instanceof EnhancedForLoopTree) {
// If the stream is used in a loop (e.g. directory streams), wrap the loop in
// try-with-resources.
fix.prefixWith(
parent,
String.format("try (%s stream = %s) {\n", streamType, state.getSourceForNode(tree)));
fix.replace(tree, "stream");
fix.postfixWith(parent, "}");
return fix.build();
} else if (parent instanceof MethodInvocationTree) {
// If the stream is used in a method that is called in an expression statement, wrap it in
// try-with-resources.
Tree grandParent = parentPath.getParentPath().getLeaf();
if (!(grandParent instanceof ExpressionStatementTree)) {
return SuggestedFix.emptyFix();
}
fix.prefixWith(
parent,
String.format("try (%s stream = %s) {\n", streamType, state.getSourceForNode(tree)));
fix.replace(tree, "stream");
fix.postfixWith(grandParent, "}");
return fix.build();
}
return SuggestedFix.emptyFix();
}
}
| 6,911
| 40.890909
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AssertFalse.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.assertionWithCondition;
import static com.google.errorprone.matchers.Matchers.booleanLiteral;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.AssertTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.AssertTree;
/**
* @author sebastian.h.monte@gmail.com (Sebastian Monte)
*/
@BugPattern(
summary =
"Assertions may be disabled at runtime and do not guarantee that execution will "
+ "halt here; consider throwing an exception instead",
severity = WARNING)
public class AssertFalse extends BugChecker implements AssertTreeMatcher {
private static final Matcher<AssertTree> ASSERT_FALSE_MATCHER =
assertionWithCondition(booleanLiteral(false));
@Override
public Description matchAssert(AssertTree tree, VisitorState state) {
if (!ASSERT_FALSE_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
return describeMatch(tree, SuggestedFix.replace(tree, "throw new AssertionError()"));
}
}
| 1,959
| 35.981132
| 89
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryLongToIntConversion.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.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.methodInvocation;
import static com.google.errorprone.matchers.Matchers.typeCast;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.suppliers.Suppliers.INT_TYPE;
import static com.google.errorprone.suppliers.Suppliers.JAVA_LANG_LONG_TYPE;
import static com.google.errorprone.suppliers.Suppliers.LONG_TYPE;
import static com.google.errorprone.util.ASTHelpers.targetType;
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.ChildMultiMatcher.MatchType;
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.TypeCastTree;
import com.sun.source.util.TreePath;
import javax.lang.model.type.TypeKind;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Converting a long or Long to an int to pass as a long parameter is usually not necessary."
+ " If this conversion is intentional, consider `Longs.constrainToRange()` instead.",
severity = WARNING)
public class UnnecessaryLongToIntConversion extends BugChecker
implements MethodInvocationTreeMatcher {
// Match static and instance methods differently because we build the suggested fix differently
// for each case.
private static final Matcher<ExpressionTree> LONG_TO_INT_STATIC_METHODS =
anyOf(
staticMethod().onClass("com.google.common.primitives.Ints").named("checkedCast"),
staticMethod().onClass("java.lang.Math").named("toIntExact"));
private static final Matcher<ExpressionTree> LONG_TO_INT_INSTANCE_METHODS =
anyOf(instanceMethod().onExactClass(JAVA_LANG_LONG_TYPE).named("intValue"));
private static final Matcher<ExpressionTree> IS_LONG_TYPE =
anyOf(isSameType(LONG_TYPE), isSameType(JAVA_LANG_LONG_TYPE));
// Matches calls to (long -> int) converter methods with arguments that are type long or Long.
private static final Matcher<ExpressionTree> LONG_TO_INT_STATIC_METHOD_ON_LONG_VALUE_MATCHER =
methodInvocation(LONG_TO_INT_STATIC_METHODS, MatchType.ALL, IS_LONG_TYPE);
private static final Matcher<ExpressionTree> LONG_TO_INT_INSTANCE_METHOD_ON_LONG_VALUE_MATCHER =
methodInvocation(LONG_TO_INT_INSTANCE_METHODS, MatchType.ALL, IS_LONG_TYPE);
// To match casts, create a Matcher of type {@code Matcher<TypeCastTree>}.
private static final Matcher<TypeCastTree> LONG_TO_INT_CAST =
typeCast(isSameType(INT_TYPE), isSameType(LONG_TYPE));
private static final String LONGS_CONSTRAIN_TO_RANGE_PREFIX = "Longs.constrainToRange(";
private static final String LONGS_CONSTRAIN_TO_RANGE_SUFFIX =
", Integer.MIN_VALUE, Integer.MAX_VALUE)";
private static final String LONGS_CONSTRAIN_TO_RANGE_IMPORT =
"com.google.common.primitives.Longs";
/**
* Matches if a long or Long is converted to an int for a long parameter in a method invocation.
*
* <p>Does **not** match if the method parameter is a Long, because passing an int or Integer for
* a Long parameter produces an incompatible types error. Does **not** match when a long or Long
* is converted to an Integer because this requires first converting to an int and then to an
* Integer. This is awkwardly complex and out of scope. Does **not** match when the conversion
* occurs in a separate statement prior the method invocation.
*/
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
for (ExpressionTree arg : tree.getArguments()) {
// The argument's type must be int.
if (!ASTHelpers.getType(arg).getKind().equals(TypeKind.INT)) {
continue;
}
// For the method being called, the parameter type must be long.
ASTHelpers.TargetType targetType =
targetType(state.withPath(new TreePath(state.getPath(), arg)));
if (targetType == null) {
continue;
}
if (!targetType.type().getKind().equals(TypeKind.LONG)) {
continue;
}
// Match if the arg is a type cast from a long to an int.
if (arg instanceof TypeCastTree && LONG_TO_INT_CAST.matches((TypeCastTree) arg, state)) {
ExpressionTree castedExpression = ((TypeCastTree) arg).getExpression();
return buildDescription(tree)
// Remove the type cast.
.addFix(SuggestedFix.replace(arg, state.getSourceForNode(castedExpression)))
// Remove the type cast and use Longs.constrainToRange() instead.
.addFix(
SuggestedFix.builder()
.replace(
arg,
LONGS_CONSTRAIN_TO_RANGE_PREFIX
+ state.getSourceForNode(castedExpression)
+ LONGS_CONSTRAIN_TO_RANGE_SUFFIX)
.addImport(LONGS_CONSTRAIN_TO_RANGE_IMPORT)
.build())
.build();
}
// Match if the arg is a static method call that converts a long or Long to an int.
// This is separate from instance methods because we build the suggested fixes differently.
if (LONG_TO_INT_STATIC_METHOD_ON_LONG_VALUE_MATCHER.matches(arg, state)) {
// Get the first argument to the method. This works because the methods we are matching have
// only one parameter, which is the long or Long parameter we care about.
ExpressionTree methodArgExpression = ((MethodInvocationTree) arg).getArguments().get(0);
String methodArg = state.getSourceForNode(methodArgExpression);
return buildDescription(tree)
// Remove the static method and just keep the arguments (i.e. the long values).
.addFix(SuggestedFix.replace(arg, methodArg))
// Remove the static method and suggest Longs.constrainToRange() instead.
.addFix(
SuggestedFix.builder()
.replace(
arg,
LONGS_CONSTRAIN_TO_RANGE_PREFIX
+ methodArg
+ LONGS_CONSTRAIN_TO_RANGE_SUFFIX)
.addImport(LONGS_CONSTRAIN_TO_RANGE_IMPORT)
.build())
.build();
}
// Match if the arg is an instance method call that converts a long or Long to an int.
if (LONG_TO_INT_INSTANCE_METHOD_ON_LONG_VALUE_MATCHER.matches(arg, state)) {
String receiver = state.getSourceForNode(ASTHelpers.getReceiver(arg));
return buildDescription(tree)
// Remove the instance method and just keep the receiver (the instance of the object).
.addFix(SuggestedFix.replace(arg, receiver))
// Remove the instance method and wrap in Longs.ConstrainToRange().
.addFix(
SuggestedFix.builder()
.replace(
arg,
LONGS_CONSTRAIN_TO_RANGE_PREFIX
+ receiver
+ LONGS_CONSTRAIN_TO_RANGE_SUFFIX)
.addImport(LONGS_CONSTRAIN_TO_RANGE_IMPORT)
.build())
.build();
}
}
return NO_MATCH;
}
}
| 8,597
| 48.131429
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/HidingField.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.util.ASTHelpers.enclosingPackage;
import static com.google.errorprone.util.ASTHelpers.getEnclosedElements;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static java.util.stream.Collectors.toCollection;
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.matchers.Description;
import com.sun.source.tree.ClassTree;
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.TypeSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.type.TypeKind;
/**
* @author sulku@google.com (Marsela Sulku)
* @author mariasam@google.com (Maria Sam)
*/
@BugPattern(
summary = "Hiding fields of superclasses may cause confusion and errors",
severity = WARNING,
altNames = {"hiding", "OvershadowingSubclassFields"})
public class HidingField extends BugChecker implements ClassTreeMatcher {
// List of types that are allowed to hide superclass fields
private static final ImmutableSet<String> IGNORED_CLASSES =
ImmutableSet.of("com.google.common.GoogleLogger", "java.util.logging.Logger");
@Override
public Description matchClass(ClassTree classTree, VisitorState visitorState) {
List<VariableTree> originalClassMembers =
classTree.getMembers().stream()
.filter(mem -> mem instanceof VariableTree)
.map(mem -> (VariableTree) mem)
.filter(
mem ->
!isSuppressed(getSymbol(mem), visitorState)
&& !isIgnoredType(mem)
&& !isStatic(mem))
.collect(toCollection(ArrayList::new));
ClassSymbol classSymbol = getSymbol(classTree);
while (!classSymbol.getSuperclass().getKind().equals(TypeKind.NONE)) {
TypeSymbol parentSymbol = classSymbol.getSuperclass().asElement();
List<Symbol> parentElements = getEnclosedElements(parentSymbol);
Map<Name, VarSymbol> parentMembers =
parentElements.stream()
.filter(mem -> (mem instanceof VarSymbol))
.map(mem -> (VarSymbol) mem)
.filter(mem -> (!mem.isPrivate() && !mem.getModifiers().contains(Modifier.STATIC)))
.collect(Collectors.toMap(Symbol::getSimpleName, mem -> mem));
checkForHiddenFields(
originalClassMembers,
parentMembers,
parentSymbol.getSimpleName(),
classTree,
visitorState);
classSymbol = (ClassSymbol) parentSymbol;
}
return Description.NO_MATCH;
}
private void checkForHiddenFields(
List<VariableTree> originalClassMembers,
Map<Name, VarSymbol> parentMembers,
Name parentClassName,
ClassTree classTree,
VisitorState visitorState) {
Iterator<VariableTree> origVariableIterator = originalClassMembers.iterator();
VariableTree origVariable = null;
while (origVariableIterator.hasNext()) {
origVariable = origVariableIterator.next();
if (parentMembers.containsKey(origVariable.getName())) {
if (isPackagePrivateAndInDiffPackage(
parentMembers.get(origVariable.getName()), classTree)) {
continue;
}
Description.Builder matchDesc = buildDescription(origVariable);
matchDesc.setMessage(
"Hiding fields of superclasses may cause confusion and errors. "
+ "This field is hiding a field of the same name in superclass: "
+ parentClassName);
visitorState.reportMatch(matchDesc.build());
origVariableIterator.remove();
}
}
}
private static boolean isIgnoredType(VariableTree variableTree) {
return IGNORED_CLASSES.contains(getSymbol(variableTree).getQualifiedName().toString());
}
private static boolean isStatic(VariableTree varTree) {
return varTree.getModifiers().getFlags().contains(Modifier.STATIC);
}
private static boolean isPackagePrivateAndInDiffPackage(
VarSymbol parentVariable, ClassTree currClass) {
if (!parentVariable.getModifiers().contains(Modifier.PRIVATE)
&& !parentVariable.getModifiers().contains(Modifier.PROTECTED)
&& !parentVariable.getModifiers().contains(Modifier.PUBLIC)) { // package-private variable
if (!enclosingPackage(parentVariable).equals(enclosingPackage(getSymbol(currClass)))) {
return true;
}
}
return false;
}
}
| 5,596
| 36.817568
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DefaultCharset.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.toType;
import static com.google.errorprone.matchers.method.MethodMatchers.constructor;
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.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import javax.inject.Inject;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Implicit use of the platform default charset, which can result in differing behaviour"
+ " between JVM executions or incorrect behavior if the encoding of the data source"
+ " doesn't match expectations.",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public class DefaultCharset extends BugChecker
implements MethodInvocationTreeMatcher, NewClassTreeMatcher {
enum CharsetFix {
UTF_8_FIX("UTF_8", "Specify UTF-8") {
@Override
void addImport(SuggestedFix.Builder fix) {
fix.addStaticImport("java.nio.charset.StandardCharsets.UTF_8");
}
},
DEFAULT_CHARSET_FIX("Charset.defaultCharset()", "Specify default charset") {
@Override
void addImport(SuggestedFix.Builder fix) {
fix.addImport("java.nio.charset.Charset");
}
};
final String replacement;
final String title;
CharsetFix(String replacement, String title) {
this.replacement = replacement;
this.title = title;
}
String replacement() {
return replacement;
}
abstract void addImport(SuggestedFix.Builder fix);
}
// ignore the constructor that takes FileDescriptor; it's rare and there's no automated fix
private static final Matcher<ExpressionTree> FILE_WRITER =
anyOf(
constructor().forClass(FileWriter.class.getName()).withParameters("java.io.File"),
constructor()
.forClass(FileWriter.class.getName())
.withParameters("java.io.File", "boolean"),
constructor().forClass(FileWriter.class.getName()).withParameters("java.lang.String"),
constructor()
.forClass(FileWriter.class.getName())
.withParameters("java.lang.String", "boolean"));
private static final Matcher<Tree> BUFFERED_WRITER =
toType(ExpressionTree.class, constructor().forClass(BufferedWriter.class.getName()));
private static final Matcher<ExpressionTree> FILE_READER =
anyOf(
constructor().forClass(FileReader.class.getName()).withParameters("java.io.File"),
constructor().forClass(FileReader.class.getName()).withParameters("java.lang.String"));
private static final Matcher<Tree> BUFFERED_READER =
toType(ExpressionTree.class, constructor().forClass(BufferedReader.class.getName()));
private static final Matcher<ExpressionTree> CTOR =
anyOf(
constructor()
.forClass(String.class.getName())
.withParametersOfType(ImmutableList.of(Suppliers.arrayOf(Suppliers.BYTE_TYPE))),
constructor()
.forClass(String.class.getName())
.withParametersOfType(
ImmutableList.of(
Suppliers.arrayOf(Suppliers.BYTE_TYPE),
Suppliers.INT_TYPE,
Suppliers.INT_TYPE)),
constructor()
.forClass(OutputStreamWriter.class.getName())
.withParametersOfType(ImmutableList.of(Suppliers.typeFromClass(OutputStream.class))),
constructor()
.forClass(InputStreamReader.class.getName())
.withParametersOfType(ImmutableList.of(Suppliers.typeFromClass(InputStream.class))));
private static final Matcher<ExpressionTree> BYTESTRING_COPY_FROM =
staticMethod().onClass("com.google.protobuf.ByteString").named("copyFrom");
private static final Matcher<ExpressionTree> STRING_GET_BYTES =
instanceMethod().onExactClass(String.class.getName()).named("getBytes").withNoParameters();
private static final Matcher<ExpressionTree> BYTE_ARRAY_OUTPUT_STREAM_TO_STRING =
instanceMethod()
.onDescendantOf(ByteArrayOutputStream.class.getName())
.named("toString")
.withNoParameters();
private static final Matcher<ExpressionTree> FILE_NEW_WRITER =
staticMethod()
.onClass(Files.class.getName())
.named("newWriter")
.withParameters("java.lang.String");
private static final Matcher<ExpressionTree> PRINT_WRITER =
anyOf(
constructor().forClass(PrintWriter.class.getName()).withParameters(File.class.getName()),
constructor()
.forClass(PrintWriter.class.getName())
.withParameters(String.class.getName()));
private static final Matcher<ExpressionTree> PRINT_WRITER_OUTPUTSTREAM =
anyOf(
constructor()
.forClass(PrintWriter.class.getName())
.withParameters(OutputStream.class.getName()),
constructor()
.forClass(PrintWriter.class.getName())
.withParameters(OutputStream.class.getName(), "boolean"));
private static final Matcher<ExpressionTree> SCANNER_MATCHER =
anyOf(
constructor()
.forClass(Scanner.class.getName())
.withParameters(InputStream.class.getName()),
constructor().forClass(Scanner.class.getName()).withParameters(File.class.getName()),
constructor().forClass(Scanner.class.getName()).withParameters(Path.class.getName()),
constructor()
.forClass(Scanner.class.getName())
.withParameters(ReadableByteChannel.class.getName()));
private final boolean byteArrayOutputStreamToString;
@Inject
DefaultCharset(ErrorProneFlags flags) {
this.byteArrayOutputStreamToString =
flags.getBoolean("DefaultCharset:ByteArrayOutputStreamToString").orElse(true);
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (state.isAndroidCompatible()) { // Android's default platform Charset is always UTF-8
return NO_MATCH;
}
if (STRING_GET_BYTES.matches(tree, state)) {
Tree parent = state.getPath().getParentPath().getLeaf();
if (parent instanceof ExpressionTree
&& BYTESTRING_COPY_FROM.matches((ExpressionTree) parent, state)) {
return byteStringFixes(tree, (ExpressionTree) parent, state);
} else {
return appendCharsets(tree, tree.getMethodSelect(), tree.getArguments(), state);
}
}
if (FILE_NEW_WRITER.matches(tree, state)) {
return appendCharsets(tree, tree.getMethodSelect(), tree.getArguments(), state);
}
if (byteArrayOutputStreamToString && BYTE_ARRAY_OUTPUT_STREAM_TO_STRING.matches(tree, state)) {
return appendCharsets(tree, tree.getMethodSelect(), tree.getArguments(), state);
}
return NO_MATCH;
}
private Description byteStringFixes(
MethodInvocationTree tree, ExpressionTree parent, VisitorState state) {
SuggestedFix.Builder builder =
byteStringFix(
tree, parent, state, "copyFrom(", ", " + CharsetFix.DEFAULT_CHARSET_FIX.replacement());
CharsetFix.DEFAULT_CHARSET_FIX.addImport(builder);
return buildDescription(tree)
.addFix(byteStringFix(tree, parent, state, "copyFromUtf8(", "").build())
.addFix(builder.build())
.build();
}
private static SuggestedFix.Builder byteStringFix(
MethodInvocationTree tree,
ExpressionTree parent,
VisitorState state,
String prefix,
String suffix) {
Tree parentReceiver = ASTHelpers.getReceiver(parent);
SuggestedFix.Builder fix = SuggestedFix.builder();
if (parentReceiver != null) {
fix.replace(
/* startPos= */ state.getEndPosition(parentReceiver),
/* endPos= */ getStartPosition(tree),
/* replaceWith= */ "." + prefix);
} else {
fix.replace(
/* startPos= */ getStartPosition(parent),
/* endPos= */ getStartPosition(tree),
/* replaceWith= */ prefix);
}
fix.replace(
state.getEndPosition(ASTHelpers.getReceiver(tree)), state.getEndPosition(tree), suffix);
return fix;
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (state.isAndroidCompatible()) {
return NO_MATCH;
}
if (CTOR.matches(tree, state)) {
return appendCharsets(tree, tree.getIdentifier(), tree.getArguments(), state);
}
if (FILE_READER.matches(tree, state)) {
return handleFileReader(tree, state);
}
if (FILE_WRITER.matches(tree, state)) {
return handleFileWriter(tree, state);
}
if (PRINT_WRITER.matches(tree, state)) {
return handlePrintWriter(tree);
}
if (PRINT_WRITER_OUTPUTSTREAM.matches(tree, state)) {
return handlePrintWriterOutputStream(tree);
}
if (SCANNER_MATCHER.matches(tree, state)) {
return handleScanner(tree);
}
return NO_MATCH;
}
private Description handleScanner(NewClassTree tree) {
Description.Builder description = buildDescription(tree);
for (CharsetFix charsetFix : CharsetFix.values()) {
SuggestedFix.Builder fix =
SuggestedFix.builder()
.postfixWith(
getOnlyElement(tree.getArguments()),
String.format(", %s.name()", charsetFix.replacement()));
charsetFix.addImport(fix);
description.addFix(fix.build());
}
return description.build();
}
boolean shouldUseGuava(VisitorState state) {
for (ImportTree importTree : state.getPath().getCompilationUnit().getImports()) {
Symbol sym = ASTHelpers.getSymbol(importTree.getQualifiedIdentifier());
if (sym == null) {
continue;
}
if (sym.getQualifiedName().contentEquals("com.google.common.io.Files")) {
return true;
}
}
return false;
}
private Description handleFileReader(NewClassTree tree, VisitorState state) {
Tree arg = getOnlyElement(tree.getArguments());
Tree parent = state.getPath().getParentPath().getLeaf();
Tree toReplace = BUFFERED_READER.matches(parent, state) ? parent : tree;
Description.Builder description = buildDescription(tree);
fileReaderFix(description, state, arg, toReplace);
return description.build();
}
private void fileReaderFix(
Description.Builder description, VisitorState state, Tree arg, Tree toReplace) {
for (CharsetFix charset : CharsetFix.values()) {
if (shouldUseGuava(state)) {
description.addFix(guavaFileReaderFix(state, arg, toReplace, charset));
} else {
description.addFix(nioFileReaderFix(state, arg, toReplace, charset));
}
}
}
private static Fix nioFileReaderFix(
VisitorState state, Tree arg, Tree toReplace, CharsetFix charset) {
SuggestedFix.Builder fix = SuggestedFix.builder();
fix.replace(
toReplace,
String.format(
"Files.newBufferedReader(%s, %s)", toPath(state, arg, fix), charset.replacement()));
fix.addImport("java.nio.file.Files");
charset.addImport(fix);
variableTypeFix(fix, state, FileReader.class, Reader.class);
return fix.build();
}
private static Fix guavaFileReaderFix(
VisitorState state, Tree fileArg, Tree toReplace, CharsetFix charset) {
SuggestedFix.Builder fix = SuggestedFix.builder();
fix.replace(
toReplace,
String.format(
"Files.newReader(%s, %s)", toFile(state, fileArg, fix), charset.replacement()));
fix.addImport("com.google.common.io.Files");
charset.addImport(fix);
variableTypeFix(fix, state, FileReader.class, Reader.class);
return fix.build();
}
private static void variableTypeFix(
SuggestedFix.Builder fix, VisitorState state, Class<?> original, Class<?> replacement) {
Tree parent = state.getPath().getParentPath().getLeaf();
Symbol sym;
switch (parent.getKind()) {
case VARIABLE:
sym = ASTHelpers.getSymbol((VariableTree) parent);
break;
case ASSIGNMENT:
sym = ASTHelpers.getSymbol(((AssignmentTree) parent).getVariable());
break;
default:
return;
}
if (!ASTHelpers.isSameType(
sym.type, state.getTypeFromString(original.getCanonicalName()), state)) {
return;
}
new TreeScanner<Void, Void>() {
@Override
public Void visitVariable(VariableTree node, Void unused) {
if (!sym.equals(ASTHelpers.getSymbol(node))) {
return null;
}
if (ASTHelpers.getStartPosition(node.getType()) == -1) {
// ignore synthetic tree nodes for `var`
return null;
}
fix.replace(node.getType(), replacement.getSimpleName())
.addImport(replacement.getCanonicalName());
return null;
}
}.scan(state.getPath().getCompilationUnit(), null);
}
private Description handleFileWriter(NewClassTree tree, VisitorState state) {
Iterator<? extends ExpressionTree> it = tree.getArguments().iterator();
Tree fileArg = it.next();
Tree appendMode = it.hasNext() ? it.next() : null;
Tree parent = state.getPath().getParentPath().getLeaf();
Tree toReplace = BUFFERED_WRITER.matches(parent, state) ? parent : tree;
Description.Builder description = buildDescription(tree);
boolean useGuava = shouldUseGuava(state);
for (CharsetFix charset : CharsetFix.values()) {
if (appendMode == null && useGuava) {
description.addFix(guavaFileWriterFix(state, fileArg, toReplace, charset));
} else {
description.addFix(
nioFileWriterFix(state, appendMode, fileArg, toReplace, charset, useGuava));
}
}
return description.build();
}
private static Fix guavaFileWriterFix(
VisitorState state, Tree fileArg, Tree toReplace, CharsetFix charset) {
SuggestedFix.Builder fix = SuggestedFix.builder();
fix.replace(
toReplace,
String.format(
"Files.newWriter(%s, %s)", toFile(state, fileArg, fix), charset.replacement()));
fix.addImport("com.google.common.io.Files");
charset.addImport(fix);
variableTypeFix(fix, state, FileWriter.class, Writer.class);
return fix.build();
}
private static Fix nioFileWriterFix(
VisitorState state,
Tree appendTree,
Tree fileArg,
Tree toReplace,
CharsetFix charset,
boolean qualify) {
SuggestedFix.Builder fix = SuggestedFix.builder();
StringBuilder sb = new StringBuilder();
if (qualify) {
sb.append("java.nio.file.Files");
} else {
sb.append("Files");
fix.addImport("java.nio.file.Files");
}
sb.append(".newBufferedWriter(");
sb.append(toPath(state, fileArg, fix));
sb.append(", ").append(charset.replacement());
charset.addImport(fix);
if (appendTree != null) {
sb.append(toAppendMode(fix, appendTree, state));
}
sb.append(")");
fix.replace(toReplace, sb.toString());
variableTypeFix(fix, state, FileWriter.class, Writer.class);
return fix.build();
}
/** Convert a boolean append mode to a StandardOpenOption. */
private static String toAppendMode(SuggestedFix.Builder fix, Tree appendArg, VisitorState state) {
// recognize constants to try to avoid `true ? CREATE, APPEND : CREATE`
Boolean value = ASTHelpers.constValue(appendArg, Boolean.class);
if (value != null) {
if (value) {
fix.addStaticImport("java.nio.file.StandardOpenOption.APPEND");
fix.addStaticImport("java.nio.file.StandardOpenOption.CREATE");
return ", CREATE, APPEND";
} else {
// CREATE is the default
return "";
}
}
fix.addImport("java.nio.file.StandardOpenOption");
fix.addStaticImport("java.nio.file.StandardOpenOption.APPEND");
fix.addStaticImport("java.nio.file.StandardOpenOption.CREATE");
return String.format(
", %s ? new StandardOpenOption[] {CREATE, APPEND} : new StandardOpenOption[] {CREATE}",
state.getSourceForNode(appendArg));
}
/** Converts a {@code String} to a {@code File}. */
private static Object toFile(VisitorState state, Tree fileArg, SuggestedFix.Builder fix) {
Type type = ASTHelpers.getType(fileArg);
if (ASTHelpers.isSubtype(type, state.getSymtab().stringType, state)) {
fix.addImport("java.io.File");
return String.format("new File(%s)", state.getSourceForNode(fileArg));
} else if (ASTHelpers.isSubtype(type, JAVA_IO_FILE.get(state), state)) {
return state.getSourceForNode(fileArg);
} else {
throw new AssertionError("unexpected type: " + type);
}
}
/** Convert a {@code String} or {@code File} argument to a {@code Path}. */
private static String toPath(VisitorState state, Tree fileArg, SuggestedFix.Builder fix) {
Type type = ASTHelpers.getType(fileArg);
if (ASTHelpers.isSubtype(type, state.getSymtab().stringType, state)) {
fix.addImport("java.nio.file.Paths");
return String.format("Paths.get(%s)", state.getSourceForNode(fileArg));
} else if (ASTHelpers.isSubtype(type, JAVA_IO_FILE.get(state), state)) {
return String.format("%s.toPath()", state.getSourceForNode(fileArg));
} else {
throw new AssertionError("unexpected type: " + type);
}
}
private Description appendCharsets(
Tree tree, Tree select, List<? extends ExpressionTree> arguments, VisitorState state) {
return buildDescription(tree)
.addFix(appendCharset(tree, select, arguments, state, CharsetFix.UTF_8_FIX))
.addFix(appendCharset(tree, select, arguments, state, CharsetFix.DEFAULT_CHARSET_FIX))
.build();
}
private static Fix appendCharset(
Tree tree,
Tree select,
List<? extends ExpressionTree> arguments,
VisitorState state,
CharsetFix charset) {
SuggestedFix.Builder fix = SuggestedFix.builder();
if (arguments.isEmpty()) {
fix.replace(
state.getEndPosition(select),
state.getEndPosition(tree),
String.format("(%s)", charset.replacement()));
} else {
fix.postfixWith(Iterables.getLast(arguments), ", " + charset.replacement());
}
charset.addImport(fix);
fix.setShortDescription(charset.title);
return fix.build();
}
private Description handlePrintWriter(NewClassTree tree) {
Description.Builder description = buildDescription(tree);
for (CharsetFix charsetFix : CharsetFix.values()) {
SuggestedFix.Builder fix =
SuggestedFix.builder()
.postfixWith(
getOnlyElement(tree.getArguments()),
String.format(", %s.name()", charsetFix.replacement()));
charsetFix.addImport(fix);
description.addFix(fix.build());
}
return description.build();
}
private Description handlePrintWriterOutputStream(NewClassTree tree) {
Tree outputStream = tree.getArguments().get(0);
Description.Builder description = buildDescription(tree);
for (CharsetFix charsetFix : CharsetFix.values()) {
SuggestedFix.Builder fix =
SuggestedFix.builder()
.prefixWith(outputStream, "new BufferedWriter(new OutputStreamWriter(")
.postfixWith(outputStream, String.format(", %s))", charsetFix.replacement()));
charsetFix.addImport(fix);
fix.addImport("java.io.BufferedWriter");
fix.addImport("java.io.OutputStreamWriter");
description.addFix(fix.build());
}
return description.build();
}
private static final Supplier<Type> JAVA_IO_FILE =
VisitorState.memoize(state -> state.getTypeFromString("java.io.File"));
}
| 22,389
| 38.075044
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/HashtableContains.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.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.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;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "contains() is a legacy method that is equivalent to containsValue()",
severity = ERROR)
public class HashtableContains extends BugChecker implements MethodInvocationTreeMatcher {
static final Matcher<ExpressionTree> CONTAINS_MATCHER =
anyOf(
instanceMethod().onDescendantOf(Hashtable.class.getName()).named("contains"),
instanceMethod().onDescendantOf(ConcurrentHashMap.class.getName()).named("contains"));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!CONTAINS_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
Description.Builder result = buildDescription(tree);
// If the collection is not raw, try to figure out if the argument looks like a key
// or a value.
List<Type> tyargs = ASTHelpers.getReceiverType(tree).getTypeArguments();
if (tyargs.size() == 2) {
// map capture variables to their bounds, e.g. `? extends Number` -> `Number`
Types types = state.getTypes();
Type key = ASTHelpers.getUpperBound(tyargs.get(0), types);
Type value = ASTHelpers.getUpperBound(tyargs.get(1), types);
Type arg = ASTHelpers.getType(Iterables.getOnlyElement(tree.getArguments()));
boolean valueShaped = types.isAssignable(arg, value);
boolean keyShaped = types.isAssignable(arg, key);
if (keyShaped && !valueShaped) {
// definitely a key
result.addFix(replaceMethodName(tree, state, "containsKey"));
result.setMessage(
String.format(
"contains() is a legacy method that is equivalent to containsValue(), but the "
+ "argument type '%s' looks like a key",
key));
} else if (valueShaped && !keyShaped) {
// definitely a value
result.addFix(replaceMethodName(tree, state, "containsValue"));
} else if (valueShaped && keyShaped) {
// ambiguous
result.addFix(replaceMethodName(tree, state, "containsValue"));
result.addFix(replaceMethodName(tree, state, "containsKey"));
result.setMessage(
String.format(
"contains() is a legacy method that is equivalent to containsValue(), but the "
+ "argument type '%s' could be a key or a value",
key));
} else {
// this shouldn't have compiled!
throw new AssertionError(
String.format(
"unexpected argument to contains(): key: %s, value: %s, argument: %s",
key, value, arg));
}
} else {
result.addFix(replaceMethodName(tree, state, "containsValue"));
}
return result.build();
}
private static Fix replaceMethodName(
MethodInvocationTree tree, VisitorState state, String newName) {
String source = state.getSourceForNode(tree.getMethodSelect());
int idx = source.lastIndexOf("contains");
String replacement =
source.substring(0, idx) + newName + source.substring(idx + "contains".length());
Fix fix = SuggestedFix.replace(tree.getMethodSelect(), replacement);
return fix;
}
}
| 4,833
| 41.034783
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UngroupedOverloads.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.getOnlyElement;
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 java.util.stream.Collectors.joining;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.LinkedHashMultimap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.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.LineMap;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.lang.model.element.Name;
/**
* @author hanuszczak@google.com (Łukasz Hanuszczak)
*/
@BugPattern(
summary =
"Constructors and methods with the same name should appear sequentially with no other code"
+ " in between, even when modifiers such as static or private differ between the"
+ " methods. Please re-order or re-name methods.",
severity = SUGGESTION)
public class UngroupedOverloads extends BugChecker implements ClassTreeMatcher {
private final Boolean batchFindings;
@Inject
UngroupedOverloads(ErrorProneFlags flags) {
batchFindings = flags.getBoolean("UngroupedOverloads:BatchFindings").orElse(false);
}
@AutoValue
abstract static class MemberWithIndex {
abstract int index();
abstract MethodTree tree();
static MemberWithIndex create(int index, MethodTree tree) {
return new AutoValue_UngroupedOverloads_MemberWithIndex(index, tree);
}
}
@AutoValue
abstract static class OverloadKey {
abstract Name name();
// TODO(cushon): re-enable this, but don't warn about interspersed static/non-static overloads
// Include static-ness when grouping overloads. Static and non-static methods are still
// overloads per the JLS, but are less interesting in practice.
// abstract boolean isStatic();
public static OverloadKey create(MethodTree methodTree) {
MethodSymbol sym = ASTHelpers.getSymbol(methodTree);
return new AutoValue_UngroupedOverloads_OverloadKey(sym.getSimpleName());
}
}
@Override
public Description matchClass(ClassTree classTree, VisitorState state) {
// collect all member methods and their indices in the list of members, grouped by name
LinkedHashMultimap<OverloadKey, MemberWithIndex> methods = LinkedHashMultimap.create();
for (int i = 0; i < classTree.getMembers().size(); ++i) {
Tree member = classTree.getMembers().get(i);
if (member instanceof MethodTree) {
MethodTree methodTree = (MethodTree) member;
if (!ASTHelpers.isGeneratedConstructor(methodTree)) {
methods.put(OverloadKey.create(methodTree), MemberWithIndex.create(i, methodTree));
}
}
}
ImmutableList<Description> descriptions =
methods.asMap().entrySet().stream()
.flatMap(
e ->
checkOverloads(
state, classTree.getMembers(), ImmutableList.copyOf(e.getValue())))
.collect(toImmutableList());
if (batchFindings && !descriptions.isEmpty()) {
SuggestedFix.Builder fix = SuggestedFix.builder();
descriptions.forEach(d -> fix.merge((SuggestedFix) getOnlyElement(d.fixes)));
return describeMatch(descriptions.get(0).position, fix.build());
}
descriptions.forEach(state::reportMatch);
return NO_MATCH;
}
private Stream<Description> checkOverloads(
VisitorState state, List<? extends Tree> members, ImmutableList<MemberWithIndex> overloads) {
if (overloads.size() <= 1) {
return Stream.empty();
}
// check if the indices of the overloads in the member list are sequential
MemberWithIndex first = overloads.get(0);
int prev = -1;
int group = 0;
Map<MemberWithIndex, Integer> groups = new LinkedHashMap<>();
for (MemberWithIndex overload : overloads) {
if (prev != -1 && prev != overload.index() - 1) {
group++;
}
groups.put(overload, group);
prev = overload.index();
}
if (group == 0) {
return Stream.empty();
}
if (overloads.stream().anyMatch(m -> isSuppressed(m.tree(), state))) {
return Stream.empty();
}
// build a fix that replaces the first overload with all the overloads grouped together
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
StringBuilder sb = new StringBuilder("\n");
sb.append(state.getSourceForNode(first.tree()));
overloads.stream()
.filter(o -> o != first)
.forEach(
o -> {
int start = state.getEndPosition(members.get(o.index() - 1));
int end = state.getEndPosition(o.tree());
sb.append(state.getSourceCode(), start, end).append('\n');
fixBuilder.replace(start, end, "");
});
fixBuilder.replace(first.tree(), sb.toString());
SuggestedFix fix = fixBuilder.build();
LineMap lineMap = state.getPath().getCompilationUnit().getLineMap();
// emit findings for each overload
return overloads.stream()
.map(
o ->
buildDescription(o.tree())
.addFix(fix)
.setMessage(createMessage(o.tree(), overloads, groups, lineMap, o))
.build());
}
private static String createMessage(
MethodTree tree,
ImmutableList<MemberWithIndex> overloads,
Map<MemberWithIndex, Integer> groups,
LineMap lineMap,
MemberWithIndex current) {
String ungroupedLines =
overloads.stream()
.filter(o -> !groups.get(o).equals(groups.get(current)))
.map(t -> lineMap.getLineNumber(getStartPosition(t.tree())))
.map(String::valueOf)
.collect(joining(", "));
MethodSymbol symbol = ASTHelpers.getSymbol(tree);
String name =
symbol.isConstructor()
? "constructor overloads"
: String.format("overloads of '%s'", symbol.getSimpleName());
return String.format(
"Overloads should be grouped together, even when modifiers such as static or private differ"
+ " between the methods; found ungrouped %s on line(s): %s",
name, ungroupedLines);
}
}
| 7,543
| 37.886598
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NullablePrimitive.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.AnnotatedTypeTreeMatcher;
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.AnnotatedTypeTree;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import java.util.List;
/**
* @author sebastian.h.monte@gmail.com (Sebastian Monte)
*/
@BugPattern(
summary = "@Nullable should not be used for primitive types since they cannot be null",
severity = WARNING,
tags = StandardTags.STYLE)
public class NullablePrimitive extends BugChecker
implements AnnotatedTypeTreeMatcher, VariableTreeMatcher, MethodTreeMatcher {
@Override
public Description matchAnnotatedType(AnnotatedTypeTree tree, VisitorState state) {
Type type = ASTHelpers.getType(tree);
return check(type, tree.getAnnotations());
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
MethodSymbol sym = ASTHelpers.getSymbol(tree);
return check(sym.getReturnType(), tree.getModifiers().getAnnotations());
}
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
return check(ASTHelpers.getSymbol(tree).type, tree.getModifiers().getAnnotations());
}
private Description check(Type type, List<? extends AnnotationTree> annotations) {
if (type == null) {
return NO_MATCH;
}
if (!type.isPrimitive()) {
return NO_MATCH;
}
AnnotationTree annotation = ASTHelpers.getAnnotationWithSimpleName(annotations, "Nullable");
if (annotation == null) {
return NO_MATCH;
}
return describeMatch(annotation, SuggestedFix.delete(annotation));
}
}
| 2,961
| 36.025
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/RethrowReflectiveOperationExceptionAsLinkageError.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.matchers.Matchers.constructor;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ThrowTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ThrowTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import java.util.List;
import javax.lang.model.element.ElementKind;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Prefer LinkageError for rethrowing ReflectiveOperationException as unchecked",
severity = WARNING)
public class RethrowReflectiveOperationExceptionAsLinkageError extends BugChecker
implements ThrowTreeMatcher {
private static final String ASSERTION_ERROR = "java.lang.AssertionError";
private static final String REFLECTIVE_OPERATION_EXCEPTION =
"java.lang.ReflectiveOperationException";
private static final Matcher<ExpressionTree> MATCHER = constructor().forClass(ASSERTION_ERROR);
@Override
public Description matchThrow(ThrowTree throwTree, VisitorState state) {
if (!MATCHER.matches(throwTree.getExpression(), state)) {
return NO_MATCH;
}
NewClassTree newClassTree = (NewClassTree) throwTree.getExpression();
List<? extends ExpressionTree> arguments = newClassTree.getArguments();
if (arguments.isEmpty() || arguments.size() > 2) {
return NO_MATCH;
}
Symbol cause = ASTHelpers.getSymbol(Iterables.getLast(arguments));
if (cause == null || !isReflectiveOperationException(state, cause)) {
return NO_MATCH;
}
String message =
arguments.size() == 1
? String.format("%s.getMessage()", cause.getSimpleName())
: state.getSourceForNode(arguments.get(0));
return describeMatch(
newClassTree,
SuggestedFix.replace(
newClassTree,
String.format("new LinkageError(%s, %s)", message, cause.getSimpleName())));
}
private static boolean isReflectiveOperationException(VisitorState state, Symbol symbol) {
return isSameType(symbol.asType(), JAVA_LANG_REFLECTIVEOPERATIONEXCEPTION.get(state), state)
&& symbol.getKind().equals(ElementKind.EXCEPTION_PARAMETER);
}
private static final Supplier<Type> JAVA_LANG_REFLECTIVEOPERATIONEXCEPTION =
VisitorState.memoize(state -> state.getTypeFromString(REFLECTIVE_OPERATION_EXCEPTION));
}
| 3,655
| 42.011765
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AsyncCallableReturnsNull.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.util.concurrent.AsyncCallable;
import com.google.errorprone.BugPattern;
/** Checks that {@link AsyncCallable} implementations do not directly {@code return null}. */
@BugPattern(
summary = "AsyncCallable should not return a null Future, only a Future whose result is null.",
severity = ERROR)
public final class AsyncCallableReturnsNull extends AbstractAsyncTypeReturnsNull {
public AsyncCallableReturnsNull() {
super(AsyncCallable.class);
}
}
| 1,208
| 35.636364
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CanBeStaticAnalyzer.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.util.ASTHelpers.isStatic;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.VisitorState;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCMemberReference;
import com.sun.tools.javac.tree.TreeScanner;
import com.sun.tools.javac.util.Names;
import java.util.HashSet;
import java.util.Set;
/** Analyzes trees for references to their enclosing instance. */
public class CanBeStaticAnalyzer extends TreeScanner {
/** Returns true if the tree references its enclosing class. */
public static boolean referencesOuter(Tree tree, Symbol owner, VisitorState state) {
CanBeStaticAnalyzer scanner = new CanBeStaticAnalyzer(owner, state);
((JCTree) tree).accept(scanner);
return !scanner.canPossiblyBeStatic || !scanner.outerReferences.isEmpty();
}
public static CanBeStaticResult canBeStaticResult(Tree tree, Symbol owner, VisitorState state) {
CanBeStaticAnalyzer scanner = new CanBeStaticAnalyzer(owner, state);
((JCTree) tree).accept(scanner);
return CanBeStaticResult.of(scanner.canPossiblyBeStatic, scanner.outerReferences);
}
private final Names names;
private final Symbol owner;
private final VisitorState state;
private boolean canPossiblyBeStatic = true;
private final Set<MethodSymbol> outerReferences = new HashSet<>();
private CanBeStaticAnalyzer(Symbol owner, VisitorState state) {
this.owner = owner;
this.state = state;
this.names = state.getNames();
}
@Override
public void visitIdent(JCTree.JCIdent tree) {
// check for unqualified references to instance members (fields and methods) declared
// in an enclosing scope
Symbol sym = tree.sym;
if (sym == null) {
return;
}
if (isStatic(sym)) {
return;
}
switch (sym.getKind()) {
case TYPE_PARAMETER:
// declaring a class as non-static just to access a type parameter is silly -
// why not just re-declare the type parameter instead of capturing it?
// TODO(cushon): consider making the suggestion anyways, maybe with a fix?
// fall through
case FIELD:
if (!isOwnedBy(sym, owner, state.getTypes())) {
canPossiblyBeStatic = false;
}
break;
case METHOD:
if (!isOwnedBy(sym, owner, state.getTypes())) {
outerReferences.add((MethodSymbol) sym);
}
break;
case CLASS:
Type enclosing = tree.type.getEnclosingType();
if (enclosing != null) {
enclosing.accept(new TypeVariableScanner(), null);
}
break;
default:
break;
}
}
private static boolean isOwnedBy(Symbol sym, Symbol owner, Types types) {
if (sym.owner == owner) {
return true;
}
if (owner instanceof TypeSymbol) {
return sym.isMemberOf((TypeSymbol) owner, types);
}
return false;
}
// check for implicit references to type parameters of the enclosing
// class in unqualified references to sibling types, e.g.:
//
// class Test<T> {
// class One {}
// class Two {
// One one; // implicit Test<T>.One
// }
// }
private class TypeVariableScanner extends Types.SimpleVisitor<Void, Void> {
@Override
public Void visitTypeVar(Type.TypeVar t, Void unused) {
canPossiblyBeStatic = false;
return null;
}
@Override
public Void visitClassType(Type.ClassType t, Void unused) {
for (Type a : t.getTypeArguments()) {
a.accept(this, null);
}
if (t.getEnclosingType() != null) {
t.getEnclosingType().accept(this, null);
}
return null;
}
@Override
public Void visitType(Type type, Void unused) {
return null;
}
}
@Override
public void visitSelect(JCTree.JCFieldAccess tree) {
super.visitSelect(tree);
// check for qualified this/super references
if (tree.name == names._this || tree.name == names._super) {
canPossiblyBeStatic = false;
}
}
@Override
public void visitNewClass(JCTree.JCNewClass tree) {
super.visitNewClass(tree);
// check for constructor invocations where the type is a member of an enclosing class,
// the enclosing instance is passed as an explicit argument
Type type = ASTHelpers.getType(tree.clazz);
if (type == null) {
return;
}
if (memberOfEnclosing(owner, state, type.tsym)) {
canPossiblyBeStatic = false;
}
}
@Override
public void visitReference(JCMemberReference tree) {
super.visitReference(tree);
if (tree.getMode() != ReferenceMode.NEW) {
return;
}
if (memberOfEnclosing(owner, state, tree.expr.type.tsym)) {
canPossiblyBeStatic = false;
}
}
/** Is sym a non-static member of an enclosing class of currentClass? */
private static boolean memberOfEnclosing(Symbol owner, VisitorState state, Symbol sym) {
if (sym == null || !sym.hasOuterInstance()) {
return false;
}
for (ClassSymbol encl = owner.owner.enclClass();
encl != null;
encl = encl.owner != null ? encl.owner.enclClass() : null) {
if (sym.isMemberOf(encl, state.getTypes())) {
return true;
}
}
return false;
}
@Override
public void visitAnnotation(JCAnnotation tree) {
// skip annotations; the keys of key/value pairs look like unqualified method invocations
}
/** Stores the result of a can-be-static query. */
@AutoValue
public abstract static class CanBeStaticResult {
/**
* Whether the method could *possibly* be static: i.e., this is false if it references an
* instance field.
*/
public abstract boolean canPossiblyBeStatic();
/** Set of instance methods referenced by the method under inspection. */
public abstract ImmutableSet<MethodSymbol> methodsReferenced();
public static CanBeStaticResult of(
boolean canPossiblyBeStatic, Set<MethodSymbol> methodsReferenced) {
return new AutoValue_CanBeStaticAnalyzer_CanBeStaticResult(
canPossiblyBeStatic, ImmutableSet.copyOf(methodsReferenced));
}
}
}
| 7,277
| 31.491071
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InexactVarargsConditional.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.Description.NO_MATCH;
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.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ConditionalExpressionTree;
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.Types;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Conditional expression in varargs call contains array and non-array arguments",
severity = ERROR)
public class InexactVarargsConditional extends BugChecker implements MethodInvocationTreeMatcher {
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
MethodSymbol sym = ASTHelpers.getSymbol(tree);
if (!sym.isVarArgs()) {
return NO_MATCH;
}
if (tree.getArguments().size() != sym.getParameters().size()) {
// explicit varargs call with more actuals than formals
return NO_MATCH;
}
Tree arg = getLast(tree.getArguments());
if (!(arg instanceof ConditionalExpressionTree)) {
return NO_MATCH;
}
Types types = state.getTypes();
if (types.isArray(getType(arg))) {
return NO_MATCH;
}
ConditionalExpressionTree cond = (ConditionalExpressionTree) arg;
boolean trueIsArray = types.isArray(getType(cond.getTrueExpression()));
if (!(trueIsArray ^ types.isArray(getType(cond.getFalseExpression())))) {
return NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
String qualified =
SuggestedFixes.qualifyType(
state, fix, types.elemtype(getLast(sym.getParameters()).asType()));
Tree toFix = !trueIsArray ? cond.getTrueExpression() : cond.getFalseExpression();
fix.prefixWith(toFix, String.format("new %s[] {", qualified)).postfixWith(toFix, "}");
return describeMatch(tree, fix.build());
}
}
| 3,100
| 40.346667
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/VarChecker.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.util.ASTHelpers.getAnnotationWithSimpleName;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.Var;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
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.util.ASTHelpers;
import com.google.errorprone.util.SourceVersion;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeInfo;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Optional;
import javax.lang.model.element.Modifier;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
name = "Var",
summary = "Non-constant variable missing @Var annotation",
severity = WARNING)
public class VarChecker extends BugChecker implements VariableTreeMatcher {
private static final String UNNECESSARY_FINAL = "Unnecessary 'final' modifier.";
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
Symbol sym = ASTHelpers.getSymbol(tree);
if (ASTHelpers.hasAnnotation(sym, Var.class, state)) {
if ((sym.flags() & Flags.EFFECTIVELY_FINAL) != 0) {
return buildDescription(tree)
.setMessage("@Var variable is never modified")
.addFix(
SuggestedFix.delete(
getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "Var")))
.build();
}
return Description.NO_MATCH;
}
if (!ASTHelpers.getGeneratedBy(state).isEmpty()) {
return Description.NO_MATCH;
}
if (TreeInfo.isReceiverParam((JCTree) tree)) {
return Description.NO_MATCH;
}
if (forLoopVariable(tree, state.getPath())) {
// for loop indices are implicitly @Var
// TODO(cushon): consider requiring @Var if the index is modified in the body of the loop
return Description.NO_MATCH;
}
switch (sym.getKind()) {
case PARAMETER:
case LOCAL_VARIABLE:
case EXCEPTION_PARAMETER:
case RESOURCE_VARIABLE:
return handleLocalOrParam(tree, state, sym);
default:
return Description.NO_MATCH;
}
}
boolean forLoopVariable(VariableTree tree, TreePath path) {
Tree parent = path.getParentPath().getLeaf();
if (!(parent instanceof ForLoopTree)) {
return false;
}
ForLoopTree forLoop = (ForLoopTree) parent;
return forLoop.getInitializer().contains(tree);
}
private Description handleLocalOrParam(VariableTree tree, VisitorState state, Symbol sym) {
if (sym.getModifiers().contains(Modifier.FINAL)) {
if (SourceVersion.supportsEffectivelyFinal(state.context)) {
// In Java 8, the final modifier is never necessary on locals/parameters because
// effectively final variables can be used anywhere a final variable is required.
Optional<SuggestedFix> fix = SuggestedFixes.removeModifiers(tree, state, Modifier.FINAL);
// The fix may not be present for TWR variables that were not explicitly final
if (fix.isPresent()) {
return buildDescription(tree).setMessage(UNNECESSARY_FINAL).addFix(fix.get()).build();
}
}
return Description.NO_MATCH;
}
if (!Collections.disjoint(
sym.owner.getModifiers(), EnumSet.of(Modifier.ABSTRACT, Modifier.NATIVE))) {
// flow information isn't collected for body-less methods
return Description.NO_MATCH;
}
if (isConsideredFinal(sym)) {
return Description.NO_MATCH;
}
return describeMatch(tree, addVarAnnotation(tree));
}
private static Fix addVarAnnotation(VariableTree tree) {
return SuggestedFix.builder().prefixWith(tree, "@Var ").addImport(Var.class.getName()).build();
}
}
| 4,997
| 38.046875
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ReferenceEquality.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 com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.util.Name;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Comparison using reference equality instead of value equality",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public class ReferenceEquality extends AbstractReferenceEquality {
@Override
protected boolean matchArgument(ExpressionTree tree, VisitorState state) {
Type type = ASTHelpers.getType(tree);
if (!type.isReference()) {
return false;
}
ClassTree classTree = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class);
if (classTree == null) {
return false;
}
Type classType = ASTHelpers.getType(classTree);
if (classType == null) {
return false;
}
if (inComparisonMethod(classType, type, state)) {
return false;
}
if (ASTHelpers.isSubtype(type, state.getSymtab().enumSym.type, state)) {
return false;
}
if (ASTHelpers.isSubtype(type, state.getSymtab().classType, state)) {
return false;
}
if (!implementsEquals(type, state)) {
return false;
}
return true;
}
private static boolean inComparisonMethod(Type classType, Type type, VisitorState state) {
Symtab symtab = state.getSymtab();
// Check for lambdas implementing the Comparator.compare functional interface.
LambdaExpressionTree lambdaTree =
ASTHelpers.findEnclosingNode(state.getPath(), LambdaExpressionTree.class);
if (lambdaTree != null) {
return ASTHelpers.isSameType(ASTHelpers.getType(lambdaTree), symtab.comparatorType, state);
}
MethodTree methodTree = ASTHelpers.findEnclosingMethod(state);
if (methodTree == null) {
return false;
}
MethodSymbol sym = ASTHelpers.getSymbol(methodTree);
if (sym.isStatic()) {
return false;
}
if (overridesMethodOnType(classType, sym, symtab.comparatorType, "compare", state)) {
return true;
}
if (overridesMethodOnType(classType, sym, symtab.comparableType, "compareTo", state)
|| overridesMethodOnType(classType, sym, symtab.objectType, "equals", state)) {
return ASTHelpers.isSameType(type, classType, state);
}
return false;
}
private static boolean overridesMethodOnType(
Type classType,
MethodSymbol methodSymbol,
Type overriddenType,
String overriddenMethodName,
VisitorState state) {
Symbol overriddenMethodSymbol = getOnlyMember(state, overriddenType, overriddenMethodName);
return methodSymbol.getSimpleName().contentEquals(overriddenMethodName)
&& methodSymbol.overrides(
overriddenMethodSymbol, classType.tsym, state.getTypes(), /* checkResult= */ false);
}
private static Symbol getOnlyMember(VisitorState state, Type type, String name) {
return getOnlyElement(type.tsym.members().getSymbolsByName(state.getName(name)));
}
/** Check if the method declares or inherits an implementation of .equals() */
public static boolean implementsEquals(Type type, VisitorState state) {
Name equalsName = EQUALS.get(state);
Symbol objectEquals = getOnlyMember(state, state.getSymtab().objectType, "equals");
for (Type sup : state.getTypes().closure(type)) {
if (sup.tsym.isInterface()) {
continue;
}
if (ASTHelpers.isSameType(sup, state.getSymtab().objectType, state)) {
return false;
}
Scope scope = sup.tsym.members();
if (scope == null) {
continue;
}
for (Symbol sym : scope.getSymbolsByName(equalsName)) {
if (sym.overrides(objectEquals, type.tsym, state.getTypes(), /* checkResult= */ false)) {
return true;
}
}
}
return false;
}
private static final Supplier<Name> EQUALS =
VisitorState.memoize(state -> state.getName("equals"));
}
| 5,269
| 35.597222
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TypeToString.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 static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.toType;
import static com.google.errorprone.predicates.TypePredicates.isDescendantOf;
import static com.google.errorprone.util.ASTHelpers.isBugCheckerCode;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.predicates.TypePredicate;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Type;
import java.util.Optional;
/**
* Flags {@code com.sun.tools.javac.code.Type#toString} usage in {@link BugChecker}s.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary = "Type#toString shouldn't be used for comparison as it is expensive and fragile.",
severity = SUGGESTION)
public class TypeToString extends AbstractToString {
private static final TypePredicate IS_TYPE = isDescendantOf("com.sun.tools.javac.code.Type");
private static final Matcher<Tree> STRING_EQUALS =
toType(
MemberSelectTree.class,
instanceMethod().onExactClass("java.lang.String").named("equals"));
private static boolean typeToStringInBugChecker(Type type, VisitorState state) {
if (!isBugCheckerCode(state)) {
return false;
}
Tree parentTree = state.getPath().getParentPath().getLeaf();
return IS_TYPE.apply(type, state) && STRING_EQUALS.matches(parentTree, state);
}
@Override
protected TypePredicate typePredicate() {
return TypeToString::typeToStringInBugChecker;
}
@Override
protected Optional<String> descriptionMessageForDefaultMatch(Type type, VisitorState state) {
return Optional.of("Type#toString shouldn't be used as it is expensive and fragile.");
}
@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();
}
}
| 2,922
| 35.08642
| 95
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/IgnoredPureGetter.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.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static javax.lang.model.element.Modifier.ABSTRACT;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.sun.source.tree.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.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import java.util.Optional;
import javax.inject.Inject;
/** Flags ignored return values from pure getters. */
@BugPattern(
severity = WARNING,
summary =
"Getters on AutoValues, AutoBuilders, and Protobuf Messages are side-effect free, so there"
+ " is no point in calling them if the return value is ignored. While there are no"
+ " side effects from the getter, the receiver may have side effects.")
public final class IgnoredPureGetter extends AbstractReturnValueIgnored {
private static final Supplier<Type> MESSAGE_LITE =
VisitorState.memoize(state -> state.getTypeFromString("com.google.protobuf.MessageLite"));
private static final Supplier<Type> MUTABLE_MESSAGE_LITE =
VisitorState.memoize(
state -> state.getTypeFromString("com.google.protobuf.MutableMessageLite"));
@Inject
IgnoredPureGetter(ConstantExpressions constantExpressions) {
super(constantExpressions);
}
@Override
protected Matcher<? super ExpressionTree> specializedMatcher() {
return IgnoredPureGetter::isPureGetter;
}
@Override
public ImmutableMap<String, ?> getMatchMetadata(ExpressionTree tree, VisitorState state) {
return pureGetterKind(tree, state)
.map(kind -> ImmutableMap.of("pure_getter_kind", kind))
.orElse(ImmutableMap.of());
}
@Override
protected Description describeReturnValueIgnored(
MethodInvocationTree methodInvocationTree, VisitorState state) {
Tree parent = state.getPath().getParentPath().getLeaf();
Description.Builder builder =
buildDescription(methodInvocationTree)
.addFix(
SuggestedFix.builder()
.setShortDescription("Remove with any side effects from the receiver")
.delete(
parent instanceof ExpressionStatementTree ? parent : methodInvocationTree)
.build());
ExpressionTree receiver = getReceiver(methodInvocationTree);
if (receiver instanceof MethodInvocationTree) {
builder.addFix(
SuggestedFix.builder()
.setShortDescription("Remove but keep side effects from the receiver")
.replace(methodInvocationTree, state.getSourceForNode(receiver))
.build());
}
return builder.build();
}
private static boolean isPureGetter(ExpressionTree tree, VisitorState state) {
return pureGetterKind(tree, state).isPresent();
}
private static Optional<PureGetterKind> pureGetterKind(ExpressionTree tree, VisitorState state) {
Symbol rawSymbol = getSymbol(tree);
if (!(rawSymbol instanceof MethodSymbol)) {
return Optional.empty();
}
MethodSymbol symbol = (MethodSymbol) rawSymbol;
Symbol owner = symbol.owner;
if (symbol.getModifiers().contains(ABSTRACT) && symbol.getParameters().isEmpty()) {
// The return value of any abstract method on an @AutoValue needs to be used.
if (hasAnnotation(owner, "com.google.auto.value.AutoValue", state)) {
return Optional.of(PureGetterKind.AUTO_VALUE);
}
// The return value of any abstract method on an @AutoBuilder (which doesn't return the
// Builder itself) needs to be used.
if (hasAnnotation(owner, "com.google.auto.value.AutoBuilder", state)
&& !isSameType(symbol.getReturnType(), owner.type, state)) {
return Optional.of(PureGetterKind.AUTO_BUILDER);
}
// The return value of any abstract method on an @AutoValue.Builder (which doesn't return the
// Builder itself) needs to be used.
if (hasAnnotation(owner, "com.google.auto.value.AutoValue.Builder", state)
&& !isSameType(symbol.getReturnType(), owner.type, state)) {
return Optional.of(PureGetterKind.AUTO_VALUE_BUILDER);
}
}
try {
if (isSubtype(owner.type, MESSAGE_LITE.get(state), state)
&& !isSubtype(owner.type, MUTABLE_MESSAGE_LITE.get(state), state)) {
return Optional.of(PureGetterKind.PROTO);
}
} catch (Symbol.CompletionFailure ignore) {
// isSubtype may throw this if some supertype's class file isn't found
// Nothing we can do about it as far as I know
}
return Optional.empty();
}
private enum PureGetterKind {
AUTO_VALUE,
AUTO_VALUE_BUILDER,
AUTO_BUILDER,
PROTO
}
}
| 6,148
| 39.721854
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TryWithResourcesVariable.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.TryTreeMatcher;
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.Tree;
import com.sun.source.tree.TryTree;
import com.sun.source.tree.VariableTree;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"This variable is unnecessary, the try-with-resources resource can be a reference to a"
+ " final or effectively final variable",
severity = WARNING)
public class TryWithResourcesVariable extends BugChecker implements TryTreeMatcher {
@Override
public Description matchTry(TryTree tree, VisitorState state) {
for (Tree resource : tree.getResources()) {
if (!(resource instanceof VariableTree)) {
continue;
}
VariableTree variableTree = (VariableTree) resource;
ExpressionTree initializer = variableTree.getInitializer();
if (!(initializer instanceof IdentifierTree)) {
continue;
}
if (!isConsideredFinal(getSymbol(initializer))) {
continue;
}
String name = ((IdentifierTree) initializer).getName().toString();
state.reportMatch(
describeMatch(
resource,
SuggestedFix.builder()
.replace(getStartPosition(variableTree), state.getEndPosition(initializer), name)
.merge(SuggestedFixes.renameVariableUsages(variableTree, name, state))
.build()));
}
return NO_MATCH;
}
}
| 2,796
| 38.957143
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InsecureCipherMode.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.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;
/**
* @author avenet@google.com (Arnaud J. Venet)
*/
@BugPattern(
name = "InsecureCryptoUsage",
altNames = {"InsecureCipherMode"},
summary =
"A standard cryptographic operation is used in a mode that is prone to vulnerabilities",
severity = ERROR)
public class InsecureCipherMode extends BugChecker implements MethodInvocationTreeMatcher {
private static final String MESSAGE_BASE = "Insecure usage of a crypto API: ";
private static final Matcher<ExpressionTree> CIPHER_GETINSTANCE_MATCHER =
staticMethod().onClass("javax.crypto.Cipher").named("getInstance");
private static final Matcher<ExpressionTree> KEY_STRUCTURE_GETINSTANCE_MATCHER =
anyOf(
staticMethod().onClass("java.security.KeyPairGenerator").named("getInstance"),
staticMethod().onClass("java.security.KeyFactory").named("getInstance"),
staticMethod().onClass("javax.crypto.KeyAgreement").named("getInstance"));
private Description buildErrorMessage(MethodInvocationTree tree, String explanation) {
Description.Builder description = buildDescription(tree);
String message = MESSAGE_BASE + explanation + ".";
description.setMessage(message);
return description.build();
}
private Description identifyEcbVulnerability(MethodInvocationTree tree) {
// We analyze the first argument of all the overloads of Cipher.getInstance().
Object argument = ASTHelpers.constValue(tree.getArguments().get(0));
if (argument == null) {
// We flag call sites where the transformation string is dynamically computed.
return buildErrorMessage(
tree, "the transformation is not a compile-time constant expression");
}
// Otherwise, we know that the transformation is specified by a string literal.
String transformation = (String) argument;
// We exclude stream ciphers (this check only makes sense for block ciphers), i.e., the RC4
// cipher. The name of this algorithm is "ARCFOUR" in the SunJce and "ARC4" in Conscrypt.
// Some other providers like JCraft also seem to use the name "RC4".
if (transformation.matches("ARCFOUR.*")
|| transformation.matches("ARC4.*")
|| transformation.matches("RC4.*")) {
return Description.NO_MATCH;
}
if (!transformation.matches(".*/.*/.*")) {
// The mode and padding shall be explicitly specified. We don't allow default settings to be
// used, regardless of the algorithm and provider.
return buildErrorMessage(tree, "the mode and padding must be explicitly specified");
}
if (transformation.matches(".*/ECB/.*")
&& !transformation.matches("RSA/.*")
&& !transformation.matches("AESWrap/.*")) {
// Otherwise, ECB mode should be explicitly specified in order to trigger the check. RSA
// is an exception, as this transformation doesn't actually implement a block cipher
// encryption mode (the input is limited by the size of the key). AESWrap is another
// exception, because this algorithm is only used to encrypt encryption keys.
return buildErrorMessage(tree, "ECB mode must not be used");
}
if (transformation.matches("ECIES.*") || transformation.matches("DHIES.*")) {
// Existing implementations of IES-based algorithms use ECB under the hood and must also be
// flagged as vulnerable. See b/30424901 for a more detailed rationale.
return buildErrorMessage(tree, "IES-based algorithms use ECB mode and are insecure");
}
return Description.NO_MATCH;
}
private Description identifyDiffieHellmanAndDsaVulnerabilities(MethodInvocationTree tree) {
// The first argument holds a string specifying the algorithm used for the operation
// considered.
Object argument = ASTHelpers.constValue(tree.getArguments().get(0));
if (argument == null) {
// We flag call sites where the algorithm specification string is dynamically computed.
return buildErrorMessage(
tree, "the algorithm specification is not a compile-time constant expression");
}
// Otherwise, we know that the algorithm is specified by a string literal.
String algorithm = (String) argument;
if (algorithm.matches("DH")) {
// Most implementations of Diffie-Hellman on prime fields have vulnerabilities. See b/31574444
// for a more detailed rationale.
return buildErrorMessage(tree, "using Diffie-Hellman on prime fields is insecure");
}
if (algorithm.matches("DSA")) {
// Some crypto libraries may accept invalid DSA signatures in specific configurations (see
// b/30262692 for details).
return buildErrorMessage(tree, "using DSA is insecure");
}
return Description.NO_MATCH;
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
Description description = checkInvocation(tree, state);
return description;
}
Description checkInvocation(MethodInvocationTree tree, VisitorState state) {
if (CIPHER_GETINSTANCE_MATCHER.matches(tree, state)) {
return identifyEcbVulnerability(tree);
}
if (KEY_STRUCTURE_GETINSTANCE_MATCHER.matches(tree, state)) {
return identifyDiffieHellmanAndDsaVulnerabilities(tree);
}
return Description.NO_MATCH;
}
}
| 6,560
| 42.450331
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ProtoRedundantSet.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.method.MethodMatchers.instanceMethod;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
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.Collection;
import java.util.Map;
import java.util.regex.Pattern;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Checks that protocol buffers built with chained builders don't set the same field twice.
*
* @author ghm@google.com (Graeme Morgan)
*/
@BugPattern(
summary = "A field on a protocol buffer was set twice in the same chained expression.",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public final class ProtoRedundantSet extends BugChecker implements MethodInvocationTreeMatcher {
/** Matches a chainable proto builder method. */
private static final Matcher<ExpressionTree> PROTO_FLUENT_METHOD =
instanceMethod()
.onDescendantOfAny(
"com.google.protobuf.GeneratedMessage.Builder",
"com.google.protobuf.GeneratedMessageLite.Builder")
.withNameMatching(Pattern.compile("^(set|add|clear|put).+"));
/**
* Matches a terminal proto builder method. That is, a chainable builder method which is either
* not followed by another method invocation, or by a method invocation which is not a {@link
* #PROTO_FLUENT_METHOD}.
*/
private static final Matcher<ExpressionTree> TERMINAL_PROTO_FLUENT_METHOD =
allOf(
PROTO_FLUENT_METHOD,
(tree, state) ->
!(state.getPath().getParentPath().getLeaf() instanceof MemberSelectTree
&& PROTO_FLUENT_METHOD.matches(
(ExpressionTree) state.getPath().getParentPath().getParentPath().getLeaf(),
state)));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!TERMINAL_PROTO_FLUENT_METHOD.matches(tree, state)) {
return Description.NO_MATCH;
}
ListMultimap<ProtoField, FieldWithValue> setters = ArrayListMultimap.create();
Type type = ASTHelpers.getReturnType(tree);
for (ExpressionTree current = tree;
PROTO_FLUENT_METHOD.matches(current, state);
current = ASTHelpers.getReceiver(current)) {
MethodInvocationTree method = (MethodInvocationTree) current;
if (!ASTHelpers.isSameType(type, ASTHelpers.getReturnType(current), state)) {
break;
}
Symbol symbol = ASTHelpers.getSymbol(current);
if (!(symbol instanceof MethodSymbol)) {
break;
}
String methodName = symbol.getSimpleName().toString();
// Break on methods like "addFooBuilder", otherwise we might be building a nested proto of the
// same type.
if (methodName.endsWith("Builder")) {
break;
}
match(method, methodName, setters);
}
setters.asMap().entrySet().removeIf(entry -> entry.getValue().size() <= 1);
if (setters.isEmpty()) {
return Description.NO_MATCH;
}
for (Map.Entry<ProtoField, Collection<FieldWithValue>> entry : setters.asMap().entrySet()) {
ProtoField protoField = entry.getKey();
Collection<FieldWithValue> values = entry.getValue();
state.reportMatch(describe(protoField, values, state));
}
return Description.NO_MATCH;
}
private Description describe(
ProtoField protoField, Collection<FieldWithValue> locations, VisitorState state) {
// We flag up all duplicate sets, but only suggest a fix if the setter is given the same
// argument (based on source code). This is to avoid the temptation to apply the fix in
// cases like,
// MyProto.newBuilder().setFoo(copy.getFoo()).setFoo(copy.getBar())
// where the correct fix is probably to replace the second 'setFoo' with 'setBar'.
SuggestedFix.Builder fix = SuggestedFix.builder();
long values =
locations.stream().map(l -> state.getSourceForNode(l.getArgument())).distinct().count();
if (values == 1) {
for (FieldWithValue field : Iterables.skip(locations, 1)) {
MethodInvocationTree method = field.getMethodInvocation();
int startPos = state.getEndPosition(ASTHelpers.getReceiver(method));
int endPos = state.getEndPosition(method);
fix.replace(startPos, endPos, "");
}
}
return buildDescription(locations.iterator().next().getArgument())
.setMessage(
String.format(
"%s was called %s with %s. Setting the same field multiple times is redundant, and "
+ "could mask a bug.",
protoField,
nTimes(locations.size()),
values == 1 ? "the same argument" : "different arguments"))
.addFix(fix.build())
.build();
}
private static void match(
MethodInvocationTree method,
String methodName,
ListMultimap<ProtoField, FieldWithValue> setters) {
for (FieldType fieldType : FieldType.values()) {
FieldWithValue match = fieldType.match(methodName, method);
if (match != null) {
setters.put(match.getField(), match);
}
}
}
private static String nTimes(int n) {
return n == 2 ? "twice" : String.format("%d times", n);
}
interface ProtoField {}
enum FieldType {
SINGLE {
@Override
@Nullable FieldWithValue match(String name, MethodInvocationTree tree) {
if (name.startsWith("set") && tree.getArguments().size() == 1) {
return FieldWithValue.of(SingleField.of(name), tree, tree.getArguments().get(0));
}
return null;
}
},
REPEATED {
@Override
@Nullable FieldWithValue match(String name, MethodInvocationTree tree) {
if (name.startsWith("set") && tree.getArguments().size() == 2) {
Integer index = ASTHelpers.constValue(tree.getArguments().get(0), Integer.class);
if (index != null) {
return FieldWithValue.of(
RepeatedField.of(name, index), tree, tree.getArguments().get(1));
}
}
return null;
}
},
MAP {
@Override
@Nullable FieldWithValue match(String name, MethodInvocationTree tree) {
if (name.startsWith("put") && tree.getArguments().size() == 2) {
Object key = ASTHelpers.constValue(tree.getArguments().get(0), Object.class);
if (key != null) {
return FieldWithValue.of(MapField.of(name, key), tree, tree.getArguments().get(1));
}
}
return null;
}
};
abstract FieldWithValue match(String name, MethodInvocationTree tree);
}
@AutoValue
abstract static class SingleField implements ProtoField {
abstract String getName();
static SingleField of(String name) {
return new AutoValue_ProtoRedundantSet_SingleField(name);
}
@Override
public final String toString() {
return String.format("%s(..)", getName());
}
}
@AutoValue
abstract static class RepeatedField implements ProtoField {
abstract String getName();
abstract int getIndex();
static RepeatedField of(String name, int index) {
return new AutoValue_ProtoRedundantSet_RepeatedField(name, index);
}
@Override
public final String toString() {
return String.format("%s(%s, ..)", getName(), getIndex());
}
}
@AutoValue
abstract static class MapField implements ProtoField {
abstract String getName();
abstract Object getKey();
static MapField of(String name, Object key) {
return new AutoValue_ProtoRedundantSet_MapField(name, key);
}
@Override
public final String toString() {
return String.format("%s(%s, ..)", getName(), getKey());
}
}
@AutoValue
abstract static class FieldWithValue {
abstract ProtoField getField();
abstract MethodInvocationTree getMethodInvocation();
abstract ExpressionTree getArgument();
static FieldWithValue of(
ProtoField field, MethodInvocationTree methodInvocationTree, ExpressionTree argumentTree) {
return new AutoValue_ProtoRedundantSet_FieldWithValue(
field, methodInvocationTree, argumentTree);
}
}
}
| 9,707
| 35.223881
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/OptionalNotPresent.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.Multisets.removeOccurrences;
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.getReceiver;
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.ConstantExpression.ConstantExpressionKind;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions.PureMethodInvocation;
import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions.Truthiness;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.stream.Stream;
import javax.inject.Inject;
/**
* @author mariasam@google.com (Maria Sam)
*/
@BugPattern(
summary =
"This Optional has been confirmed to be empty at this point, so the call to `get()` or"
+ " `orElseThrow()` will always throw.",
severity = WARNING)
public final class OptionalNotPresent extends BugChecker implements CompilationUnitTreeMatcher {
private static final Matcher<ExpressionTree> OPTIONAL_GET =
anyOf(
instanceMethod().onDescendantOf("com.google.common.base.Optional").named("get"),
instanceMethod().onDescendantOf("java.util.Optional").namedAnyOf("get", "orElseThrow"));
private final ConstantExpressions constantExpressions;
@Inject
OptionalNotPresent(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 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) {
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;
}
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 visitMethodInvocation(MethodInvocationTree tree, Void unused) {
if (OPTIONAL_GET.matches(tree, state)) {
var receiver = getReceiver(tree);
if (receiver != null) {
constantExpressions
.constantExpression(receiver, state)
.ifPresent(o -> checkForEmptiness(tree, o));
}
}
return super.visitMethodInvocation(tree, null);
}
private void checkForEmptiness(
MethodInvocationTree tree, ConstantExpression constantExpression) {
if (getMethodInvocations(truths)
.filter(
truth ->
truth.symbol() instanceof MethodSymbol
&& truth.symbol().getSimpleName().contentEquals("isEmpty"))
.flatMap(truth -> truth.receiver().stream())
.anyMatch(constantExpression::equals)
|| getMethodInvocations(falsehoods)
.filter(
truth ->
truth.symbol() instanceof MethodSymbol
&& truth.symbol().getSimpleName().contentEquals("isPresent"))
.flatMap(truth -> truth.receiver().stream())
.anyMatch(constantExpression::equals)) {
state.reportMatch(describeMatch(tree));
}
}
private Stream<PureMethodInvocation> getMethodInvocations(Multiset<ConstantExpression> truths) {
return truths.stream()
.filter(truth -> truth.kind().equals(ConstantExpressionKind.PURE_METHOD))
.map(ConstantExpression::pureMethod);
}
}
}
| 5,994
| 40.061644
| 116
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/EmptyIfStatement.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.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.isLastStatementInBlock;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.EmptyStatementTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.EmptyStatementTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
/**
* This checker finds and fixes empty statements after an if, with no else part. For example: if
* (foo == 10);
*
* <p>It attempts to match javac's -Xlint:empty warning behavior, which can be found in
* com/sun/tools/javac/comp/Check.java.
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
@BugPattern(
name = "EmptyIf",
altNames = {"empty"},
summary = "Empty statement after if",
severity = ERROR)
public class EmptyIfStatement extends BugChecker implements EmptyStatementTreeMatcher {
/**
* Match empty statement if: - Parent statement is an if - The then part of the parent if is an
* empty statement, and - The else part of the parent if does not exist
*/
@Override
public Description matchEmptyStatement(EmptyStatementTree tree, VisitorState state) {
TreePath parentPath = state.getPath().getParentPath();
Tree parent = parentPath.getLeaf();
if (!(parent instanceof IfTree)) {
return NO_MATCH;
}
IfTree ifTree = (IfTree) parent;
if (!(ifTree.getThenStatement() instanceof EmptyStatementTree)
|| ifTree.getElseStatement() != null) {
return NO_MATCH;
}
/*
* We suggest different fixes depending on what follows the parent if statement.
* If there is no statement following the if, then suggest deleting the whole
* if statement. If the next statement is a block, then suggest deleting the
* empty then part of the if. If the next statement is not a block, then also
* suggest deleting the empty then part of the if.
*/
if (isLastStatementInBlock().matches(ifTree, state.withPath(parentPath))) {
// No following statements. Delete whole if.
return describeMatch(parent, SuggestedFix.delete(parent));
} else {
// There are more statements. Delete the empty then part of the if.
return describeMatch(
ifTree.getThenStatement(), SuggestedFix.delete(ifTree.getThenStatement()));
}
}
}
| 3,244
| 38.096386
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryMethodInvocationMatcher.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.staticMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.matchers.method.MethodMatchers.MethodMatcher;
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 java.util.List;
/**
* {@link Matchers#methodInvocation(Matcher)} is not exactly deprecated, but it is legacy, and in
* particular is not needed when the argument is a MethodMatcher, since MethodMatcher already does
* the unwrapping that methodInvocation does.
*
* @author amalloy@google.com (Alan Malloy)
*/
@BugPattern(
summary = "It is not necessary to wrap a MethodMatcher with methodInvocation().",
severity = WARNING)
public class UnnecessaryMethodInvocationMatcher extends BugChecker
implements MethodInvocationTreeMatcher {
private static final String MATCHERS = Matchers.class.getCanonicalName();
private static final Matcher<ExpressionTree> METHOD_INVOCATION =
staticMethod().onClass(MATCHERS).named("methodInvocation");
private static final Matcher<ExpressionTree> COMBINATOR =
staticMethod().onClass(MATCHERS).namedAnyOf("allOf", "anyOf", "not");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!METHOD_INVOCATION.matches(tree, state)) {
return NO_MATCH;
}
List<? extends ExpressionTree> arguments = tree.getArguments();
if (arguments.size() != 1) {
// We can only unwrap if they haven't specified additional behavior.
return NO_MATCH;
}
Type methodMatcherType = state.getTypeFromString(MethodMatcher.class.getCanonicalName());
ExpressionTree argument = arguments.get(0);
if (!containsOnlyMethodMatchers(argument, methodMatcherType, state)) {
return NO_MATCH;
}
return describeMatch(tree, SuggestedFix.replace(tree, state.getSourceForNode(argument)));
}
private static boolean containsOnlyMethodMatchers(
ExpressionTree expressionTree, Type methodMatcherType, VisitorState state) {
if (ASTHelpers.isSubtype(ASTHelpers.getType(expressionTree), methodMatcherType, state)) {
return true;
}
if (!COMBINATOR.matches(expressionTree, state)) {
return false;
}
for (ExpressionTree argument : ((MethodInvocationTree) expressionTree).getArguments()) {
if (!containsOnlyMethodMatchers(argument, methodMatcherType, state)) {
return false;
}
}
return true;
}
}
| 3,662
| 40.625
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AbstractReturnValueIgnored.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.base.Preconditions.checkArgument;
import static com.google.common.base.Suppliers.memoize;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Lists.reverse;
import static com.google.common.collect.Multimaps.toMultimap;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ResultUsePolicy.EXPECTED;
import static com.google.errorprone.bugpatterns.checkreturnvalue.ResultUsePolicy.UNSPECIFIED;
import static com.google.errorprone.fixes.SuggestedFix.delete;
import static com.google.errorprone.fixes.SuggestedFix.postfixWith;
import static com.google.errorprone.fixes.SuggestedFix.prefixWith;
import static com.google.errorprone.fixes.SuggestedFixes.qualifyStaticImport;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.isThrowingFunctionalInterface;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.Matchers.parentNode;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.enclosingClass;
import static com.google.errorprone.util.ASTHelpers.getResultType;
import static com.google.errorprone.util.ASTHelpers.getRootAssignable;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.getTypeSubstitution;
import static com.google.errorprone.util.ASTHelpers.getUpperBound;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static com.google.errorprone.util.ASTHelpers.isVoidType;
import static com.google.errorprone.util.ASTHelpers.matchingMethods;
import static com.google.errorprone.util.FindIdentifiers.findAllIdents;
import static com.sun.source.tree.Tree.Kind.EXPRESSION_STATEMENT;
import static com.sun.source.tree.Tree.Kind.MEMBER_SELECT;
import static com.sun.source.tree.Tree.Kind.METHOD_INVOCATION;
import static com.sun.source.tree.Tree.Kind.NEW_CLASS;
import static com.sun.tools.javac.parser.Tokens.TokenKind.RPAREN;
import static java.lang.String.format;
import static java.util.stream.IntStream.range;
import static java.util.stream.Stream.concat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MultimapBuilder;
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.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.bugpatterns.checkreturnvalue.ResultUsePolicy;
import com.google.errorprone.bugpatterns.checkreturnvalue.ResultUsePolicyAnalyzer;
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.matchers.UnusedReturnValueMatcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
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.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.TypeVariableSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTag;
import java.lang.reflect.InvocationHandler;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Stream;
import javax.lang.model.element.Name;
import javax.lang.model.type.TypeKind;
/**
* An abstract base class to match API usages in which the return value is not used.
*
* <p>In addition to regular contexts in which a return value isn't used (e.g.: the result of {@code
* String.trim()} is just ignored), this class has the capacity to determine if the result is cast
* in such a way as to lose important static type information.
*
* <p>If an analysis extending this base class chooses to care about this circumstance, they can
* override {@link #lostType} to define the type information they wish to keep.
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
public abstract class AbstractReturnValueIgnored extends BugChecker
implements MethodInvocationTreeMatcher,
MemberReferenceTreeMatcher,
ReturnTreeMatcher,
NewClassTreeMatcher,
ResultUsePolicyAnalyzer<ExpressionTree, VisitorState> {
private final Supplier<UnusedReturnValueMatcher> unusedReturnValueMatcher =
memoize(() -> UnusedReturnValueMatcher.get(allowInExceptionThrowers()));
private final Supplier<Matcher<ExpressionTree>> matcher =
memoize(() -> allOf(unusedReturnValueMatcher.get(), this::isCheckReturnValue));
private final Supplier<Matcher<MemberReferenceTree>> lostReferenceTreeMatcher =
memoize(
() ->
allOf(
(t, s) -> isObjectReturningMethodReferenceExpression(t, s),
not((t, s) -> isExemptedInterfaceType(getType(t), s)),
not((t, s) -> isThrowingFunctionalInterface(getType(t), s)),
specializedMatcher()));
private final ConstantExpressions constantExpressions;
// TODO(ghm): Remove once possible.
protected AbstractReturnValueIgnored() {
this(ConstantExpressions.fromFlags(ErrorProneFlags.empty()));
}
protected AbstractReturnValueIgnored(ConstantExpressions constantExpressions) {
this.constantExpressions = constantExpressions;
}
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocationTree, VisitorState state) {
Description description =
matcher.get().matches(methodInvocationTree, state)
? describeReturnValueIgnored(methodInvocationTree, state)
: NO_MATCH;
if (!description.equals(NO_MATCH)) {
return description;
}
return checkLostType(methodInvocationTree, state);
}
@Override
public Description matchNewClass(NewClassTree newClassTree, VisitorState state) {
return matcher.get().matches(newClassTree, state)
? describeReturnValueIgnored(newClassTree, state)
: NO_MATCH;
}
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
Description description =
matcher.get().matches(tree, state) ? describeReturnValueIgnored(tree, state) : NO_MATCH;
if (!lostType(state).isPresent() || !description.equals(NO_MATCH)) {
return description;
}
if (lostReferenceTreeMatcher.get().matches(tree, state)) {
return describeMatch(tree);
}
return description;
}
@Override
public boolean isCovered(ExpressionTree tree, VisitorState state) {
return isCheckReturnValue(tree, state);
}
@Override
public ResultUsePolicy getMethodPolicy(ExpressionTree expression, VisitorState state) {
return isCheckReturnValue(expression, state) ? EXPECTED : UNSPECIFIED;
}
/**
* Returns whether the given expression's return value should be used according to this checker,
* regardless of whether or not the return value is actually used.
*/
private boolean isCheckReturnValue(ExpressionTree tree, VisitorState state) {
// TODO(cgdecker): Just replace specializedMatcher with this?
return specializedMatcher().matches(tree, state);
}
/**
* Match whatever additional conditions concrete subclasses want to match (a list of known
* side-effect-free methods, has a @CheckReturnValue annotation, etc.).
*/
protected abstract Matcher<? super ExpressionTree> specializedMatcher();
/** Check for occurrences of this type being lost, i.e. cast to {@link Object}. */
protected Optional<Type> lostType(VisitorState state) {
return Optional.empty();
}
protected String lostTypeMessage(String returnedType, String declaredReturnType) {
return format("Returning %s from method that returns %s.", returnedType, declaredReturnType);
}
/**
* Override this to return false to forbid discarding return values in testers that are testing
* whether an exception is thrown.
*/
protected boolean allowInExceptionThrowers() {
return true;
}
/**
* Fixes the error by assigning the result of the call to the receiver reference, or deleting the
* method call. Subclasses may override if they prefer a different description.
*/
protected Description describeReturnValueIgnored(
MethodInvocationTree methodInvocationTree, VisitorState state) {
return buildDescription(methodInvocationTree)
.addAllFixes(fixesAtCallSite(methodInvocationTree, state))
.setMessage(getMessage(getSymbol(methodInvocationTree).getSimpleName()))
.build();
}
final ImmutableList<Fix> fixesAtCallSite(ExpressionTree invocationTree, VisitorState state) {
checkArgument(
invocationTree.getKind() == METHOD_INVOCATION || invocationTree.getKind() == NEW_CLASS,
"unexpected kind: %s",
invocationTree.getKind());
Tree parent = state.getPath().getParentPath().getLeaf();
Type resultType = getType(invocationTree);
// Find the root of the field access chain, i.e. a.intern().trim() ==> a.
/*
* TODO(cpovirk): Enhance getRootAssignable to return array accesses (e.g., `x[y]`)? If we do,
* then we'll also need to accept `symbol == null` (which is fine, since all we need the symbol
* for is to check against `this`, and `x[y]` is not `this`.)
*/
ExpressionTree identifierExpr =
invocationTree.getKind() == METHOD_INVOCATION
? getRootAssignable((MethodInvocationTree) invocationTree)
: null; // null root assignable for constructor calls (as well as some method calls)
Symbol symbol = getSymbol(identifierExpr);
Type identifierType = getType(identifierExpr);
/*
* A map from short description to fix instance (even though every short description ultimately
* will become _part of_ a fix instance later).
*
* As always, the order of suggested fixes can matter. In practice, it probably matters mostly
* just to the checker's own tests. But it also affects the order in which the fixes are printed
* during compile errors, and it affects which fix is chosen for automatically generated fix CLs
* (though those should be rare inside Google: b/244334502#comment13).
*
* Note that, when possible, we have separate code that suggests adding @CanIgnoreReturnValue in
* preference to all the fixes below.
*
* The _names_ of the fixes probably don't actually matter inside Google: b/204435834#comment4.
* Luckily, they're not a ton harder to include than plain code comments would be.
*/
ImmutableMap.Builder<String, SuggestedFix> fixes = ImmutableMap.builder();
if (MOCKITO_VERIFY.matches(invocationTree, state)) {
ExpressionTree maybeCallToMock =
((MethodInvocationTree) invocationTree).getArguments().get(0);
if (maybeCallToMock.getKind() == METHOD_INVOCATION) {
ExpressionTree maybeMethodSelectOnMock =
((MethodInvocationTree) maybeCallToMock).getMethodSelect();
if (maybeMethodSelectOnMock.getKind() == MEMBER_SELECT) {
MemberSelectTree maybeSelectOnMock = (MemberSelectTree) maybeMethodSelectOnMock;
// For this suggestion, we want to move the closing parenthesis:
// verify(foo .bar())
// ^ v
// +------+
//
// The result is:
// verify(foo).bar()
//
// TODO(cpovirk): Suggest this only if `foo` looks like an actual mock object.
SuggestedFix.Builder fix = SuggestedFix.builder();
fix.postfixWith(maybeSelectOnMock.getExpression(), ")");
int closingParen =
reverse(state.getOffsetTokensForNode(invocationTree)).stream()
.filter(t -> t.kind() == RPAREN)
.findFirst()
.get()
.pos();
fix.replace(closingParen, closingParen + 1, "");
fixes.put(
format("Verify that %s was called", maybeSelectOnMock.getIdentifier()), fix.build());
}
}
}
boolean considerBlanketFixes = true;
if (resultType != null && resultType.getKind() == TypeKind.BOOLEAN) {
// Fix by calling either assertThat(...).isTrue() or verify(...).
if (state.errorProneOptions().isTestOnlyTarget()) {
SuggestedFix.Builder fix = SuggestedFix.builder();
fix.prefixWith(
invocationTree,
qualifyStaticImport("com.google.common.truth.Truth.assertThat", fix, state) + "(")
.postfixWith(invocationTree, ").isTrue()");
fixes.put("Assert that the result is true", fix.build());
} else {
SuggestedFix.Builder fix = SuggestedFix.builder();
fix.prefixWith(
invocationTree,
qualifyStaticImport("com.google.common.base.Verify.verify", fix, state) + "(")
.postfixWith(invocationTree, ")");
fixes.put("Insert a runtime check that the result is true", fix.build());
}
} else if (resultType != null
// By looking for any isTrue() method, we handle not just Truth but also AssertJ.
&& matchingMethods(
NAME_OF_IS_TRUE.get(state),
m -> m.getParameters().isEmpty(),
resultType,
state.getTypes())
.anyMatch(m -> true)) {
fixes.put("Assert that the result is true", postfixWith(invocationTree, ".isTrue()"));
considerBlanketFixes = false;
}
if (identifierExpr != null
&& symbol != null
&& !symbol.name.contentEquals("this")
&& resultType != null
&& state.getTypes().isAssignable(resultType, identifierType)) {
fixes.put(
"Assign result back to variable",
prefixWith(invocationTree, state.getSourceForNode(identifierExpr) + " = "));
}
/*
* TODO(cpovirk): Suggest returning the value from the enclosing method where possible... *if*
* we can find a good heuristic. We could consider "Is the return type a protobuf" and/or "Is
* this a constructor call or build() call?"
*/
if (parent.getKind() == EXPRESSION_STATEMENT
&& !constantExpressions.constantExpression(invocationTree, state).isPresent()
&& considerBlanketFixes) {
ImmutableSet<String> identifiersInScope =
findAllIdents(state).stream().map(v -> v.name.toString()).collect(toImmutableSet());
concat(Stream.of("unused"), range(2, 10).mapToObj(i -> "unused" + i))
// TODO(b/72928608): Handle even local variables declared *later* within this scope.
// TODO(b/250568455): Also check whether we have suggested this name before in this scope.
.filter(n -> !identifiersInScope.contains(n))
.findFirst()
.ifPresent(
n ->
fixes.put(
"Suppress error by assigning to a variable",
prefixWith(parent, format("var %s = ", n))));
}
if (parent.getKind() == EXPRESSION_STATEMENT && considerBlanketFixes) {
if (constantExpressions.constantExpression(invocationTree, state).isPresent()) {
fixes.put("Delete call", delete(parent));
} else {
fixes.put("Delete call and any side effects", delete(parent));
}
}
return fixes.buildOrThrow().entrySet().stream()
.map(
e -> SuggestedFix.builder().merge(e.getValue()).setShortDescription(e.getKey()).build())
.collect(toImmutableList());
}
/**
* Uses the default description for results ignored via a method reference. Subclasses may
* override if they prefer a different description.
*/
protected Description describeReturnValueIgnored(
MemberReferenceTree memberReferenceTree, VisitorState state) {
return buildDescription(memberReferenceTree)
.setMessage(
getMessage(
state.getName(descriptiveNameForMemberReference(memberReferenceTree, state))))
.build();
}
/**
* Uses the default description for results ignored via a constructor call. Subclasses may
* override if they prefer a different description.
*/
protected Description describeReturnValueIgnored(NewClassTree newClassTree, VisitorState state) {
return buildDescription(newClassTree)
.setMessage(
format(
"Ignored return value of '%s'",
state.getSourceForNode(newClassTree.getIdentifier())))
.build();
}
private static String descriptiveNameForMemberReference(
MemberReferenceTree memberReferenceTree, VisitorState state) {
if (memberReferenceTree.getMode() == ReferenceMode.NEW) {
// The qualifier expression *should* just be the name of the class here
return state.getSourceForNode(memberReferenceTree.getQualifierExpression());
}
return memberReferenceTree.getName().toString();
}
/**
* Returns the diagnostic message. Can be overridden by subclasses to provide a customized
* diagnostic that includes the name of the invoked method.
*/
protected String getMessage(Name name) {
return message();
}
private Description checkLostType(MethodInvocationTree tree, VisitorState state) {
Optional<Type> optionalType = lostType(state);
if (!optionalType.isPresent()) {
return NO_MATCH;
}
Type lostType = optionalType.get();
MethodSymbol sym = getSymbol(tree);
Type returnType = getResultType(tree);
Type returnedFutureType = state.getTypes().asSuper(returnType, lostType.tsym);
if (returnedFutureType != null
&& !returnedFutureType.hasTag(TypeTag.ERROR) // work around error-prone#996
&& !returnedFutureType.isRaw()) {
if (isSubtype(
getUpperBound(returnedFutureType.getTypeArguments().get(0), state.getTypes()),
lostType,
state)) {
return buildDescription(tree)
.setMessage(format("Method returns a nested type, %s", returnType))
.build();
}
// The type variable that determines the generic on the returned type was not an instance of
// that type.
// However, many methods (like guava's Futures.transform) have signatures like this:
// Future<O> do(SomeObject<? extends O>). If O resolves to java.lang.Object or ?, then a
// SomeObject<Future> is a valid parameter to pass, but results in a nested future.
Type methodReturnType = sym.getReturnType();
List<TypeVariableSymbol> typeParameters = sym.getTypeParameters();
Set<TypeVariableSymbol> returnTypeChoosing = new HashSet<>();
// For each type variable on the method, see if we can reach the type declared as the param
// of the returned type, by traversing its type bounds. If we can reach it, we know that if
// an argument is passed to an invocation of this method where the type variable is a subtype
// of type, that means that a nested type is being returned.
for (TypeVariableSymbol tvs : typeParameters) {
Queue<TypeVariableSymbol> queue = new ArrayDeque<>();
queue.add(tvs);
while (!queue.isEmpty()) {
TypeVariableSymbol currentTypeParam = queue.remove();
for (Type typeParam : methodReturnType.getTypeArguments()) {
if (typeParam.tsym == currentTypeParam) {
returnTypeChoosing.add(tvs);
}
}
for (Type toAdd : currentTypeParam.getBounds()) {
if (toAdd.tsym instanceof TypeVariableSymbol) {
queue.add((TypeVariableSymbol) toAdd.tsym);
}
}
}
}
// If at least one of the method's type parameters is involved in determining the returned
// type, check each passed parameter to ensure that it is never passed as a subtype
// of the type.
if (!returnTypeChoosing.isEmpty()) {
ListMultimap<TypeVariableSymbol, TypeInfo> resolved = getResolvedGenerics(tree);
for (TypeVariableSymbol returnTypeChoosingSymbol : returnTypeChoosing) {
List<TypeInfo> types = resolved.get(returnTypeChoosingSymbol);
for (TypeInfo type : types) {
if (isSubtype(type.resolvedVariableType, lostType, state)) {
return buildDescription(type.tree)
.setMessage(
format(
"Invocation produces a nested type - Type variable %s, as part of return "
+ "type %s resolved to %s.",
returnTypeChoosingSymbol, methodReturnType, type.resolvedVariableType))
.build();
}
}
}
}
}
if (allOf(
allOf(
parentNode(AbstractReturnValueIgnored::isObjectReturningLambdaExpression),
not(unusedReturnValueMatcher.get()::isAllowed)),
specializedMatcher(),
not((t, s) -> isVoidType(getType(t), s)))
.matches(tree, state)) {
return describeReturnValueIgnored(tree, state);
}
return NO_MATCH;
}
private static final class TypeInfo {
private final TypeVariableSymbol sym;
private final Type resolvedVariableType;
private final Tree tree;
private TypeInfo(TypeVariableSymbol sym, Type resolvedVariableType, Tree tree) {
this.sym = sym;
this.resolvedVariableType = resolvedVariableType;
this.tree = tree;
}
}
private static ListMultimap<TypeVariableSymbol, TypeInfo> getResolvedGenerics(
MethodInvocationTree tree) {
Type type = getType(tree.getMethodSelect());
ImmutableListMultimap<TypeVariableSymbol, Type> subst =
getTypeSubstitution(type, getSymbol(tree));
return subst.entries().stream()
.map(e -> new TypeInfo(e.getKey(), e.getValue(), tree))
.collect(
toMultimap(
k -> k.sym, k -> k, MultimapBuilder.linkedHashKeys().arrayListValues()::build));
}
private static boolean isObjectReturningMethodReferenceExpression(
MemberReferenceTree tree, VisitorState state) {
return functionalInterfaceReturnsObject(getType(tree), state);
}
private static boolean isObjectReturningLambdaExpression(Tree tree, VisitorState state) {
if (!(tree instanceof LambdaExpressionTree)) {
return false;
}
Type type = getType(tree);
return functionalInterfaceReturnsObject(type, state) && !isExemptedInterfaceType(type, state);
}
/**
* Checks that the return value of a functional interface is void. Note, we do not use
* ASTHelpers.isVoidType here, return values of Void are actually type-checked. Only
* void-returning functions silently ignore return values of any type.
*/
private static boolean functionalInterfaceReturnsObject(Type interfaceType, VisitorState state) {
Type objectType = state.getSymtab().objectType;
return isSubtype(
objectType,
getUpperBound(
state.getTypes().findDescriptorType(interfaceType).getReturnType(), state.getTypes()),
state);
}
private static final ImmutableSet<String> EXEMPTED_TYPES =
ImmutableSet.of(
"org.mockito.stubbing.Answer",
"graphql.schema.DataFetcher",
"org.jmock.lib.action.CustomAction",
"net.sf.cglib.proxy.MethodInterceptor",
"org.aopalliance.intercept.MethodInterceptor",
InvocationHandler.class.getName());
private static boolean isExemptedInterfaceType(Type type, VisitorState state) {
return EXEMPTED_TYPES.stream()
.map(state::getTypeFromString)
.anyMatch(t -> isSubtype(type, t, state));
}
private static boolean isExemptedInterfaceMethod(MethodSymbol symbol, VisitorState state) {
return isExemptedInterfaceType(enclosingClass(symbol).type, state);
}
/** Returning a type from a lambda or method that returns Object loses the type information. */
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
Optional<Type> optionalType = lostType(state);
if (!optionalType.isPresent()) {
return NO_MATCH;
}
Type objectType = state.getSymtab().objectType;
Type lostType = optionalType.get();
Type resultType = getResultType(tree.getExpression());
if (resultType == null) {
return NO_MATCH;
}
if (resultType.getKind() == TypeKind.NULL || resultType.getKind() == TypeKind.NONE) {
return NO_MATCH;
}
if (isSubtype(resultType, lostType, state)) {
// Traverse enclosing nodes of this return tree until either a lambda or a Method is reached.
for (Tree enclosing : state.getPath()) {
if (enclosing instanceof MethodTree) {
MethodTree methodTree = (MethodTree) enclosing;
MethodSymbol symbol = getSymbol(methodTree);
if (isSubtype(objectType, symbol.getReturnType(), state)
&& !isExemptedInterfaceMethod(symbol, state)) {
return buildDescription(tree)
.setMessage(
lostTypeMessage(resultType.toString(), symbol.getReturnType().toString()))
.build();
} else {
break;
}
}
if (enclosing instanceof LambdaExpressionTree) {
LambdaExpressionTree lambdaTree = (LambdaExpressionTree) enclosing;
if (isObjectReturningLambdaExpression(lambdaTree, state)) {
return buildDescription(tree)
.setMessage(lostTypeMessage(resultType.toString(), "Object"))
.build();
} else {
break;
}
}
}
}
return NO_MATCH;
}
private static final Matcher<ExpressionTree> MOCKITO_VERIFY =
staticMethod().onClass("org.mockito.Mockito").named("verify");
private static final com.google.errorprone.suppliers.Supplier<com.sun.tools.javac.util.Name>
NAME_OF_IS_TRUE = VisitorState.memoize(state -> state.getName("isTrue"));
}
| 27,767
| 43.006339
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ReturnValueIgnored.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.anyMethod;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.constructor;
import static com.google.errorprone.matchers.Matchers.kindIs;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.Matchers.packageStartsWith;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.predicates.TypePredicates.isDescendantOf;
import static com.google.errorprone.predicates.TypePredicates.isExactTypeAny;
import static com.google.errorprone.util.ASTHelpers.enclosingPackage;
import static com.google.errorprone.util.ASTHelpers.getReceiverType;
import static com.google.errorprone.util.ASTHelpers.getReturnType;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableMap;
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.threadsafety.ConstantExpressions;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import java.util.regex.Pattern;
import javax.inject.Inject;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
/** A checker which produces an error when a return value is accidentally discarded. */
@BugPattern(
altNames = {"ResultOfMethodCallIgnored", "CheckReturnValue"},
summary = "Return value of this method must be used",
severity = ERROR)
public class ReturnValueIgnored extends AbstractReturnValueIgnored {
/**
* A set of types which this checker should examine method calls on.
*
* <p>There are also some high-priority return value ignored checks in SpotBugs for various
* threading constructs which do not return the same type as the receiver. This check does not
* deal with them, since the fix is less straightforward. See a list of the SpotBugs checks here:
* https://github.com/spotbugs/spotbugs/blob/master/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/CheckReturnAnnotationDatabase.java
*/
private static final ImmutableSet<String> TYPES_TO_CHECK =
ImmutableSet.of("java.math.BigInteger", "java.math.BigDecimal", "java.nio.file.Path");
/**
* Matches method invocations in which the method being called is on an instance of a type in the
* TYPES_TO_CHECK set and returns the same type (e.g. String.trim() returns a String).
*/
private static final Matcher<ExpressionTree> RETURNS_SAME_TYPE =
allOf(
not(kindIs(Kind.NEW_CLASS)), // Constructor calls don't have a "receiver"
(tree, state) -> {
Type receiverType = getReceiverType(tree);
return TYPES_TO_CHECK.contains(receiverType.toString())
&& isSameType(receiverType, getReturnType(tree), state);
});
/**
* This matcher allows the following methods in {@code java.time} (and {@code org.threeten.bp}):
*
* <ul>
* <li>any methods named {@code parse}
* <li>any static method named {@code of}
* <li>any static method named {@code from}
* <li>any instance method starting with {@code append} on {@link
* java.time.format.DateTimeFormatterBuilder}
* <li>{@link java.time.temporal.ChronoField#checkValidIntValue}
* <li>{@link java.time.temporal.ChronoField#checkValidValue}
* <li>{@link java.time.temporal.ValueRange#checkValidValue}
* </ul>
*/
private static final Matcher<ExpressionTree> ALLOWED_JAVA_TIME_METHODS =
anyOf(
staticMethod().anyClass().named("parse"),
instanceMethod().anyClass().named("parse"),
staticMethod().anyClass().named("of"),
staticMethod().anyClass().named("from"),
staticMethod().onClassAny("java.time.ZoneId", "org.threeten.bp.ZoneId").named("ofOffset"),
instanceMethod()
.onExactClassAny(
"java.time.format.DateTimeFormatterBuilder",
"org.threeten.bp.format.DateTimeFormatterBuilder")
.withNameMatching(Pattern.compile("^(append|parse|pad|optional).*")),
instanceMethod()
.onExactClassAny(
"java.time.temporal.ChronoField", "org.threeten.bp.temporal.ChronoField")
.named("checkValidIntValue"),
instanceMethod()
.onExactClassAny(
"java.time.temporal.ChronoField", "org.threeten.bp.temporal.ChronoField")
.named("checkValidValue"),
instanceMethod()
.onExactClassAny(
"java.time.temporal.ValueRange", "org.threeten.bp.temporal.ValueRange")
.named("checkValidValue"));
/**
* {@link java.time} (and by extension {@code org.threeten.bp}) types are immutable. The only
* methods we allow ignoring the return value on are the {@code parse}-style APIs since folks
* often use it for validation.
*/
private static boolean javaTimeTypes(ExpressionTree tree, VisitorState state) {
// don't analyze the library or its tests as they do weird things
if (packageStartsWith("java.time").matches(tree, state)
|| packageStartsWith("org.threeten.bp").matches(tree, state)) {
return false;
}
Symbol symbol = getSymbol(tree);
if (symbol instanceof MethodSymbol) {
String qualifiedName = enclosingPackage(symbol.owner).getQualifiedName().toString();
return (qualifiedName.startsWith("java.time") || qualifiedName.startsWith("org.threeten.bp"))
&& symbol.getModifiers().contains(Modifier.PUBLIC)
&& !ALLOWED_JAVA_TIME_METHODS.matches(tree, state);
}
return false;
}
/**
* Methods in {@link java.util.function} are pure, and their return values should not be
* discarded.
*/
private static boolean functionalMethod(ExpressionTree tree, VisitorState state) {
Symbol symbol = getSymbol(tree);
return symbol instanceof MethodSymbol
&& enclosingPackage(symbol.owner).getQualifiedName().contentEquals("java.util.function");
}
/**
* The return value of stream methods should always be checked (except for forEach and
* forEachOrdered, which are void-returning and won't be checked by AbstractReturnValueIgnored).
*/
private static final Matcher<ExpressionTree> STREAM_METHODS =
instanceMethod().onDescendantOf("java.util.stream.BaseStream");
/**
* The return values of {@link java.util.Arrays} methods should always be checked (except for
* void-returning ones, which won't be checked by AbstractReturnValueIgnored).
*/
private static final Matcher<ExpressionTree> ARRAYS_METHODS =
staticMethod().onClass("java.util.Arrays");
/**
* The return values of {@link java.lang.String} methods should always be checked (except for
* void-returning ones, which won't be checked by AbstractReturnValueIgnored).
*/
private static final Matcher<ExpressionTree> STRING_METHODS =
anyMethod().onClass("java.lang.String");
private static final ImmutableSet<String> PRIMITIVE_TYPES =
ImmutableSet.of(
"java.lang.Boolean",
"java.lang.Byte",
"java.lang.Character",
"java.lang.Double",
"java.lang.Float",
"java.lang.Integer",
"java.lang.Long",
"java.lang.Short");
/** All methods on the primitive wrapper types. */
private static final Matcher<ExpressionTree> PRIMITIVE_NON_PARSING_METHODS =
anyMethod().onClass(isExactTypeAny(PRIMITIVE_TYPES));
/**
* Parsing-style methods on the primitive wrapper types (e.g., {@link
* java.lang.Integer#decode(String)}).
*/
// TODO(kak): Instead of special casing the parsing style methods, we could consider looking for a
// surrounding try/catch block (which folks use to validate input data).
private static final Matcher<ExpressionTree> PRIMITIVE_PARSING_METHODS =
anyOf(
staticMethod().onClass("java.lang.Character").namedAnyOf("toChars", "codePointCount"),
staticMethod().onClassAny(PRIMITIVE_TYPES).named("decode"),
staticMethod()
.onClassAny(PRIMITIVE_TYPES)
.withNameMatching(Pattern.compile("^parse[A-z]*")),
staticMethod()
.onClassAny(PRIMITIVE_TYPES)
.named("valueOf")
.withParameters("java.lang.String"),
staticMethod()
.onClassAny(PRIMITIVE_TYPES)
.named("valueOf")
.withParameters("java.lang.String", "int"));
// TODO(kak): we may want to change this to an opt-out list per class (e.g., check _all_ of the
// methods on `java.util.Collection`, except this set. That would be much more future-proof.
// However, we need to make sure we're only checking the APIs defined on the interface, and not
// all methods on the descendant type.
/** APIs to check on the {@link java.util.Collection} interface. */
private static final Matcher<ExpressionTree> COLLECTION_METHODS =
anyOf(
instanceMethod()
.onDescendantOf("java.util.Collection")
.named("contains")
.withParameters("java.lang.Object"),
instanceMethod()
.onDescendantOf("java.util.Collection")
.named("containsAll")
.withParameters("java.util.Collection"),
instanceMethod()
.onDescendantOf("java.util.Collection")
.named("isEmpty")
.withNoParameters(),
instanceMethod().onDescendantOf("java.util.Collection").named("size").withNoParameters(),
instanceMethod()
.onDescendantOf("java.util.Collection")
.named("stream")
.withNoParameters(),
instanceMethod()
.onDescendantOf("java.util.Collection")
.named("toArray")
.withNoParameters(),
instanceMethod()
.onDescendantOf("java.util.Collection")
.named("toArray")
.withParameters("java.util.function.IntFunction"));
/** APIs to check on the {@link java.util.Map} interface. */
// TODO(b/188207175): consider adding Map.get() and Map.getOrDefault()
private static final Matcher<ExpressionTree> MAP_METHODS =
anyOf(
instanceMethod()
.onDescendantOf("java.util.Map")
.namedAnyOf("containsKey", "containsValue")
.withParameters("java.lang.Object"),
instanceMethod()
.onDescendantOf("java.util.Map")
.namedAnyOf("isEmpty", "size", "entrySet", "keySet", "values"),
staticMethod().onClass("java.util.Map").namedAnyOf("of", "copyOf", "entry", "ofEntries"));
/** APIs to check on the {@link java.util.Map.Entry} interface. */
private static final Matcher<ExpressionTree> MAP_ENTRY_METHODS =
anyOf(
staticMethod().onClass("java.util.Map.Entry"),
instanceMethod().onDescendantOf("java.util.Map.Entry").namedAnyOf("getKey", "getValue"));
/** APIs to check on the {@link java.lang.Iterable} interface. */
private static final Matcher<ExpressionTree> ITERABLE_METHODS =
anyOf(
instanceMethod()
.onDescendantOf("java.lang.Iterable")
.named("iterator")
.withNoParameters(),
instanceMethod()
.onDescendantOf("java.lang.Iterable")
.named("spliterator")
.withNoParameters());
/** APIs to check on the {@link java.util.Iterator} interface. */
private static final Matcher<ExpressionTree> ITERATOR_METHODS =
instanceMethod().onDescendantOf("java.util.Iterator").named("hasNext").withNoParameters();
private static final Matcher<ExpressionTree> COLLECTOR_METHODS =
anyOf(
anyMethod().onClass("java.util.stream.Collector"),
anyMethod().onClass("java.util.stream.Collectors"));
/**
* The return values of primitive types (e.g., {@link java.lang.Integer}) should always be checked
* (except for parsing-type methods and void-returning methods, which won't be checked by
* AbstractReturnValueIgnored).
*/
private static final Matcher<ExpressionTree> PRIMITIVE_METHODS =
allOf(not(PRIMITIVE_PARSING_METHODS), PRIMITIVE_NON_PARSING_METHODS);
/**
* The return values of {@link java.util.Optional} methods should always be checked (except for
* void-returning ones, which won't be checked by AbstractReturnValueIgnored).
*/
private static final Matcher<ExpressionTree> OPTIONAL_METHODS =
anyMethod().onClass("java.util.Optional");
/**
* The return values of {@link java.util.concurrent.TimeUnit} methods should always be checked.
*/
private static final Matcher<ExpressionTree> TIME_UNIT_METHODS =
anyMethod().onClass("java.util.concurrent.TimeUnit");
/** APIs to check on {@code JodaTime} types. */
// TODO(kak): there's a ton more we could do here
private static final Matcher<ExpressionTree> JODA_TIME_METHODS =
anyOf(
instanceMethod()
.onDescendantOf("org.joda.time.ReadableInstant")
.named("getMillis")
.withNoParameters(),
instanceMethod()
.onDescendantOf("org.joda.time.ReadableDuration")
.named("getMillis")
.withNoParameters());
private static final String PROTO_MESSAGE = "com.google.protobuf.MessageLite";
/**
* The return values of {@code ProtoMessage.newBuilder()}, {@code protoBuilder.build()} and {@code
* protoBuilder.buildPartial()} should always be checked.
*/
private static final Matcher<ExpressionTree> PROTO_METHODS =
anyOf(
staticMethod().onDescendantOf(PROTO_MESSAGE).named("newBuilder"),
instanceMethod()
.onDescendantOf(PROTO_MESSAGE + ".Builder")
.namedAnyOf("build", "buildPartial"));
private static final Matcher<ExpressionTree> CLASS_METHODS =
allOf(
anyMethod().onClass("java.lang.Class"),
not(staticMethod().onClass("java.lang.Class").named("forName")),
not(instanceMethod().onExactClass("java.lang.Class").named("getMethod")));
private static final Matcher<ExpressionTree> OBJECT_METHODS =
anyOf(
instanceMethod()
.onDescendantOf("java.lang.Object")
.namedAnyOf("getClass", "hashCode", "clone", "toString")
.withNoParameters(),
instanceMethod()
.onDescendantOf("java.lang.Object")
.namedAnyOf("equals")
.withParameters("java.lang.Object"));
private static final Matcher<ExpressionTree> CHAR_SEQUENCE_METHODS =
anyMethod().onClass("java.lang.CharSequence");
private static final Matcher<ExpressionTree> ENUM_METHODS = anyMethod().onClass("java.lang.Enum");
private static final Matcher<ExpressionTree> THROWABLE_METHODS =
instanceMethod()
.onDescendantOf("java.lang.Throwable")
.namedAnyOf(
"getCause", "getLocalizedMessage", "getMessage", "getStackTrace", "getSuppressed");
private static final Matcher<ExpressionTree> OBJECTS_METHODS =
allOf(
staticMethod().onClass("java.util.Objects"),
not(
staticMethod()
.onClass("java.util.Objects")
.namedAnyOf(
"checkFromIndexSize",
"checkFromToIndex",
"checkIndex",
"requireNonNull",
"requireNonNullElse",
"requireNonNullElseGet")));
/**
* Constructors of Guice modules must always be used (likely a sign they were not properly
* installed).
*/
private static final Matcher<ExpressionTree> MODULE_CONSTRUCTORS =
constructor().forClass(isDescendantOf("com.google.inject.Module"));
private static final Matcher<? super ExpressionTree> SPECIALIZED_MATCHER =
anyOf(
// keep-sorted start
ARRAYS_METHODS,
CHAR_SEQUENCE_METHODS,
COLLECTION_METHODS,
COLLECTOR_METHODS,
ENUM_METHODS,
ITERABLE_METHODS,
ITERATOR_METHODS,
JODA_TIME_METHODS,
MAP_ENTRY_METHODS,
MAP_METHODS,
MODULE_CONSTRUCTORS,
OBJECTS_METHODS,
OBJECT_METHODS,
OPTIONAL_METHODS,
PRIMITIVE_METHODS,
PROTO_METHODS,
RETURNS_SAME_TYPE,
ReturnValueIgnored::functionalMethod,
ReturnValueIgnored::javaTimeTypes,
STREAM_METHODS,
STRING_METHODS,
THROWABLE_METHODS,
TIME_UNIT_METHODS
// keep-sorted end
);
private static final ImmutableBiMap<String, Matcher<ExpressionTree>> FLAG_MATCHERS =
ImmutableBiMap.of("ReturnValueIgnored:ClassMethods", CLASS_METHODS);
private final Matcher<ExpressionTree> matcher;
@Inject
ReturnValueIgnored(ErrorProneFlags flags, ConstantExpressions constantExpressions) {
super(constantExpressions);
this.matcher = createMatcher(flags);
}
private static Matcher<ExpressionTree> createMatcher(ErrorProneFlags flags) {
ImmutableSet.Builder<Matcher<? super ExpressionTree>> builder = ImmutableSet.builder();
builder.add(SPECIALIZED_MATCHER);
FLAG_MATCHERS.keySet().stream()
.filter(flagName -> flags.getBoolean(flagName).orElse(true))
.map(FLAG_MATCHERS::get)
.forEach(builder::add);
return anyOf(builder.build());
}
@Override
public Matcher<? super ExpressionTree> specializedMatcher() {
return matcher;
}
@Override
public ImmutableMap<String, ?> getMatchMetadata(ExpressionTree tree, VisitorState state) {
return FLAG_MATCHERS.values().stream()
.filter(matcher -> matcher.matches(tree, state))
.findFirst()
.map(FLAG_MATCHERS.inverse()::get)
.map(flag -> ImmutableMap.of("flag", flag))
.orElse(ImmutableMap.of());
}
@Override
protected String getMessage(Name name) {
return String.format("Return value of '%s' must be used", name);
}
}
| 19,403
| 41.834437
| 134
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JUnitParameterMethodNotFound.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.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Streams.stream;
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.isJUnit4TestRunnerOfType;
import static com.google.errorprone.matchers.JUnitMatchers.wouldRunInJUnit4;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.hasArgumentWithValue;
import static com.google.errorprone.util.ASTHelpers.getType;
import com.google.common.base.CaseFormat;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
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.google.errorprone.matchers.Matchers;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ClassType;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
/**
* Checks if the methods specified in {@code junitparams.Parameters} annotation to provide
* parameters exists.
*
* <p>This checks for the required method in the current class and all the base classes. In case the
* required method is present in a superclass, this check would generate a false positive.
*/
@BugPattern(summary = "The method for providing parameters was not found.", severity = ERROR)
public class JUnitParameterMethodNotFound extends BugChecker implements MethodTreeMatcher {
private static final Matcher<AnnotationTree> PARAMETERS_ANNOTATION_MATCHER =
Matchers.isSameType("junitparams.Parameters");
private static final MultiMatcher<ClassTree, AnnotationTree> PARAMETERIZED_TEST_RUNNER =
Matchers.annotations(
AT_LEAST_ONE,
hasArgumentWithValue(
/* argumentName= */ "value",
isJUnit4TestRunnerOfType(ImmutableSet.of("junitparams.JUnitParamsRunner"))));
private static final Matcher<MethodTree> ENCLOSING_CLASS_PARAMETERIZED_TEST_RUNNER_MATCHER =
Matchers.enclosingClass(PARAMETERIZED_TEST_RUNNER);
private static final Matcher<MethodTree> POSSIBLE_PARAMETERIZED_TEST_METHOD_MATCHER =
allOf(ENCLOSING_CLASS_PARAMETERIZED_TEST_RUNNER_MATCHER, wouldRunInJUnit4);
private static final String JUNIT_PARAMETER_METHOD_PREFIX = "parametersFor";
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!POSSIBLE_PARAMETERIZED_TEST_METHOD_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
Optional<? extends AnnotationTree> parametersAnnotation =
tree.getModifiers().getAnnotations().stream()
.filter(annotationTree -> PARAMETERS_ANNOTATION_MATCHER.matches(annotationTree, state))
.findFirst();
if (!parametersAnnotation.isPresent()) {
return Description.NO_MATCH;
}
ImmutableSet<String> methodsInSourceClass = ImmutableSet.of();
Set<String> requiredMethods = new TreeSet<>();
ImmutableList<? extends AssignmentTree> annotationsArguments =
parametersAnnotation.get().getArguments().stream()
.filter(expressionTree -> expressionTree.getKind() == Kind.ASSIGNMENT)
.map(expressionTree -> (AssignmentTree) expressionTree)
.collect(toImmutableList());
if (annotationsArguments.isEmpty()) {
requiredMethods.add(JUNIT_PARAMETER_METHOD_PREFIX + toPascalCase(tree.getName().toString()));
} else {
Optional<? extends AssignmentTree> paramMethodAssignmentTree =
getParamAssignmentTree(annotationsArguments, /* parameterName= */ "method");
if (paramMethodAssignmentTree.isPresent()) {
String paramMethods =
(String) ASTHelpers.constValue(paramMethodAssignmentTree.get().getExpression());
Splitter.on(',').trimResults().splitToStream(paramMethods).forEach(requiredMethods::add);
// If source argument is present in the annotation the method should be searched in the
// class specified by the argument.
methodsInSourceClass = getMethodIdentifiersInSourceAnnotation(annotationsArguments, state);
}
}
if (methodsInSourceClass.isEmpty()) {
methodsInSourceClass = getAllMethodIdentifiersForType(getClassType(tree), state);
}
Set<String> missingMethods = Sets.difference(requiredMethods, methodsInSourceClass);
if (missingMethods.isEmpty()) {
return Description.NO_MATCH;
}
return buildDescription(tree)
.setMessage(String.format("%s method(s) not found", String.join(",", missingMethods)))
.build();
}
private static Type getClassType(MethodTree tree) {
return ASTHelpers.enclosingClass(ASTHelpers.getSymbol(tree)).type;
}
private static ImmutableSet<String> getMethodIdentifiersInSourceAnnotation(
ImmutableList<? extends AssignmentTree> annotationsArguments, VisitorState state) {
Optional<? extends AssignmentTree> paramSourceAssignmentTree =
getParamAssignmentTree(annotationsArguments, /* parameterName= */ "source");
if (!paramSourceAssignmentTree.isPresent()) {
return ImmutableSet.of();
}
ClassType classType = (ClassType) getType(paramSourceAssignmentTree.get().getExpression());
Type typeArgument = classType.getTypeArguments().get(0);
return getAllMethodIdentifiersForType(typeArgument, state);
}
private static Optional<? extends AssignmentTree> getParamAssignmentTree(
ImmutableList<? extends AssignmentTree> annotationsArguments, String parameterName) {
return annotationsArguments.stream()
.filter(
assignmentTree ->
((IdentifierTree) assignmentTree.getVariable())
.getName()
.contentEquals(parameterName))
.findFirst();
}
private static ImmutableSet<String> getAllMethodIdentifiersForType(
Type type, VisitorState state) {
// As we require only the method identifier set for the given type, the value of skipInterface
// argument would not affect the final computed set.
return stream(state.getTypes().membersClosure(type, /* skipInterface= */ false).getSymbols())
.filter(MethodSymbol.class::isInstance)
.map(methodSymbol -> methodSymbol.getSimpleName().toString())
.collect(toImmutableSet());
}
private static String toPascalCase(String methodName) {
return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, methodName);
}
}
| 7,913
| 42.245902
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InstanceOfAndCastMatchWrongType.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.util.ASTHelpers.getStartPosition;
import com.google.common.base.Objects;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.TypeCastTreeMatcher;
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.ArrayAccessTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.InstanceOfTree;
import com.sun.source.tree.LiteralTree;
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.util.TreePath;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Types;
import javax.annotation.Nullable;
/**
* @author sulku@google.com (Marsela Sulku)
* @author mariasam@google.com (Maria Sam)
*/
@BugPattern(
summary = "Casting inside an if block should be plausibly consistent with the instanceof type",
severity = WARNING)
public class InstanceOfAndCastMatchWrongType extends BugChecker implements TypeCastTreeMatcher {
@Override
public Description matchTypeCast(TypeCastTree typeCastTree, VisitorState visitorState) {
CastingMatcher castingMatcher = new CastingMatcher();
if (!(typeCastTree.getExpression() instanceof IdentifierTree
|| typeCastTree.getExpression() instanceof ArrayAccessTree)) {
return Description.NO_MATCH;
}
if (castingMatcher.matches(typeCastTree, visitorState)) {
return describeMatch(
typeCastTree,
SuggestedFix.replace(
castingMatcher.nodeToReplace, visitorState.getSourceForNode(typeCastTree.getType())));
}
return Description.NO_MATCH;
}
/** Matches any Tree that casts to a type that is disjoint from the stored type. */
private static class CastingMatcher implements Matcher<Tree> {
Tree nodeToReplace;
/**
* This method matches a TypeCastTree, then iterates up to the nearest if tree with a condition
* that looks for an instanceof pattern that matches the expression acted upon. It then checks
* to see if the cast is plausible (if the classes are not disjoint)
*
* @param tree TypeCastTree that is matched
* @param state VisitorState
*/
@Override
public boolean matches(Tree tree, VisitorState state) {
// finds path from first enclosing node to the top level tree
TreePath pathToTop =
ASTHelpers.findPathFromEnclosingNodeToTopLevel(state.getPath(), IfTree.class);
while (pathToTop != null) {
IfTree ifTree = (IfTree) pathToTop.getLeaf();
ExpressionTree expressionTree = ASTHelpers.stripParentheses(ifTree.getCondition());
TreeScannerInstanceOfWrongType treeScannerInstanceOfWrongType =
new TreeScannerInstanceOfWrongType(state);
treeScannerInstanceOfWrongType.scan(expressionTree, ((TypeCastTree) tree).getExpression());
Tree treeInstance = treeScannerInstanceOfWrongType.getRelevantTree();
// check to make sure that the if tree encountered has a relevant instanceof statement
// in the condition
if (treeInstance == null) {
pathToTop = ASTHelpers.findPathFromEnclosingNodeToTopLevel(pathToTop, IfTree.class);
continue;
}
// if the specific TypeCastTree is in the else statement, then ignore
if (ifTree.getElseStatement() != null
&& Iterables.contains(state.getPath(), ifTree.getElseStatement())) {
return false;
}
Types types = state.getTypes();
InstanceOfTree instanceOfTree = (InstanceOfTree) treeInstance;
nodeToReplace = instanceOfTree.getType();
// Scan for earliest assignment expression in "then" block of if statement
treeScannerInstanceOfWrongType.scan(
ifTree.getThenStatement(), instanceOfTree.getExpression());
int pos = treeScannerInstanceOfWrongType.earliestStart;
if (pos < getStartPosition(tree)) {
return false;
}
boolean isCastable =
types.isCastable(
types.erasure(ASTHelpers.getType(instanceOfTree.getType())),
types.erasure(ASTHelpers.getType(tree)));
ExpressionTree typeCastExp = ((TypeCastTree) tree).getExpression();
boolean isSameExpression = expressionsEqual(typeCastExp, instanceOfTree.getExpression());
return isSameExpression && !isCastable;
}
return false;
}
}
static class TreeScannerInstanceOfWrongType extends TreeScanner<Void, ExpressionTree> {
// represents the earliest position of a relevant assignment
int earliestStart = Integer.MAX_VALUE;
private InstanceOfTree relevantTree;
private boolean notApplicable = false;
private final VisitorState state;
@Nullable
InstanceOfTree getRelevantTree() {
if (notApplicable) {
return null;
}
return relevantTree;
}
public TreeScannerInstanceOfWrongType(VisitorState currState) {
state = currState;
}
@Override
public Void visitBinary(BinaryTree binTree, ExpressionTree expr) {
if (binTree.getKind().equals(Kind.CONDITIONAL_OR)) {
notApplicable = true;
}
return super.visitBinary(binTree, expr);
}
@Override
public Void visitUnary(UnaryTree tree, ExpressionTree expr) {
if (tree.getKind().equals(Kind.LOGICAL_COMPLEMENT)) {
notApplicable = true;
}
return super.visitUnary(tree, expr);
}
@Override
public Void visitInstanceOf(InstanceOfTree tree, ExpressionTree expr) {
if (expressionsEqual(tree.getExpression(), expr)) {
relevantTree = tree;
}
return super.visitInstanceOf(tree, expr);
}
@Override
public Void visitAssignment(AssignmentTree tree, ExpressionTree expr) {
if (expressionsEqual(tree.getVariable(), expr)) {
earliestStart = Math.min(earliestStart, state.getEndPosition(tree));
}
return super.visitAssignment(tree, expr);
}
}
/**
* Determines whether two {@link ExpressionTree} instances are equal. Only handles the cases
* relevant to this checker: array accesses, identifiers, and literals. Returns false for all
* other cases.
*/
private static boolean expressionsEqual(ExpressionTree expr1, ExpressionTree expr2) {
if (!expr1.getKind().equals(expr2.getKind())) {
return false;
}
if (!expr1.getKind().equals(Kind.ARRAY_ACCESS)
&& !expr1.getKind().equals(Kind.IDENTIFIER)
&& !(expr1 instanceof LiteralTree)) {
return false;
}
if (expr1.getKind() == Kind.ARRAY_ACCESS) {
ArrayAccessTree arrayAccessTree1 = (ArrayAccessTree) expr1;
ArrayAccessTree arrayAccessTree2 = (ArrayAccessTree) expr2;
return expressionsEqual(arrayAccessTree1.getExpression(), arrayAccessTree2.getExpression())
&& expressionsEqual(arrayAccessTree1.getIndex(), arrayAccessTree2.getIndex());
}
if (expr1 instanceof LiteralTree) {
LiteralTree literalTree1 = (LiteralTree) expr1;
LiteralTree literalTree2 = (LiteralTree) expr2;
return literalTree1.getValue().equals(literalTree2.getValue());
}
return Objects.equal(ASTHelpers.getSymbol(expr1), ASTHelpers.getSymbol(expr2));
}
}
| 8,417
| 36.0837
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ASTHelpersSuggestions.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.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
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;
/** A BugPattern; see the summary */
@BugPattern(summary = "Prefer ASTHelpers instead of calling this API directly", severity = WARNING)
public class ASTHelpersSuggestions extends BugChecker implements MethodInvocationTreeMatcher {
private static final Supplier<Type> MODULE_SYMBOL =
Suppliers.typeFromString("com.sun.tools.javac.code.Symbol.ModuleSymbol");
private static final Matcher<ExpressionTree> SYMBOL =
anyOf(
instanceMethod()
.onDescendantOf("com.sun.tools.javac.code.Symbol")
.namedAnyOf("isDirectlyOrIndirectlyLocal", "isLocal", "packge"),
instanceMethod()
.onClass((t, s) -> isSubtype(MODULE_SYMBOL.get(s), t, s))
.namedAnyOf("isStatic"));
private static final Matcher<ExpressionTree> SCOPE =
instanceMethod().onDescendantOf("com.sun.tools.javac.code.Scope");
private static final ImmutableMap<String, String> NAMES =
ImmutableMap.of(
"packge", "enclosingPackage",
"isDirectlyOrIndirectlyLocal", "isLocal");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
ExpressionTree receiver = getReceiver(tree);
if (receiver == null) {
return NO_MATCH;
}
if (SYMBOL.matches(tree, state)) {
MethodSymbol sym = getSymbol(tree);
String name = sym.getSimpleName().toString();
name = NAMES.getOrDefault(name, name);
return describeMatch(
tree,
SuggestedFix.builder()
.addStaticImport("com.google.errorprone.util.ASTHelpers." + name)
.prefixWith(tree, name + "(")
.replace(state.getEndPosition(receiver), state.getEndPosition(tree), ")")
.build());
}
if (SCOPE.matches(tree, state)) {
MethodSymbol sym = getSymbol(tree);
Type filter = COM_SUN_TOOLS_JAVAC_UTIL_FILTER.get(state);
Type predicate = JAVA_UTIL_FUNCTION_PREDICATE.get(state);
if (sym.getParameters().stream()
.anyMatch(
p ->
isSameType(filter, p.asType(), state)
|| isSameType(predicate, p.asType(), state))) {
return describeMatch(
tree,
SuggestedFix.builder()
.addStaticImport("com.google.errorprone.util.ASTHelpers.scope")
.prefixWith(receiver, "scope(")
.postfixWith(receiver, ")")
.build());
}
}
return NO_MATCH;
}
private static final Supplier<Type> COM_SUN_TOOLS_JAVAC_UTIL_FILTER =
VisitorState.memoize(state -> state.getTypeFromString("com.sun.tools.javac.util.Filter"));
private static final Supplier<Type> JAVA_UTIL_FUNCTION_PREDICATE =
VisitorState.memoize(state -> state.getTypeFromString("java.util.function.Predicate"));
}
| 4,664
| 41.027027
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/OptionalEquality.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.ImmutableSet;
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.Type;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary = "Comparison using reference equality instead of value equality",
severity = ERROR)
public class OptionalEquality extends AbstractReferenceEquality {
private static final ImmutableSet<String> OPTIONAL_CLASSES =
ImmutableSet.of(com.google.common.base.Optional.class.getName(), "java.util.Optional");
@Override
protected boolean matchArgument(ExpressionTree tree, VisitorState state) {
Type type = ASTHelpers.getType(tree);
for (String className : OPTIONAL_CLASSES) {
if (ASTHelpers.isSameType(type, state.getTypeFromString(className), state)) {
return true;
}
}
return false;
}
}
| 1,733
| 35.125
| 93
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StaticMockMember.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.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.hasModifier;
import static javax.lang.model.element.Modifier.STATIC;
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.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import java.util.Optional;
import javax.lang.model.element.Modifier;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"@Mock members of test classes shouldn't share state between tests and preferably be"
+ " non-static",
severity = WARNING)
public final class StaticMockMember extends BugChecker implements VariableTreeMatcher {
private static final Matcher<Tree> STATIC_MOCK =
allOf(hasModifier(STATIC), hasAnnotation("org.mockito.Mock"));
@Override
public Description matchVariable(VariableTree varTree, VisitorState state) {
if (!STATIC_MOCK.matches(varTree, state)) {
return NO_MATCH;
}
Optional<SuggestedFix> optionalFix =
SuggestedFixes.removeModifiers(varTree, state, Modifier.STATIC);
if (!optionalFix.isPresent()) {
return NO_MATCH;
}
if (SuggestedFixes.compilesWithFix(optionalFix.get(), state)) {
return describeMatch(varTree, optionalFix.get());
} else {
return describeMatch(varTree);
}
}
}
| 2,552
| 37.104478
| 93
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/JUnit4SetUpNotRun.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.JUnitMatchers.JUNIT_AFTER_ANNOTATION;
import static com.google.errorprone.matchers.JUnitMatchers.JUNIT_AFTER_CLASS_ANNOTATION;
import static com.google.errorprone.matchers.JUnitMatchers.JUNIT_BEFORE_ANNOTATION;
import static com.google.errorprone.matchers.JUnitMatchers.JUNIT_BEFORE_CLASS_ANNOTATION;
import static com.google.errorprone.matchers.JUnitMatchers.hasJUnit4BeforeAnnotations;
import static com.google.errorprone.matchers.JUnitMatchers.looksLikeJUnit3SetUp;
import static com.google.errorprone.matchers.JUnitMatchers.looksLikeJUnit4Before;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.not;
import com.google.errorprone.BugPattern;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.MethodTree;
import java.util.Arrays;
import java.util.List;
/**
* Checks for the existence of a JUnit3 style setUp() method in a JUnit4 test class or methods
* annotated with a non-JUnit4 @Before annotation.
*
* @author glorioso@google.com (Nick Glorioso)
*/
@BugPattern(
summary = "setUp() method will not be run; please add JUnit's @Before annotation",
severity = ERROR)
public class JUnit4SetUpNotRun extends AbstractJUnit4InitMethodNotRun {
@Override
protected Matcher<MethodTree> methodMatcher() {
return allOf(
anyOf(looksLikeJUnit3SetUp, looksLikeJUnit4Before), not(hasJUnit4BeforeAnnotations));
}
@Override
protected String correctAnnotation() {
return JUNIT_BEFORE_ANNOTATION;
}
@Override
protected List<AnnotationReplacements> annotationReplacements() {
return Arrays.asList(
new AnnotationReplacements(JUNIT_AFTER_ANNOTATION, JUNIT_BEFORE_ANNOTATION),
new AnnotationReplacements(JUNIT_AFTER_CLASS_ANNOTATION, JUNIT_BEFORE_CLASS_ANNOTATION));
}
}
| 2,641
| 39.646154
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MissingDefault.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.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import com.google.common.collect.Iterables;
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.ASTHelpers;
import com.google.errorprone.util.Reachability;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.SwitchTree;
import com.sun.tools.javac.code.Type;
import java.util.List;
import java.util.Optional;
import javax.lang.model.element.ElementKind;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"The Google Java Style Guide requires that each switch statement includes a default"
+ " statement group, even if it contains no code. (This requirement is lifted for any"
+ " switch statement that covers all values of an enum.)",
severity = WARNING)
public class MissingDefault extends BugChecker implements SwitchTreeMatcher {
@Override
public Description matchSwitch(SwitchTree tree, VisitorState state) {
Type switchType = ASTHelpers.getType(tree.getExpression());
if (switchType.asElement().getKind() == ElementKind.ENUM) {
// enum switches can omit the default if they're exhaustive, which is enforced separately
// by MissingCasesInEnumSwitch
return NO_MATCH;
}
Optional<? extends CaseTree> maybeDefault =
tree.getCases().stream().filter(c -> c.getExpression() == null).findFirst();
if (!maybeDefault.isPresent()) {
Description.Builder description = buildDescription(tree);
if (!tree.getCases().isEmpty()) {
// Inserting the default after the last case is easier than finding the closing brace
// for the switch statement. Hopefully we don't often see switches with zero cases.
CaseTree lastCase = getLast(tree.getCases());
String replacement;
List<? extends StatementTree> statements = lastCase.getStatements();
if (statements == null
|| statements.isEmpty()
|| Reachability.canCompleteNormally(Iterables.getLast(statements))) {
replacement = "\nbreak;\ndefault: // fall out\n";
} else {
replacement = "\ndefault: // fall out\n";
}
description.addFix(SuggestedFix.postfixWith(getLast(tree.getCases()), replacement));
}
return description.build();
}
CaseTree defaultCase = maybeDefault.get();
List<? extends StatementTree> statements = defaultCase.getStatements();
if (statements != null && !statements.isEmpty()) {
return NO_MATCH;
}
// If `default` case is empty, and last in switch, add `// fall out` comment
// TODO(epmjohnston): Maybe move comment logic to https://errorprone.info/bugpattern/FallThrough
int idx = tree.getCases().indexOf(defaultCase);
if (idx != tree.getCases().size() - 1) {
return NO_MATCH;
}
if (state
.getOffsetTokens(state.getEndPosition(defaultCase), state.getEndPosition(tree))
.stream()
.anyMatch(t -> !t.comments().isEmpty())) {
return NO_MATCH;
}
return buildDescription(defaultCase)
.setMessage("Default case should be documented with a comment")
.addFix(SuggestedFix.postfixWith(defaultCase, " // fall out"))
.build();
}
}
| 4,323
| 42.676768
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ThrowsUncheckedException.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.getType;
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.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.Type;
import java.util.ArrayList;
import java.util.List;
/**
* Suggests to remove the unchecked throws clause.
*
* @author yulissa@google.com (Yulissa Arroyo-Paredes)
*/
@BugPattern(
summary = "Unchecked exceptions do not need to be declared in the method signature.",
severity = SUGGESTION)
public class ThrowsUncheckedException extends BugChecker implements MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (tree.getThrows().isEmpty()) {
return NO_MATCH;
}
List<ExpressionTree> uncheckedExceptions = new ArrayList<>();
for (ExpressionTree exception : tree.getThrows()) {
Type exceptionType = getType(exception);
if (isSubtype(exceptionType, state.getSymtab().runtimeExceptionType, state)
|| isSubtype(exceptionType, state.getSymtab().errorType, state)) {
uncheckedExceptions.add(exception);
}
}
if (uncheckedExceptions.isEmpty()) {
return NO_MATCH;
}
return describeMatch(
uncheckedExceptions.get(0),
SuggestedFixes.deleteExceptions(tree, state, uncheckedExceptions));
}
}
| 2,433
| 36.446154
| 89
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BanClassLoader.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.matchers.Matchers.anyMethod;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.constructor;
import static com.google.errorprone.matchers.Matchers.isExtensionOf;
import static com.google.errorprone.predicates.TypePredicates.allOf;
import static com.google.errorprone.predicates.TypePredicates.isDescendantOf;
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.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
/** A {@link BugChecker} that detects use of the unsafe JNDI API system. */
@BugPattern(
summary =
"Using dangerous ClassLoader APIs may deserialize untrusted user input into bytecode,"
+ " leading to remote code execution vulnerabilities",
severity = SeverityLevel.ERROR)
public final class BanClassLoader extends BugChecker
implements MethodInvocationTreeMatcher, NewClassTreeMatcher, ClassTreeMatcher {
private static final Matcher<ExpressionTree> METHOD_MATCHER =
anyOf(
anyMethod().onDescendantOf("java.lang.ClassLoader").named("defineClass"),
anyMethod().onDescendantOf("java.lang.invoke.MethodHandles.Lookup").named("defineClass"),
anyMethod()
.onDescendantOf("java.rmi.server.RMIClassLoader")
.namedAnyOf("loadClass", "loadProxyClass"),
anyMethod()
.onDescendantOf("java.rmi.server.RMIClassLoaderSpi")
.namedAnyOf("loadClass", "loadProxyClass"));
private static final Matcher<ExpressionTree> CONSTRUCTOR_MATCHER =
constructor().forClass(allOf(isDescendantOf("java.net.URLClassLoader")));
private static final Matcher<ClassTree> EXTEND_CLASS_MATCHER =
isExtensionOf("java.net.URLClassLoader");
private <T extends Tree> Description matchWith(T tree, VisitorState state, Matcher<T> matcher) {
if (state.errorProneOptions().isTestOnlyTarget() || !matcher.matches(tree, state)) {
return Description.NO_MATCH;
}
Description.Builder description = buildDescription(tree);
return description.build();
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return matchWith(tree, state, METHOD_MATCHER);
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
return matchWith(tree, state, CONSTRUCTOR_MATCHER);
}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
return matchWith(tree, state, EXTEND_CLASS_MATCHER);
}
}
| 3,770
| 40.43956
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DeadException.java
|
/*
* Copyright 2011 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.enclosingClass;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.kindIs;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.Matchers.parentNode;
import static com.google.errorprone.suppliers.Suppliers.THROWABLE_TYPE;
import static com.sun.source.tree.Tree.Kind.EXPRESSION_STATEMENT;
import static com.sun.source.tree.Tree.Kind.IF;
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.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.sun.source.tree.BlockTree;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
/**
* @author alexeagle@google.com (Alex Eagle)
*/
@BugPattern(
altNames = "ThrowableInstanceNeverThrown",
summary = "Exception created but not thrown",
severity = ERROR)
public class DeadException extends BugChecker implements NewClassTreeMatcher {
public static final Matcher<Tree> MATCHER =
allOf(
parentNode(kindIs(EXPRESSION_STATEMENT)),
isSubtypeOf(THROWABLE_TYPE),
not(
anyOf(
enclosingClass(JUnitMatchers.isJUnit3TestClass),
enclosingClass(JUnitMatchers.isAmbiguousJUnitVersion),
enclosingClass(JUnitMatchers.isJUnit4TestClass))));
@Override
public Description matchNewClass(NewClassTree newClassTree, VisitorState state) {
if (!MATCHER.matches(newClassTree, state)) {
return Description.NO_MATCH;
}
StatementTree parent = (StatementTree) state.getPath().getParentPath().getLeaf();
boolean isLastStatement =
anyOf(
new ChildOfBlockOrCase<>(
ChildMultiMatcher.MatchType.LAST, Matchers.<StatementTree>isSame(parent)),
// it could also be a bare if statement with no braces
parentNode(parentNode(kindIs(IF))))
.matches(newClassTree, state);
Fix fix;
if (isLastStatement) {
fix = SuggestedFix.prefixWith(newClassTree, "throw ");
} else {
fix = SuggestedFix.delete(parent);
}
return describeMatch(newClassTree, fix);
}
private static class ChildOfBlockOrCase<T extends Tree>
extends ChildMultiMatcher<T, StatementTree> {
public ChildOfBlockOrCase(MatchType matchType, Matcher<StatementTree> nodeMatcher) {
super(matchType, nodeMatcher);
}
@Override
protected Iterable<? extends StatementTree> getChildNodes(T tree, VisitorState state) {
Tree enclosing = state.findEnclosing(CaseTree.class, BlockTree.class);
if (enclosing == null) {
return ImmutableList.of();
}
if (enclosing instanceof BlockTree) {
return ((BlockTree) enclosing).getStatements();
} else if (enclosing instanceof CaseTree) {
return ((CaseTree) enclosing).getStatements();
} else {
// findEnclosing given two types must return something of one of those types
throw new IllegalStateException("enclosing tree not a BlockTree or CaseTree");
}
}
}
}
| 4,572
| 38.08547
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BadAnnotationImplementation.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.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.kindIs;
import static com.google.errorprone.suppliers.Suppliers.ANNOTATION_TYPE;
import static com.sun.source.tree.Tree.Kind.CLASS;
import static com.sun.source.tree.Tree.Kind.ENUM;
import com.google.common.base.Verify;
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.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.util.Name;
import java.lang.annotation.Annotation;
import java.util.function.Predicate;
import javax.annotation.Nullable;
/**
* Checker that ensures implementations of {@link Annotation} override equals and hashCode.
* Otherwise, the implementation inherits equals and hashCode from {@link Object}, and those do not
* meet the contract specified by the {@link Annotation} interface.
*/
@BugPattern(
summary =
"Classes that implement Annotation must override equals and hashCode. Consider "
+ "using AutoAnnotation instead of implementing Annotation by hand.",
severity = ERROR)
public class BadAnnotationImplementation extends BugChecker implements ClassTreeMatcher {
private static final Matcher<ClassTree> CLASS_TREE_MATCHER =
allOf(anyOf(kindIs(CLASS), kindIs(ENUM)), isSubtypeOf(ANNOTATION_TYPE));
@Override
public Description matchClass(ClassTree classTree, VisitorState state) {
if (!CLASS_TREE_MATCHER.matches(classTree, state)) {
return Description.NO_MATCH;
}
// If this is an enum that is trying to implement Annotation, give a special error message.
if (classTree.getKind() == Kind.ENUM) {
return buildDescription(classTree)
.setMessage(
"Enums cannot correctly implement Annotation because their equals and hashCode "
+ "methods are final. Consider using AutoAnnotation instead of implementing "
+ "Annotation by hand.")
.build();
}
// Otherwise walk up type hierarchy looking for equals and hashcode methods
MethodSymbol equals = null;
MethodSymbol hashCode = null;
Types types = state.getTypes();
Name equalsName = EQUALS.get(state);
Predicate<MethodSymbol> equalsPredicate =
methodSymbol ->
!methodSymbol.isStatic()
&& ((methodSymbol.flags() & Flags.SYNTHETIC) == 0)
&& ((methodSymbol.flags() & Flags.ABSTRACT) == 0)
&& methodSymbol.getParameters().size() == 1
&& types.isSameType(
methodSymbol.getParameters().get(0).type, state.getSymtab().objectType);
Name hashCodeName = HASHCODE.get(state);
Predicate<MethodSymbol> hashCodePredicate =
methodSymbol ->
!methodSymbol.isStatic()
&& ((methodSymbol.flags() & Flags.SYNTHETIC) == 0)
&& ((methodSymbol.flags() & Flags.ABSTRACT) == 0)
&& methodSymbol.getParameters().isEmpty();
for (Type sup : types.closure(ASTHelpers.getSymbol(classTree).type)) {
if (equals == null) {
equals = getMatchingMethod(sup, equalsName, equalsPredicate);
}
if (hashCode == null) {
hashCode = getMatchingMethod(sup, hashCodeName, hashCodePredicate);
}
}
Verify.verifyNotNull(equals);
Verify.verifyNotNull(hashCode);
Symbol objectSymbol = state.getSymtab().objectType.tsym;
if (equals.owner.equals(objectSymbol) || hashCode.owner.equals(objectSymbol)) {
return describeMatch(classTree);
}
return Description.NO_MATCH;
}
@Nullable
private static MethodSymbol getMatchingMethod(
Type type, Name name, Predicate<MethodSymbol> predicate) {
Scope scope = type.tsym.members();
for (Symbol sym : scope.getSymbolsByName(name)) {
if (!(sym instanceof MethodSymbol)) {
continue;
}
MethodSymbol methodSymbol = (MethodSymbol) sym;
if (predicate.test(methodSymbol)) {
return methodSymbol;
}
}
return null;
}
private static final Supplier<Name> EQUALS =
VisitorState.memoize(state -> state.getName("equals"));
private static final Supplier<Name> HASHCODE =
VisitorState.memoize(state -> state.getName("hashCode"));
}
| 5,655
| 38.830986
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ForEachIterable.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
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.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.getUpperBound;
import static com.google.errorprone.util.ASTHelpers.stripParentheses;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.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.BlockTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.tree.WhileLoopTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTag;
import java.util.List;
import javax.annotation.Nullable;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "This loop can be replaced with an enhanced for loop.", severity = SUGGESTION)
public class ForEachIterable extends BugChecker implements VariableTreeMatcher {
private static final Matcher<ExpressionTree> HAS_NEXT =
instanceMethod().onDescendantOf("java.util.Iterator").named("hasNext");
private static final Matcher<ExpressionTree> NEXT =
instanceMethod().onDescendantOf("java.util.Iterator").named("next");
private static final Matcher<ExpressionTree> ITERATOR =
instanceMethod().onDescendantOf("java.lang.Iterable").named("iterator").withNoParameters();
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
if (!ASTHelpers.isSameType(getType(tree.getType()), state.getSymtab().iteratorType, state)) {
return NO_MATCH;
}
Tree parent = state.getPath().getParentPath().getLeaf();
if (parent instanceof BlockTree) {
return matchWhile(tree, (BlockTree) parent, state);
}
if (parent instanceof ForLoopTree) {
return matchFor(tree, (ForLoopTree) parent, state);
}
return NO_MATCH;
}
/**
* Match for loops that can be rewritten to enhanced-for, e.g.:
*
* <pre>{@code
* for (Iterator<T> iterator = list.iterator(); iterator.hasNext(); ) {
* doSomething(iterator.next());
* }
* }</pre>
*/
private Description matchFor(VariableTree tree, ForLoopTree forTree, VisitorState state) {
List<? extends StatementTree> initializer = forTree.getInitializer();
if (initializer.size() != 1 || !getOnlyElement(initializer).equals(tree)) {
return NO_MATCH;
}
if (!forTree.getUpdate().isEmpty()) {
return NO_MATCH;
}
return match(
tree, state, getStartPosition(forTree), forTree.getCondition(), forTree.getStatement());
}
private Description matchWhile(VariableTree tree, BlockTree blockTree, VisitorState state) {
List<? extends StatementTree> statements = blockTree.getStatements();
int nextIdx = statements.indexOf(tree) + 1;
if (nextIdx >= statements.size()) {
return NO_MATCH;
}
StatementTree next = statements.get(nextIdx);
if (!(next instanceof WhileLoopTree)) {
return NO_MATCH;
}
VarSymbol iterator = getSymbol(tree);
for (int i = nextIdx + 1; i < statements.size(); i++) {
if (!findUses(state, statements.get(i), iterator).isEmpty()) {
return NO_MATCH;
}
}
WhileLoopTree whileLoop = (WhileLoopTree) next;
return match(
tree, state, getStartPosition(tree), whileLoop.getCondition(), whileLoop.getStatement());
}
private Description match(
VariableTree tree,
VisitorState state,
int startPosition,
ExpressionTree condition,
StatementTree body) {
if (tree.getInitializer() == null || !ITERATOR.matches(tree.getInitializer(), state)) {
return NO_MATCH;
}
VarSymbol iterator = getSymbol(tree);
if (!isHasNext(iterator, stripParentheses(condition), state)) {
return NO_MATCH;
}
ImmutableList<TreePath> uses = findUses(state, body, iterator);
if (uses.size() != 1 || !uses.stream().allMatch(p -> isNext(tree, state, p))) {
return NO_MATCH;
}
Type iteratorType =
state.getTypes().asSuper(getType(tree.getType()), state.getSymtab().iteratorType.tsym);
if (iteratorType == null || iteratorType.getTypeArguments().isEmpty()) {
return NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
VariableTree existingVariable = existingVariable(iterator, body, state);
String replacement;
if (existingVariable != null) {
replacement = existingVariable.getName().toString();
fix.delete(existingVariable);
} else {
replacement = "element";
uses.forEach(
p -> {
TreePath path = p.getParentPath().getParentPath();
switch (path.getParentPath().getLeaf().getKind()) {
case EXPRESSION_STATEMENT:
fix.delete(path.getParentPath().getLeaf());
break;
default:
fix.replace(path.getLeaf(), replacement);
break;
}
});
}
Type elementType = getOnlyElement(iteratorType.getTypeArguments());
if (elementType.hasTag(TypeTag.WILDCARD)) {
elementType = getUpperBound(elementType, state.getTypes());
}
Tree iterableExprNode = getReceiver(tree.getInitializer());
String iterableExpr =
iterableExprNode != null ? state.getSourceForNode(iterableExprNode) : "this";
fix.replace(
startPosition,
getStartPosition(body),
String.format(
"for (%s %s : %s) ",
SuggestedFixes.prettyType(state, fix, elementType), replacement, iterableExpr));
return describeMatch(tree, fix.build());
}
private ImmutableList<TreePath> findUses(
VisitorState state, StatementTree body, VarSymbol iterator) {
ImmutableList.Builder<TreePath> uses = ImmutableList.builder();
new TreePathScanner<Void, Void>() {
@Override
public Void visitIdentifier(IdentifierTree identifierTree, Void unused) {
if (iterator.equals(getSymbol(identifierTree))) {
uses.add(getCurrentPath());
}
return super.visitIdentifier(identifierTree, null);
}
}.scan(state.withPath(new TreePath(state.getPath().getParentPath(), body)).getPath(), null);
return uses.build();
}
@Nullable
private static VariableTree existingVariable(
VarSymbol varSymbol, StatementTree body, VisitorState state) {
if (!(body instanceof BlockTree)) {
return null;
}
List<? extends StatementTree> statements = ((BlockTree) body).getStatements();
if (statements.isEmpty()) {
return null;
}
StatementTree first = statements.iterator().next();
if (!(first instanceof VariableTree)) {
return null;
}
VariableTree variableTree = (VariableTree) first;
if (variableTree.getInitializer() == null) {
return null;
}
if (!NEXT.matches(variableTree.getInitializer(), state)) {
return null;
}
if (!varSymbol.equals(ASTHelpers.getSymbol(getReceiver(variableTree.getInitializer())))) {
return null;
}
return variableTree;
}
private static boolean isNext(VariableTree tree, VisitorState state, TreePath p) {
Tree parentTree = p.getParentPath().getLeaf();
if (!(parentTree instanceof ExpressionTree)) {
return false;
}
ExpressionTree parent = (ExpressionTree) parentTree;
return NEXT.matches(parent, state) && getSymbol(tree).equals(getSymbol(getReceiver(parent)));
}
private static boolean isHasNext(
VarSymbol iterator, ExpressionTree condition, VisitorState state) {
return HAS_NEXT.matches(condition, state) && iterator.equals(getSymbol(getReceiver(condition)));
}
}
| 9,323
| 37.85
| 100
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.