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/TypeParameterUnusedInFormals.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 com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.TypeVar; import com.sun.tools.javac.code.Types; import java.util.HashSet; import java.util.Set; @BugPattern( summary = "Declaring a type parameter that is only used in the return type is a misuse of" + " generics: operations on the type parameter are unchecked, it hides unsafe casts at" + " invocations of the method, and it interacts badly with method overload resolution.", severity = WARNING, tags = StandardTags.FRAGILE_CODE) public class TypeParameterUnusedInFormals extends BugChecker implements MethodTreeMatcher { @Override public Description matchMethod(MethodTree tree, VisitorState state) { MethodSymbol methodSymbol = ASTHelpers.getSymbol(tree); // Only match methods where the return type is just a type parameter. // e.g. the following is OK: <T> List<T> newArrayList(); TypeVar retType; switch (methodSymbol.getReturnType().getKind()) { case TYPEVAR: retType = (TypeVar) methodSymbol.getReturnType(); break; default: return Description.NO_MATCH; } if (!methodSymbol.equals(retType.tsym.owner)) { return Description.NO_MATCH; } // Ignore f-bounds. // e.g.: <T extends Enum<T>> T unsafeEnumDeserializer(); if (retType.getUpperBound() != null && TypeParameterFinder.visit(retType.getUpperBound()).contains(retType.tsym)) { return Description.NO_MATCH; } // Ignore cases where the type parameter is used in the declaration of a formal parameter. // e.g.: <T> T noop(T t); for (VarSymbol formalParam : methodSymbol.getParameters()) { if (TypeParameterFinder.visit(formalParam.type).contains(retType.tsym)) { return Description.NO_MATCH; } } return describeMatch(tree); } /** * A visitor that records the set of {@link com.sun.tools.javac.code.Type.TypeVar}s referenced by * the current type. */ private static class TypeParameterFinder extends Types.DefaultTypeVisitor<Void, Void> { static Set<Symbol.TypeSymbol> visit(Type type) { TypeParameterFinder visitor = new TypeParameterFinder(); type.accept(visitor, null); return visitor.seen; } private final Set<Symbol.TypeSymbol> seen = new HashSet<>(); @Override public Void visitClassType(Type.ClassType type, Void unused) { if (type instanceof Type.IntersectionClassType) { // TypeVisitor doesn't support intersection types natively visitIntersectionClassType((Type.IntersectionClassType) type); } else { for (Type t : type.getTypeArguments()) { t.accept(this, null); } } return null; } public void visitIntersectionClassType(Type.IntersectionClassType type) { for (Type component : type.getComponents()) { component.accept(this, null); } } @Override public Void visitWildcardType(Type.WildcardType type, Void unused) { if (type.getSuperBound() != null) { type.getSuperBound().accept(this, null); } if (type.getExtendsBound() != null) { type.getExtendsBound().accept(this, null); } return null; } @Override public Void visitArrayType(Type.ArrayType type, Void unused) { type.elemtype.accept(this, null); return null; } @Override public Void visitTypeVar(Type.TypeVar type, Void unused) { // only visit f-bounds once: if (!seen.add(type.tsym)) { return null; } if (type.getUpperBound() != null) { type.getUpperBound().accept(this, null); } return null; } @Override public Void visitType(Type type, Void unused) { return null; } } }
5,004
32.145695
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ThrowIfUncheckedKnownChecked.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.fixes.SuggestedFix.delete; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.argument; import static com.google.errorprone.matchers.Matchers.argumentCount; 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; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.UnionType; /** Catches no-op calls to {@code Throwables.throwIfUnchecked}. */ @BugPattern(summary = "throwIfUnchecked(knownCheckedException) is a no-op.", severity = ERROR) public class ThrowIfUncheckedKnownChecked extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<MethodInvocationTree> IS_THROW_IF_UNCHECKED = allOf( anyOf( staticMethod().onClass("com.google.common.base.Throwables").named("throwIfUnchecked"), staticMethod() .onClass("com.google.common.base.Throwables") .named("propagateIfPossible")), argumentCount(1)); private static final Matcher<ExpressionTree> IS_KNOWN_CHECKED_EXCEPTION = new Matcher<ExpressionTree>() { @Override public boolean matches(ExpressionTree tree, VisitorState state) { Type type = ASTHelpers.getType(tree); if (type.isUnion()) { for (TypeMirror alternative : ((UnionType) type).getAlternatives()) { if (!isKnownCheckedException(state, (Type) alternative)) { return false; } } return true; } else { return isKnownCheckedException(state, type); } } boolean isKnownCheckedException(VisitorState state, Type type) { Types types = state.getTypes(); Symtab symtab = state.getSymtab(); // Check erasure for generics. type = types.erasure(type); return // Has to be some Exception: A variable of type Throwable might be an Error. types.isSubtype(type, symtab.exceptionType) // Has to be some subtype: A variable of type Exception might be a RuntimeException. && !types.isSameType(type, symtab.exceptionType) // Can't be of type RuntimeException. && !types.isSubtype(type, symtab.runtimeExceptionType); } }; @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (IS_THROW_IF_UNCHECKED.matches(tree, state) && argument(0, IS_KNOWN_CHECKED_EXCEPTION).matches(tree, state)) { return describeMatch(tree, delete(state.getPath().getParentPath().getLeaf())); } return NO_MATCH; } }
4,106
42.231579
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ErroneousBitwiseExpression.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.Tree.Kind; import java.util.Objects; /** A BugPattern; see the summary. */ @BugPattern( summary = "This expression evaluates to 0. If this isn't an error, consider expressing it as a" + " literal 0.", severity = WARNING) public final class ErroneousBitwiseExpression extends BugChecker implements BinaryTreeMatcher { @Override public Description matchBinary(BinaryTree tree, VisitorState state) { if (tree.getKind() != Kind.AND) { return NO_MATCH; } Object constantValue = ASTHelpers.constValue(tree); // Constants of the form A & B which evaluate to a literal 0 are probably trying to combine // bitwise flags using |. return Objects.equals(constantValue, 0) || Objects.equals(constantValue, 0L) ? describeMatch( tree, SuggestedFix.replace( /* startPos= */ state.getEndPosition(tree.getLeftOperand()), /* endPos= */ getStartPosition(tree.getRightOperand()), " | ")) : NO_MATCH; } }
2,263
38.719298
95
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ReturnsNullCollection.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.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import static com.google.errorprone.matchers.Matchers.methodReturns; import static com.google.errorprone.util.ASTHelpers.getSymbol; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.dataflow.nullnesspropagation.TrustingNullnessAnalysis; import com.google.errorprone.fixes.Fix; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ReturnTree; import java.util.Optional; /** * Flags methods with collection return types which return {@code null} in some cases but don't * annotate the method as @Nullable. * * @author bhagwani@google.com (Sumit Bhagwani) */ @BugPattern( summary = "Method has a collection return type and returns {@code null} in some cases but does not" + " annotate the method as @Nullable. See Effective Java 3rd Edition Item 54.", severity = SUGGESTION) public class ReturnsNullCollection extends AbstractMethodReturnsNull { private static boolean methodWithoutNullable(MethodTree tree, VisitorState state) { return !TrustingNullnessAnalysis.hasNullableAnnotation(getSymbol(tree)); } private static final Matcher<MethodTree> METHOD_RETURNS_COLLECTION_WITHOUT_NULLABLE_ANNOTATION = allOf( anyOf( methodReturns(isSubtypeOf("java.util.Collection")), methodReturns(isSubtypeOf("java.util.Map")), methodReturns(isSubtypeOf("com.google.common.collect.Multimap"))), ReturnsNullCollection::methodWithoutNullable); public ReturnsNullCollection() { super(METHOD_RETURNS_COLLECTION_WITHOUT_NULLABLE_ANNOTATION); } @Override protected Optional<Fix> provideFix(ReturnTree tree) { return Optional.empty(); } }
2,687
37.956522
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryStaticImport.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ImportTreeMatcher; import com.google.errorprone.bugpatterns.StaticImports.StaticImportInfo; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.tree.ImportTree; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Using static imports for types is unnecessary", severity = SUGGESTION, documentSuppression = false, tags = StandardTags.STYLE) public class UnnecessaryStaticImport extends BugChecker implements ImportTreeMatcher { @Override public Description matchImport(ImportTree tree, VisitorState state) { StaticImportInfo importInfo = StaticImports.tryCreate(tree, state); if (importInfo == null || !importInfo.members().isEmpty()) { return Description.NO_MATCH; } return describeMatch(tree, SuggestedFix.replace(tree, importInfo.importStatement())); } }
1,853
38.446809
90
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LockNotBeforeTry.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.FRAGILE_CODE; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getStartPosition; 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.sun.source.tree.BlockTree; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TryTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreeScanner; import org.checkerframework.checker.nullness.qual.Nullable; /** * Suggests that calls to {@code Lock.lock} must be immediately followed by a {@code try-finally} * that calls {@code Lock.unlock}. * * @author ghm@google.com (Graeme Morgan) */ @BugPattern( summary = "Calls to Lock#lock should be immediately followed by a try block which releases the lock.", severity = WARNING, tags = FRAGILE_CODE) public final class LockNotBeforeTry extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> LOCK = instanceMethod().onDescendantOf("java.util.concurrent.locks.Lock").named("lock"); private static final Matcher<ExpressionTree> UNLOCK = instanceMethod().onDescendantOf("java.util.concurrent.locks.Lock").named("unlock"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!LOCK.matches(tree, state)) { return NO_MATCH; } Tree parent = state.getPath().getParentPath().getLeaf(); if (!(parent instanceof StatementTree)) { return NO_MATCH; } Tree enclosing = state.getPath().getParentPath().getParentPath().getLeaf(); if (!(enclosing instanceof BlockTree)) { return NO_MATCH; } BlockTree block = (BlockTree) enclosing; int index = block.getStatements().indexOf(parent); if (index + 1 < block.getStatements().size()) { StatementTree nextStatement = block.getStatements().get(index + 1); if (nextStatement instanceof TryTree) { return NO_MATCH; } } return describe(tree, state.getPath().getParentPath(), state); } private Description describe( MethodInvocationTree lockInvocation, TreePath statementPath, VisitorState state) { Tree lockStatement = statementPath.getLeaf(); ExpressionTree lockee = getReceiver(lockInvocation); if (lockee == null) { return NO_MATCH; } TryTree enclosingTry = state.findEnclosing(TryTree.class); if (enclosingTry != null && releases(enclosingTry, lockee, state)) { Description.Builder description = buildDescription(lockInvocation); if (enclosingTry.getBlock().getStatements().indexOf(lockStatement) == 0) { description.addFix( SuggestedFix.builder() .replace(lockStatement, "") .prefixWith(enclosingTry, state.getSourceForNode(lockStatement)) .build()); } return description .setMessage( String.format( "Prefer obtaining the lock for %s outside the try block. That way, if #lock" + " throws, the lock is not erroneously released.", state.getSourceForNode(getReceiver(lockInvocation)))) .build(); } Tree enclosing = state.getPath().getParentPath().getParentPath().getLeaf(); if (!(enclosing instanceof BlockTree)) { return NO_MATCH; } BlockTree block = (BlockTree) enclosing; int index = block.getStatements().indexOf(lockStatement); // Scan through the enclosing statements for (StatementTree statement : Iterables.skip(block.getStatements(), index + 1)) { // ... for a try/finally which releases this lock. if (statement instanceof TryTree && releases((TryTree) statement, lockee, state)) { int start = getStartPosition(statement); int end = getStartPosition(((TryTree) statement).getBlock().getStatements().get(0)); SuggestedFix fix = SuggestedFix.builder() .replace(start, end, "") .postfixWith( lockStatement, state.getSourceCode().subSequence(start, end).toString()) .build(); return buildDescription(lockInvocation) .addFix(fix) .setMessage( "Prefer locking *immediately* before the try block which releases the lock to" + " avoid the possibility of any intermediate statements throwing.") .build(); } // ... or an unlock at the same level. if (statement instanceof ExpressionStatementTree) { ExpressionTree expression = ((ExpressionStatementTree) statement).getExpression(); if (acquires(expression, lockee, state)) { return buildDescription(lockInvocation) .setMessage( String.format( "Did you forget to release the lock on %s?", state.getSourceForNode(getReceiver(lockInvocation)))) .build(); } if (releases(expression, lockee, state)) { SuggestedFix fix = SuggestedFix.builder() .postfixWith(lockStatement, "try {") .prefixWith(statement, "} finally {") .postfixWith(statement, "}") .build(); return buildDescription(lockInvocation) .addFix(fix) .setMessage( String.format( "Prefer releasing the lock on %s inside a finally block.", state.getSourceForNode(getReceiver(lockInvocation)))) .build(); } } } return NO_MATCH; } private static boolean releases(TryTree tryTree, ExpressionTree lockee, VisitorState state) { if (tryTree.getFinallyBlock() == null) { return false; } // False if a different lock was released, true if 'lockee' was released, null otherwise. Boolean released = new TreeScanner<Boolean, Void>() { @Override public @Nullable Boolean reduce(Boolean r1, Boolean r2) { return r1 == null ? r2 : (r2 == null ? null : r1 && r2); } @Override public Boolean visitMethodInvocation(MethodInvocationTree node, Void unused) { if (UNLOCK.matches(node, state)) { return releases(node, lockee, state); } return super.visitMethodInvocation(node, null); } }.scan(tryTree.getFinallyBlock(), null); return released == null ? false : released; } private static boolean releases(ExpressionTree node, ExpressionTree lockee, VisitorState state) { if (!UNLOCK.matches(node, state)) { return false; } ExpressionTree receiver = getReceiver(node); return receiver != null && UNLOCK.matches(node, state) && state.getSourceForNode(receiver).equals(state.getSourceForNode(lockee)); } private static boolean acquires(ExpressionTree node, ExpressionTree lockee, VisitorState state) { if (!LOCK.matches(node, state)) { return false; } ExpressionTree receiver = getReceiver(node); return receiver != null && LOCK.matches(node, state) && state.getSourceForNode(receiver).equals(state.getSourceForNode(lockee)); } }
8,685
40.361905
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TruthGetOrDefault.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.WARNING; 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.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.Objects; /** * Flags ambiguous usages of {@code Map#getOrDefault} within {@code Truth#assertThat}. * * @author bhagwani@google.com (Sumit Bhagwani) */ @BugPattern( summary = "Asserting on getOrDefault is unclear; prefer containsEntry or doesNotContainKey", severity = WARNING) public final class TruthGetOrDefault extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> ASSERT_THAT = staticMethod().onClass("com.google.common.truth.Truth").named("assertThat"); private static final Matcher<ExpressionTree> GET_OR_DEFAULT_MATCHER = instanceMethod().onDescendantOf("java.util.Map").named("getOrDefault"); private static final Matcher<ExpressionTree> SUBJECT_EQUALS_MATCHER = instanceMethod() .onDescendantOf("com.google.common.truth.Subject") .named("isEqualTo") .withParameters("java.lang.Object"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!SUBJECT_EQUALS_MATCHER.matches(tree, state)) { return Description.NO_MATCH; } ExpressionTree rec = ASTHelpers.getReceiver(tree); if (rec == null) { return Description.NO_MATCH; } if (!ASSERT_THAT.matches(rec, state)) { return Description.NO_MATCH; } ExpressionTree arg = getOnlyElement(((MethodInvocationTree) rec).getArguments()); if (!GET_OR_DEFAULT_MATCHER.matches(arg, state)) { return Description.NO_MATCH; } MethodInvocationTree argMethodInvocationTree = (MethodInvocationTree) arg; ExpressionTree defaultVal = argMethodInvocationTree.getArguments().get(1); ExpressionTree expectedVal = getOnlyElement(tree.getArguments()); Match match = areValuesSame(defaultVal, expectedVal, state); switch (match) { case UNKNOWN: return Description.NO_MATCH; case DIFFERENT: return describeMatch( tree, SuggestedFix.builder() .replace( argMethodInvocationTree, state.getSourceForNode(ASTHelpers.getReceiver(argMethodInvocationTree))) .replace( state.getEndPosition(rec), state.getEndPosition(tree.getMethodSelect()), ".containsEntry") .replace( tree.getArguments().get(0), state.getSourceForNode(argMethodInvocationTree.getArguments().get(0)) + ", " + state.getSourceForNode(tree.getArguments().get(0))) .build()); case SAME: return describeMatch( tree, SuggestedFix.builder() .replace(arg, state.getSourceForNode(ASTHelpers.getReceiver(arg))) .replace( state.getEndPosition(rec), state.getEndPosition(tree.getMethodSelect()), ".doesNotContainKey") .replace( tree.getArguments().get(0), state.getSourceForNode(argMethodInvocationTree.getArguments().get(0))) .build()); } return Description.NO_MATCH; } private enum Match { SAME, DIFFERENT, UNKNOWN; } /** * Returns {@code Match.SAME} or {@code Match.DIFFERENT} when it can confidently say that both * expressions are same or different, otherwise returns {@code Match.UNKNOWN}. */ private static Match areValuesSame( ExpressionTree defaultVal, ExpressionTree expectedVal, VisitorState state) { if (ASTHelpers.sameVariable(defaultVal, expectedVal)) { return Match.SAME; } Object expectedConstVal = ASTHelpers.constValue(expectedVal); Object defaultConstVal = ASTHelpers.constValue(defaultVal); if (expectedConstVal == null || defaultConstVal == null) { return Match.UNKNOWN; } if (Objects.equals(defaultConstVal, expectedConstVal)) { return Match.SAME; } if (!state .getTypes() .isSameType(ASTHelpers.getType(expectedVal), ASTHelpers.getType(defaultVal))) { return Match.UNKNOWN; } return Match.DIFFERENT; } }
5,621
37.772414
96
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DeduplicateConstants.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.util.ASTHelpers.isConsideredFinal; 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.google.errorprone.util.ASTHelpers; import com.sun.source.tree.BlockTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.LiteralTree; 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.VarSymbol; import com.sun.tools.javac.util.Name; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * A checker that suggests deduplicating literals with existing constant variables. * * @author cushon@google.com (Liam Miller-Cushon) */ @BugPattern( summary = "This expression was previously declared as a constant;" + " consider replacing this occurrence.", severity = ERROR) public class DeduplicateConstants extends BugChecker implements CompilationUnitTreeMatcher { /** A lexical scope for constant declarations. */ static class Scope { /** A map from string literals to constant declarations. */ private final HashMap<String, VarSymbol> values = new HashMap<>(); /** Declarations that are hidden in the current scope. */ private final Set<Name> hidden = new HashSet<>(); /** The parent of the current scope. */ private final Scope parent; Scope(Scope parent) { this.parent = parent; } /** Enters a new sub-scope. */ Scope enter() { return new Scope(this); } /** Returns an in-scope constant variable with the given value. */ @Nullable public VarSymbol get(String value) { VarSymbol sym = getInternal(value); if (sym == null) { return null; } if (hidden.contains(sym.getSimpleName())) { return null; } return sym; } @Nullable private VarSymbol getInternal(String value) { VarSymbol sym = values.get(value); if (sym != null) { return sym; } if (parent != null) { sym = parent.get(value); if (sym != null) { return sym; } } return null; } /** Adds a constant declaration with the given value to the current scope. */ public void put(String value, VarSymbol sym) { hidden.remove(sym.getSimpleName()); values.put(value, sym); } /** * Records a non-constant variable declaration that hides any previously declared constants of * the same name. */ public void remove(VarSymbol sym) { hidden.add(sym.getSimpleName()); } } @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { Table<VarSymbol, Tree, SuggestedFix> fixes = HashBasedTable.create(); new TreeScanner<Void, Scope>() { @Override public Void visitBlock(BlockTree tree, Scope scope) { // enter a new block scope (includes block trees for method and class bodies) return super.visitBlock(tree, scope.enter()); } @Override public Void visitVariable(VariableTree tree, Scope scope) { // record that this variables hides previous declarations before entering its initializer scope.remove(ASTHelpers.getSymbol(tree)); scan(tree.getInitializer(), scope); saveConstValue(tree, scope); return null; } @Override public Void visitLiteral(LiteralTree tree, Scope scope) { replaceLiteral(tree, scope, state); return super.visitLiteral(tree, scope); } private void replaceLiteral(LiteralTree tree, Scope scope, VisitorState state) { Object value = ASTHelpers.constValue(tree); if (value == null) { return; } VarSymbol sym = scope.get(state.getSourceForNode(tree)); if (sym == null) { return; } SuggestedFix fix = SuggestedFix.replace(tree, sym.getSimpleName().toString()); fixes.put(sym, tree, fix); } private void saveConstValue(VariableTree tree, Scope scope) { VarSymbol sym = ASTHelpers.getSymbol(tree); if (!isConsideredFinal(sym)) { return; } // heuristic: long string constants are generally more interesting than short ones, or // than non-string constants (e.g. `""`, `0`, or `false`). String constValue = ASTHelpers.constValue(tree.getInitializer(), String.class); if (constValue == null || constValue.length() <= 1) { return; } scope.put(state.getSourceForNode(tree.getInitializer()), sym); } }.scan(tree, new Scope(null)); for (Map.Entry<VarSymbol, Map<Tree, SuggestedFix>> entries : fixes.rowMap().entrySet()) { Map<Tree, SuggestedFix> occurrences = entries.getValue(); if (occurrences.size() < 2) { // heuristic: only de-duplicate when there are two or more occurrences continue; } // report the finding on each occurrence, but provide a fix for all related occurrences, // so it works better on changed-lines only SuggestedFix fix = mergeFix(occurrences.values()); occurrences.keySet().forEach(t -> state.reportMatch(describeMatch(t, fix))); } return Description.NO_MATCH; } private static SuggestedFix mergeFix(Collection<SuggestedFix> fixes) { SuggestedFix.Builder fix = SuggestedFix.builder(); fixes.forEach(fix::merge); return fix.build(); } }
6,589
32.969072
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TryFailThrowable.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterables.getLast; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.bugpatterns.TryFailThrowable.CaughtType.JAVA_LANG_ERROR; import static com.google.errorprone.bugpatterns.TryFailThrowable.CaughtType.JAVA_LANG_THROWABLE; import static com.google.errorprone.bugpatterns.TryFailThrowable.CaughtType.SOME_ASSERTION_FAILURE; import static com.google.errorprone.bugpatterns.TryFailThrowable.MatchResult.doesNotMatch; import static com.google.errorprone.bugpatterns.TryFailThrowable.MatchResult.matches; import static com.google.errorprone.fixes.SuggestedFix.replace; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isStatic; import static com.sun.source.tree.Tree.Kind.BLOCK; import static com.sun.source.tree.Tree.Kind.EMPTY_STATEMENT; import static com.sun.source.tree.Tree.Kind.METHOD; import static com.sun.source.tree.Tree.Kind.METHOD_INVOCATION; import static java.lang.String.format; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.TryTreeMatcher; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.BlockTree; import com.sun.source.tree.CatchTree; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TryTree; 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.code.Types; import java.util.List; /** * A bug checker for the following code pattern: * * <pre> * try { * // do something * Assert.fail(); // or any Assert.assert* * // maybe do something more * } catch (Throwable t) { * // empty or only comments * } * </pre> * * * Matches all static methods named "fail" and starting with "assert" from the following classes: * * <ul> * <li>{@code org.junit.Assert}, * <li>{@code junit.framework.Assert}, * <li>{@code junit.framework.TestCase} - which overrides the methods from Assert in order to * deprecate them and * <li>every class whose name ends with "MoreAsserts". * </ul> * * Possible improvements/generalizations of this matcher: * * <ul> * <li>support multiple catch() blocks * </ul> * * @author adamwos@google.com (Adam Wos) */ @BugPattern( summary = "Catching Throwable/Error masks failures from fail() or assert*() in the try block", severity = ERROR) public class TryFailThrowable extends BugChecker implements TryTreeMatcher { private static final Matcher<VariableTree> javaLangThrowable = isSameType("java.lang.Throwable"); private static final Matcher<VariableTree> javaLangError = isSameType("java.lang.Error"); private static final Matcher<VariableTree> someAssertionFailure = anyOf( isSameType("java.lang.AssertionError"), isSameType("junit.framework.AssertionFailedError")); private static final Matcher<ExpressionTree> failOrAssert = new Matcher<ExpressionTree>() { @Override public boolean matches(ExpressionTree item, VisitorState state) { if (item.getKind() != METHOD_INVOCATION) { return false; } Symbol sym = getSymbol(item); if (!(sym instanceof MethodSymbol)) { throw new IllegalArgumentException("not a method call"); } if (!isStatic(sym)) { return false; } String methodName = sym.getQualifiedName().toString(); String className = sym.owner.getQualifiedName().toString(); // TODO(cpovirk): Look for literal "throw new AssertionError()," etc. return (methodName.startsWith("assert") || methodName.startsWith("fail")) && (className.equals("org.junit.Assert") || className.equals("junit.framework.Assert") || className.equals("junit.framework.TestCase") || className.endsWith("MoreAsserts")); } }; @Override public Description matchTry(TryTree tree, VisitorState state) { MatchResult matchResult = tryTreeMatches(tree, state); if (!matchResult.matched()) { return NO_MATCH; } Description.Builder builder = buildDescription(tree.getCatches().get(0).getParameter()); if (matchResult.caughtType == JAVA_LANG_THROWABLE) { builder.addFix(fixByCatchingException(tree)); } if (matchResult.caughtType == SOME_ASSERTION_FAILURE) { builder.addFix(fixByThrowingJavaLangError(matchResult.failStatement, state)); } builder.addFix(fixWithReturnOrBoolean(tree, matchResult.failStatement, state)); return builder.build(); } private static Fix fixByCatchingException(TryTree tryTree) { VariableTree catchParameter = getOnlyCatch(tryTree).getParameter(); return replace(catchParameter, "Exception " + catchParameter.getName()); } private static Fix fixByThrowingJavaLangError(StatementTree failStatement, VisitorState state) { String messageSnippet = getMessageSnippet(failStatement, state, HasOtherParameters.FALSE); return replace(failStatement, format("throw new Error(%s);", messageSnippet)); } private static Fix fixWithReturnOrBoolean( TryTree tryTree, StatementTree failStatement, VisitorState state) { Tree parent = state.getPath().getParentPath().getLeaf(); Tree grandparent = state.getPath().getParentPath().getParentPath().getLeaf(); if (parent.getKind() == BLOCK && grandparent.getKind() == METHOD && tryTree == getLastStatement((BlockTree) parent)) { return fixWithReturn(tryTree, failStatement, state); } else { return fixWithBoolean(tryTree, failStatement, state); } } private static Fix fixWithReturn( TryTree tryTree, StatementTree failStatement, VisitorState state) { SuggestedFix.Builder builder = SuggestedFix.builder(); builder.delete(failStatement); builder.replace(getOnlyCatch(tryTree).getBlock(), "{ return; }"); // TODO(cpovirk): Use the file's preferred assertion API. String messageSnippet = getMessageSnippet(failStatement, state, HasOtherParameters.FALSE); builder.postfixWith(tryTree, format("fail(%s);", messageSnippet)); return builder.build(); } private static Fix fixWithBoolean( TryTree tryTree, StatementTree failStatement, VisitorState state) { SuggestedFix.Builder builder = SuggestedFix.builder(); builder.delete(failStatement); builder.prefixWith(tryTree, "boolean threw = false;"); builder.replace(getOnlyCatch(tryTree).getBlock(), "{ threw = true; }"); // TODO(cpovirk): Use the file's preferred assertion API. String messageSnippet = getMessageSnippet(failStatement, state, HasOtherParameters.TRUE); builder.postfixWith(tryTree, format("assertTrue(%sthrew);", messageSnippet)); return builder.build(); } private static String getMessageSnippet( StatementTree failStatement, VisitorState state, HasOtherParameters hasOtherParameters) { ExpressionTree expression = ((ExpressionStatementTree) failStatement).getExpression(); MethodSymbol sym = (MethodSymbol) getSymbol(expression); String tail = hasOtherParameters == HasOtherParameters.TRUE ? ", " : ""; // The above casts were checked earlier by failOrAssert. return hasInitialStringParameter(sym, state) ? state.getSourceForNode(((MethodInvocationTree) expression).getArguments().get(0)) + tail : ""; } /** * Whether the assertion method we're inserting a call to has extra parameters besides its message * (like {@code assertTrue}) or not (like {@code fail}). */ enum HasOtherParameters { TRUE, FALSE; } private static boolean hasInitialStringParameter(MethodSymbol sym, VisitorState state) { Types types = state.getTypes(); List<VarSymbol> parameters = sym.getParameters(); return !parameters.isEmpty() && types.isSameType(parameters.get(0).type, state.getSymtab().stringType); } private static MatchResult tryTreeMatches(TryTree tryTree, VisitorState state) { BlockTree tryBlock = tryTree.getBlock(); List<? extends StatementTree> statements = tryBlock.getStatements(); if (statements.isEmpty()) { return doesNotMatch(); } // Check if any of the statements is a fail or assert* method (i.e. any // method that can throw an AssertionFailedError) StatementTree failStatement = null; for (StatementTree statement : statements) { if (!(statement instanceof ExpressionStatementTree)) { continue; } if (failOrAssert.matches(((ExpressionStatementTree) statement).getExpression(), state)) { failStatement = statement; break; } } if (failStatement == null) { return doesNotMatch(); } // Verify that the only catch clause catches Throwable List<? extends CatchTree> catches = tryTree.getCatches(); if (catches.size() != 1) { // TODO(adamwos): this could be supported - only the last catch would need // to be checked - it would either be Throwable or Error. return doesNotMatch(); } CatchTree catchTree = catches.get(0); VariableTree catchType = catchTree.getParameter(); boolean catchesThrowable = javaLangThrowable.matches(catchType, state); boolean catchesError = javaLangError.matches(catchType, state); boolean catchesOtherError = someAssertionFailure.matches(catchType, state); if (!catchesThrowable && !catchesError && !catchesOtherError) { return doesNotMatch(); } // Verify that the catch block is empty or contains only comments. List<? extends StatementTree> catchStatements = catchTree.getBlock().getStatements(); for (StatementTree catchStatement : catchStatements) { // Comments are not a part of the AST. Therefore, we should either get // an empty list of statements (regardless of the number of comments), // or a list of empty statements. if (!Matchers.<Tree>kindIs(EMPTY_STATEMENT).matches(catchStatement, state)) { return doesNotMatch(); } } return matches( failStatement, catchesThrowable ? JAVA_LANG_THROWABLE : catchesError ? JAVA_LANG_ERROR : SOME_ASSERTION_FAILURE); } static final class MatchResult { static final MatchResult DOES_NOT_MATCH = new MatchResult(null, null); static MatchResult matches(StatementTree failStatement, CaughtType caughtType) { return new MatchResult(checkNotNull(failStatement), checkNotNull(caughtType)); } static MatchResult doesNotMatch() { return DOES_NOT_MATCH; } final StatementTree failStatement; final CaughtType caughtType; MatchResult(StatementTree failStatement, CaughtType caughtType) { this.failStatement = failStatement; this.caughtType = caughtType; } boolean matched() { return caughtType != null; } } enum CaughtType { JAVA_LANG_ERROR, JAVA_LANG_THROWABLE, SOME_ASSERTION_FAILURE, ; } private static StatementTree getLastStatement(BlockTree blockTree) { return getLast(blockTree.getStatements()); } private static CatchTree getOnlyCatch(TryTree tryTree) { return tryTree.getCatches().get(0); } }
12,671
38.849057
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DoNotClaimAnnotations.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.VisitorState.memoize; import static com.google.errorprone.matchers.Description.NO_MATCH; import com.google.common.collect.ImmutableList; 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.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ReturnTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Stream; import javax.lang.model.element.Name; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Don't 'claim' annotations in annotation processors; Processor#process should" + " unconditionally return `false`", severity = WARNING) public class DoNotClaimAnnotations extends BugChecker implements MethodTreeMatcher { private static final Supplier<Name> PROCESS_NAME = memoize(s -> s.getName("process")); private static final Supplier<ImmutableList<Type>> PARAMETER_TYPES = memoize( s -> Stream.of("java.util.Set", "javax.annotation.processing.RoundEnvironment") .map(s::getTypeFromString) .filter(x -> x != null) .collect(toImmutableList())); private static final Supplier<Symbol> PROCESSOR_SYMBOL = memoize(s -> s.getSymbolFromString("javax.annotation.processing.Processor")); @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (!tree.getName().equals(PROCESS_NAME.get(state))) { return NO_MATCH; } MethodSymbol sym = ASTHelpers.getSymbol(tree); if (!ASTHelpers.isSameType(sym.getReturnType(), state.getSymtab().booleanType, state)) { return NO_MATCH; } if (sym.getParameters().size() != 2) { return NO_MATCH; } if (!Streams.zip( sym.getParameters().stream(), PARAMETER_TYPES.get(state).stream(), (p, t) -> ASTHelpers.isSameType(p.asType(), t, state)) .allMatch(x -> x)) { return NO_MATCH; } if (!sym.owner.enclClass().isSubClass(PROCESSOR_SYMBOL.get(state), state.getTypes())) { return NO_MATCH; } List<ReturnTree> returns = new ArrayList<>(); new TreeScanner<Void, Void>() { @Override public Void visitLambdaExpression(LambdaExpressionTree node, Void aVoid) { return null; } @Override public Void visitClass(ClassTree node, Void aVoid) { return null; } @Override public Void visitReturn(ReturnTree node, Void unused) { if (!Objects.equals(ASTHelpers.constValue(node.getExpression(), Boolean.class), false)) { returns.add(node); } return super.visitReturn(node, null); } }.scan(tree.getBody(), null); if (returns.isEmpty()) { return NO_MATCH; } SuggestedFix.Builder fix = SuggestedFix.builder(); for (ReturnTree returnTree : returns) { if (Objects.equals(ASTHelpers.constValue(returnTree.getExpression(), Boolean.class), true)) { fix.replace(returnTree.getExpression(), "false"); } } return describeMatch(returns.get(0), fix.build()); } }
4,555
36.344262
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AssertionFailureIgnored.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.collect.Iterables.getLast; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.BugPattern.StandardTags.LIKELY_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.staticMethod; import static com.google.errorprone.util.ASTHelpers.isSubtype; import com.google.common.collect.Iterables; import com.google.common.collect.Streams; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.method.MethodMatchers; import com.google.errorprone.predicates.TypePredicates; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.ThrowTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.UnionClassType; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCCatch; import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; import com.sun.tools.javac.tree.JCTree.JCTry; import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.annotation.Nullable; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "This assertion throws an AssertionError if it fails, which will be caught by an enclosing" + " try block.", // TODO(cushon): promote this to an error and turn down TryFailThrowable severity = WARNING, tags = LIKELY_ERROR) public class AssertionFailureIgnored extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> ASSERTION = staticMethod() .onClassAny("org.junit.Assert", "junit.framework.Assert", "junit.framework.TestCase") .withNameMatching(Pattern.compile("fail|assert.*")); private static final Matcher<ExpressionTree> NEW_THROWABLE = MethodMatchers.constructor().forClass(TypePredicates.isDescendantOf("java.lang.Throwable")); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!ASSERTION.matches(tree, state)) { return NO_MATCH; } JCTry tryStatement = enclosingTry(state); if (tryStatement == null) { return NO_MATCH; } Optional<JCCatch> maybeCatchTree = catchesType(tryStatement, state.getSymtab().assertionErrorType, state); if (!maybeCatchTree.isPresent()) { return NO_MATCH; } JCCatch catchTree = maybeCatchTree.get(); VarSymbol parameter = ASTHelpers.getSymbol(catchTree.getParameter()); boolean rethrows = firstNonNull( new TreeScanner<Boolean, Void>() { @Override public Boolean visitThrow(ThrowTree tree, Void unused) { if (Objects.equals(parameter, ASTHelpers.getSymbol(tree.getExpression()))) { return true; } if (NEW_THROWABLE.matches(tree.getExpression(), state) && ((NewClassTree) tree.getExpression()) .getArguments().stream() .anyMatch( arg -> Objects.equals(parameter, ASTHelpers.getSymbol(arg)))) { return true; } return super.visitThrow(tree, null); } @Override public Boolean reduce(Boolean a, Boolean b) { return firstNonNull(a, false) || firstNonNull(b, false); } }.scan(catchTree.getBlock(), null), false); if (rethrows) { return NO_MATCH; } Description.Builder description = buildDescription(tree); buildFix(tryStatement, tree, state).ifPresent(description::addFix); return description.build(); } // Provide a fix for one of the classic blunders: // rewrite `try { ..., fail(); } catch (AssertionError e) { ... }` // to `AssertionError e = assertThrows(AssertionError.class, () -> ...); ...`. private static Optional<Fix> buildFix( JCTry tryStatement, MethodInvocationTree tree, VisitorState state) { if (!ASTHelpers.getSymbol(tree).getSimpleName().contentEquals("fail")) { // ignore non-failure asserts return Optional.empty(); } JCBlock block = tryStatement.getBlock(); if (!expressionStatement((t, s) -> t.equals(tree)) .matches(getLast(block.getStatements()), state)) { // the `fail()` should be the last expression statement in the try block return Optional.empty(); } if (tryStatement.getCatches().size() != 1) { // the fix is less clear for multiple catch clauses return Optional.empty(); } JCCatch catchTree = Iterables.getOnlyElement(tryStatement.getCatches()); if (catchTree.getParameter().getType().getKind() == Kind.UNION_TYPE) { // variables can't have union types return Optional.empty(); } SuggestedFix.Builder fix = SuggestedFix.builder(); boolean expression = block.getStatements().size() == 2 && block.getStatements().get(0).getKind() == Kind.EXPRESSION_STATEMENT; int startPosition; int endPosition; if (expression) { JCExpressionStatement expressionTree = (JCExpressionStatement) block.getStatements().get(0); startPosition = expressionTree.getStartPosition(); endPosition = state.getEndPosition(expressionTree.getExpression()); } else { startPosition = block.getStartPosition(); endPosition = getLast(tryStatement.getBlock().getStatements()).getStartPosition(); } if (catchTree.getBlock().getStatements().isEmpty()) { fix.addStaticImport("org.junit.Assert.assertThrows"); fix.replace( tryStatement.getStartPosition(), startPosition, String.format( "assertThrows(%s.class, () -> ", state.getSourceForNode(catchTree.getParameter().getType()))) .replace(endPosition, state.getEndPosition(catchTree), (expression ? "" : "}") + ");\n"); } else { fix.addStaticImport("org.junit.Assert.assertThrows") .prefixWith(tryStatement, state.getSourceForNode(catchTree.getParameter())) .replace( tryStatement.getStartPosition(), startPosition, String.format( " = assertThrows(%s.class, () -> ", state.getSourceForNode(catchTree.getParameter().getType()))) .replace( /* startPos= */ endPosition, /* endPos= */ catchTree.getBlock().getStatements().get(0).getStartPosition(), (expression ? "" : "}") + ");\n") .replace( state.getEndPosition(getLast(catchTree.getBlock().getStatements())), state.getEndPosition(catchTree), ""); } return Optional.of(fix.build()); } private static Optional<JCCatch> catchesType( JCTry tryStatement, Type assertionErrorType, VisitorState state) { return tryStatement.getCatches().stream() .filter( catchTree -> { Type type = ASTHelpers.getType(catchTree.getParameter()); return (type.isUnion() ? Streams.stream(((UnionClassType) type).getAlternativeTypes()) : Stream.of(type)) .anyMatch(caught -> isSubtype(assertionErrorType, caught, state)); }) .findFirst(); } @Nullable private static JCTry enclosingTry(VisitorState state) { Tree prev = null; for (Tree parent : state.getPath()) { switch (parent.getKind()) { case METHOD: case LAMBDA_EXPRESSION: return null; case TRY: JCTry tryStatement = (JCTry) parent; return tryStatement.getBlock().equals(prev) ? tryStatement : null; default: // fall out } prev = parent; } return null; } }
9,406
40.623894
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnsafeFinalization.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import com.google.common.collect.ImmutableList; import com.google.common.collect.Streams; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.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.MethodTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Flags.Flag; 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.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.util.Name; import java.util.EnumSet; import java.util.Optional; import java.util.stream.Stream; import javax.lang.model.element.ElementKind; import javax.lang.model.type.TypeKind; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "Finalizer may run before native code finishes execution", severity = WARNING) public class UnsafeFinalization 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) { MethodSymbol sym = ASTHelpers.getSymbol(tree); // Match invocations of static native methods. if (!sym.isStatic() || !ASTHelpers.asFlagSet(sym.flags()).contains(Flag.NATIVE)) { return NO_MATCH; } // Find the enclosing method declaration where the invocation occurs. MethodTree method = ASTHelpers.findEnclosingMethod(state); if (method == null) { return NO_MATCH; } // Don't check native methods called from static methods and constructors: // static methods don't have an instance to finalize, and we shouldn't need to worry about // finalization during construction. MethodSymbol enclosing = ASTHelpers.getSymbol(method); if (enclosing.isStatic() || enclosing.isConstructor()) { return NO_MATCH; } // Check if any arguments of the static native method are members (e.g. fields) of the enclosing // class. We're only looking for cases where the static native uses state of the enclosing class // that may become invalid after finalization. ImmutableList<Symbol> arguments = tree.getArguments().stream() .map(ASTHelpers::getSymbol) .filter(x -> x != null) .collect(toImmutableList()); if (arguments.stream() .filter( x -> EnumSet.of(TypeKind.INT, TypeKind.LONG) .contains(state.getTypes().unboxedTypeOrType(x.asType()).getKind())) .noneMatch(arg -> arg.isMemberOf(enclosing.enclClass(), state.getTypes()))) { // no instance state is passed to the native method return NO_MATCH; } if (arguments.stream() .anyMatch( arg -> arg.getSimpleName().contentEquals("this") && arg.isMemberOf(enclosing.enclClass(), state.getTypes()))) { // the instance is passed to the native method return NO_MATCH; } Symbol finalizeSym = getFinalizer(state, enclosing.enclClass()); if (finalizeSym == null || finalizeSym.equals(enclosing)) { // Don't check native methods called from within the implementation of finalize. return NO_MATCH; } if (finalizeSym.enclClass().equals(state.getSymtab().objectType.asElement())) { // Inheriting finalize from Object doesn't count. return NO_MATCH; } boolean[] sawFence = {false}; new TreeScanner<Void, Void>() { @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { if (FENCE_MATCHER.matches(tree, state)) { sawFence[0] = true; } return null; } }.scan(state.getPath().getCompilationUnit(), null); if (sawFence[0]) { // Ignore methods that contain a use of reachabilityFence. return NO_MATCH; } return describeMatch(tree); } private static Symbol getFinalizer(VisitorState state, ClassSymbol enclosing) { Type finalizerType = COM_GOOGLE_COMMON_LABS_BASE_FINALIZER.get(state); Optional<VarSymbol> finalizerField = state.getTypes().closure(enclosing.asType()).stream() .flatMap(s -> getFields(s.asElement())) .filter(s -> ASTHelpers.isSameType(finalizerType, s.asType(), state)) .findFirst(); if (finalizerField.isPresent()) { return finalizerField.get(); } return ASTHelpers.resolveExistingMethod( state, enclosing.enclClass(), FINALIZE.get(state), /* argTypes= */ ImmutableList.of(), /* tyargTypes= */ ImmutableList.of()); } private static Stream<VarSymbol> getFields(TypeSymbol s) { return Streams.stream( ASTHelpers.scope(s.members()).getSymbols(m -> m.getKind() == ElementKind.FIELD)) .map(VarSymbol.class::cast); } private static final Supplier<Name> FINALIZE = VisitorState.memoize(state -> state.getName("finalize")); private static final Supplier<Type> COM_GOOGLE_COMMON_LABS_BASE_FINALIZER = VisitorState.memoize( state -> state.getTypeFromString("com.google.common.labs.base.Finalizer")); }
6,682
41.031447
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DoNotUseRuleChain.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.Streams.stream; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.anyMethod; import static java.util.stream.Collectors.joining; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.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.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import java.util.List; import java.util.Optional; import javax.lang.model.element.ElementKind; /** * Identifies {@code RuleChain} class fields and proposes refactoring to ordered {@code @Rule(order * = n)}. */ @BugPattern( tags = {StandardTags.REFACTORING}, summary = "Prefer using `@Rule` with an explicit order over declaring a `RuleChain`. " + "RuleChain was the only way to declare ordered rules before JUnit 4.13. Newer " + "versions should use the cleaner individual `@Rule(order = n)` option.", severity = WARNING) public class DoNotUseRuleChain extends BugChecker implements VariableTreeMatcher { private static final String TEST_RULE_VAR_PREFIX = "testRule"; private static final String JUNIT_RULE_CHAIN_IMPORT_PATH = "org.junit.rules.RuleChain"; private static final String JUNIT_CLASS_RULE_IMPORT_PATH = "org.junit.ClassRule"; private static final String JUNIT_RULE_IMPORT_PATH = "org.junit.Rule"; private static final Matcher<ExpressionTree> RULE_CHAIN_METHOD_MATCHER = anyMethod().onDescendantOf(JUNIT_RULE_CHAIN_IMPORT_PATH).namedAnyOf("around", "outerRule"); @Override public Description matchVariable(VariableTree tree, VisitorState state) { VarSymbol symbol = ASTHelpers.getSymbol(tree); if (symbol.getKind() != ElementKind.FIELD || !isRuleChainExpression(tree, state) || !isClassWithSingleRule(state) || isChainedRuleChain(tree, state)) { return Description.NO_MATCH; } return describeMatch(tree, refactor(tree, state)); } private static boolean isRuleChainExpression(VariableTree tree, VisitorState state) { ExpressionTree expression = tree.getInitializer(); if (expression == null) { return false; } return RULE_CHAIN_METHOD_MATCHER.matches(expression, state); } /** * This refactoring only matches classes that feature a single occurrence of a {@code @Rule}. This * is done to avoid breaking some edge cases where more than one RuleChain might be declared or a * mixture of {@code @Rule} and {@code @RuleChain}. */ private static boolean isClassWithSingleRule(VisitorState state) { Optional<ClassTree> classTree = getClassTree(state); if (classTree.isEmpty()) { return false; } return classTree.get().getMembers().stream() .filter(tree -> ASTHelpers.hasAnnotation(tree, JUNIT_RULE_IMPORT_PATH, state)) .count() == 1; } private static Optional<ClassTree> getClassTree(VisitorState state) { return stream(state.getPath().iterator()) .filter(parent -> parent.getKind() == Kind.CLASS) .map(ClassTree.class::cast) .findFirst(); } /** * Don't evaluate if there is a {@code RuleChain} expression inside a {@code * RuleChain.outerRule()} or {@code RuleChain.around()} method. */ private static boolean isChainedRuleChain(VariableTree tree, VisitorState state) { return getOrderedExpressions(tree, state).stream() .map(DoNotUseRuleChain::getArgumentExpression) .anyMatch(ex -> Matchers.isSameType(JUNIT_RULE_CHAIN_IMPORT_PATH).matches(ex, state)); } private static SuggestedFix refactor(VariableTree tree, VisitorState state) { SuggestedFix.Builder fix = SuggestedFix.builder(); ImmutableList<ExpressionTree> expressions = getOrderedExpressions(tree, state); String replacement = ""; for (int i = 0; i < expressions.size(); i++) { ExpressionTree expression = getArgumentExpression(expressions.get(i)); addImportIfNecessary(expression, fix); replacement += extractRuleFromExpression(expression, i, tree, state); } fix.removeImport(JUNIT_RULE_CHAIN_IMPORT_PATH); fix.replace(tree, replacement); return fix.build(); } /** * Since {@code ASTHelpers.getReceiver()} goes into reverse order, the expression list must be * reversed in order for them to follow the required ordering from {@code @Rule(order = n)}. */ private static ImmutableList<ExpressionTree> getOrderedExpressions( VariableTree tree, VisitorState state) { ImmutableList.Builder<ExpressionTree> expressions = ImmutableList.builder(); for (ExpressionTree ex = tree.getInitializer(); RULE_CHAIN_METHOD_MATCHER.matches(ex, state); ex = ASTHelpers.getReceiver(ex)) { expressions.add(ex); } return expressions.build().reverse(); } // Gets the only argument from {@code RuleChain.outerRule()} or {@code RuleChain.around()} to use // as the variable value from the new ordered {@code @Rule(order = n)} private static ExpressionTree getArgumentExpression(ExpressionTree ex) { MethodInvocationTree methodInvocation = (MethodInvocationTree) ex; return methodInvocation.getArguments().get(0); } private static void addImportIfNecessary(ExpressionTree expression, SuggestedFix.Builder fix) { Type originalType = ASTHelpers.getResultType(expression); if (ImmutableSet.of(Kind.METHOD_INVOCATION, Kind.LAMBDA_EXPRESSION) .contains(expression.getKind())) { fix.addImport(originalType.tsym.getQualifiedName().toString()); } } private static String extractRuleFromExpression( ExpressionTree expression, int order, VariableTree tree, VisitorState state) { String className = className(expression); return String.format( "%s(order = %d)\npublic %sfinal %s %s = %s;\n", annotationName(tree, state), order, ASTHelpers.getSymbol(tree).isStatic() ? "static " : "", className, classToVariableName(className), state.getSourceForNode(expression)); } private static String className(ExpressionTree expression) { Type originalType = ASTHelpers.getResultType(expression); List<Type> arguments = originalType.getTypeArguments(); String className = originalType.tsym.getSimpleName().toString(); if (!arguments.isEmpty()) { String argumentString = arguments.stream().map(t -> t.tsym.getSimpleName().toString()).collect(joining(", ")); return String.format("%s<%s>", className, argumentString); } return className; } private static String annotationName(VariableTree tree, VisitorState state) { if (ASTHelpers.hasAnnotation(tree, JUNIT_CLASS_RULE_IMPORT_PATH, state)) { return "@ClassRule"; } return "@Rule"; } private static String classToVariableName(String className) { return String.format("%s%s", TEST_RULE_VAR_PREFIX, className) .replace("<", "") .replace(">", "") .replace(",", "") .replace(" ", ""); } }
8,335
39.076923
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallSuggester.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.WARNING; import static com.google.errorprone.bugpatterns.DoNotCallChecker.DO_NOT_CALL; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.enclosingClass; import static com.google.errorprone.util.ASTHelpers.findClass; import static com.google.errorprone.util.ASTHelpers.findSuperMethods; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static com.google.errorprone.util.ASTHelpers.methodCanBeOverridden; 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.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.tree.MethodTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.ThrowTree; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; import javax.lang.model.element.Modifier; /** * If a method always throws an exception, consider annotating it with {@code @DoNotCall} to prevent * calls at compile-time instead failing at runtime. */ @BugPattern( summary = "Consider annotating methods that always throw with @DoNotCall. " + "Read more at https://errorprone.info/bugpattern/DoNotCall", severity = WARNING) public class DoNotCallSuggester extends BugChecker implements MethodTreeMatcher { // TODO(kak): Consider adding "newInstance" to this list (some frameworks use that method name) private static final ImmutableSet<String> METHOD_PREFIXES_TO_IGNORE = ImmutableSet.of( // likely providing Dagger bindings "produce", "provide"); private static final ImmutableSet<String> METHOD_SUBSTRINGS_TO_IGNORE = ImmutableSet.of( // common substrings in the names of exception factory methods "throw", "fail", "exception", "propagate"); private static final ImmutableSet<String> ANNOTATIONS_TO_IGNORE = ImmutableSet.of( // ignore methods that are already annotated w/ @DoNotCall DO_NOT_CALL, // We exclude methods that are overrides; at call sites, rarely is the variable reference // statically typed as the subclass (often it's typed as the interface type), so adding // @DoNotCall won't actually help any callers. "java.lang.Override", // dagger provider / producers "dagger.Provides", "dagger.producers.Produces", // starlark API boundary "net.starlark.java.annot.StarlarkMethod"); private static final ImmutableSet<String> PARENT_CLASS_TO_IGNORE = ImmutableSet.of( // a Guice module w/ bindings "com.google.inject.AbstractModule"); private static final ImmutableSet<String> RETURNED_SUPER_TYPES_TO_IGNORE = ImmutableSet.of( // a throwable "java.lang.Throwable"); @Override public Description matchMethod(MethodTree tree, VisitorState state) { // if we can't find the method symbol, exit MethodSymbol symbol = getSymbol(tree); // if the method is abstract, exit if (tree.getBody() == null) { return NO_MATCH; } // if the body does not contain exactly 1 statement, exit if (tree.getBody().getStatements().size() != 1) { return NO_MATCH; } // if the method is private or overrideable, exit if (symbol.getModifiers().contains(Modifier.PRIVATE) || methodCanBeOverridden(symbol)) { return NO_MATCH; } // if the single statement is not a ThrowTree, exit StatementTree statement = getOnlyElement(tree.getBody().getStatements()); if (!(statement instanceof ThrowTree)) { return NO_MATCH; } // if the enclosing class extends from a known frameworks class, exit ClassSymbol enclosingClass = enclosingClass(symbol); Type enclosingType = getType(findClass(enclosingClass, state)); for (String parentClass : PARENT_CLASS_TO_IGNORE) { Type parentClassType = state.getTypeFromString(parentClass); if (isSubtype(enclosingType, parentClassType, state)) { return NO_MATCH; } } // if the enclosing class is anonymous, exit if (enclosingClass.isAnonymous()) { return NO_MATCH; } // if the method name starts a banned prefix, exit String methodName = tree.getName().toString().toLowerCase(); for (String methodPrefix : METHOD_PREFIXES_TO_IGNORE) { if (methodName.startsWith(methodPrefix)) { return NO_MATCH; } } // if a method name contais a banned substring, exit for (String methodSubstring : METHOD_SUBSTRINGS_TO_IGNORE) { if (methodName.contains(methodSubstring)) { return NO_MATCH; } } // if the method is annotated with a banned annotation, exit for (String annotationToIgnore : ANNOTATIONS_TO_IGNORE) { if (hasAnnotation(tree, annotationToIgnore, state)) { return NO_MATCH; } } // if the method returns a banned type, exit Type returnType = getType(tree.getReturnType()); for (String returnedSuperType : RETURNED_SUPER_TYPES_TO_IGNORE) { Type throwableType = state.getTypeFromString(returnedSuperType); if (isSubtype(returnType, throwableType, state)) { return NO_MATCH; } } // if the method is an "effective override" (they forgot to add @Override), exit if (!findSuperMethods(symbol, state.getTypes()).isEmpty()) { return NO_MATCH; } // otherwise, suggest annotating the method with @DoNotCall Type thrownType = getType(((ThrowTree) statement).getExpression()); // TODO(kak): Consider possibly stripping "java.lang" (users should be familiar with those!) SuggestedFix fix = SuggestedFix.builder() .addImport(DO_NOT_CALL) .prefixWith(tree, "@DoNotCall(\"Always throws " + thrownType + "\") ") .build(); return buildDescription(tree) .setMessage( "Methods that always throw an exception should be annotated with @DoNotCall to prevent" + " calls at compilation time vs. at runtime (note that adding @DoNotCall will" + " break any existing callers of this API).") .addFix(fix) .build(); } }
7,392
38.747312
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NonAtomicVolatileUpdate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.assignment; import static com.google.errorprone.matchers.Matchers.binaryTree; import static com.google.errorprone.matchers.Matchers.inSynchronized; import static com.google.errorprone.matchers.Matchers.kindIs; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.Matchers.sameVariable; import static com.google.errorprone.matchers.Matchers.toType; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.AssignmentTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.CompoundAssignmentTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.UnaryTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.UnaryTree; import javax.lang.model.element.Modifier; /** Detects non-atomic updates to volatile variables. */ @BugPattern( summary = "This update of a volatile variable is non-atomic", severity = WARNING, tags = StandardTags.FRAGILE_CODE) public class NonAtomicVolatileUpdate extends BugChecker implements UnaryTreeMatcher, CompoundAssignmentTreeMatcher, AssignmentTreeMatcher { /** Extracts the expression from a UnaryTree and applies a matcher to it. */ private static Matcher<UnaryTree> expressionFromUnaryTree(Matcher<ExpressionTree> exprMatcher) { return new Matcher<UnaryTree>() { @Override public boolean matches(UnaryTree tree, VisitorState state) { return exprMatcher.matches(tree.getExpression(), state); } }; } /** Extracts the variable from a CompoundAssignmentTree and applies a matcher to it. */ private static Matcher<CompoundAssignmentTree> variableFromCompoundAssignmentTree( Matcher<ExpressionTree> exprMatcher) { return new Matcher<CompoundAssignmentTree>() { @Override public boolean matches(CompoundAssignmentTree tree, VisitorState state) { return exprMatcher.matches(tree.getVariable(), state); } }; } /** Extracts the variable from an AssignmentTree and applies a matcher to it. */ private static Matcher<AssignmentTree> variableFromAssignmentTree( Matcher<ExpressionTree> exprMatcher) { return new Matcher<AssignmentTree>() { @Override public boolean matches(AssignmentTree tree, VisitorState state) { return exprMatcher.matches(tree.getVariable(), state); } }; } /** * Matches patterns like i++ and i-- in which i is volatile, and the pattern is not enclosed by a * synchronized block. */ private static final Matcher<UnaryTree> unaryIncrementDecrementMatcher = allOf( expressionFromUnaryTree(Matchers.<ExpressionTree>hasModifier(Modifier.VOLATILE)), not(inSynchronized()), anyOf( kindIs(Kind.POSTFIX_INCREMENT), kindIs(Kind.PREFIX_INCREMENT), kindIs(Kind.POSTFIX_DECREMENT), kindIs(Kind.PREFIX_DECREMENT))); @Override public Description matchUnary(UnaryTree tree, VisitorState state) { if (unaryIncrementDecrementMatcher.matches(tree, state)) { return describeMatch(tree); } return Description.NO_MATCH; } /** * Matches patterns like i += 1 and i -= 1 in which i is volatile, and the pattern is not enclosed * by a synchronized block. */ private static final Matcher<CompoundAssignmentTree> compoundAssignmentIncrementDecrementMatcher = allOf( variableFromCompoundAssignmentTree( Matchers.<ExpressionTree>hasModifier(Modifier.VOLATILE)), not(inSynchronized()), anyOf(kindIs(Kind.PLUS_ASSIGNMENT), kindIs(Kind.MINUS_ASSIGNMENT))); @Override public Description matchCompoundAssignment(CompoundAssignmentTree tree, VisitorState state) { if (compoundAssignmentIncrementDecrementMatcher.matches(tree, state)) { return describeMatch(tree); } return Description.NO_MATCH; } /** * Matches patterns like i = i + 1 and i = i - 1 in which i is volatile, and the pattern is not * enclosed by a synchronized block. */ private static Matcher<AssignmentTree> assignmentIncrementDecrementMatcher( ExpressionTree variable) { return allOf( variableFromAssignmentTree(Matchers.<ExpressionTree>hasModifier(Modifier.VOLATILE)), not(inSynchronized()), assignment( Matchers.<ExpressionTree>anything(), toType( BinaryTree.class, Matchers.<BinaryTree>allOf( Matchers.<BinaryTree>anyOf(kindIs(Kind.PLUS), kindIs(Kind.MINUS)), binaryTree(sameVariable(variable), Matchers.<ExpressionTree>anything()))))); } @Override public Description matchAssignment(AssignmentTree tree, VisitorState state) { if (assignmentIncrementDecrementMatcher(tree.getVariable()).matches(tree, state)) { return describeMatch(tree); } return Description.NO_MATCH; } }
6,236
39.5
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MissingImplementsComparable.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.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.compareToMethodDeclaration; import static com.google.errorprone.matchers.Matchers.hasAnnotation; import static com.google.errorprone.matchers.Matchers.not; 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.MethodTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Classes implementing valid compareTo function should implement Comparable interface", severity = WARNING) public class MissingImplementsComparable extends BugChecker implements MethodTreeMatcher { private static final Matcher<MethodTree> COMPARABLE_WITHOUT_OVERRIDE = allOf(compareToMethodDeclaration(), not(hasAnnotation("java.lang.Override"))); private static final Matcher<ClassTree> IS_COMPARABLE = Matchers.isSubtypeOf("java.lang.Comparable"); @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (!COMPARABLE_WITHOUT_OVERRIDE.matches(tree, state)) { return Description.NO_MATCH; } ClassTree enclosingClass = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class); if (enclosingClass == null || IS_COMPARABLE.matches(enclosingClass, state)) { return Description.NO_MATCH; } if (!isSameType( getType(getOnlyElement(tree.getParameters())), getType(enclosingClass), state)) { return Description.NO_MATCH; } return describeMatch(tree); } }
2,796
41.378788
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ImmutableMemberCollection.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.ImmutableMap.toImmutableMap; import static com.google.common.collect.Streams.stream; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.hasAnnotationWithSimpleName; import static com.google.errorprone.matchers.Matchers.hasModifier; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.matchers.Matchers.kindIs; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.shouldKeep; import com.google.auto.value.AutoValue; 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.ImmutableSetMultimap; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ListMultimap; import com.google.common.collect.SetMultimap; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.ParameterizedTypeTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Optional; import java.util.Set; import java.util.SortedMap; import javax.lang.model.element.Modifier; /** Refactoring to suggest Immutable types for member collection that are not mutated. */ @BugPattern( summary = "If you don't intend to mutate a member collection prefer using Immutable types.", severity = SUGGESTION) public final class ImmutableMemberCollection extends BugChecker implements ClassTreeMatcher { private static final ImmutableSet<String> MUTATING_METHODS = ImmutableSet.of( "add", "addAll", "clear", "compute", "computeIfAbsent", "computeIfPresent", "forcePut", "merge", "pollFirst", "pollFirstEntry", "pollLast", "pollLastEntry", "put", "putAll", "putIfAbsent", "remove", "removeAll", "removeIf", "replace", "replaceAll", "replaceValues", "retainAll", "set", "sort"); private static final ImmutableSet<ReplaceableType<?>> REPLACEABLE_TYPES = ImmutableSet.of( ReplaceableType.create(NavigableSet.class, ImmutableSortedSet.class), ReplaceableType.create(Set.class, ImmutableSet.class), ReplaceableType.create(List.class, ImmutableList.class), ReplaceableType.create(ListMultimap.class, ImmutableListMultimap.class), ReplaceableType.create(SetMultimap.class, ImmutableSetMultimap.class), ReplaceableType.create(SortedMap.class, ImmutableSortedMap.class), ReplaceableType.create(Map.class, ImmutableMap.class)); private static final Matcher<Tree> PRIVATE_FINAL_VAR_MATCHER = allOf(kindIs(Kind.VARIABLE), hasModifier(Modifier.PRIVATE), hasModifier(Modifier.FINAL)); // TODO(ashishkedia) : Share this with ImmutableSetForContains. private static final Matcher<Tree> EXCLUSIONS = anyOf( (t, s) -> shouldKeep(t), hasAnnotationWithSimpleName("Bind"), hasAnnotationWithSimpleName("Inject")); @Override public Description matchClass(ClassTree classTree, VisitorState state) { ImmutableMap<Symbol, ReplaceableVar> replaceableVars = classTree.getMembers().stream() .filter(member -> PRIVATE_FINAL_VAR_MATCHER.matches(member, state)) .filter(member -> !EXCLUSIONS.matches(member, state)) .filter(member -> !isSuppressed(member, state)) .map(VariableTree.class::cast) .flatMap(varTree -> stream(isReplaceable(varTree, state))) .collect(toImmutableMap(ReplaceableVar::symbol, var -> var)); if (replaceableVars.isEmpty()) { return Description.NO_MATCH; } HashSet<Symbol> isPotentiallyMutated = new HashSet<>(); ImmutableSetMultimap.Builder<Symbol, Tree> initTreesBuilder = ImmutableSetMultimap.builder(); new TreePathScanner<Void, VisitorState>() { @Override public Void visitAssignment(AssignmentTree assignmentTree, VisitorState visitorState) { Symbol varSymbol = getSymbol(assignmentTree.getVariable()); if (replaceableVars.containsKey(varSymbol) && assignmentTree.getExpression() != null) { initTreesBuilder.put(varSymbol, assignmentTree.getExpression()); } return scan(assignmentTree.getExpression(), visitorState); } @Override public Void visitVariable(VariableTree variableTree, VisitorState visitorState) { VarSymbol varSym = getSymbol(variableTree); if (replaceableVars.containsKey(varSym) && variableTree.getInitializer() != null) { initTreesBuilder.put(varSym, variableTree.getInitializer()); } return super.visitVariable(variableTree, visitorState); } @Override public Void visitIdentifier(IdentifierTree identifierTree, VisitorState visitorState) { recordVarMutation(getSymbol(identifierTree)); return super.visitIdentifier(identifierTree, visitorState); } @Override public Void visitMemberSelect(MemberSelectTree memberSelectTree, VisitorState visitorState) { recordVarMutation(getSymbol(memberSelectTree)); return super.visitMemberSelect(memberSelectTree, visitorState); } @Override public Void visitMethodInvocation( MethodInvocationTree methodInvocationTree, VisitorState visitorState) { ExpressionTree receiver = getReceiver(methodInvocationTree); if (replaceableVars.containsKey(getSymbol(receiver))) { MemberSelectTree selectTree = (MemberSelectTree) methodInvocationTree.getMethodSelect(); if (!MUTATING_METHODS.contains(selectTree.getIdentifier().toString())) { // This is a safe read only method invoked on a replaceable collection member. methodInvocationTree.getTypeArguments().forEach(type -> scan(type, visitorState)); methodInvocationTree.getArguments().forEach(arg -> scan(arg, visitorState)); return null; } } return super.visitMethodInvocation(methodInvocationTree, visitorState); } private void recordVarMutation(Symbol sym) { if (replaceableVars.containsKey(sym)) { isPotentiallyMutated.add(sym); } } }.scan(state.findPathToEnclosing(CompilationUnitTree.class), state); ImmutableSetMultimap<Symbol, Tree> initTrees = initTreesBuilder.build(); SuggestedFix.Builder suggestedFix = SuggestedFix.builder(); replaceableVars.values().stream() .filter( var -> var.areAllInitImmutable(initTrees.get(var.symbol()), state) || !isPotentiallyMutated.contains(var.symbol())) .forEach( replaceableVar -> suggestedFix.merge( replaceableVar.getFix(initTrees.get(replaceableVar.symbol()), state))); if (suggestedFix.isEmpty()) { return Description.NO_MATCH; } return describeMatch(classTree, suggestedFix.build()); } private static Optional<ReplaceableVar> isReplaceable(VariableTree tree, VisitorState state) { return REPLACEABLE_TYPES.stream() .filter(type -> isSameType(type.interfaceType()).matches(tree, state)) .findFirst() .map(type -> ReplaceableVar.create(tree, type)); } @AutoValue abstract static class ReplaceableType<M> { abstract Class<M> interfaceType(); abstract Class<? extends M> immutableType(); static <M> ReplaceableType<M> create(Class<M> interfaceType, Class<? extends M> immutableType) { return new AutoValue_ImmutableMemberCollection_ReplaceableType<>( interfaceType, immutableType); } } @AutoValue abstract static class ReplaceableVar { abstract Symbol symbol(); abstract ReplaceableType<?> type(); abstract Tree declaredType(); static ReplaceableVar create(VariableTree variableTree, ReplaceableType<?> type) { return new AutoValue_ImmutableMemberCollection_ReplaceableVar( getSymbol(variableTree), type, variableTree.getType()); } private SuggestedFix getFix(ImmutableSet<Tree> initTrees, VisitorState state) { SuggestedFix.Builder fixBuilder = SuggestedFix.builder() .replace(stripTypeParameters(declaredType()), type().immutableType().getSimpleName()) .addImport(type().immutableType().getName()); initTrees.stream() .filter(initTree -> !isSameType(type().immutableType()).matches(initTree, state)) .forEach(init -> fixBuilder.replace(init, wrapWithImmutableCopy(init, state))); return fixBuilder.build(); } private String wrapWithImmutableCopy(Tree tree, VisitorState state) { String type = type().immutableType().getSimpleName(); return type + ".copyOf(" + state.getSourceForNode(tree) + ")"; } private boolean areAllInitImmutable(ImmutableSet<Tree> initTrees, VisitorState state) { return initTrees.stream() .allMatch(initTree -> isSameType(type().immutableType()).matches(initTree, state)); } private static Tree stripTypeParameters(Tree tree) { return tree.getKind().equals(Kind.PARAMETERIZED_TYPE) ? ((ParameterizedTypeTree) tree).getType() : tree; } } }
11,275
41.074627
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/IndexOfChar.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.getType; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.method.MethodMatchers; import com.google.errorprone.suppliers.Suppliers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Types; import java.util.List; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "The first argument to indexOf is a Unicode code point, and the second is the index to" + " start the search from", severity = ERROR) public class IndexOfChar extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> MATCHER = MethodMatchers.instanceMethod() .onExactClass(Suppliers.STRING_TYPE) .namedAnyOf("indexOf", "lastIndexOf") .withParameters("int", "int"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return NO_MATCH; } List<? extends ExpressionTree> arguments = tree.getArguments(); Symtab syms = state.getSymtab(); Types types = state.getTypes(); if (types.isSameType(types.unboxedTypeOrType(getType(arguments.get(0))), syms.intType) && types.isSameType(types.unboxedTypeOrType(getType(arguments.get(1))), syms.charType)) { return describeMatch( tree, SuggestedFix.builder() .replace(arguments.get(0), state.getSourceForNode(arguments.get(1))) .replace(arguments.get(1), state.getSourceForNode(arguments.get(0))) .build()); } return NO_MATCH; } }
2,866
39.957143
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TypeParameterShadowing.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.util.ASTHelpers.isStatic; import com.google.common.collect.ImmutableSet; import com.google.common.collect.MoreCollectors; import com.google.common.collect.Streams; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeParameterTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.TypeVariableSymbol; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.lang.model.element.Name; @BugPattern( summary = "Type parameter declaration overrides another type parameter already declared", severity = WARNING, tags = StandardTags.STYLE) public class TypeParameterShadowing extends BugChecker implements MethodTreeMatcher, ClassTreeMatcher { @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (tree.getTypeParameters().isEmpty()) { return Description.NO_MATCH; } return findDuplicatesOf(tree, tree.getTypeParameters(), state); } @Override public Description matchClass(ClassTree tree, VisitorState state) { if (tree.getTypeParameters().isEmpty()) { return Description.NO_MATCH; } return findDuplicatesOf(tree, tree.getTypeParameters(), state); } private Description findDuplicatesOf( Tree tree, List<? extends TypeParameterTree> typeParameters, VisitorState state) { Symbol symbol = ASTHelpers.getSymbol(tree); if (symbol == null) { return Description.NO_MATCH; } List<TypeVariableSymbol> enclosingTypeSymbols = typeVariablesEnclosing(symbol); if (enclosingTypeSymbols.isEmpty()) { return Description.NO_MATCH; } // See if the passed in list typeParameters exist in the enclosingTypeSymbols List<TypeVariableSymbol> conflictingTypeSymbols = new ArrayList<>(); typeParameters.forEach( param -> enclosingTypeSymbols.stream() .filter(tvs -> tvs.name.contentEquals(param.getName())) .findFirst() .ifPresent(conflictingTypeSymbols::add)); if (conflictingTypeSymbols.isEmpty()) { return Description.NO_MATCH; } // Describes what's the conflicting type and where it is Description.Builder descriptionBuilder = buildDescription(tree); String message = "Found aliased type parameters: " + conflictingTypeSymbols.stream() .map(tvs -> tvs.name + " declared in " + tvs.owner.getSimpleName()) .collect(Collectors.joining("\n")); descriptionBuilder.setMessage(message); // Map conflictingTypeSymbol to its new name ImmutableSet<String> typeVarsInScope = Streams.concat(enclosingTypeSymbols.stream(), symbol.getTypeParameters().stream()) .map(v -> v.name.toString()) .collect(toImmutableSet()); SuggestedFix.Builder fixBuilder = SuggestedFix.builder(); conflictingTypeSymbols.stream() .map( v -> SuggestedFixes.renameTypeParameter( typeParameterInList(typeParameters, v), tree, replacementTypeVarName(v.name, typeVarsInScope), state)) .forEach(fixBuilder::merge); descriptionBuilder.addFix(fixBuilder.build()); return descriptionBuilder.build(); } // Package-private for TypeNameShadowing static TypeParameterTree typeParameterInList( List<? extends TypeParameterTree> typeParameters, Symbol v) { return typeParameters.stream() .filter(t -> t.getName().contentEquals(v.name)) .collect(MoreCollectors.onlyElement()); } private static final Pattern TRAILING_DIGIT_EXTRACTOR = Pattern.compile("^(.*?)(\\d+)$"); // T -> T2 // T2 -> T3 // T -> T4 (if T2 and T3 already exist) // Package-private for TypeNameShadowing static String replacementTypeVarName(Name name, Set<String> superTypeVars) { String baseName = name.toString(); int typeVarNum = 2; Matcher matcher = TRAILING_DIGIT_EXTRACTOR.matcher(name); if (matcher.matches()) { baseName = matcher.group(1); typeVarNum = Integer.parseInt(matcher.group(2)) + 1; } String replacementName; while (superTypeVars.contains(replacementName = baseName + typeVarNum)) { typeVarNum++; } return replacementName; } // Get list of type params of every enclosing class private static List<TypeVariableSymbol> typeVariablesEnclosing(Symbol sym) { List<TypeVariableSymbol> typeVarScopes = new ArrayList<>(); outer: while (!isStatic(sym)) { sym = sym.owner; switch (sym.getKind()) { case PACKAGE: break outer; case METHOD: case CLASS: typeVarScopes.addAll(sym.getTypeParameters()); break; default: // fall out } } return typeVarScopes; } }
6,311
34.460674
93
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/IdentityBinaryExpression.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.toType; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.constValue; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSameType; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; import java.util.Optional; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( altNames = "SelfEquality", summary = "A binary expression where both operands are the same is usually incorrect.", severity = ERROR) public class IdentityBinaryExpression extends BugChecker implements BinaryTreeMatcher { private static final Matcher<Tree> ASSERTION = toType( ExpressionTree.class, staticMethod().anyClass().namedAnyOf("assertTrue", "assertFalse", "assertThat")); @Override @SuppressWarnings("TreeToString") public Description matchBinary(BinaryTree tree, VisitorState state) { if (constValue(tree.getLeftOperand()) != null) { switch (tree.getKind()) { case LEFT_SHIFT: // bit field initialization, e.g. `1 << 1`, `1 << 2`, ... case DIVIDE: // aspect ratios, e.g. `1.0f / 1.0f`, `2.0f / 3.0f`, ... case MINUS: // character arithmetic, e.g. `'A' - 'A'`, `'B' - 'A'`, ... return NO_MATCH; default: // fall out } } String replacement; switch (tree.getKind()) { case DIVIDE: replacement = "1"; break; case MINUS: case REMAINDER: replacement = "0"; break; case GREATER_THAN_EQUAL: case LESS_THAN_EQUAL: case EQUAL_TO: if (ASSERTION.matches(state.getPath().getParentPath().getLeaf(), state)) { return NO_MATCH; } replacement = "true"; break; case LESS_THAN: case GREATER_THAN: case NOT_EQUAL_TO: case XOR: if (ASSERTION.matches(state.getPath().getParentPath().getLeaf(), state)) { return NO_MATCH; } replacement = "false"; break; case AND: case OR: case CONDITIONAL_AND: case CONDITIONAL_OR: replacement = state.getSourceForNode(tree.getLeftOperand()); break; case LEFT_SHIFT: case RIGHT_SHIFT: case UNSIGNED_RIGHT_SHIFT: replacement = null; // ¯\_(ツ)_/¯ break; case MULTIPLY: case PLUS: default: return NO_MATCH; } // toString rather than getSourceForNode is intentional. if (!tree.getLeftOperand().toString().equals(tree.getRightOperand().toString())) { return NO_MATCH; } switch (tree.getKind()) { case NOT_EQUAL_TO: // X != X is only true when X is NaN, so suggest isNaN(X) replacement = isNanReplacement(tree, state).orElse(replacement); break; case EQUAL_TO: // X == X is true unless X is NaN, so suggest !isNaN(X) replacement = isNanReplacement(tree, state).map(r -> "!" + r).orElse(replacement); break; default: // fall out } Description.Builder description = buildDescription(tree); if (replacement != null) { description.setMessage( String.format( "A binary expression where both operands are the same is usually incorrect;" + " the value of this expression is equivalent to `%s`.", replacement)); } return description.build(); } private static Optional<String> isNanReplacement(BinaryTree tree, VisitorState state) { Types types = state.getTypes(); Symtab symtab = state.getSymtab(); Type type = getType(tree.getLeftOperand()); if (type == null) { return Optional.empty(); } type = types.unboxedTypeOrType(type); String name; if (isSameType(type, symtab.floatType, state)) { name = "Float"; } else if (isSameType(type, symtab.doubleType, state)) { name = "Double"; } else { return Optional.empty(); } return Optional.of( String.format("%s.isNaN(%s)", name, state.getSourceForNode(tree.getLeftOperand()))); } }
5,424
34.690789
92
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AbstractUseSwitch.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.getLast; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSubtype; import com.google.common.base.Optional; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.IfTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.Reachability; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.BreakTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.IfTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.TreeInfo; import com.sun.tools.javac.tree.TreeMaker; import java.util.ArrayList; import java.util.List; import org.checkerframework.checker.nullness.qual.Nullable; /** Helper for refactoring from if-else chains to switches. */ public abstract class AbstractUseSwitch extends BugChecker implements IfTreeMatcher { private static final int MIN_BRANCHES = 3; private static final Matcher<ExpressionTree> EQUALS = instanceMethod().anyClass().named("equals").withParameters("java.lang.Object"); /** Returns the source text that should appear in a {@code case} statement in the fix. */ protected abstract @Nullable String getExpressionForCase( VisitorState state, ExpressionTree argument); private static boolean isValidCaseBlock(StatementTree tree) { if (!(tree instanceof JCBlock)) { return false; } boolean[] good = {true}; new TreeScanner<Void, Void>() { @Override public Void visitBreak(BreakTree t, Void v) { // breaks would definitely break a switch! good[0] = false; return null; } @Override public Void visitVariable(VariableTree t, Void v) { // If there are variables, we'd need braces; we just forbid them blindly for now. good[0] = false; return null; } }.scan(tree, null); return good[0]; } /** Returns the source code from a JCBlock {...} without the curly brackets. */ private static CharSequence getBlockContents(BlockTree block, VisitorState state) { List<? extends StatementTree> statements = block.getStatements(); if (statements.isEmpty()) { return ""; } int start = ((JCTree) statements.get(0)).getStartPosition(); int end = state.getEndPosition(getLast(statements)); return state.getSourceCode().subSequence(start, end); } @Override public Description matchIf(IfTree tree, VisitorState state) { if (state.getPath().getParentPath().getLeaf().getKind() == Kind.IF) { return NO_MATCH; } List<String> stringConstants = new ArrayList<>(); List<JCBlock> branches = new ArrayList<>(); IdentifierTree var = null; StatementTree statementTree = tree; do { IfTree ifTree = (IfTree) statementTree; ExpressionTree cond = TreeInfo.skipParens((JCExpression) ifTree.getCondition()); ExpressionTree lhs; ExpressionTree rhs; if (EQUALS.matches(cond, state)) { MethodInvocationTree call = (MethodInvocationTree) cond; lhs = getReceiver(call); rhs = getOnlyElement(call.getArguments()); } else if (cond.getKind().equals(Kind.EQUAL_TO)) { BinaryTree equalTo = (BinaryTree) cond; lhs = equalTo.getLeftOperand(); rhs = equalTo.getRightOperand(); } else { return NO_MATCH; } if (!(lhs instanceof IdentifierTree)) { return NO_MATCH; } IdentifierTree identifierTree = (IdentifierTree) lhs; if (var == null) { var = identifierTree; // This is the first if block, and identifierTree is the string variable } else if (!(identifierTree.getName().equals(var.getName()) && isValidCaseBlock(ifTree.getThenStatement()))) { return NO_MATCH; } if (!isSubtype(getType(lhs), getType(rhs), state)) { return NO_MATCH; } String expressionForCase = getExpressionForCase(state, rhs); if (expressionForCase == null) { return NO_MATCH; } stringConstants.add(expressionForCase); if (ifTree.getThenStatement().getKind() == Kind.BLOCK) { branches.add((JCBlock) ifTree.getThenStatement()); } else { TreeMaker maker = TreeMaker.instance(state.context); branches.add( maker.Block( 0, com.sun.tools.javac.util.List.of((JCStatement) ifTree.getThenStatement()))); } statementTree = ifTree.getElseStatement(); } while (statementTree instanceof IfTree); Optional<JCBlock> defaultBranch = (statementTree instanceof JCBlock) ? Optional.of((JCBlock) statementTree) : Optional.absent(); if (stringConstants.size() + defaultBranch.asSet().size() < MIN_BRANCHES) { return NO_MATCH; } StringBuilder builder = new StringBuilder(); builder.append("switch (").append(var.getName()).append(") {\n"); for (int i = 0; i < stringConstants.size(); i++) { builder .append("case ") .append(stringConstants.get(i)) .append(":\n") .append(getBlockContents(branches.get(i), state)); if (Reachability.canCompleteNormally(branches.get(i))) { builder.append("\nbreak;\n"); } } builder .append("default:\n") .append( defaultBranch.isPresent() ? getBlockContents(defaultBranch.get(), state) : "// fall through") .append("\n}"); return describeMatch(tree, SuggestedFix.replace(tree, builder.toString())); } }
7,109
37.432432
95
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SuppressWarningsWithoutExplanation.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.LinkType.CUSTOM; 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.hasArgumentWithValue; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.matchers.Matchers.stringLiteral; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import com.google.common.collect.ImmutableRangeSet; import com.google.common.collect.Range; import com.google.common.collect.RangeSet; import com.google.common.collect.TreeRangeSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.ErrorProneToken; import com.google.errorprone.util.ErrorProneTokens; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.LineMap; import com.sun.source.tree.Tree; import com.sun.tools.javac.parser.Tokens.Comment; /** * Finds occurrences of {@code @SuppressWarnings} where there is definitely no explanation for why * it is safe. * * <p>The Google style guide mandates this for <em>all</em> suppressions; this is only matching on * {@code deprecation} as a trial. */ @BugPattern( summary = "Use of @SuppressWarnings should be accompanied by a comment describing why the warning is" + " safe to ignore.", tags = BugPattern.StandardTags.STYLE, severity = WARNING, linkType = CUSTOM, link = "https://google.github.io/styleguide/javaguide.html#s8.4.2-how-to-handle-a-warning") public final class SuppressWarningsWithoutExplanation extends BugChecker implements CompilationUnitTreeMatcher { private static final Matcher<AnnotationTree> SUPPRESS_WARNINGS = allOf( isSameType(SuppressWarnings.class), hasArgumentWithValue("value", stringLiteral("deprecation"))); private final boolean emitDummyFixes; public SuppressWarningsWithoutExplanation() { this(false); } public SuppressWarningsWithoutExplanation(boolean emitDummyFixes) { this.emitDummyFixes = emitDummyFixes; } @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { if (!ASTHelpers.getGeneratedBy(state).isEmpty()) { return NO_MATCH; } ImmutableRangeSet<Long> linesWithComments = linesWithComments(state); new SuppressibleTreePathScanner<Void, Void>(state) { @Override public Void visitAnnotation(AnnotationTree annotationTree, Void unused) { if (!SUPPRESS_WARNINGS.matches(annotationTree, state)) { return super.visitAnnotation(annotationTree, null); } LineMap lineMap = state.getPath().getCompilationUnit().getLineMap(); Tree parent = getCurrentPath().getParentPath().getLeaf(); // Expand by +/- one to accept comments either before or after the suppression. Range<Long> linesCovered = Range.closed( lineMap.getLineNumber(getStartPosition(parent)) - 1, lineMap.getLineNumber(state.getEndPosition(parent)) + 1); if (!linesWithComments.intersects(linesCovered)) { state.reportMatch( describeMatch( annotationTree, emitDummyFixes ? SuggestedFix.postfixWith(annotationTree, " // Safe because...") : SuggestedFix.emptyFix())); } return super.visitAnnotation(annotationTree, null); } }.scan(tree, null); return NO_MATCH; } private static ImmutableRangeSet<Long> linesWithComments(VisitorState state) { RangeSet<Long> lines = TreeRangeSet.create(); ErrorProneTokens tokens = new ErrorProneTokens(state.getSourceCode().toString(), state.context); LineMap lineMap = tokens.getLineMap(); for (ErrorProneToken token : tokens.getTokens()) { for (Comment comment : token.comments()) { lines.add( Range.closed( lineMap.getLineNumber(comment.getSourcePos(0)), lineMap.getLineNumber(comment.getSourcePos(comment.getText().length() - 1)))); } } return ImmutableRangeSet.copyOf(lines); } }
5,283
40.28125
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/FieldCanBeLocal.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.SUGGESTION; import static com.google.errorprone.util.ASTHelpers.getAnnotation; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.shouldKeep; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.MultimapBuilder; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; 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.AnnotationTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import java.lang.annotation.ElementType; import java.lang.annotation.Target; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.lang.model.element.ElementKind; /** Flags fields which can be replaced with local variables. */ @BugPattern( altNames = {"unused", "Unused"}, summary = "This field can be replaced with a local variable in the methods that use it.", severity = SUGGESTION, documentSuppression = false) public final class FieldCanBeLocal extends BugChecker implements CompilationUnitTreeMatcher { private static final ImmutableSet<ElementType> VALID_ON_LOCAL_VARIABLES = Sets.immutableEnumSet(ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE); @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { Map<VarSymbol, TreePath> potentialFields = new LinkedHashMap<>(); SetMultimap<VarSymbol, TreePath> unconditionalAssignments = MultimapBuilder.linkedHashKeys().linkedHashSetValues().build(); SetMultimap<VarSymbol, Tree> uses = MultimapBuilder.linkedHashKeys().linkedHashSetValues().build(); new SuppressibleTreePathScanner<Void, Void>(state) { @Override public Void visitVariable(VariableTree variableTree, Void unused) { VarSymbol symbol = getSymbol(variableTree); if (symbol.getKind() == ElementKind.FIELD && symbol.isPrivate() && canBeLocal(variableTree) && !shouldKeep(variableTree) && !symbol.getSimpleName().toString().startsWith("unused")) { potentialFields.put(symbol, getCurrentPath()); } return null; } private boolean canBeLocal(VariableTree variableTree) { if (variableTree.getModifiers() == null) { return true; } return variableTree.getModifiers().getAnnotations().stream() .allMatch(this::canBeUsedOnLocalVariable); } private boolean canBeUsedOnLocalVariable(AnnotationTree annotationTree) { // TODO(b/137842683): Should this (and all other places using getAnnotation with Target) be // replaced with annotation mirror traversals? // This is safe given we know that Target does not have Class fields. Target target = getAnnotation(annotationTree, Target.class); if (target == null) { return true; } return !Sets.intersection(VALID_ON_LOCAL_VARIABLES, ImmutableSet.copyOf(target.value())) .isEmpty(); } }.scan(state.getPath(), null); new TreePathScanner<Void, Void>() { boolean inMethod = false; @Override public Void visitClass(ClassTree classTree, Void unused) { if (isSuppressed(classTree, state)) { return null; } inMethod = false; return super.visitClass(classTree, unused); } @Override public Void visitMethod(MethodTree methodTree, Void unused) { if (methodTree.getBody() == null) { return null; } handleMethodLike(new TreePath(getCurrentPath(), methodTree.getBody())); inMethod = true; super.visitMethod(methodTree, null); inMethod = false; return null; } @Override public Void visitLambdaExpression(LambdaExpressionTree lambdaExpressionTree, Void unused) { if (lambdaExpressionTree.getBody() == null) { return null; } handleMethodLike(new TreePath(getCurrentPath(), lambdaExpressionTree.getBody())); inMethod = true; super.visitLambdaExpression(lambdaExpressionTree, null); inMethod = false; return null; } private void handleMethodLike(TreePath treePath) { int depth = Iterables.size(getCurrentPath()); new TreePathScanner<Void, Void>() { Set<VarSymbol> unconditionallyAssigned = new HashSet<>(); @Override public Void visitAssignment(AssignmentTree assignmentTree, Void unused) { scan(assignmentTree.getExpression(), null); Symbol symbol = getSymbol(assignmentTree.getVariable()); if (!(symbol instanceof VarSymbol)) { return scan(assignmentTree.getVariable(), null); } VarSymbol varSymbol = (VarSymbol) symbol; if (!potentialFields.containsKey(varSymbol)) { return scan(assignmentTree.getVariable(), null); } // An unconditional assignment in a MethodTree is three levels deeper than the // MethodTree itself. if (Iterables.size(getCurrentPath()) == depth + 3) { unconditionallyAssigned.add(varSymbol); unconditionalAssignments.put(varSymbol, getCurrentPath()); } return scan(assignmentTree.getVariable(), null); } @Override public Void visitIdentifier(IdentifierTree identifierTree, Void unused) { handleIdentifier(identifierTree); return super.visitIdentifier(identifierTree, null); } @Override public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void unused) { handleIdentifier(memberSelectTree); return super.visitMemberSelect(memberSelectTree, null); } private void handleIdentifier(Tree tree) { Symbol symbol = getSymbol(tree); if (!(symbol instanceof VarSymbol)) { return; } VarSymbol varSymbol = (VarSymbol) symbol; uses.put(varSymbol, tree); if (!unconditionallyAssigned.contains(varSymbol)) { potentialFields.remove(varSymbol); } } @Override public Void visitNewClass(NewClassTree node, Void unused) { unconditionallyAssigned.clear(); return super.visitNewClass(node, null); } @Override public Void visitMethodInvocation(MethodInvocationTree node, Void unused) { unconditionallyAssigned.clear(); return super.visitMethodInvocation(node, null); } @Override public Void visitMethod(MethodTree methodTree, Void unused) { return null; } @Override public Void visitLambdaExpression( LambdaExpressionTree lambdaExpressionTree, Void unused) { return null; } }.scan(treePath, null); } @Override public Void visitIdentifier(IdentifierTree identifierTree, Void unused) { if (!inMethod) { potentialFields.remove(getSymbol(identifierTree)); } return null; } @Override public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void unused) { if (!inMethod) { potentialFields.remove(getSymbol(memberSelectTree)); } return super.visitMemberSelect(memberSelectTree, null); } }.scan(state.getPath(), null); for (Map.Entry<VarSymbol, TreePath> entry : potentialFields.entrySet()) { VarSymbol varSymbol = entry.getKey(); TreePath declarationSite = entry.getValue(); Collection<TreePath> assignmentLocations = unconditionalAssignments.get(varSymbol); if (assignmentLocations.isEmpty()) { continue; } SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTree = (VariableTree) declarationSite.getLeaf(); String type = state.getSourceForNode(variableTree.getType()); String annotations = getAnnotationSource(state, variableTree); fix.delete(declarationSite.getLeaf()); Set<Tree> deletedTrees = new HashSet<>(); Set<Tree> scopesDeclared = new HashSet<>(); for (TreePath assignmentSite : assignmentLocations) { AssignmentTree assignmentTree = (AssignmentTree) assignmentSite.getLeaf(); Symbol rhsSymbol = getSymbol(assignmentTree.getExpression()); // If the RHS of the assignment is a variable with the same name as the field, just remove // the assignment. String assigneeName = getSymbol(assignmentTree.getVariable()).getSimpleName().toString(); if (rhsSymbol != null && assignmentTree.getExpression() instanceof IdentifierTree && rhsSymbol.getSimpleName().contentEquals(assigneeName)) { deletedTrees.add(assignmentTree.getVariable()); fix.delete(assignmentSite.getParentPath().getLeaf()); } else { Tree scope = assignmentSite.getParentPath().getParentPath().getLeaf(); if (scopesDeclared.add(scope)) { fix.prefixWith(assignmentSite.getLeaf(), annotations + " " + type + " "); } } } // Strip "this." off any uses of the field. for (Tree usage : uses.get(varSymbol)) { if (deletedTrees.contains(usage) || usage.getKind() == Kind.IDENTIFIER || usage.getKind() != Kind.MEMBER_SELECT) { continue; } ExpressionTree selected = ((MemberSelectTree) usage).getExpression(); if (!(selected instanceof IdentifierTree)) { continue; } IdentifierTree ident = (IdentifierTree) selected; if (ident.getName().contentEquals("this")) { fix.replace(getStartPosition(ident), state.getEndPosition(ident) + 1, ""); } } state.reportMatch(describeMatch(declarationSite.getLeaf(), fix.build())); } return Description.NO_MATCH; } private static String getAnnotationSource(VisitorState state, VariableTree variableTree) { List<? extends AnnotationTree> annotations = variableTree.getModifiers().getAnnotations(); if (annotations == null || annotations.isEmpty()) { return ""; } return state .getSourceCode() .subSequence( getStartPosition(annotations.get(0)), state.getEndPosition(getLast(annotations))) .toString(); } }
12,388
38.708333
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/IterableAndIterator.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.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import com.google.common.collect.Lists; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ClassTree; import com.sun.source.tree.Tree; import java.util.Iterator; import java.util.List; /** * @author jsjeon@google.com (Jinseong Jeon) */ @BugPattern( summary = "Class should not implement both `Iterable` and `Iterator`", severity = WARNING, tags = StandardTags.FRAGILE_CODE) public class IterableAndIterator extends BugChecker implements ClassTreeMatcher { private static final String ITERABLE = Iterable.class.getCanonicalName(); private static final String ITERATOR = Iterator.class.getCanonicalName(); /** Matches if a class/interface is subtype of Iterable */ private static final Matcher<Tree> ITERABLE_MATCHER = isSubtypeOf(ITERABLE); /** Matches if a class/interface is subtype of Iterator */ private static final Matcher<Tree> ITERATOR_MATCHER = isSubtypeOf(ITERATOR); /** Matches if a class/interface is subtype of Iterable _and_ Iterator */ private static final Matcher<Tree> ITERABLE_AND_ITERATOR_MATCHER = allOf(ITERABLE_MATCHER, ITERATOR_MATCHER); private static boolean matchAnySuperType(ClassTree tree, VisitorState state) { List<Tree> superTypes = Lists.<Tree>newArrayList(tree.getImplementsClause()); Tree superClass = tree.getExtendsClause(); if (superClass != null) { superTypes.add(superClass); } return superTypes.stream() .anyMatch(superType -> ITERABLE_AND_ITERATOR_MATCHER.matches(superType, state)); } @Override public Description matchClass(ClassTree tree, VisitorState state) { if (ITERABLE_AND_ITERATOR_MATCHER.matches(tree, state)) { // Filter out inherited case to not warn again if (matchAnySuperType(tree, state)) { return Description.NO_MATCH; } // TODO: Distinguish direct implementation and indirect cases // TODO: Suggest removing Iterable or Iterator, along with implemented methods return describeMatch(tree); } return Description.NO_MATCH; } }
3,162
36.654762
88
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessarilyVisible.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Sets.immutableEnumSet; import static com.google.common.collect.Sets.intersection; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.fixes.SuggestedFixes.removeModifiers; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.annotationsAmong; import static com.google.errorprone.util.ASTHelpers.findSuperMethod; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasDirectAnnotationWithSimpleName; 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.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.MethodTree; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.util.Name; import java.util.Set; import java.util.stream.Stream; import javax.lang.model.element.Modifier; /** Suggests restricting the visibility of methods which should only be called by a framework. */ @BugPattern( altNames = "RestrictInjectVisibility", summary = "Some methods (such as those annotated with @Inject or @Provides) are only intended to be" + " called by a framework, and so should have default visibility.", severity = WARNING) public final class UnnecessarilyVisible extends BugChecker implements MethodTreeMatcher { private static final ImmutableSet<Modifier> VISIBILITY_MODIFIERS = immutableEnumSet(Modifier.PROTECTED, Modifier.PUBLIC); private static final Supplier<ImmutableSet<Name>> FRAMEWORK_ANNOTATIONS = VisitorState.memoize( s -> Stream.of( "com.google.inject.Inject", "com.google.inject.Provides", "com.google.inject.multibindings.ProvidesIntoMap", "com.google.inject.multibindings.ProvidesIntoSet", "dagger.Provides", "javax.inject.Inject") .map(s::getName) .collect(toImmutableSet())); private static final Supplier<ImmutableSet<Name>> INJECT_ANNOTATIONS = VisitorState.memoize( s -> Stream.of("com.google.inject.Inject", "javax.inject.Inject") .map(s::getName) .collect(toImmutableSet())); private static final String VISIBLE_FOR_TESTING_CAVEAT = " If this is only for testing purposes, consider annotating the element with" + " @VisibleForTesting."; @Override public Description matchMethod(MethodTree tree, VisitorState state) { MethodSymbol symbol = getSymbol(tree); if (annotationsAmong(symbol, FRAMEWORK_ANNOTATIONS.get(state), state).isEmpty()) { return NO_MATCH; } if (findSuperMethod(symbol, state.getTypes()).isPresent()) { return NO_MATCH; } if (hasDirectAnnotationWithSimpleName(tree, "VisibleForTesting")) { return NO_MATCH; } Set<Modifier> badModifiers = intersection(tree.getModifiers().getFlags(), VISIBILITY_MODIFIERS); if (badModifiers.isEmpty()) { return NO_MATCH; } return buildDescription(tree) .addFix( removeModifiers(tree.getModifiers(), state, badModifiers) .orElse(SuggestedFix.emptyFix())) .setMessage( message() + (annotationsAmong(symbol, INJECT_ANNOTATIONS.get(state), state).isEmpty() ? "" : VISIBLE_FOR_TESTING_CAVEAT)) .build(); } }
4,539
41.037037
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TruthConstantAsserts.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.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.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import java.util.regex.Pattern; /** * Points out if Truth Library assert is called on a constant. * * @author bhagwani@google.com (Sumit Bhagwani) */ @BugPattern( summary = "Truth Library assert is called on a constant.", severity = WARNING, tags = StandardTags.FRAGILE_CODE) public class TruthConstantAsserts extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> ASSERT_THAT = staticMethod().onClass("com.google.common.truth.Truth").named("assertThat"); private static final Pattern EQ_NEQ = Pattern.compile("isEqualTo|isNotEqualTo"); private static final Matcher<ExpressionTree> TRUTH_SUBJECT_CALL = instanceMethod() .onDescendantOf("com.google.common.truth.Subject") .withNameMatching(EQ_NEQ) .withParameters("java.lang.Object"); @Override public Description matchMethodInvocation( MethodInvocationTree methodInvocationTree, VisitorState state) { if (methodInvocationTree.getArguments().isEmpty()) { return Description.NO_MATCH; } if (!TRUTH_SUBJECT_CALL.matches(methodInvocationTree, state)) { return Description.NO_MATCH; } ExpressionTree rec = ASTHelpers.getReceiver(methodInvocationTree); if (rec == null) { return Description.NO_MATCH; } if (!ASSERT_THAT.matches(rec, state)) { return Description.NO_MATCH; } ExpressionTree expr = getOnlyElement(((MethodInvocationTree) rec).getArguments()); if (expr == null) { return Description.NO_MATCH; } // check that argument of assertThat is a constant if (ASTHelpers.constValue(expr) == null) { return Description.NO_MATCH; } // check that expectation isn't a constant ExpressionTree expectation = getOnlyElement(methodInvocationTree.getArguments()); if (ASTHelpers.constValue(expectation) != null) { return Description.NO_MATCH; } SuggestedFix fix = SuggestedFix.swap(expr, expectation); return describeMatch(methodInvocationTree, fix); } }
3,508
37.56044
93
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ThreeLetterTimeZoneID.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 com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.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.Tree; import java.time.Duration; import java.time.ZoneId; import java.util.TimeZone; /** * @author awturner@google.com (Andy Turner) */ @BugPattern( summary = "Three-letter time zone identifiers are deprecated, may be ambiguous, and might not do " + "what you intend; the full IANA time zone ID should be used instead.", severity = WARNING) public class ThreeLetterTimeZoneID extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> METHOD_MATCHER = MethodMatchers.staticMethod() .onClass("java.util.TimeZone") .named("getTimeZone") .withParameters("java.lang.String"); private static final Matcher<ExpressionTree> JODATIME_METHOD_MATCHER = MethodMatchers.staticMethod() .onClass("org.joda.time.DateTimeZone") .named("forTimeZone") .withParameters("java.util.TimeZone"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!METHOD_MATCHER.matches(tree, state)) { return Description.NO_MATCH; } String value = ASTHelpers.constValue(tree.getArguments().get(0), String.class); if (value == null) { // Value isn't a compile-time constant, so we can't know if it's unsafe. return Description.NO_MATCH; } Replacement replacement = getReplacement(value, isInJodaTimeContext(state), message()); if (replacement.replacements.isEmpty()) { return Description.NO_MATCH; } Description.Builder builder = buildDescription(tree).setMessage(replacement.message); for (String r : replacement.replacements) { builder.addFix( SuggestedFix.replace(tree.getArguments().get(0), state.getConstantExpression(r))); } return builder.build(); } @VisibleForTesting static Replacement getReplacement(String id, boolean inJodaTimeContext, String message) { switch (id) { case "EST": return handleNonDaylightSavingsZone( inJodaTimeContext, "America/New_York", "Etc/GMT+5", message); case "HST": return handleNonDaylightSavingsZone( inJodaTimeContext, "Pacific/Honolulu", "Etc/GMT+10", message); case "MST": return handleNonDaylightSavingsZone( inJodaTimeContext, "America/Denver", "Etc/GMT+7", message); default: // Fall through, we will handle it below. } String zoneIdReplacement = ZoneId.SHORT_IDS.get(id); if (zoneIdReplacement == null) { return Replacement.NO_REPLACEMENT; } if (id.endsWith("ST")) { TimeZone timeZone = TimeZone.getTimeZone(id); if (timeZone.observesDaylightTime()) { // Make sure that the offset is a whole number of hours; otherwise, there is no Etc/GMT+X // zone. Custom time zones don't need to be handled. long hours = Duration.ofMillis(timeZone.getRawOffset()).toHours(); long millis = Duration.ofHours(hours).toMillis(); if (millis == timeZone.getRawOffset()) { // This is a "X Standard Time" zone, but it observes daylight savings. // Suggest the equivalent zone, as well as a fixed zone at the non-daylight savings // offset. String fixedOffset = String.format("Etc/GMT%+d", -hours); String newDescription = message + "\n\n" + observesDaylightSavingsMessage("TimeZone", zoneIdReplacement, fixedOffset); return new Replacement(newDescription, ImmutableList.of(zoneIdReplacement, fixedOffset)); } } } return new Replacement(message, ImmutableList.of(zoneIdReplacement)); } // American time zones for which the TLA doesn't observe daylight savings. // http://www-01.ibm.com/support/docview.wss?uid=swg21250503#3char // How we handle it depends upon whether we are in a JodaTime context or not. static Replacement handleNonDaylightSavingsZone( boolean inJodaTimeContext, String daylightSavingsZone, String fixedOffset, String message) { if (inJodaTimeContext) { String newDescription = message + "\n\n" + observesDaylightSavingsMessage("DateTimeZone", daylightSavingsZone, fixedOffset); return new Replacement(newDescription, ImmutableList.of(daylightSavingsZone, fixedOffset)); } else { String newDescription = message + "\n\n" + "This TimeZone will not observe daylight savings. " + "If this is intended, use " + fixedOffset + " instead; to observe daylight savings, use " + daylightSavingsZone + "."; return new Replacement(newDescription, ImmutableList.of(fixedOffset, daylightSavingsZone)); } } private static String observesDaylightSavingsMessage( String type, String daylightSavingsZone, String fixedOffset) { return "This " + type + " will observe daylight savings. " + "If this is intended, use " + daylightSavingsZone + " instead; otherwise use " + fixedOffset + "."; } private static boolean isInJodaTimeContext(VisitorState state) { if (state.getPath().getParentPath() != null) { Tree parentLeaf = state.getPath().getParentPath().getLeaf(); if (parentLeaf instanceof ExpressionTree && JODATIME_METHOD_MATCHER.matches((ExpressionTree) parentLeaf, state)) { return true; } } return false; } @VisibleForTesting static final class Replacement { static final Replacement NO_REPLACEMENT = new Replacement("", ImmutableList.of()); final String message; final ImmutableList<String> replacements; Replacement(String message, ImmutableList<String> replacements) { this.message = message; this.replacements = replacements; } } }
7,274
37.903743
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StaticAssignmentInConstructor.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isStatic; 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.AssignmentTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MethodTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; /** Checks for static fields being assigned within constructors. */ @BugPattern( severity = WARNING, summary = "This assignment is to a static field. Mutating static state from a constructor is highly" + " error-prone.") public final class StaticAssignmentInConstructor extends BugChecker implements MethodTreeMatcher { @Override public Description matchMethod(MethodTree tree, VisitorState state) { MethodSymbol methodSymbol = getSymbol(tree); if (!methodSymbol.isConstructor()) { return NO_MATCH; } new TreeScanner<Void, Void>() { @Override public Void visitClass(ClassTree classTree, Void unused) { return null; } @Override public Void visitMethod(MethodTree methodTree, Void unused) { return null; } @Override public Void visitLambdaExpression(LambdaExpressionTree lambdaExpressionTree, Void unused) { return null; } @Override public Void visitAssignment(AssignmentTree assignmentTree, Void unused) { Symbol symbol = getSymbol(assignmentTree.getVariable()); if (symbol != null && isStatic(symbol) && shouldEmitFinding(assignmentTree)) { state.reportMatch(describeMatch(assignmentTree)); } return super.visitAssignment(assignmentTree, null); } private boolean shouldEmitFinding(AssignmentTree assignmentTree) { if (!(assignmentTree.getExpression() instanceof IdentifierTree)) { return true; } IdentifierTree identifierTree = ((IdentifierTree) assignmentTree.getExpression()); return !identifierTree.getName().contentEquals("this"); } }.scan(tree.getBody(), null); return NO_MATCH; } }
3,216
36.406977
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/Finally.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.BreakTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ContinueTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ThrowTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.BreakTree; import com.sun.source.tree.ContinueTree; import com.sun.source.tree.LabeledStatementTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.SwitchTree; import com.sun.source.tree.ThrowTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TryTree; import com.sun.tools.javac.tree.JCTree.JCBreak; import com.sun.tools.javac.tree.JCTree.JCContinue; import com.sun.tools.javac.util.Name; /** * Matches the behaviour of javac's finally Xlint warning. * * <p>1) Any return statement in a finally block is an error 2) An uncaught throw statement in a * finally block is an error. We can't always know whether a specific exception will be caught, so * we report errors for throw statements that are not contained in a try with at least one catch * block. 3) A continue statement in a finally block is an error if it breaks out of a (possibly * labeled) loop that is outside the enclosing finally. 4) A break statement in a finally block is * an error if it breaks out of a (possibly labeled) loop or a switch statement that is outside the * enclosing finally. * * @author eaftan@google.com (Eddie Aftandilian) * @author cushon@google.com (Liam Miller-Cushon) */ @BugPattern( altNames = {"finally", "ThrowFromFinallyBlock"}, summary = "If you return or throw from a finally, then values returned or thrown from the" + " try-catch block will be ignored. Consider using try-with-resources instead.", severity = WARNING, tags = StandardTags.FRAGILE_CODE) public class Finally extends BugChecker implements ContinueTreeMatcher, ThrowTreeMatcher, BreakTreeMatcher, ReturnTreeMatcher { @Override public Description matchContinue(ContinueTree tree, VisitorState state) { if (new FinallyJumpMatcher((JCContinue) tree).matches(tree, state)) { return describeMatch(tree); } return Description.NO_MATCH; } @Override public Description matchBreak(BreakTree tree, VisitorState state) { if (new FinallyJumpMatcher((JCBreak) tree).matches(tree, state)) { return describeMatch(tree); } return Description.NO_MATCH; } @Override public Description matchThrow(ThrowTree tree, VisitorState state) { if (new FinallyThrowMatcher().matches(tree, state)) { return describeMatch(tree); } return Description.NO_MATCH; } @Override public Description matchReturn(ReturnTree tree, VisitorState state) { if (new FinallyCompletionMatcher<ReturnTree>().matches(tree, state)) { return describeMatch(tree); } return Description.NO_MATCH; } private enum MatchResult { KEEP_LOOKING, NO_MATCH, FOUND_ERROR; } /** * Base class for all finally matchers. Walks up the tree of enclosing statements and reports an * error if it finds an enclosing finally block. * * @param <T> The type of the tree node to match against */ private static class FinallyCompletionMatcher<T extends StatementTree> implements Matcher<T> { /** * Matches a StatementTree type by walking that statement's ancestor chain. * * @return true if an error is found. */ @Override public boolean matches(T tree, VisitorState state) { Tree prevTree = null; for (Tree leaf : state.getPath()) { switch (leaf.getKind()) { case METHOD: case LAMBDA_EXPRESSION: case CLASS: return false; default: break; } MatchResult mr = matchAncestor(leaf, prevTree); if (mr != MatchResult.KEEP_LOOKING) { return mr == MatchResult.FOUND_ERROR; } prevTree = leaf; } return false; } /** Match a tree in the ancestor chain given the ancestor's immediate descendant. */ protected MatchResult matchAncestor(Tree leaf, Tree prevTree) { if (leaf instanceof TryTree) { TryTree tryTree = (TryTree) leaf; if (tryTree.getFinallyBlock() != null && tryTree.getFinallyBlock().equals(prevTree)) { return MatchResult.FOUND_ERROR; } } return MatchResult.KEEP_LOOKING; } } /** Ancestor matcher for statements that break or continue out of a finally block. */ private static class FinallyJumpMatcher extends FinallyCompletionMatcher<StatementTree> { private final Name label; private final JumpType jumpType; private enum JumpType { BREAK, CONTINUE } public FinallyJumpMatcher(JCContinue jcContinue) { this.label = jcContinue.getLabel(); this.jumpType = JumpType.CONTINUE; } public FinallyJumpMatcher(JCBreak jcBreak) { this.label = jcBreak.getLabel(); this.jumpType = JumpType.BREAK; } /** * The target of a jump statement (break or continue) is (1) the enclosing loop if the jump is * unlabeled (2) the enclosing LabeledStatementTree with matching label if the jump is labeled * (3) the enclosing switch statement if the jump is a break * * <p>If the target of a break or continue statement is encountered before reaching a finally * block, return NO_MATCH. */ @Override protected MatchResult matchAncestor(Tree leaf, Tree prevTree) { // (1) if (label == null) { switch (leaf.getKind()) { case WHILE_LOOP: case DO_WHILE_LOOP: case FOR_LOOP: case ENHANCED_FOR_LOOP: return MatchResult.NO_MATCH; default: break; } } // (2) if (label != null && leaf instanceof LabeledStatementTree && label.equals(((LabeledStatementTree) leaf).getLabel())) { return MatchResult.NO_MATCH; } // (3) if (jumpType == JumpType.BREAK && leaf instanceof SwitchTree) { return MatchResult.NO_MATCH; } return super.matchAncestor(leaf, prevTree); } } /** Match throw statements that are not caught. */ private static class FinallyThrowMatcher extends FinallyCompletionMatcher<ThrowTree> { @Override protected MatchResult matchAncestor(Tree tree, Tree prevTree) { if (tree instanceof TryTree) { TryTree tryTree = (TryTree) tree; if (tryTree.getBlock().equals(prevTree) && !tryTree.getCatches().isEmpty()) { // The current ancestor is a try block with associated catch blocks. return MatchResult.NO_MATCH; } } return super.matchAncestor(tree, prevTree); } } }
7,804
33.082969
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ComparisonOutOfRange.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.fixes.SuggestedFix.replace; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.suppliers.Suppliers.BYTE_TYPE; import static com.google.errorprone.suppliers.Suppliers.CHAR_TYPE; import static com.google.errorprone.suppliers.Suppliers.INT_TYPE; import static com.google.errorprone.suppliers.Suppliers.LONG_TYPE; import static com.google.errorprone.suppliers.Suppliers.SHORT_TYPE; import static com.google.errorprone.util.ASTHelpers.constValue; import static com.google.errorprone.util.ASTHelpers.isSameType; import static com.google.errorprone.util.ASTHelpers.matchBinaryTree; import static com.sun.source.tree.Tree.Kind.EQUAL_TO; import static com.sun.source.tree.Tree.Kind.NOT_EQUAL_TO; import static java.lang.String.format; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Range; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Type; import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.function.IntPredicate; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Comparison to value that is out of range for the compared type", explanation = "This checker looks for comparisons to values that are too high or too low for the compared" + " type. For example, bytes may have a value in the range " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE + ". Comparing a byte for equality with a value outside that range will always evaluate" + " to false and usually indicates an error in the code.", severity = ERROR) public class ComparisonOutOfRange extends BugChecker implements BinaryTreeMatcher { @Override public Description matchBinary(BinaryTree tree, VisitorState state) { BOUNDS_FOR_PRIMITIVES.forEach( (testedValueType, range) -> { // Match trees that have one constant operand and another of the specified type. List<ExpressionTree> binaryTreeMatches = matchBinaryTree( tree, Arrays.asList( ComparisonOutOfRange::hasNumericConstantValue, anyOf( isSameType(testedValueType), isSameType(s -> s.getTypes().boxedTypeOrType(testedValueType.get(s))))), state); if (binaryTreeMatches == null) { return; } Tree constant = binaryTreeMatches.get(0); Number numericConstantValue = constValue(constant) instanceof Character ? Long.valueOf(((Character) constValue(constant)).charValue()) : (Number) constValue(constant); // We define a class whose first method we'll call immediately. // This lets us have a bunch of fields and parameters in scope for our helper methods. class MatchAttempt<N extends Number & Comparable<? super N>> { final N constantValue; final N minValue; final N maxValue; MatchAttempt(Function<Number, N> numericPromotion) { this.constantValue = numericPromotion.apply(numericConstantValue); this.minValue = numericPromotion.apply(range.lowerEndpoint()); this.maxValue = numericPromotion.apply(range.upperEndpoint()); } Description matchConstantResult() { switch (tree.getKind()) { case EQUAL_TO: return matchOutOfBounds(/* willEvaluateTo= */ false); case NOT_EQUAL_TO: return matchOutOfBounds(/* willEvaluateTo= */ true); case LESS_THAN: return matchMinAndMaxHaveSameResult(cmp -> cmp < 0); case LESS_THAN_EQUAL: return matchMinAndMaxHaveSameResult(cmp -> cmp <= 0); case GREATER_THAN: return matchMinAndMaxHaveSameResult(cmp -> cmp > 0); case GREATER_THAN_EQUAL: return matchMinAndMaxHaveSameResult(cmp -> cmp >= 0); default: return NO_MATCH; } } Description matchOutOfBounds(boolean willEvaluateTo) { return constantValue.compareTo(minValue) < 0 || constantValue.compareTo(maxValue) > 0 ? describeMatch(willEvaluateTo) : NO_MATCH; } /* * If `minValue < constant` and `maxValue < constant` are both true, then `anything < * constant` is true. * * The same holds if we replace "<" with another inequality operator, if we replace * "true" with "false," or if we move "constant" to the left operand. */ Description matchMinAndMaxHaveSameResult(IntPredicate op) { boolean minResult; boolean maxResult; if (constant == tree.getRightOperand()) { minResult = op.test(minValue.compareTo(constantValue)); maxResult = op.test(maxValue.compareTo(constantValue)); } else { minResult = op.test(constantValue.compareTo(minValue)); maxResult = op.test(constantValue.compareTo(maxValue)); } return minResult == maxResult ? describeMatch(/* willEvaluateTo= */ minResult) : NO_MATCH; } /** * Suggested fixes are as follows. For the byte equality case, convert the constant to * its byte representation. For example, "255" becomes "-1. For other cases, replace the * comparison with "true"/"false" since it's not clear what was intended and that is * semantically equivalent. * * <p>TODO(eaftan): Suggested fixes don't handle side-effecting expressions, such as (d * = reader.read()) == -1. Maybe add special case handling for assignments. */ Description describeMatch(boolean willEvaluateTo) { boolean byteEqualityMatch = isSameType(testedValueType.get(state), state.getSymtab().byteType, state) && (tree.getKind() == EQUAL_TO || tree.getKind() == NOT_EQUAL_TO); return buildDescription(tree) .addFix( byteEqualityMatch ? replace(constant, Byte.toString(constantValue.byteValue())) : replace(tree, Boolean.toString(willEvaluateTo))) .setMessage( format( "%ss may have a value in the range %d to %d; " + "therefore, this comparison to %s will always evaluate to %s", testedValueType.get(state).tsym.name, range.lowerEndpoint(), range.upperEndpoint(), // TODO(cpovirk): Would it be better to show numericConstantValue? state.getSourceForNode(constant), willEvaluateTo)) .build(); } } // JLS 5.6.2 - Binary Numeric Promotion: // - If either is double, other is converted to double. // - If either is float, other is converted to float. // - If either is long, other is converted to long. // - Otherwise, both are converted to int. // // Here, we're looking only at comparisons between an integral type and some constant. // Thus, the only value that can be floating-point is the constant, and that's the // only case in which we promote to a floating-point type. // // We promote both the constant and the bounds. // // Promoting the constant changes nothing: It it was integral, it remains integral and // still has the same value, even if it's represented as a larger type. If it was // floating-point, it's either untouched or promoted from float to double, which gives // it a more precise type that it can't take advantage of because its source was still // a float. // // Promoting the bound *can* change its value in the case of promoting an integral // value to a floating-point value: For example, Integer.MAX_VALUE is rounded up to // 2^31, regardless of whether we're promoting to float or to double. Thus, an // equality comparison between an int and a float/double value of 2^31 is allowed, // since it can be either true or false, even though you'd need to move from int to // long in order to actually hold the value 2^31. // // Thus: // // When we promote integral types, we can always promote to long. // // When we promote to floating-point types, I *think* we could get away with always // promoting to double. That would work because the bounds of int, etc. round to the // same value, whether we're promoting them to float or to double (thanks to how close // the bounds are to a power of two). However, that feels scarier to rely on, // especially if we might ever use this promotion code for other purposes, like to // determine whether a value promoted to float has any fractional part. MatchAttempt<?> matchAttempt; if (numericConstantValue instanceof Double) { matchAttempt = new MatchAttempt<>(Number::doubleValue); } else if (numericConstantValue instanceof Float) { matchAttempt = new MatchAttempt<>(Number::floatValue); } else { // It's an Integer or a Long (sometimes because we replaced a Character with a Long). matchAttempt = new MatchAttempt<>(Number::longValue); } state.reportMatch(matchAttempt.matchConstantResult()); }); return NO_MATCH; } private static final ImmutableMap<Supplier<Type>, Range<Long>> BOUNDS_FOR_PRIMITIVES = ImmutableMap.of( BYTE_TYPE, range(Byte.MIN_VALUE, Byte.MAX_VALUE), CHAR_TYPE, range(Character.MIN_VALUE, Character.MAX_VALUE), SHORT_TYPE, range(Short.MIN_VALUE, Short.MAX_VALUE), INT_TYPE, range(Integer.MIN_VALUE, Integer.MAX_VALUE), LONG_TYPE, range(Long.MIN_VALUE, Long.MAX_VALUE)); private static Range<Long> range(long min, long max) { return Range.closed(min, max); } private static boolean hasNumericConstantValue(ExpressionTree tree, VisitorState state) { return constValue(tree) instanceof Number || constValue(tree) instanceof Character; } }
12,171
47.883534
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SerializableReads.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 com.google.common.collect.ImmutableSet; /** List of banned methods for {@link BanSerializableRead}. */ public final class SerializableReads { private SerializableReads() {} public static final ImmutableSet<String> BANNED_OBJECT_INPUT_STREAM_METHODS = ImmutableSet.of( // Prevent reading objects unsafely into memory. "readObject", // This is the same, the default value. "defaultReadObject", // This is for trusted subclasses. "readObjectOverride", // Ultimately, a lot of the safety worries come from being able to construct arbitrary // classes via reading in class descriptors. I don't think anyone will bother calling this // directly, but I don't see any reason not to block it. "readClassDescriptor", // These are basically the same as above. "resolveClass", "resolveObject"); }
1,592
34.4
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MissingTestCall.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.Streams.findLast; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.streamReceivers; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ReturnTree; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; import java.util.HashSet; import java.util.Set; import javax.annotation.Nullable; import javax.lang.model.element.ElementKind; /** * Matches test helpers which require a terminating method to be called. * * @author ghm@google.com (Graeme Morgan) */ @BugPattern( summary = "A terminating method call is required for a test helper to have any effect.", severity = ERROR) public final class MissingTestCall extends BugChecker implements MethodTreeMatcher { private static final ImmutableSet<MethodPairing> PAIRINGS = ImmutableSet.of( MethodPairing.of( "EqualsTester", instanceMethod() .onDescendantOf("com.google.common.testing.EqualsTester") .named("addEqualityGroup"), instanceMethod() .onDescendantOf("com.google.common.testing.EqualsTester") .named("testEquals")), MethodPairing.of( "BugCheckerRefactoringTestHelper", instanceMethod() .onDescendantOf("com.google.errorprone.BugCheckerRefactoringTestHelper") .namedAnyOf( "addInput", "addInputLines", "addInputFile", "addOutput", "addOutputLines", "addOutputFile", "expectUnchanged"), instanceMethod() .onDescendantOf("com.google.errorprone.BugCheckerRefactoringTestHelper") .named("doTest")), MethodPairing.of( "CompilationTestHelper", instanceMethod() .onDescendantOf("com.google.errorprone.CompilationTestHelper") .namedAnyOf("addSourceLines", "addSourceFile", "expectNoDiagnostics"), instanceMethod() .onDescendantOf("com.google.errorprone.CompilationTestHelper") .named("doTest"))); @Override public Description matchMethod(MethodTree tree, VisitorState state) { ImmutableSet<MethodPairing> pairings = PAIRINGS; Set<MethodPairing> required = new HashSet<>(); Set<MethodPairing> called = new HashSet<>(); new TreePathScanner<Void, Void>() { @Override public Void visitMethodInvocation(MethodInvocationTree node, Void unused) { for (MethodPairing pairing : pairings) { VisitorState stateWithPath = state.withPath(getCurrentPath()); if (pairing.ifCall().matches(node, stateWithPath)) { if (!isField(getUltimateReceiver(node)) && stateWithPath.findPathToEnclosing(ReturnTree.class) == null) { required.add(pairing); } } if (pairing.mustCall().matches(node, stateWithPath)) { called.add(pairing); } } return super.visitMethodInvocation(node, null); } }.scan(state.getPath(), null); return Sets.difference(required, called).stream() .findFirst() .map( p -> buildDescription(tree) .setMessage( String.format( "%s requires a terminating method call to have any effect.", p.name())) .build()) .orElse(NO_MATCH); } @Nullable private static ExpressionTree getUltimateReceiver(ExpressionTree tree) { return findLast(streamReceivers(tree)).orElse(null); } private static boolean isField(@Nullable ExpressionTree tree) { if (!(tree instanceof IdentifierTree)) { return false; } Symbol symbol = getSymbol(tree); return symbol != null && symbol.getKind() == ElementKind.FIELD; } @AutoValue abstract static class MethodPairing { abstract String name(); abstract Matcher<ExpressionTree> ifCall(); abstract Matcher<ExpressionTree> mustCall(); private static MethodPairing of( String name, Matcher<ExpressionTree> ifCall, Matcher<ExpressionTree> mustCall) { return new AutoValue_MissingTestCall_MethodPairing(name, ifCall, mustCall); } } }
5,877
37.418301
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.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.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Strings.nullToEmpty; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.getLast; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.SERIALIZATION_METHODS; 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.getType; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.isStatic; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static com.google.errorprone.util.ASTHelpers.shouldKeep; import static com.google.errorprone.util.SideEffectAnalysis.hasSideEffect; 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 com.google.auto.value.AutoValue; import com.google.common.base.Ascii; import com.google.common.collect.ArrayListMultimap; 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.Iterables; import com.google.common.collect.ListMultimap; import com.google.common.collect.Multimaps; 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.CompilationUnitTreeMatcher; 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.suppliers.Suppliers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ArrayAccessTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.DoWhileLoopTree; import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ErroneousTree; import com.sun.source.tree.ExpressionStatementTree; 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.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.TryTree; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.VariableTree; import com.sun.source.tree.WhileLoopTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAssign; import com.sun.tools.javac.tree.JCTree.JCAssignOp; import com.sun.tools.javac.util.Position; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nullable; import javax.inject.Inject; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.type.NullType; /** Bugpattern to detect unused declarations. */ @BugPattern( altNames = {"unused", "UnusedParameters"}, summary = "Unused.", severity = WARNING, documentSuppression = false) public final class UnusedVariable extends BugChecker implements CompilationUnitTreeMatcher { private static final String EXEMPT_PREFIX = "unused"; private static final ImmutableSet<String> EXEMPT_NAMES = ImmutableSet.of("ignored"); /** * The set of annotation full names which exempt annotated element from being reported as unused. */ private static final ImmutableSet<String> EXEMPTING_VARIABLE_ANNOTATIONS = ImmutableSet.of( "javax.persistence.Basic", "javax.persistence.Column", "javax.persistence.Id", "javax.persistence.Version", "javax.xml.bind.annotation.XmlElement", "org.junit.Rule", "org.openqa.selenium.support.FindAll", "org.openqa.selenium.support.FindBy", "org.openqa.selenium.support.FindBys", "org.apache.beam.sdk.transforms.DoFn.TimerId", "org.apache.beam.sdk.transforms.DoFn.StateId"); // TODO(ghm): Find a sensible place to dedupe this with UnnecessarilyVisible. private static final ImmutableSet<String> ANNOTATIONS_INDICATING_PARAMETERS_SHOULD_BE_CHECKED = ImmutableSet.of( "com.google.inject.Inject", "com.google.inject.Provides", "com.google.inject.multibindings.ProvidesIntoMap", "com.google.inject.multibindings.ProvidesIntoSet", "dagger.Provides", "javax.inject.Inject"); private final ImmutableSet<String> methodAnnotationsExemptingParameters; /** The set of types exempting a type that is extending or implementing them. */ private static final ImmutableSet<String> EXEMPTING_SUPER_TYPES = ImmutableSet.of(); /** The set of types exempting a field of type extending them. */ private static final ImmutableSet<String> EXEMPTING_FIELD_SUPER_TYPES = ImmutableSet.of("org.junit.rules.TestRule"); private static final ImmutableSet<String> SPECIAL_FIELDS = ImmutableSet.of( "serialVersionUID", // TAG fields are used by convention in Android apps. "TAG"); private final boolean reportInjectedFields; @Inject UnusedVariable(ErrorProneFlags flags) { ImmutableSet.Builder<String> methodAnnotationsExemptingParameters = ImmutableSet.<String>builder().add("org.robolectric.annotation.Implementation"); flags .getList("Unused:methodAnnotationsExemptingParameters") .ifPresent(methodAnnotationsExemptingParameters::addAll); this.methodAnnotationsExemptingParameters = methodAnnotationsExemptingParameters.build(); this.reportInjectedFields = flags.getBoolean("Unused:ReportInjectedFields").orElse(false); } @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { // We will skip reporting on the whole compilation if there are any native methods found. // Use a TreeScanner to find all local variables and fields. if (hasNativeMethods(tree)) { return Description.NO_MATCH; } VariableFinder variableFinder = new VariableFinder(state); variableFinder.scan(state.getPath(), null); // Map of symbols to variable declarations. Initially this is a map of all of the local variable // and fields. As we go we remove those variables which are used. Map<Symbol, TreePath> unusedElements = variableFinder.unusedElements; // Whether a symbol should only be checked for reassignments (e.g. public methods' parameters). Set<Symbol> onlyCheckForReassignments = variableFinder.onlyCheckForReassignments; // Map of symbols to their usage sites. In this map we also include the definition site in // addition to all the trees where symbol is used. This map is designed to keep the usage sites // of variables (parameters, fields, locals). // // We populate this map when analyzing the unused variables and then use it to generate // appropriate fixes for them. ListMultimap<Symbol, TreePath> usageSites = variableFinder.usageSites; FilterUsedVariables filterUsedVariables = new FilterUsedVariables(unusedElements, usageSites); filterUsedVariables.scan(state.getPath(), null); // Keeps track of whether a symbol was _ever_ used (between reassignments). Set<Symbol> isEverUsed = filterUsedVariables.isEverUsed; List<UnusedSpec> unusedSpecs = filterUsedVariables.unusedSpecs; // Add the left-over unused variables... for (Map.Entry<Symbol, TreePath> entry : unusedElements.entrySet()) { unusedSpecs.add( UnusedSpec.of(entry.getKey(), entry.getValue(), usageSites.get(entry.getKey()), null)); } ImmutableListMultimap<Symbol, UnusedSpec> unusedSpecsBySymbol = Multimaps.index(unusedSpecs, UnusedSpec::symbol); for (Map.Entry<Symbol, Collection<UnusedSpec>> entry : unusedSpecsBySymbol.asMap().entrySet()) { Symbol unusedSymbol = entry.getKey(); Collection<UnusedSpec> specs = entry.getValue(); ImmutableList<TreePath> allUsageSites = specs.stream().flatMap(u -> u.usageSites().stream()).collect(toImmutableList()); if (!unusedElements.containsKey(unusedSymbol)) { isEverUsed.add(unusedSymbol); } SuggestedFix makeFirstAssignmentDeclaration = makeAssignmentDeclaration(unusedSymbol, specs, allUsageSites, state); // Don't complain if this is a public method and we only overwrote it once. if (onlyCheckForReassignments.contains(unusedSymbol) && specs.size() <= 1) { continue; } Tree unused = specs.iterator().next().assignmentPath().getLeaf(); VarSymbol symbol = (VarSymbol) unusedSymbol; ImmutableList<SuggestedFix> fixes; if (symbol.getKind() == ElementKind.PARAMETER && !onlyCheckForReassignments.contains(unusedSymbol) && !isEverUsed.contains(unusedSymbol)) { fixes = buildUnusedParameterFixes(symbol, allUsageSites, state); } else { fixes = buildUnusedVarFixes(symbol, allUsageSites, state); } state.reportMatch( buildDescription(unused) .setMessage( String.format( "%s %s '%s' is never read.", isEverUsed.contains(symbol) ? "This assignment to the" : "The", describeVariable(symbol), symbol.name)) .addAllFixes( fixes.stream() .map( f -> SuggestedFix.builder() .merge(makeFirstAssignmentDeclaration) .merge(f) .build()) .collect(toImmutableList())) .build()); } return Description.NO_MATCH; } private static SuggestedFix makeAssignmentDeclaration( Symbol unusedSymbol, Collection<UnusedSpec> specs, ImmutableList<TreePath> allUsageSites, VisitorState state) { if (unusedSymbol.getKind() != ElementKind.LOCAL_VARIABLE) { return SuggestedFix.emptyFix(); } Optional<VariableTree> removedVariableTree = allUsageSites.stream() .filter(tp -> tp.getLeaf() instanceof VariableTree) .findFirst() .map(tp -> (VariableTree) tp.getLeaf()); // Find the first reassignment which wasn't only used by an ultimately unused assignment. If // there is one, it should become a variable declaration. Optional<AssignmentTree> reassignment = specs.stream() .map(UnusedSpec::terminatingAssignment) .flatMap(Streams::stream) .filter( a -> allUsageSites.stream() .noneMatch( tp -> tp.getLeaf() instanceof ExpressionStatementTree && ((ExpressionStatementTree) tp.getLeaf()) .getExpression() .equals(a))) .findFirst(); if (removedVariableTree.isPresent() && reassignment.isPresent()) { return SuggestedFix.prefixWith( // not needed if top-level statement reassignment.get(), state.getSourceForNode(removedVariableTree.get().getType()) + " "); } return SuggestedFix.emptyFix(); } private static String describeVariable(VarSymbol symbol) { switch (symbol.getKind()) { case FIELD: return "field"; case LOCAL_VARIABLE: return "local variable"; case PARAMETER: return "parameter"; default: return "variable"; } } private static boolean hasNativeMethods(CompilationUnitTree tree) { AtomicBoolean hasAnyNativeMethods = new AtomicBoolean(false); new TreeScanner<Void, Void>() { @Override public Void visitMethod(MethodTree tree, Void unused) { if (tree.getModifiers().getFlags().contains(Modifier.NATIVE)) { hasAnyNativeMethods.set(true); } return null; } }.scan(tree, null); return hasAnyNativeMethods.get(); } // https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-ExpressionStatement private static final ImmutableSet<Tree.Kind> TOP_LEVEL_EXPRESSIONS = ImmutableSet.of( Tree.Kind.ASSIGNMENT, Tree.Kind.PREFIX_INCREMENT, Tree.Kind.PREFIX_DECREMENT, Tree.Kind.POSTFIX_INCREMENT, Tree.Kind.POSTFIX_DECREMENT, Tree.Kind.METHOD_INVOCATION, Tree.Kind.NEW_CLASS); private static boolean needsBlock(TreePath path) { Tree leaf = path.getLeaf(); class Visitor extends SimpleTreeVisitor<Boolean, Void> { @Override public Boolean visitIf(IfTree tree, Void unused) { return tree.getThenStatement() == leaf || tree.getElseStatement() == leaf; } @Override public Boolean visitDoWhileLoop(DoWhileLoopTree tree, Void unused) { return tree.getStatement() == leaf; } @Override public Boolean visitWhileLoop(WhileLoopTree tree, Void unused) { return tree.getStatement() == leaf; } @Override public Boolean visitForLoop(ForLoopTree tree, Void unused) { return tree.getStatement() == leaf; } @Override public Boolean visitEnhancedForLoop(EnhancedForLoopTree tree, Void unused) { return tree.getStatement() == leaf; } } return firstNonNull(path.getParentPath().getLeaf().accept(new Visitor(), null), false); } private static ImmutableList<SuggestedFix> buildUnusedVarFixes( Symbol varSymbol, List<TreePath> usagePaths, VisitorState state) { // Don't suggest a fix for fields annotated @Inject: we can warn on them, but they *could* be // used outside the class. if (ASTHelpers.hasDirectAnnotationWithSimpleName(varSymbol, "Inject")) { return ImmutableList.of(); } ElementKind varKind = varSymbol.getKind(); boolean encounteredSideEffects = false; SuggestedFix.Builder keepSideEffectsFix = SuggestedFix.builder().setShortDescription("remove unused variable"); SuggestedFix.Builder removeSideEffectsFix = SuggestedFix.builder().setShortDescription("remove unused variable and any side effects"); for (TreePath usagePath : usagePaths) { StatementTree statement = (StatementTree) usagePath.getLeaf(); if (statement.getKind() == Kind.VARIABLE) { if (getSymbol(statement).getKind() == ElementKind.PARAMETER) { continue; } VariableTree variableTree = (VariableTree) statement; ExpressionTree initializer = variableTree.getInitializer(); if (hasSideEffect(initializer) && TOP_LEVEL_EXPRESSIONS.contains(initializer.getKind())) { encounteredSideEffects = true; if (varKind == ElementKind.FIELD) { String newContent = String.format( "%s{ %s; }", isStatic(varSymbol) ? "static " : "", state.getSourceForNode(initializer)); keepSideEffectsFix.merge( SuggestedFixes.replaceIncludingComments(usagePath, newContent, state)); removeSideEffectsFix.replace(statement, ""); } else { keepSideEffectsFix.replace( statement, String.format("%s;", state.getSourceForNode(initializer))); removeSideEffectsFix.replace(statement, ""); } } else if (isEnhancedForLoopVar(usagePath)) { String modifiers = nullToEmpty( variableTree.getModifiers() == null ? null : state.getSourceForNode(variableTree.getModifiers())); String newContent = String.format( "%s%s unused", modifiers.isEmpty() ? "" : (modifiers + " "), state.getSourceForNode(variableTree.getType())); // The new content for the second fix should be identical to the content for the first // fix in this case because we can't just remove the enhanced for loop variable. keepSideEffectsFix.replace(variableTree, newContent); removeSideEffectsFix.replace(variableTree, newContent); } else { String replacement = needsBlock(usagePath) ? "{}" : ""; keepSideEffectsFix.merge( SuggestedFixes.replaceIncludingComments(usagePath, replacement, state)); removeSideEffectsFix.merge( SuggestedFixes.replaceIncludingComments(usagePath, replacement, state)); } continue; } else if (statement.getKind() == Kind.EXPRESSION_STATEMENT) { JCTree tree = (JCTree) ((ExpressionStatementTree) statement).getExpression(); if (tree instanceof CompoundAssignmentTree) { if (hasSideEffect(((CompoundAssignmentTree) tree).getExpression())) { // If it's a compound assignment, there's no reason we'd want to remove the expression, // so don't set `encounteredSideEffects` based on this usage. SuggestedFix replacement = SuggestedFix.replace( tree.getStartPosition(), ((JCAssignOp) tree).getExpression().getStartPosition(), ""); keepSideEffectsFix.merge(replacement); removeSideEffectsFix.merge(replacement); continue; } } else if (tree instanceof AssignmentTree) { if (hasSideEffect(((AssignmentTree) tree).getExpression())) { encounteredSideEffects = true; keepSideEffectsFix.replace( tree.getStartPosition(), ((JCAssign) tree).getExpression().getStartPosition(), ""); removeSideEffectsFix.replace(statement, ""); continue; } } } String replacement = needsBlock(usagePath) ? "{}" : ""; keepSideEffectsFix.replace(statement, replacement); removeSideEffectsFix.replace(statement, replacement); } return encounteredSideEffects ? ImmutableList.of(removeSideEffectsFix.build(), keepSideEffectsFix.build()) : ImmutableList.of(keepSideEffectsFix.build()); } private static ImmutableList<SuggestedFix> buildUnusedParameterFixes( Symbol varSymbol, List<TreePath> usagePaths, VisitorState state) { MethodSymbol methodSymbol = (MethodSymbol) varSymbol.owner; int index = methodSymbol.params.indexOf(varSymbol); SuggestedFix.Builder fix = SuggestedFix.builder(); for (TreePath path : usagePaths) { fix.delete(path.getLeaf()); } new TreePathScanner<Void, Void>() { @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { if (getSymbol(tree).equals(methodSymbol)) { removeByIndex(tree.getArguments()); } return super.visitMethodInvocation(tree, null); } @Override public Void visitMethod(MethodTree tree, Void unused) { if (getSymbol(tree).equals(methodSymbol)) { removeByIndex(tree.getParameters()); } return super.visitMethod(tree, null); } private void removeByIndex(List<? extends Tree> trees) { if (index >= trees.size()) { // possible when removing a varargs parameter with no corresponding formal parameters return; } if (trees.size() == 1) { Tree tree = getOnlyElement(trees); if (getStartPosition(tree) == -1 || state.getEndPosition(tree) == -1) { // TODO(b/118437729): handle bogus source positions in enum declarations return; } fix.delete(tree); return; } int startPos; int endPos; if (index >= 1) { startPos = state.getEndPosition(trees.get(index - 1)); endPos = state.getEndPosition(trees.get(index)); } else { startPos = getStartPosition(trees.get(index)); endPos = getStartPosition(trees.get(index + 1)); } if (index == methodSymbol.params().size() - 1 && methodSymbol.isVarArgs()) { endPos = state.getEndPosition(getLast(trees)); } if (startPos == Position.NOPOS || endPos == Position.NOPOS) { // TODO(b/118437729): handle bogus source positions in enum declarations return; } fix.replace(startPos, endPos, ""); } }.scan(state.getPath().getCompilationUnit(), null); return ImmutableList.of(fix.build()); } private static boolean isEnhancedForLoopVar(TreePath variablePath) { Tree tree = variablePath.getLeaf(); Tree parent = variablePath.getParentPath().getLeaf(); return parent instanceof EnhancedForLoopTree && ((EnhancedForLoopTree) parent).getVariable() == tree; } /** * Looks at the list of {@code annotations} and see if there is any annotation which exists {@code * exemptingAnnotations}. */ private static boolean exemptedByAnnotation(List<? extends AnnotationTree> annotations) { for (AnnotationTree annotation : annotations) { Type annotationType = ASTHelpers.getType(annotation); if (annotationType == null) { continue; } TypeSymbol tsym = annotationType.tsym; if (EXEMPTING_VARIABLE_ANNOTATIONS.contains(tsym.getQualifiedName().toString())) { return true; } } return false; } private static boolean exemptedByName(Name name) { String nameString = name.toString(); return Ascii.toLowerCase(nameString).startsWith(EXEMPT_PREFIX) || EXEMPT_NAMES.contains(nameString); } private class VariableFinder extends TreePathScanner<Void, Void> { private final Map<Symbol, TreePath> unusedElements = new HashMap<>(); private final Set<Symbol> onlyCheckForReassignments = new HashSet<>(); private final ListMultimap<Symbol, TreePath> usageSites = ArrayListMultimap.create(); private final VisitorState state; private VariableFinder(VisitorState state) { this.state = state; } @Override public Void visitVariable(VariableTree variableTree, Void unused) { if (exemptedByName(variableTree.getName())) { return null; } if (isSuppressed(variableTree, state)) { return null; } VarSymbol symbol = getSymbol(variableTree); if (symbol.getKind() == ElementKind.FIELD && symbol.getSimpleName().contentEquals("CREATOR") && isSubtype(symbol.type, PARCELABLE_CREATOR.get(state), state)) { return null; } if (symbol.getKind() == ElementKind.FIELD && exemptedFieldBySuperType(getType(variableTree), state)) { return null; } super.visitVariable(variableTree, null); // Return if the element is exempted by an annotation. if (exemptedByAnnotation(variableTree.getModifiers().getAnnotations()) || shouldKeep(variableTree)) { return null; } switch (symbol.getKind()) { case FIELD: // We are only interested in private fields and those which are not special. if (isFieldEligibleForChecking(variableTree, symbol)) { unusedElements.put(symbol, getCurrentPath()); usageSites.put(symbol, getCurrentPath()); } break; case LOCAL_VARIABLE: unusedElements.put(symbol, getCurrentPath()); usageSites.put(symbol, getCurrentPath()); break; case PARAMETER: // ignore the receiver parameter if (variableTree.getName().contentEquals("this")) { return null; } unusedElements.put(symbol, getCurrentPath()); if (!isParameterSubjectToAnalysis(symbol)) { onlyCheckForReassignments.add(symbol); } break; default: break; } return null; } private boolean exemptedFieldBySuperType(Type type, VisitorState state) { return EXEMPTING_FIELD_SUPER_TYPES.stream() .anyMatch(t -> isSubtype(type, state.getTypeFromString(t), state)); } private boolean isFieldEligibleForChecking(VariableTree variableTree, VarSymbol symbol) { if (reportInjectedFields && variableTree.getModifiers().getFlags().isEmpty() && ASTHelpers.hasDirectAnnotationWithSimpleName(variableTree, "Inject")) { return true; } if ((symbol.flags() & RECORD_FLAG) == RECORD_FLAG) { return false; } return canBeRemoved(symbol) && !SPECIAL_FIELDS.contains(symbol.getSimpleName().toString()); } private static final long RECORD_FLAG = 1L << 61; /** Returns whether {@code sym} can be removed without updating call sites in other files. */ private boolean isParameterSubjectToAnalysis(Symbol sym) { checkArgument(sym.getKind() == ElementKind.PARAMETER); Symbol enclosingMethod = sym.owner; for (String annotationName : methodAnnotationsExemptingParameters) { if (hasAnnotation(enclosingMethod, annotationName, state)) { return false; } } if (ANNOTATIONS_INDICATING_PARAMETERS_SHOULD_BE_CHECKED.stream() .anyMatch(a -> hasAnnotation(enclosingMethod, a, state))) { return true; } return enclosingMethod.getModifiers().contains(Modifier.PRIVATE); } @Override public Void visitTry(TryTree node, Void unused) { // Skip resources, as while these may not be referenced, they are used. scan(node.getBlock(), null); scan(node.getCatches(), null); scan(node.getFinallyBlock(), null); return null; } @Override public Void visitClass(ClassTree tree, Void unused) { if (isSuppressed(tree, state)) { return null; } if (EXEMPTING_SUPER_TYPES.stream() .anyMatch(t -> isSubtype(getType(tree), Suppliers.typeFromString(t).get(state), state))) { return null; } return super.visitClass(tree, null); } @Override public Void visitLambdaExpression(LambdaExpressionTree node, Void unused) { // skip lambda parameters return scan(node.getBody(), null); } @Override public Void visitMethod(MethodTree tree, Void unused) { if (SERIALIZATION_METHODS.matches(tree, state)) { return scan(tree.getBody(), null); } return isSuppressed(tree, state) ? null : super.visitMethod(tree, unused); } } private static final class FilterUsedVariables extends TreePathScanner<Void, Void> { private boolean leftHandSideAssignment = false; // When this greater than zero, the usage of identifiers are real. private int inArrayAccess = 0; // This is true when we are processing a `return` statement. Elements used in return statement // must not be considered unused. private boolean inReturnStatement = false; // When this greater than zero, the usage of identifiers are real because they are in a method // call. private int inMethodCall = 0; private final Map<Symbol, TreePath> assignmentSite = new HashMap<>(); private TreePath currentExpressionStatement = null; private final Map<Symbol, TreePath> unusedElements; private final ListMultimap<Symbol, TreePath> usageSites; // Keeps track of whether a symbol was _ever_ used (between reassignments). private final Set<Symbol> isEverUsed = new HashSet<>(); private final List<UnusedSpec> unusedSpecs = new ArrayList<>(); private final ImmutableMap<Symbol, TreePath> declarationSites; private FilterUsedVariables( Map<Symbol, TreePath> unusedElements, ListMultimap<Symbol, TreePath> usageSites) { this.unusedElements = unusedElements; this.usageSites = usageSites; this.declarationSites = ImmutableMap.copyOf(unusedElements); } private boolean isInExpressionStatementTree() { Tree parent = getCurrentPath().getParentPath().getLeaf(); return parent != null && parent.getKind() == Kind.EXPRESSION_STATEMENT; } private boolean isUsed(@Nullable Symbol symbol) { return symbol != null && (!leftHandSideAssignment || inReturnStatement || inArrayAccess > 0 || inMethodCall > 0) && unusedElements.containsKey(symbol); } @Override public Void visitVariable(VariableTree tree, Void unused) { VarSymbol symbol = getSymbol(tree); if (hasBeenAssigned(tree, symbol)) { assignmentSite.put(symbol, getCurrentPath()); } return super.visitVariable(tree, null); } private boolean hasBeenAssigned(VariableTree tree, VarSymbol symbol) { if (symbol == null) { return false; } // Parameters and enhanced for loop variables are always considered assigned. if (symbol.getKind() == ElementKind.PARAMETER) { return true; } if (getCurrentPath().getParentPath().getLeaf() instanceof EnhancedForLoopTree) { return true; } // Otherwise it's assigned if the VariableTree has an initializer. if (unusedElements.containsKey(symbol) && tree.getInitializer() != null) { return true; } return false; } @Override public Void visitExpressionStatement(ExpressionStatementTree tree, Void unused) { currentExpressionStatement = getCurrentPath(); super.visitExpressionStatement(tree, null); currentExpressionStatement = null; return null; } @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { Symbol symbol = getSymbol(tree); // Filtering out identifier symbol from vars map. These are real usages of identifiers. if (isUsed(symbol)) { unusedElements.remove(symbol); } if (currentExpressionStatement != null && unusedElements.containsKey(symbol)) { usageSites.put(symbol, currentExpressionStatement); } return null; } @Override public Void visitAssignment(AssignmentTree tree, Void unused) { scan(tree.getExpression(), null); // If a variable is used in the left hand side of an assignment that does not count as a // usage. if (isInExpressionStatementTree()) { handleReassignment(tree); leftHandSideAssignment = true; scan(tree.getVariable(), null); leftHandSideAssignment = false; } else { super.visitAssignment(tree, null); } return null; } /** * Deals with assignment trees; works out if the assignment definitely overwrites the variable * in all ways that could be observed as we scan forwards. */ private void handleReassignment(AssignmentTree tree) { Tree parent = getCurrentPath().getParentPath().getLeaf(); if (!(parent instanceof StatementTree)) { return; } if (tree.getVariable().getKind() != Kind.IDENTIFIER) { return; } if (ASTHelpers.findEnclosingNode(getCurrentPath(), ForLoopTree.class) != null) { return; } Symbol symbol = getSymbol(tree.getVariable()); // Check if it was actually assigned to at this depth (or is a parameter). if (!((assignmentSite.containsKey(symbol) && symbol.getKind() == ElementKind.LOCAL_VARIABLE) || symbol.getKind() == ElementKind.PARAMETER)) { return; } // Don't regard assigning `null` as a potentially unused assignment, as people do this for GC // reasons. if (getType(tree.getExpression()) instanceof NullType) { return; } TreePath lastAssignmentSite = assignmentSite.get(symbol); if (lastAssignmentSite == null) { return; } TreePath declarationSite = declarationSites.get(symbol); if (declarationSite == null) { return; } if (scopeDepth(declarationSite) != Iterables.size(getCurrentPath().getParentPath())) { return; } if (unusedElements.containsKey(symbol)) { unusedSpecs.add(UnusedSpec.of(symbol, lastAssignmentSite, usageSites.get(symbol), tree)); } else { isEverUsed.add(symbol); } unusedElements.put(symbol, getCurrentPath()); usageSites.removeAll(symbol); usageSites.put(symbol, getCurrentPath().getParentPath()); assignmentSite.put(symbol, getCurrentPath().getParentPath()); } // This is a crude proxy for when a variable is unconditionally overwritten. It doesn't match // all cases, but it catches a reassignment at the same depth. private static int scopeDepth(TreePath assignmentSite) { if (assignmentSite.getParentPath().getLeaf() instanceof EnhancedForLoopTree) { return Iterables.size(assignmentSite) + 1; } if (assignmentSite.getLeaf() instanceof VariableTree) { VarSymbol symbol = getSymbol((VariableTree) assignmentSite.getLeaf()); if (symbol.getKind() == ElementKind.PARAMETER) { return Iterables.size(assignmentSite) + 1; } } return Iterables.size(assignmentSite); } @Override public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void unused) { Symbol symbol = getSymbol(memberSelectTree); if (isUsed(symbol)) { unusedElements.remove(symbol); } else if (currentExpressionStatement != null && unusedElements.containsKey(symbol)) { usageSites.put(symbol, currentExpressionStatement); } // Clear leftHandSideAssignment and descend down the tree to catch any variables in the // receiver of this member select, which _are_ considered used. boolean wasLeftHandAssignment = leftHandSideAssignment; leftHandSideAssignment = false; super.visitMemberSelect(memberSelectTree, null); leftHandSideAssignment = wasLeftHandAssignment; return null; } @Override public Void visitMemberReference(MemberReferenceTree tree, Void unused) { super.visitMemberReference(tree, null); MethodSymbol symbol = getSymbol(tree); symbol.getParameters().forEach(unusedElements::remove); return null; } @Override public Void visitCompoundAssignment(CompoundAssignmentTree tree, Void unused) { if (isInExpressionStatementTree()) { leftHandSideAssignment = true; scan(tree.getVariable(), null); leftHandSideAssignment = false; scan(tree.getExpression(), null); } else { super.visitCompoundAssignment(tree, null); } return null; } @Override public Void visitArrayAccess(ArrayAccessTree node, Void unused) { inArrayAccess++; super.visitArrayAccess(node, null); inArrayAccess--; return null; } @Override public Void visitReturn(ReturnTree node, Void unused) { inReturnStatement = true; scan(node.getExpression(), null); inReturnStatement = false; return null; } @Override public Void visitUnary(UnaryTree tree, Void unused) { // If unary expression is inside another expression, then this is a real usage of unary // operand. // Example: // array[i++] = 0; // 'i' has a real usage here. 'array' might not have. // list.get(i++); // But if it is like this: // i++; // Then it is possible that this is not a real usage of 'i'. if (isInExpressionStatementTree() && (tree.getKind() == POSTFIX_DECREMENT || tree.getKind() == POSTFIX_INCREMENT || tree.getKind() == PREFIX_DECREMENT || tree.getKind() == PREFIX_INCREMENT)) { leftHandSideAssignment = true; scan(tree.getExpression(), null); leftHandSideAssignment = false; } else { super.visitUnary(tree, null); } return null; } @Override public Void visitErroneous(ErroneousTree tree, Void unused) { return scan(tree.getErrorTrees(), null); } /** * Looks at method invocations and removes the invoked private methods from {@code * #unusedElements}. */ @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { inMethodCall++; super.visitMethodInvocation(tree, null); inMethodCall--; return null; } } @AutoValue abstract static class UnusedSpec { /** {@link Symbol} of the unused element. */ abstract Symbol symbol(); /** {@link VariableTree} or {@link AssignmentTree} for the original assignment site. */ abstract TreePath assignmentPath(); /** * All the usage sites of this variable that we claim are unused (including the initial * declaration/assignment). */ abstract ImmutableList<TreePath> usageSites(); /** * If this usage chain was terminated by an unconditional reassignment, the corresponding {@link * AssignmentTree}. */ abstract Optional<AssignmentTree> terminatingAssignment(); private static UnusedSpec of( Symbol symbol, TreePath assignmentPath, Iterable<TreePath> treePaths, @Nullable AssignmentTree assignmentTree) { return new AutoValue_UnusedVariable_UnusedSpec( symbol, assignmentPath, ImmutableList.copyOf(treePaths), Optional.ofNullable(assignmentTree)); } } private static final Supplier<Type> PARCELABLE_CREATOR = VisitorState.memoize(state -> state.getTypeFromString("android.os.Parcelable.Creator")); }
39,907
38.59127
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BadShiftAmount.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.kindIs; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; /** * @author bill.pugh@gmail.com (Bill Pugh) * @author eaftan@google.com (Eddie Aftandilian) */ @BugPattern(summary = "Shift by an amount that is out of range", severity = ERROR) public class BadShiftAmount extends BugChecker implements BinaryTreeMatcher { /** * Matches if the left operand is an int, byte, short, or char, and the right operand is a literal * that is not in the range 0-31 inclusive. * * <p>In a shift expression, byte, short, and char undergo unary numeric promotion and are * promoted to int. See JLS 5.6.1. */ private static final Matcher<BinaryTree> BAD_SHIFT_AMOUNT_INT = new Matcher<BinaryTree>() { @Override public boolean matches(BinaryTree tree, VisitorState state) { Type leftType = ASTHelpers.getType(tree.getLeftOperand()); Types types = state.getTypes(); Symtab symtab = state.getSymtab(); if (!(types.isSameType(leftType, symtab.intType)) && !(types.isSameType(leftType, symtab.byteType)) && !(types.isSameType(leftType, symtab.shortType)) && !(types.isSameType(leftType, symtab.charType))) { return false; } ExpressionTree rightOperand = tree.getRightOperand(); if (rightOperand instanceof LiteralTree) { Object rightValue = ((LiteralTree) rightOperand).getValue(); if (rightValue instanceof Number) { int intValue = ((Number) rightValue).intValue(); return intValue < 0 || intValue > 31; } } return false; } }; public static final Matcher<BinaryTree> BINARY_TREE_MATCHER = allOf( anyOf( kindIs(Kind.LEFT_SHIFT), kindIs(Kind.RIGHT_SHIFT), kindIs(Kind.UNSIGNED_RIGHT_SHIFT)), BAD_SHIFT_AMOUNT_INT); @Override public Description matchBinary(BinaryTree tree, VisitorState state) { if (!BINARY_TREE_MATCHER.matches(tree, state)) { return Description.NO_MATCH; } /* * For shift amounts in [32, 63], cast the left operand to long. Otherwise change the shift * amount to whatever would actually be used. */ int intValue = ((Number) ((LiteralTree) tree.getRightOperand()).getValue()).intValue(); Fix fix; if (intValue >= 32 && intValue <= 63) { if (tree.getLeftOperand().getKind() == Kind.INT_LITERAL) { fix = SuggestedFix.postfixWith(tree.getLeftOperand(), "L"); } else { fix = SuggestedFix.prefixWith(tree, "(long) "); } } else { // This is the equivalent shift distance according to JLS 15.19. String actualShiftDistance = Integer.toString(intValue & 0x1f); fix = SuggestedFix.replace(tree.getRightOperand(), actualShiftDistance); } return describeMatch(tree, fix); } }
4,405
37.649123
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InitializeInline.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.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isConsideredFinal; 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.sun.source.tree.AssignmentTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ModifiersTree; 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.TreePathScanner; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.util.Position; import java.util.ArrayList; import java.util.List; /** * Bugpattern to encourage initializing effectively final variables inline with their declaration, * if possible. */ @BugPattern( summary = "Initializing variables in their declaring statement is clearer, where possible.", severity = WARNING) public final class InitializeInline extends BugChecker implements VariableTreeMatcher { @Override public Description matchVariable(VariableTree tree, VisitorState state) { Tree declarationParent = state.getPath().getParentPath().getLeaf(); if (declarationParent instanceof ClassTree) { return NO_MATCH; } VarSymbol symbol = getSymbol(tree); if (!isConsideredFinal(symbol)) { return NO_MATCH; } List<TreePath> assignments = new ArrayList<>(); new TreePathScanner<Void, Void>() { @Override public Void visitAssignment(AssignmentTree node, Void unused) { if (symbol.equals(getSymbol(node.getVariable()))) { assignments.add(getCurrentPath()); } return super.visitAssignment(node, null); } }.scan(state.getPath().getParentPath(), null); if (assignments.size() != 1) { return NO_MATCH; } TreePath soleAssignmentPath = getOnlyElement(assignments); Tree grandParent = soleAssignmentPath.getParentPath().getParentPath().getLeaf(); if (!(soleAssignmentPath.getParentPath().getLeaf() instanceof StatementTree && grandParent.equals(declarationParent))) { return NO_MATCH; } ModifiersTree modifiersTree = tree.getModifiers(); String modifiers = modifiersTree == null || state.getEndPosition(modifiersTree) == Position.NOPOS ? "" : (state.getSourceForNode(modifiersTree) + " "); return describeMatch( tree, SuggestedFix.builder() .replace(tree, "") .prefixWith( soleAssignmentPath.getLeaf(), modifiers + state.getSourceForNode(tree.getType()) + " ") .build()); } }
3,699
37.541667
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ClassNamedLikeTypeParameter.java
/* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.TypeParameterNaming.TypeParameterNamingClassification; import com.google.errorprone.matchers.Description; import com.sun.source.tree.ClassTree; /** * @author glorioso@google.com */ @BugPattern( summary = "This class's name looks like a Type Parameter.", severity = SUGGESTION, tags = StandardTags.STYLE) public class ClassNamedLikeTypeParameter extends BugChecker implements ClassTreeMatcher { @Override public Description matchClass(ClassTree tree, VisitorState state) { // Here, if a class is named like a Type Parameter, it's a bad thing. return TypeParameterNamingClassification.classify(tree.getSimpleName().toString()).isValidName() ? describeMatch(tree) : Description.NO_MATCH; } }
1,719
36.391304
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ComplexBooleanConstant.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 com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.UnaryTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.tools.javac.tree.JCTree.JCLiteral; import java.util.Objects; import org.checkerframework.checker.nullness.qual.Nullable; /** * @author Sumit Bhagwani (bhagwani@google.com) */ @BugPattern( summary = "Non-trivial compile time constant boolean expressions shouldn't be used.", severity = WARNING) public class ComplexBooleanConstant extends BugChecker implements BinaryTreeMatcher { @Override public Description matchBinary(BinaryTree tree, VisitorState state) { Boolean constValue = booleanValue(tree); if (constValue == null) { return Description.NO_MATCH; } return buildDescription(tree) .addFix(SuggestedFix.replace(tree, constValue.toString())) .setMessage( String.format( "This expression always evaluates to `%s`, prefer a boolean literal for clarity.", constValue)) .build(); } @Nullable Boolean booleanValue(BinaryTree tree) { if (tree.getLeftOperand() instanceof JCLiteral && tree.getRightOperand() instanceof JCLiteral) { return ASTHelpers.constValue(tree, Boolean.class); } // Handle `&& false` and `|| true` even if the other operand is a non-trivial constant // (including constant fields). SimpleTreeVisitor<Boolean, Void> boolValue = new SimpleTreeVisitor<Boolean, Void>() { @Override public @Nullable Boolean visitLiteral(LiteralTree node, Void unused) { if (node.getValue() instanceof Boolean) { return (Boolean) node.getValue(); } return null; } @Override public @Nullable Boolean visitUnary(UnaryTree node, Void unused) { Boolean r = node.getExpression().accept(this, null); if (r == null) { return null; } switch (node.getKind()) { case LOGICAL_COMPLEMENT: return !r; default: return null; } } }; Boolean lhs = tree.getLeftOperand().accept(boolValue, null); Boolean rhs = tree.getRightOperand().accept(boolValue, null); switch (tree.getKind()) { case CONDITIONAL_AND: case AND: if (lhs != null && rhs != null) { return lhs && rhs; } if (Objects.equals(lhs, Boolean.FALSE) || Objects.equals(rhs, Boolean.FALSE)) { return false; } break; case CONDITIONAL_OR: case OR: if (lhs != null && rhs != null) { return lhs || rhs; } if (Objects.equals(lhs, Boolean.TRUE) || Objects.equals(rhs, Boolean.TRUE)) { return true; } break; default: // fall out } return null; } }
3,951
33.973451
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ExtendsAutoValue.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.common.collect.ImmutableSet; 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.matchers.Description; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.tools.javac.util.Name; /** Makes sure that you are not extending a class that has @AutoValue as an annotation. */ @BugPattern( summary = "Do not extend an @AutoValue/@AutoOneOf class in non-generated code.", severity = SeverityLevel.ERROR) public final class ExtendsAutoValue extends BugChecker implements ClassTreeMatcher { private static final Supplier<ImmutableSet<Name>> AUTOS = VisitorState.memoize( s -> ImmutableSet.of( s.getName("com.google.auto.value.AutoValue"), s.getName("com.google.auto.value.AutoOneOf"))); @Override public Description matchClass(ClassTree tree, VisitorState state) { if (tree.getExtendsClause() == null) { // Doesn't extend anything, can't possibly be a violation. return Description.NO_MATCH; } if (!ASTHelpers.annotationsAmong( ASTHelpers.getSymbol(tree.getExtendsClause()), AUTOS.get(state), state) .isEmpty()) { // Violation: one of its superclasses extends AutoValue. if (!isInGeneratedCode(state)) { return buildDescription(tree).build(); } } return Description.NO_MATCH; } private static boolean isInGeneratedCode(VisitorState state) { // Skip generated code. Yes, I know we can do this via a flag but we should always ignore // generated code, so to be sure, manually check it. return !ASTHelpers.getGeneratedBy(state).isEmpty(); } }
2,564
36.720588
93
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NullableOnContainingClass.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static java.lang.annotation.ElementType.TYPE_PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher; 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.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.AnnotationTree; 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.tools.javac.code.Symbol; import java.lang.annotation.ElementType; import java.lang.annotation.Target; import java.util.List; /** A bugpattern; see the summary. */ @BugPattern( summary = "Type-use nullability annotations should annotate the inner class, not the outer class" + " (e.g., write `A.@Nullable B` instead of `@Nullable A.B`).", severity = ERROR) public final class NullableOnContainingClass extends BugChecker implements MemberSelectTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { @Override public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) { if (!(tree.getExpression() instanceof AnnotatedTypeTree)) { return NO_MATCH; } return handle(((AnnotatedTypeTree) tree.getExpression()).getAnnotations(), tree, state); } @Override public Description matchMethod(MethodTree tree, VisitorState state) { return handle(tree.getModifiers().getAnnotations(), tree.getReturnType(), state); } @Override public Description matchVariable(VariableTree tree, VisitorState state) { return handle(tree.getModifiers().getAnnotations(), tree.getType(), state); } private Description handle( List<? extends AnnotationTree> annotations, Tree type, VisitorState state) { if (!(type instanceof MemberSelectTree)) { return NO_MATCH; } int endOfOuterType = state.getEndPosition(((MemberSelectTree) type).getExpression()); for (AnnotationTree annotation : annotations) { if (!isOnlyTypeAnnotation(getSymbol(annotation))) { continue; } if (NULLABLE_ANNOTATION_NAMES.contains(getType(annotation).tsym.getSimpleName().toString())) { if (state.getEndPosition(annotation) < endOfOuterType) { return describeMatch( annotation, SuggestedFix.builder() .delete(annotation) .replace( endOfOuterType + 1, endOfOuterType + 1, state.getSourceForNode(annotation) + " ") .build()); } } } return NO_MATCH; } /** * True if this annotation is only {@link TYPE_USE}, or only {@link TYPE_USE} and {@link * TYPE_PARAMETER}. */ private static boolean isOnlyTypeAnnotation(Symbol anno) { Target target = anno.getAnnotation(Target.class); ImmutableSet<ElementType> elementTypes = target == null ? ImmutableSet.of() : ImmutableSet.copyOf(target.value()); return elementTypes.contains(TYPE_USE) && TYPE_USE_OR_TYPE_PARAMETER.containsAll(elementTypes); } private static final ImmutableSet<String> NULLABLE_ANNOTATION_NAMES = ImmutableSet.of("Nullable", "NonNull", "NullableType"); private static final ImmutableSet<ElementType> TYPE_USE_OR_TYPE_PARAMETER = ImmutableSet.of(TYPE_USE, TYPE_PARAMETER); }
4,617
39.156522
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryDefaultInEnumSwitch.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getLast; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import static com.google.errorprone.util.Reachability.canCompleteNormally; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.common.collect.Sets.SetView; 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.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.CaseTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.SwitchTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.tree.JCTree.JCSwitch; import java.util.List; import javax.lang.model.element.ElementKind; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Switch handles all enum values: an explicit default case is unnecessary and defeats error" + " checking for non-exhaustive switches.", severity = WARNING) public class UnnecessaryDefaultInEnumSwitch extends BugChecker implements SwitchTreeMatcher { private static final String DESCRIPTION_MOVED_DEFAULT = "Switch handles all enum values: move code from the default case to execute after the " + "switch statement to enable checking for non-exhaustive switches. " + "That is, prefer: `switch (...) { ... } throw new AssertionError();` to " + "`switch (...) { ... default: throw new AssertionError(); }`"; private static final String DESCRIPTION_REMOVED_DEFAULT = "Switch handles all enum values: the default case can be omitted to enable enforcement " + "at compile-time that the switch statement is exhaustive."; private static final String DESCRIPTION_UNRECOGNIZED = "Switch handles all enum values except for `UNRECOGNIZED`. The default case can be changed " + "to `UNRECOGNIZED` to enable compile-time enforcement that the switch statement is " + "exhaustive"; @Override public Description matchSwitch(SwitchTree switchTree, VisitorState state) { // Only look at enum switches. TypeSymbol switchType = ((JCSwitch) switchTree).getExpression().type.tsym; if (switchType.getKind() != ElementKind.ENUM) { return NO_MATCH; } // Extract default case and the one before it. CaseTree caseBeforeDefault = null; CaseTree defaultCase = null; for (CaseTree caseTree : switchTree.getCases()) { if (caseTree.getExpression() == null) { defaultCase = caseTree; break; } else { caseBeforeDefault = caseTree; } } if (caseBeforeDefault == null || defaultCase == null) { return NO_MATCH; } SetView<String> unhandledCases = unhandledCases(switchTree, switchType); if (unhandledCases.equals(ImmutableSet.of("UNRECOGNIZED"))) { // switch handles all values of an proto-generated enum except for 'UNRECOGNIZED'. return fixUnrecognized(switchTree, defaultCase, state); } if (unhandledCases.isEmpty()) { // switch is exhaustive, remove the default if we can. return fixDefault(switchTree, caseBeforeDefault, defaultCase, state); } // switch is non-exhaustive, default can stay. return NO_MATCH; } private Description fixDefault( SwitchTree switchTree, CaseTree caseBeforeDefault, CaseTree defaultCase, VisitorState state) { List<? extends StatementTree> defaultStatements = defaultCase.getStatements(); if (defaultStatements == null) { // TODO(b/177258673): provide fixes for `case -> ...` return buildDescription(defaultCase).setMessage(DESCRIPTION_REMOVED_DEFAULT).build(); } if (trivialDefault(defaultStatements)) { // deleting `default:` or `default: break;` is a no-op return buildDescription(defaultCase) .setMessage(DESCRIPTION_REMOVED_DEFAULT) .addFix(SuggestedFix.delete(defaultCase)) .build(); } String defaultContents = getDefaultCaseContents(defaultCase, defaultStatements, state); if (!canCompleteNormally(switchTree)) { // if the switch statement cannot complete normally, then deleting the default // and moving its statements to after the switch statement is a no-op SuggestedFix fix = SuggestedFix.builder() .postfixWith(switchTree, defaultContents) .delete(defaultCase) .build(); return buildDescription(defaultCase) .setMessage(DESCRIPTION_MOVED_DEFAULT) .addFix(fix) .build(); } // The switch is already exhaustive, we want to delete the default. // There are a few modes we need to handle: // 1) switch (..) { // case FOO: // default: doWork(); // } // In this mode, we need to lift the statements from 'default' into FOO, otherwise // we change the code. This mode also captures any variation of statements in FOO // where any of them would fall-through (e.g, if (!bar) { break; } ) -- if bar is // true then we'd fall through. // // 2) switch (..) { // case FOO: break; // default: doDefault(); // } // In this mode, we can safely delete 'default'. // // 3) var x; // switch (..) { // case FOO: x = 1; break; // default: x = 2; // } // doWork(x); // In this mode, we can't delete 'default' because javac analysis requires that 'x' // must be set before using it. // To solve this, we take the approach of: // Try deleting the code entirely. If it fails to compile, we've broken (3) -> no match. // Try lifting the code to the prior case statement. If it fails to compile, we had (2) // and the code is unreachable -- so use (2) as the strategy. Otherwise, use (1). if (!SuggestedFixes.compilesWithFix(SuggestedFix.delete(defaultCase), state)) { return NO_MATCH; // case (3) } if (!canCompleteNormally(caseBeforeDefault)) { // case (2) -- If the case before the default can't complete normally, // it's OK to to delete the default. return buildDescription(defaultCase) .setMessage(DESCRIPTION_REMOVED_DEFAULT) .addFix(SuggestedFix.delete(defaultCase)) .build(); } // case (1) -- If it can complete, we need to merge the default into it. SuggestedFix.Builder fix = SuggestedFix.builder().delete(defaultCase); fix.postfixWith(caseBeforeDefault, defaultContents); return buildDescription(defaultCase) .setMessage(DESCRIPTION_REMOVED_DEFAULT) .addFix(fix.build()) .build(); } private Description fixUnrecognized( SwitchTree switchTree, CaseTree defaultCase, VisitorState state) { List<? extends StatementTree> defaultStatements = defaultCase.getStatements(); Description.Builder unrecognizedDescription = buildDescription(defaultCase).setMessage(DESCRIPTION_UNRECOGNIZED); if (defaultStatements == null) { // TODO(b/177258673): provide fixes for `case -> ...` return unrecognizedDescription.build(); } if (trivialDefault(defaultStatements)) { // the default case is empty or contains only `break` -- replace it with `case UNRECOGNIZED:` // with fall out. SuggestedFix fix = SuggestedFix.replace(defaultCase, "case UNRECOGNIZED: \n // continue below"); return unrecognizedDescription.addFix(fix).build(); } String defaultContents = getDefaultCaseContents(defaultCase, defaultStatements, state); if (!canCompleteNormally(switchTree)) { // the switch statement cannot complete normally -- replace default with // `case UNRECOGNIZED: break;` and move content of default case to after the switch tree. SuggestedFix fix = SuggestedFix.builder() .replace(defaultCase, "case UNRECOGNIZED: \n break;") .postfixWith(switchTree, defaultContents) .build(); return unrecognizedDescription.addFix(fix).build(); } SuggestedFix fix = SuggestedFix.replace(defaultCase, "case UNRECOGNIZED:" + defaultContents); if (!SuggestedFixes.compilesWithFix(fix, state)) { // code in the default case can't be deleted -- no fix available. return NO_MATCH; } // delete default and move its contents into `UNRECOGNIZED` case. return unrecognizedDescription.addFix(fix).build(); } /** Returns true if the default is empty, or contains only a break statement. */ private static boolean trivialDefault(List<? extends StatementTree> defaultStatements) { if (defaultStatements.isEmpty()) { return true; } return (defaultStatements.size() == 1 && getOnlyElement(defaultStatements).getKind() == Tree.Kind.BREAK); } private static SetView<String> unhandledCases(SwitchTree tree, TypeSymbol switchType) { ImmutableSet<String> handledCases = tree.getCases().stream() .map(CaseTree::getExpression) .filter(IdentifierTree.class::isInstance) .map(p -> ((IdentifierTree) p).getName().toString()) .collect(toImmutableSet()); return Sets.difference(ASTHelpers.enumValues(switchType), handledCases); } private static String getDefaultCaseContents( CaseTree defaultCase, List<? extends StatementTree> defaultStatements, VisitorState state) { CharSequence sourceCode = state.getSourceCode(); if (sourceCode == null) { return ""; } String defaultSource = sourceCode .subSequence( getStartPosition(defaultStatements.get(0)), state.getEndPosition(getLast(defaultStatements))) .toString(); String initialComments = comments(defaultCase, defaultStatements, sourceCode); return initialComments + defaultSource; } /** Returns the comments between the "default:" case and the first statement within it, if any. */ private static String comments( CaseTree defaultCase, List<? extends StatementTree> defaultStatements, CharSequence sourceCode) { // If there are no statements, then there can be no comments that we strip, // because comments are attached to the statements, not the "default:" case. if (defaultStatements.isEmpty()) { return ""; } // To extract the comments, we have to get the source code from // "default:" to the first statement, and then strip off "default:", because // we have no way of identifying the end position of just the "default:" statement. int defaultStart = getStartPosition(defaultCase); int statementStart = getStartPosition(defaultStatements.get(0)); String defaultAndComments = sourceCode.subSequence(defaultStart, statementStart).toString(); String comments = defaultAndComments .substring(defaultAndComments.indexOf("default:") + "default:".length()) .trim(); if (!comments.isEmpty()) { comments = "\n" + comments + "\n"; } return comments; } }
12,347
42.632509
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/PackageInfo.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 com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.CompilationUnitTree; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Declaring types inside package-info.java files is very bad form", severity = ERROR) public class PackageInfo extends BugChecker implements CompilationUnitTreeMatcher { @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { if (tree.getSourceFile() == null) { return NO_MATCH; } String name = ASTHelpers.getFileName(tree); int idx = name.lastIndexOf('/'); if (idx != -1) { name = name.substring(idx + 1); } if (!name.equals("package-info.java")) { return NO_MATCH; } if (tree.getTypeDecls().isEmpty()) { return NO_MATCH; } return describeMatch(tree.getTypeDecls().get(0)); } }
1,915
35.150943
90
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ConstantOverflow.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.getStartPosition; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSameType; import com.google.common.math.IntMath; import com.google.common.math.LongMath; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher; 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.BinaryTree; import com.sun.source.tree.ConditionalExpressionTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.PrimitiveTypeTree; 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.SimpleTreeVisitor; import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.util.Position; import javax.annotation.Nullable; import javax.lang.model.type.TypeKind; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "Compile-time constant expression overflows", severity = ERROR) public class ConstantOverflow extends BugChecker implements BinaryTreeMatcher { @Override public Description matchBinary(BinaryTree tree, VisitorState state) { TreePath path = state.getPath().getParentPath(); while (path != null && path.getLeaf() instanceof ExpressionTree) { if (path.getLeaf() instanceof BinaryTree) { // only match on the outermost nested binary expression return NO_MATCH; } path = path.getParentPath(); } try { tree.accept(CONSTANT_VISITOR, null); return NO_MATCH; } catch (ArithmeticException e) { Description.Builder description = buildDescription(tree); Fix longFix = longFix(tree, state); if (longFix != null) { description.addFix(longFix); } return description.build(); } } /** * If the left operand of an int binary expression is an int literal, suggest making it a long. */ @Nullable private static Fix longFix(ExpressionTree expr, VisitorState state) { BinaryTree binExpr = null; while (expr instanceof BinaryTree) { binExpr = (BinaryTree) expr; expr = binExpr.getLeftOperand(); } if (!(expr instanceof LiteralTree) || expr.getKind() != Kind.INT_LITERAL) { return null; } Type intType = state.getSymtab().intType; if (!isSameType(getType(binExpr), intType, state)) { return null; } SuggestedFix.Builder fix = SuggestedFix.builder().postfixWith(expr, "L"); Tree parent = state.getPath().getParentPath().getLeaf(); if (parent instanceof VariableTree && isSameType(getType(parent), intType, state)) { Tree type = ((VariableTree) parent).getType(); if (getStartPosition(type) != Position.NOPOS) { fix.replace(type, "long"); } } return fix.build(); } /** A compile-time constant expression evaluator that checks for overflow. */ private static final SimpleTreeVisitor<Number, Void> CONSTANT_VISITOR = new SimpleTreeVisitor<Number, Void>() { @Nullable @Override public Number visitConditionalExpression(ConditionalExpressionTree node, Void p) { Number ifTrue = node.getTrueExpression().accept(this, null); Number ifFalse = node.getFalseExpression().accept(this, null); Boolean condition = ASTHelpers.constValue(node.getCondition(), Boolean.class); if (condition == null) { return null; } return condition ? ifTrue : ifFalse; } @Override public Number visitParenthesized(ParenthesizedTree node, Void p) { return node.getExpression().accept(this, null); } @Nullable @Override public Number visitUnary(UnaryTree node, Void p) { Number value = node.getExpression().accept(this, null); if (value == null) { return null; } if (value instanceof Long) { return unop(node.getKind(), value.longValue()); } else { return unop(node.getKind(), value.intValue()); } } @Nullable @Override public Number visitBinary(BinaryTree node, Void p) { Number lhs = node.getLeftOperand().accept(this, null); Number rhs = node.getRightOperand().accept(this, null); if (lhs == null || rhs == null) { return null; } // assume that e.g. `Integer.MIN_VALUE - 1` is intentional switch (node.getKind()) { case MINUS: if ((lhs instanceof Long && lhs.longValue() == Long.MIN_VALUE) || (lhs instanceof Integer && lhs.intValue() == Integer.MIN_VALUE)) { return null; } break; case PLUS: if ((lhs instanceof Long && lhs.longValue() == Long.MAX_VALUE) || (lhs instanceof Integer && lhs.intValue() == Integer.MAX_VALUE)) { return null; } break; default: break; } if (lhs instanceof Long || rhs instanceof Long) { return binop(node.getKind(), lhs.longValue(), rhs.longValue()); } else { return binop(node.getKind(), lhs.intValue(), rhs.intValue()); } } @Nullable @Override public Number visitTypeCast(TypeCastTree node, Void p) { Number value = node.getExpression().accept(this, null); if (value == null) { return null; } if (!(node.getType() instanceof PrimitiveTypeTree)) { return null; } TypeKind kind = ((PrimitiveTypeTree) node.getType()).getPrimitiveTypeKind(); return cast(kind, value); } @Override public Number visitMemberSelect(MemberSelectTree node, Void p) { return getIntegralConstant(node); } @Override public Number visitIdentifier(IdentifierTree node, Void p) { return getIntegralConstant(node); } @Override public Number visitLiteral(LiteralTree node, Void unused) { return getIntegralConstant(node); } }; @Nullable private static Long unop(Kind kind, long value) { switch (kind) { case UNARY_PLUS: return +value; case UNARY_MINUS: return -value; case BITWISE_COMPLEMENT: return ~value; default: return null; } } @Nullable private static Integer unop(Kind kind, int value) { switch (kind) { case UNARY_PLUS: return +value; case UNARY_MINUS: return -value; case BITWISE_COMPLEMENT: return ~value; default: return null; } } @Nullable static Long binop(Kind kind, long lhs, long rhs) { switch (kind) { case MULTIPLY: return LongMath.checkedMultiply(lhs, rhs); case DIVIDE: return lhs / rhs; case REMAINDER: return lhs % rhs; case PLUS: return LongMath.checkedAdd(lhs, rhs); case MINUS: return LongMath.checkedSubtract(lhs, rhs); case LEFT_SHIFT: return lhs << rhs; case RIGHT_SHIFT: return lhs >> rhs; case UNSIGNED_RIGHT_SHIFT: return lhs >>> rhs; case AND: return lhs & rhs; case XOR: return lhs ^ rhs; case OR: return lhs | rhs; default: return null; } } @Nullable static Integer binop(Kind kind, int lhs, int rhs) { switch (kind) { case MULTIPLY: return IntMath.checkedMultiply(lhs, rhs); case DIVIDE: return lhs / rhs; case REMAINDER: return lhs % rhs; case PLUS: return IntMath.checkedAdd(lhs, rhs); case MINUS: return IntMath.checkedSubtract(lhs, rhs); case LEFT_SHIFT: return lhs << rhs; case RIGHT_SHIFT: return lhs >> rhs; case UNSIGNED_RIGHT_SHIFT: return lhs >>> rhs; case AND: return lhs & rhs; case XOR: return lhs ^ rhs; case OR: return lhs | rhs; default: return null; } } @Nullable private static Number cast(TypeKind kind, Number value) { switch (kind) { case SHORT: return value.shortValue(); case INT: return value.intValue(); case LONG: return value.longValue(); case BYTE: return value.byteValue(); case CHAR: return (int) (char) value.intValue(); default: return null; } } @Nullable private static Number getIntegralConstant(Tree node) { Number number = ASTHelpers.constValue(node, Number.class); if (number instanceof Integer || number instanceof Long) { return number; } return null; } }
10,231
30.875389
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NonCanonicalStaticImport.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ImportTreeMatcher; import com.google.errorprone.bugpatterns.StaticImports.StaticImportInfo; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.tree.ImportTree; /** * Types shouldn't be statically by their non-canonical name. * * @author cushon@google.com (Liam Miller-Cushon) */ @BugPattern( summary = "Static import of type uses non-canonical name", severity = ERROR, documentSuppression = false) public class NonCanonicalStaticImport extends BugChecker implements ImportTreeMatcher { @Override public Description matchImport(ImportTree tree, VisitorState state) { StaticImportInfo importInfo = StaticImports.tryCreate(tree, state); if (importInfo == null || importInfo.isCanonical() || !importInfo.members().isEmpty()) { return Description.NO_MATCH; } return describeMatch(tree, SuggestedFix.replace(tree, importInfo.importStatement())); } }
1,819
36.142857
92
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TransientMisuse.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.LinkType.NONE; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; 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.sun.source.tree.VariableTree; import javax.lang.model.element.Modifier; /** * Warns against use of both {@code static} and {@code transient} modifiers on field declarations. */ @BugPattern( summary = "Static fields are implicitly transient, so the explicit modifier is unnecessary", linkType = NONE, severity = WARNING) public class TransientMisuse extends BugChecker implements VariableTreeMatcher { @Override public Description matchVariable(VariableTree tree, VisitorState state) { if (tree.getModifiers() .getFlags() .containsAll(ImmutableList.of(Modifier.STATIC, Modifier.TRANSIENT))) { return describeMatch( tree, SuggestedFixes.removeModifiers(tree, state, Modifier.TRANSIENT) .orElse(SuggestedFix.emptyFix())); } return Description.NO_MATCH; } }
1,996
36.679245
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LongDoubleConversion.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.constValue; import static com.google.errorprone.util.ASTHelpers.getType; 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.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; 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 = "Conversion from long to double may lose precision; use an explicit cast to double if this" + " was intentional", severity = WARNING) public final class LongDoubleConversion extends BugChecker implements MethodInvocationTreeMatcher { @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { for (ExpressionTree argument : tree.getArguments()) { checkArgument(argument, state); } return NO_MATCH; } private void checkArgument(ExpressionTree argument, VisitorState state) { if (!getType(argument).getKind().equals(TypeKind.LONG)) { return; } Object constant = constValue(argument); if (constant instanceof Long && constant.equals((long) ((Long) constant).doubleValue())) { return; } ASTHelpers.TargetType targetType = targetType(state.withPath(new TreePath(state.getPath(), argument))); if (targetType != null && targetType.type().getKind().equals(TypeKind.DOUBLE)) { String replacement = SuggestedFixes.castTree(argument, "double", state); state.reportMatch(describeMatch(argument, SuggestedFix.replace(argument, replacement))); } } }
2,824
39.942029
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/IdentityHashMapUsage.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.method.MethodMatchers.constructor; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.AssignmentTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; 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.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.code.Type; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "IdentityHashMap usage shouldn't be intermingled with Map", severity = WARNING) public class IdentityHashMapUsage extends BugChecker implements MethodInvocationTreeMatcher, AssignmentTreeMatcher, VariableTreeMatcher, NewClassTreeMatcher { private static final String IDENTITY_HASH_MAP = "java.util.IdentityHashMap"; private static final Matcher<ExpressionTree> IHM_ONE_ARG_METHODS = instanceMethod().onExactClass(IDENTITY_HASH_MAP).namedAnyOf("equals", "putAll"); private static final Matcher<ExpressionTree> IHM_CTOR_MAP_ARG = constructor().forClass(IDENTITY_HASH_MAP).withParameters("java.util.Map"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (IHM_ONE_ARG_METHODS.matches(tree, state) && !ASTHelpers.isSameType( ASTHelpers.getType(tree.getArguments().get(0)), JAVA_UTIL_IDENTITYHASHMAP.get(state), state)) { return describeMatch(tree); } return Description.NO_MATCH; } @Override public Description matchAssignment(AssignmentTree tree, VisitorState state) { Type ihmType = JAVA_UTIL_IDENTITYHASHMAP.get(state); if (!ASTHelpers.isSameType(ASTHelpers.getType(tree.getExpression()), ihmType, state)) { return Description.NO_MATCH; } if (!ASTHelpers.isSameType(ASTHelpers.getType(tree.getVariable()), ihmType, state)) { return describeMatch(tree); } return Description.NO_MATCH; } @Override public Description matchVariable(VariableTree tree, VisitorState state) { if (tree.getInitializer() == null) { // method params don't have initializers. return Description.NO_MATCH; } Type ihmType = JAVA_UTIL_IDENTITYHASHMAP.get(state); if (ASTHelpers.isSameType(ASTHelpers.getType(tree.getType()), ihmType, state)) { return Description.NO_MATCH; } Type type = ASTHelpers.getType(tree.getInitializer()); if (ASTHelpers.isSameType(type, ihmType, state)) { SuggestedFix.Builder fix = SuggestedFix.builder(); fix.replace(tree.getType(), SuggestedFixes.qualifyType(state, fix, type)); return describeMatch(tree, fix.build()); } return Description.NO_MATCH; } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { if (IHM_CTOR_MAP_ARG.matches(tree, state) && !ASTHelpers.isSameType( ASTHelpers.getType(tree.getArguments().get(0)), JAVA_UTIL_IDENTITYHASHMAP.get(state), state)) { return describeMatch(tree); } return Description.NO_MATCH; } private static final Supplier<Type> JAVA_UTIL_IDENTITYHASHMAP = VisitorState.memoize(state -> state.getTypeFromString(IDENTITY_HASH_MAP)); }
4,715
39.655172
91
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ComputeIfAbsentAmbiguousReference.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MemberReferenceTree.ReferenceMode; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.util.Name; import java.util.List; import java.util.stream.Collectors; /** * Flags ambiguous creations of objects in {@link java.util.Map#computeIfAbsent}. * * @author bhagwani@google.com (Sumit Bhagwani) */ @BugPattern( summary = "computeIfAbsent passes the map key to the provided class's constructor", severity = ERROR) public final class ComputeIfAbsentAmbiguousReference extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> COMPUTE_IF_ABSENT = instanceMethod().onDescendantOf("java.util.Map").named("computeIfAbsent"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!COMPUTE_IF_ABSENT.matches(tree, state)) { return NO_MATCH; } ExpressionTree mappingFunctionArg = tree.getArguments().get(1); if (!(mappingFunctionArg instanceof MemberReferenceTree)) { return NO_MATCH; } MemberReferenceTree memberReferenceTree = (MemberReferenceTree) mappingFunctionArg; if (memberReferenceTree.getMode() != ReferenceMode.NEW) { return NO_MATCH; } ExpressionTree expressionTree = memberReferenceTree.getQualifierExpression(); Symbol symbol = ASTHelpers.getSymbol(expressionTree); if (!(symbol instanceof ClassSymbol)) { return NO_MATCH; } ClassSymbol classSymbol = (ClassSymbol) symbol; ImmutableList<MethodSymbol> constructors = ASTHelpers.getConstructors(classSymbol); List<MethodSymbol> zeroArgConstructors = constructors.stream() .filter(methodSymbol -> methodSymbol.type.getParameterTypes().isEmpty()) .collect(Collectors.toList()); if (zeroArgConstructors.size() != 1) { return NO_MATCH; } List<MethodSymbol> oneArgConstructors = constructors.stream() .filter(methodSymbol -> methodSymbol.type.getParameterTypes().size() == 1) .collect(Collectors.toList()); if (oneArgConstructors.isEmpty()) { return NO_MATCH; } ExpressionTree onlyArgument = tree.getArguments().get(0); if (onlyArgument instanceof IdentifierTree) { IdentifierTree onlyArgumentIdentifier = (IdentifierTree) onlyArgument; Name constructorParamName = oneArgConstructors.get(0).getParameters().get(0).getSimpleName(); if (constructorParamName.equals(onlyArgumentIdentifier.getName())) { return NO_MATCH; } } return describeMatch(memberReferenceTree); } }
4,128
40.29
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/FuturesGetCheckedIllegalExceptionType.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.anyOf; import static com.google.errorprone.matchers.Matchers.argument; import static com.google.errorprone.matchers.Matchers.classLiteral; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.getEnclosedElements; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSameType; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static com.sun.tools.javac.code.TypeTag.BOT; import static javax.lang.model.element.Modifier.PUBLIC; import com.google.common.collect.Iterables; import com.google.common.util.concurrent.Futures; 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.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.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; import java.util.List; /** * Checks for calls to Guava's {@code Futures.getChecked} method that will always fail because they * pass an incompatible exception type. */ @BugPattern( summary = "Futures.getChecked requires a checked exception type with a standard constructor.", severity = ERROR) public final class FuturesGetCheckedIllegalExceptionType extends BugChecker implements MethodInvocationTreeMatcher { @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!FUTURES_GET_CHECKED_MATCHER.matches(tree, state)) { return NO_MATCH; } /* * Check for RuntimeException first: There would be no sense in telling the user that the * problem is related to which constructors are available if we'd reject the call anyway. */ if (PASSED_RUNTIME_EXCEPTION_TYPE.matches(tree, state)) { return describeUncheckedExceptionTypeMatch( tree, SuggestedFix.builder() .replace( tree, "getUnchecked(" + state.getSourceForNode(tree.getArguments().get(0)) + ")") .addStaticImport(Futures.class.getName() + ".getUnchecked") .build()); } if (PASSED_TYPE_WITHOUT_USABLE_CONSTRUCTOR.matches(tree, state)) { return describeNoValidConstructorMatch(tree); } return NO_MATCH; } private static final Matcher<ExpressionTree> FUTURES_GET_CHECKED_MATCHER = anyOf(staticMethod().onClass(Futures.class.getName()).named("getChecked")); private static final Matcher<ExpressionTree> CLASS_OBJECT_FOR_CLASS_EXTENDING_RUNTIME_EXCEPTION = new Matcher<ExpressionTree>() { @Override public boolean matches(ExpressionTree tree, VisitorState state) { Types types = state.getTypes(); Type classType = state.getSymtab().classType; Type runtimeExceptionType = state.getSymtab().runtimeExceptionType; Type argType = getType(tree); // Make sure that the argument is a Class<Something> (and not null/bottom). if (!isSubtype(argType, classType, state) || argType.getTag() == BOT) { return false; } List<Type> typeArguments = argType.getTypeArguments(); Type exceptionType = Iterables.getFirst(typeArguments, null); return types.isSubtype(exceptionType, runtimeExceptionType); } }; private static final Matcher<MethodInvocationTree> PASSED_RUNTIME_EXCEPTION_TYPE = argument(1, CLASS_OBJECT_FOR_CLASS_EXTENDING_RUNTIME_EXCEPTION); private static final Matcher<ExpressionTree> CLASS_OBJECT_FOR_CLASS_WITHOUT_USABLE_CONSTRUCTOR = classLiteral( new Matcher<ExpressionTree>() { @Override public boolean matches(ExpressionTree tree, VisitorState state) { ClassSymbol classSymbol = (ClassSymbol) getSymbol(tree); if (classSymbol == null) { return false; } if (classSymbol.isInner()) { return true; } for (Symbol enclosedSymbol : getEnclosedElements(classSymbol)) { if (!enclosedSymbol.isConstructor()) { continue; } MethodSymbol constructorSymbol = (MethodSymbol) enclosedSymbol; if (canBeUsedByGetChecked(constructorSymbol, state)) { return false; } } return true; } }); private static final Matcher<MethodInvocationTree> PASSED_TYPE_WITHOUT_USABLE_CONSTRUCTOR = argument(1, CLASS_OBJECT_FOR_CLASS_WITHOUT_USABLE_CONSTRUCTOR); private static boolean canBeUsedByGetChecked(MethodSymbol constructor, VisitorState state) { Type stringType = state.getSymtab().stringType; Type throwableType = state.getSymtab().throwableType; // TODO(cpovirk): Check visibility of enclosing types (assuming that it matters to getChecked). if (!constructor.getModifiers().contains(PUBLIC)) { return false; } for (VarSymbol param : constructor.getParameters()) { if (!isSameType(param.asType(), stringType, state) && !isSameType(param.asType(), throwableType, state)) { return false; } } return true; } private Description describeUncheckedExceptionTypeMatch(Tree tree, Fix fix) { return buildDescription(tree) .setMessage( "The exception class passed to getChecked must be a checked exception, " + "not a RuntimeException.") .addFix(fix) .build(); } private Description describeNoValidConstructorMatch(Tree tree) { return buildDescription(tree) .setMessage( "The exception class passed to getChecked must declare a public constructor whose " + "only parameters are of type String or Throwable.") .build(); } }
7,281
39.455556
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/EqualsUnsafeCast.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.equalsMethodDeclaration; import static com.google.errorprone.util.ASTHelpers.findEnclosingNode; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSubtype; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.InstanceOfTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.TypeCastTree; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Type; import java.util.ArrayList; import java.util.List; /** * Checks for {@code equals} implementations making unsafe casts. * * @author ghm@google.com (Graeme Morgan) */ @BugPattern( summary = "The contract of #equals states that it should return false for incompatible types, " + "while this implementation may throw ClassCastException.", severity = WARNING) public final class EqualsUnsafeCast extends BugChecker implements MethodTreeMatcher { @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (!equalsMethodDeclaration().matches(tree, state)) { return NO_MATCH; } Symbol parameter = getSymbol(getOnlyElement(tree.getParameters())); new TreePathScanner<Void, Void>() { private boolean methodInvoked = false; private final List<Type> checkedTypes = new ArrayList<>(); @Override public Void visitInstanceOf(InstanceOfTree node, Void unused) { checkedTypes.add(getType(node.getType())); return super.visitInstanceOf(node, null); } @Override public Void visitMethodInvocation(MethodInvocationTree node, Void unused) { // Some equals implementations rely on super#equals for their class check. To avoid false // positives there, consider any method invocation to imply that this might be safe. // This also matches for any class comparisons with getClass. methodInvoked = true; return null; } @Override public Void visitTypeCast(TypeCastTree node, Void unused) { ExpressionTree expression = node.getExpression(); if (!methodInvoked && expression.getKind() == Kind.IDENTIFIER && parameter.equals(getSymbol(expression)) && checkedTypes.stream().noneMatch(t -> isSubtype(t, getType(node.getType()), state))) { StatementTree enclosingStatement = findEnclosingNode(getCurrentPath(), StatementTree.class); state.reportMatch( describeMatch( node, SuggestedFix.prefixWith( enclosingStatement, String.format( "if (!(%s instanceof %s)) { return false; }", state.getSourceForNode(expression), state.getSourceForNode(node.getType()))))); } return super.visitTypeCast(node, null); } }.scan(state.getPath(), null); return NO_MATCH; } }
4,386
38.522523
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ToStringReturnsNull.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matchers; import com.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; /** * ToString should not return null. * * @author eleanorh@google.com (Eleanor Harris) * @author siyuanl@google.com (Siyuan Liu) */ @BugPattern( summary = "An implementation of Object.toString() should never return null.", severity = WARNING) public class ToStringReturnsNull extends BugChecker implements MethodTreeMatcher { @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (!Matchers.toStringMethodDeclaration().matches(tree, state)) { return Description.NO_MATCH; } return tree.accept(new FindReturnNullLiteralScanner(), null) ? describeMatch(tree) : Description.NO_MATCH; } private static class FindReturnNullLiteralScanner extends BooleanScanner { @Override public Boolean visitLambdaExpression(LambdaExpressionTree node, Void unused) { return false; } @Override public Boolean visitClass(ClassTree node, Void unused) { return false; } @Override public Boolean visitReturn(ReturnTree node, Void unused) { ExpressionTree expression = node.getExpression(); return expression != null && new ReturnExpressionScanner().scan(expression, null); } private static class ReturnExpressionScanner extends BooleanScanner { @Override public Boolean scan(Tree tree, Void unused) { switch (tree.getKind()) { case NULL_LITERAL: return true; case PARENTHESIZED: case CONDITIONAL_EXPRESSION: return super.scan(tree, unused); default: return false; } } } } private abstract static class BooleanScanner extends TreeScanner<Boolean, Void> { @Override public Boolean scan(Tree tree, Void unused) { return Boolean.TRUE.equals(super.scan(tree, unused)); } @Override public final Boolean reduce(Boolean a, Boolean b) { return Boolean.TRUE.equals(a) || Boolean.TRUE.equals(b); } } }
3,240
30.77451
88
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InvalidPatternSyntax.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 com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.matchers.Description; import com.sun.source.tree.MethodInvocationTree; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * @author mdempsky@google.com (Matthew Dempsky) */ @BugPattern(summary = "Invalid syntax used for a regular expression", severity = ERROR) public class InvalidPatternSyntax extends AbstractPatternSyntaxChecker { private static final String MESSAGE_BASE = "Invalid syntax used for a regular expression: "; @Override protected final Description matchRegexLiteral( MethodInvocationTree tree, VisitorState state, String pattern, int flags) { try { Pattern.compile(pattern, flags); return NO_MATCH; } catch (PatternSyntaxException e) { return buildDescription(tree).setMessage(MESSAGE_BASE + e.getMessage()).build(); } } }
1,723
34.916667
94
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/FieldCanBeFinal.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.SUGGESTION; import static com.google.errorprone.util.ASTHelpers.canBeRemoved; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.shouldKeep; 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.CompilationUnitTreeMatcher; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import java.util.Collection; import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.Map; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; /** * @author Liam Miller-Cushon (cushon@google.com) */ @BugPattern( summary = "This field is only assigned during initialization; consider making it final", severity = SUGGESTION) public class FieldCanBeFinal extends BugChecker implements CompilationUnitTreeMatcher { /** Annotations that imply a field is non-constant. */ // TODO(cushon): consider supporting @Var as a meta-annotation private static final ImmutableSet<String> IMPLICIT_VAR_ANNOTATIONS = ImmutableSet.of( // keep-sorted start "com.beust.jcommander.Parameter", "com.google.common.annotations.NonFinalForGwt", "com.google.errorprone.annotations.Var", "com.google.gwt.uibinder.client.UiField", "com.google.inject.Inject", "com.google.inject.testing.fieldbinder.Bind", "com.google.testing.junit.testparameterinjector.TestParameter", "javax.inject.Inject", "javax.jdo.annotations.Persistent", "javax.persistence.Id", "javax.xml.bind.annotation.XmlAttribute", "org.kohsuke.args4j.Argument", "org.kohsuke.args4j.Option", "org.mockito.Spy", "picocli.CommandLine.Option" // keep-sorted end ); private static final String OBJECTIFY_PREFIX = "com.googlecode.objectify."; /** * Annotations that imply a field is non-constant, and that do not have a canonical * implementation. Instead, we match on any annotation with one of the following simple names. */ private static final ImmutableSet<String> IMPLICIT_VAR_ANNOTATION_SIMPLE_NAMES = ImmutableSet.of("NonFinalForTesting", "NotFinalForTesting"); /** Unary operator kinds that implicitly assign to their operand. */ private static final ImmutableSet<Kind> UNARY_ASSIGNMENT = Sets.immutableEnumSet( Kind.PREFIX_DECREMENT, Kind.POSTFIX_DECREMENT, Kind.PREFIX_INCREMENT, Kind.POSTFIX_INCREMENT); /** The initialization context where an assignment occurred. */ private enum InitializationContext { /** A class (static) initializer. */ STATIC, /** An instance initializer. */ INSTANCE, /** Neither a static or instance initializer. */ NONE } /** A record of all assignments to variables in the current compilation unit. */ private static class VariableAssignmentRecords { private final Map<VarSymbol, VariableAssignments> assignments = new LinkedHashMap<>(); /** Returns all {@link VariableAssignments} in the current compilation unit. */ private Collection<VariableAssignments> getAssignments() { return assignments.values(); } /** Records an assignment to a variable. */ private void recordAssignment(Tree tree, InitializationContext init) { Symbol sym = ASTHelpers.getSymbol(tree); if (sym != null && sym.getKind() == ElementKind.FIELD) { recordAssignment((VarSymbol) sym, init); } } /** Records an assignment to a variable. */ private void recordAssignment(VarSymbol sym, InitializationContext init) { getDeclaration(sym).recordAssignment(init); } private VariableAssignments getDeclaration(VarSymbol sym) { return assignments.computeIfAbsent(sym, VariableAssignments::new); } /** Records a variable declaration. */ private void recordDeclaration(VarSymbol sym, VariableTree tree) { getDeclaration(sym).recordDeclaration(tree); } } /** A record of all assignments to a specific variable in the current compilation unit. */ private static class VariableAssignments { private final VarSymbol sym; private final EnumSet<InitializationContext> writes = EnumSet.noneOf(InitializationContext.class); private VariableTree declaration; VariableAssignments(VarSymbol sym) { this.sym = sym; } /** Records an assignment to the variable. */ private void recordAssignment(InitializationContext init) { writes.add(init); } /** Records that a variable was declared in this compilation unit. */ private void recordDeclaration(VariableTree tree) { declaration = tree; } /** Returns true if the variable is effectively final. */ private boolean isEffectivelyFinal() { if (declaration == null) { return false; } if (sym.getModifiers().contains(Modifier.FINAL)) { // actually final != effectively final return false; } if (writes.contains(InitializationContext.NONE)) { return false; } // The unsound heuristic for effectively final fields is that they are initialized at least // once in an initializer with the right static-ness. Multiple initializations are allowed // because we don't consider control flow, and zero initializations are allowed to handle // class and instance initializers, and delegating constructors that don't initialize the // field directly. InitializationContext wanted; InitializationContext other; if (sym.isStatic()) { wanted = InitializationContext.STATIC; other = InitializationContext.INSTANCE; } else { wanted = InitializationContext.INSTANCE; other = InitializationContext.STATIC; } if (writes.contains(other)) { return false; } return writes.contains(wanted) || (sym.flags() & Flags.HASINIT) == Flags.HASINIT; } private VariableTree declaration() { return declaration; } } @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { VariableAssignmentRecords writes = new VariableAssignmentRecords(); new FinalScanner(writes, state).scan(state.getPath(), InitializationContext.NONE); for (VariableAssignments var : writes.getAssignments()) { if (!var.isEffectivelyFinal()) { continue; } if (!canBeRemoved(var.sym)) { continue; } if (shouldKeep(var.declaration)) { continue; } if (IMPLICIT_VAR_ANNOTATIONS.stream().anyMatch(a -> hasAnnotation(var.sym, a, state))) { continue; } for (Attribute.Compound anno : var.sym.getAnnotationMirrors()) { TypeElement annoElement = (TypeElement) anno.getAnnotationType().asElement(); if (IMPLICIT_VAR_ANNOTATION_SIMPLE_NAMES.contains(annoElement.getSimpleName().toString())) { return Description.NO_MATCH; } if (annoElement.getQualifiedName().toString().startsWith(OBJECTIFY_PREFIX)) { return Description.NO_MATCH; } } VariableTree varDecl = var.declaration(); SuggestedFixes.addModifiers(varDecl, state, Modifier.FINAL) .filter(f -> SuggestedFixes.compilesWithFix(f, state)) .ifPresent(f -> state.reportMatch(describeMatch(varDecl, f))); } return Description.NO_MATCH; } /** Record assignments to possibly-final variables in a compilation unit. */ private class FinalScanner extends TreePathScanner<Void, InitializationContext> { private final VariableAssignmentRecords writes; private final VisitorState compilationState; private FinalScanner(VariableAssignmentRecords writes, VisitorState compilationState) { this.writes = writes; this.compilationState = compilationState; } @Override public Void visitVariable(VariableTree node, InitializationContext init) { VarSymbol sym = ASTHelpers.getSymbol(node); if (sym.getKind() == ElementKind.FIELD && !isSuppressed(node, compilationState)) { writes.recordDeclaration(sym, node); } return super.visitVariable(node, InitializationContext.NONE); } @Override public Void visitLambdaExpression( LambdaExpressionTree lambdaExpressionTree, InitializationContext init) { // reset the initialization context when entering lambda return super.visitLambdaExpression(lambdaExpressionTree, InitializationContext.NONE); } @Override public Void visitBlock(BlockTree node, InitializationContext init) { if (getCurrentPath().getParentPath().getLeaf().getKind() == Kind.CLASS) { init = node.isStatic() ? InitializationContext.STATIC : InitializationContext.INSTANCE; } return super.visitBlock(node, init); } @Override public Void visitMethod(MethodTree node, InitializationContext init) { MethodSymbol sym = ASTHelpers.getSymbol(node); if (sym.isConstructor()) { init = InitializationContext.INSTANCE; } return super.visitMethod(node, init); } @Override public Void visitAssignment(AssignmentTree node, InitializationContext init) { if (init == InitializationContext.INSTANCE && !isThisAccess(node.getVariable())) { // don't record assignments in initializers that aren't to members of the object // being initialized init = InitializationContext.NONE; } writes.recordAssignment(node.getVariable(), init); return super.visitAssignment(node, init); } private boolean isThisAccess(Tree tree) { if (tree.getKind() == Kind.IDENTIFIER) { return true; } if (tree.getKind() != Kind.MEMBER_SELECT) { return false; } ExpressionTree selected = ((MemberSelectTree) tree).getExpression(); if (!(selected instanceof IdentifierTree)) { return false; } IdentifierTree ident = (IdentifierTree) selected; return ident.getName().contentEquals("this"); } @Override public Void visitClass(ClassTree node, InitializationContext init) { VisitorState state = compilationState.withPath(getCurrentPath()); if (isSuppressed(node, state)) { return null; } for (Attribute.Compound anno : getSymbol(node).getAnnotationMirrors()) { TypeElement annoElement = (TypeElement) anno.getAnnotationType().asElement(); if (annoElement.getQualifiedName().toString().startsWith(OBJECTIFY_PREFIX)) { return null; } } // reset the initialization context when entering a new declaration return super.visitClass(node, InitializationContext.NONE); } @Override public Void visitCompoundAssignment(CompoundAssignmentTree node, InitializationContext init) { init = InitializationContext.NONE; writes.recordAssignment(node.getVariable(), init); return super.visitCompoundAssignment(node, init); } @Override public Void visitUnary(UnaryTree node, InitializationContext init) { if (UNARY_ASSIGNMENT.contains(node.getKind())) { init = InitializationContext.NONE; writes.recordAssignment(node.getExpression(), init); } return super.visitUnary(node, init); } } }
13,278
36.94
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MockitoUsage.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.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 java.util.List; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "Missing method call for verify(mock) here", severity = ERROR) public class MockitoUsage extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> MOCK_METHOD = anyOf( staticMethod().onClass("org.mockito.Mockito").withSignature("<T>when(T)"), staticMethod().onClass("org.mockito.Mockito").withSignature("<T>verify(T)"), staticMethod() .onClass("org.mockito.Mockito") .withSignature("<T>verify(T,org.mockito.verification.VerificationMode)")); private static final Matcher<ExpressionTree> NEVER_METHOD = staticMethod().onClass("org.mockito.Mockito").named("never").withNoParameters(); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MOCK_METHOD.matches(tree, state)) { return Description.NO_MATCH; } if (state.getPath().getParentPath().getLeaf().getKind() != Tree.Kind.EXPRESSION_STATEMENT) { return Description.NO_MATCH; } String message = String.format("Missing method call for %s here", state.getSourceForNode(tree)); Description.Builder builder = buildDescription(tree).setMessage(message); buildFix(builder, tree, state); return builder.build(); } /** * Create fixes for invalid assertions. * * <ul> * <li>Rewrite `verify(mock.bar())` to `verify(mock).bar()` * <li>Rewrite `verify(mock.bar(), times(N))` to `verify(mock, times(N)).bar()` * <li>Rewrite `verify(mock, never())` to `verifyZeroInteractions(mock)` * <li>Finally, offer to delete the mock statement. * </ul> */ private static void buildFix( Description.Builder builder, MethodInvocationTree tree, VisitorState state) { MethodInvocationTree mockitoCall = tree; List<? extends ExpressionTree> args = mockitoCall.getArguments(); Tree mock = mockitoCall.getArguments().get(0); boolean isVerify = ASTHelpers.getSymbol(tree).getSimpleName().contentEquals("verify"); if (isVerify && mock.getKind() == Kind.METHOD_INVOCATION) { MethodInvocationTree invocation = (MethodInvocationTree) mock; String verify = state.getSourceForNode(mockitoCall.getMethodSelect()); String receiver = state.getSourceForNode(ASTHelpers.getReceiver(invocation)); String mode = args.size() > 1 ? ", " + state.getSourceForNode(args.get(1)) : ""; String call = state.getSourceForNode(invocation).substring(receiver.length()); builder.addFix( SuggestedFix.replace(tree, String.format("%s(%s%s)%s", verify, receiver, mode, call))); } if (isVerify && args.size() > 1 && NEVER_METHOD.matches(args.get(1), state)) { // TODO(cushon): handle times(0) the same as never() builder.addFix( SuggestedFix.builder() .addStaticImport("org.mockito.Mockito.verifyZeroInteractions") .replace( tree, String.format("verifyZeroInteractions(%s)", state.getSourceForNode(mock))) .build()); } // Always suggest the naive semantics-preserving option, which is just to // delete the assertion: Tree parent = state.getPath().getParentPath().getLeaf(); if (parent.getKind() == Kind.EXPRESSION_STATEMENT) { // delete entire expression statement builder.addFix(SuggestedFix.delete(parent)); } else { builder.addFix(SuggestedFix.delete(tree)); } } }
4,953
44.036364
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TypeEqualsChecker.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.argument; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.staticEqualsInvocation; import static com.google.errorprone.matchers.Matchers.toType; import static com.google.errorprone.matchers.Matchers.typePredicateMatcher; import static com.google.errorprone.predicates.TypePredicates.isDescendantOf; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.predicates.TypePredicate; import com.sun.source.tree.MethodInvocationTree; /** * Flags com.sun.tools.javac.code.Type#equals usage. * * @author bhagwani@google.com (Sumit Bhagwani) */ @BugPattern( name = "TypeEquals", summary = "com.sun.tools.javac.code.Type doesn't override Object.equals and instances are not" + " interned by javac, so testing types for equality should be done with" + " Types#isSameType instead", severity = WARNING) public class TypeEqualsChecker extends BugChecker implements MethodInvocationTreeMatcher { private static final TypePredicate TYPE_MIRROR = isDescendantOf("javax.lang.model.type.TypeMirror"); private static final Matcher<MethodInvocationTree> TYPE_EQUALS = anyOf( toType(MethodInvocationTree.class, instanceMethod().onClass(TYPE_MIRROR).named("equals")), allOf( staticEqualsInvocation(), argument(0, typePredicateMatcher(TYPE_MIRROR)), argument(1, typePredicateMatcher(TYPE_MIRROR)))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!TYPE_EQUALS.matches(tree, state)) { return Description.NO_MATCH; } return describeMatch(tree); } }
2,847
39.685714
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NonFinalCompileTimeConstant.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.util.ASTHelpers.isConsideredFinal; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.matchers.CompileTimeConstantExpressionMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.code.Symbol.VarSymbol; /** * Enforce that @CompileTimeConstant parameters are final or effectively final. * * @author cushon@google.com (Liam Miller-Cushon) */ @BugPattern( summary = "@CompileTimeConstant parameters should be final or effectively final", severity = ERROR) public class NonFinalCompileTimeConstant extends BugChecker implements MethodTreeMatcher { @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (tree.getBody() == null) { return NO_MATCH; } for (VariableTree parameter : tree.getParameters()) { VarSymbol sym = ASTHelpers.getSymbol(parameter); if (!CompileTimeConstantExpressionMatcher.hasCompileTimeConstantAnnotation(state, sym)) { continue; } if (isConsideredFinal(sym)) { continue; } return describeMatch(parameter); } return NO_MATCH; } }
2,189
34.901639
95
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/WaitNotInLoop.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.inLoop; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.WaitMatchers.waitMethod; import static com.google.errorprone.matchers.WaitMatchers.waitMethodWithTimeout; 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.MethodInvocationTree; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.tree.JCTree.JCIf; /** * @author eaftan@google.com (Eddie Aftandilian) */ // TODO(eaftan): Doesn't handle the case that the enclosing method is always called in a loop. @BugPattern( summary = "Because of spurious wakeups, Object.wait() and Condition.await() must always be " + "called in a loop", severity = WARNING, tags = StandardTags.FRAGILE_CODE) public class WaitNotInLoop extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<MethodInvocationTree> matcher = allOf(waitMethod, not(inLoop())); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!matcher.matches(tree, state)) { return Description.NO_MATCH; } Description.Builder description = buildDescription(tree); MethodSymbol sym = ASTHelpers.getSymbol(tree); description.setMessage( String.format("Because of spurious wakeups, %s must always be called in a loop", sym)); // If this looks like the "Wait until a condition becomes true" case from the wiki content, // rewrite the enclosing if to a while. Other fixes are too complicated to construct // mechanically, so we provide detailed instructions in the wiki content. if (!waitMethodWithTimeout.matches(tree, state)) { JCIf enclosingIf = ASTHelpers.findEnclosingNode(state.getPath().getParentPath(), JCIf.class); if (enclosingIf != null && enclosingIf.getElseStatement() == null) { CharSequence ifSource = state.getSourceForNode(enclosingIf); if (ifSource == null) { // Source isn't available, so we can't construct a fix return description.build(); } String replacement = ifSource.toString().replaceFirst("if", "while"); return description.addFix(SuggestedFix.replace(enclosingIf, replacement)).build(); } } return description.build(); } }
3,524
41.987805
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StringBuilderInitWithChar.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 com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.util.Convert; import javax.lang.model.type.TypeKind; /** * @author lowasser@google.com (Louis Wasserman) */ @BugPattern( severity = ERROR, summary = "StringBuilder does not have a char constructor; this invokes the int constructor.") public class StringBuilderInitWithChar extends BugChecker implements NewClassTreeMatcher { @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { if (ASTHelpers.isSameType( state.getSymtab().stringBuilderType, ASTHelpers.getType(tree.getIdentifier()), state) && tree.getArguments().size() == 1) { ExpressionTree argument = tree.getArguments().get(0); Type type = ASTHelpers.getType(argument); if (type.getKind() == TypeKind.CHAR) { if (argument.getKind() == Kind.CHAR_LITERAL) { char ch = (Character) ((LiteralTree) argument).getValue(); return describeMatch( tree, SuggestedFix.replace(argument, "\"" + Convert.quote(Character.toString(ch)) + "\"")); } else { return describeMatch( tree, SuggestedFix.replace( tree, "new StringBuilder().append(" + state.getSourceForNode(argument) + ")")); } } } return Description.NO_MATCH; } }
2,536
38.640625
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BoxedPrimitiveEquality.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.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isStatic; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.sun.source.tree.ExpressionTree; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import javax.inject.Inject; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Comparison using reference equality instead of value equality. Reference equality of" + " boxed primitive types is usually not useful, as they are value objects, and it is" + " bug-prone, as instances are cached for some values but not others.", altNames = {"NumericEquality"}, severity = ERROR) public final class BoxedPrimitiveEquality extends AbstractReferenceEquality { @Inject BoxedPrimitiveEquality() {} @Override protected boolean matchArgument(ExpressionTree tree, VisitorState state) { var type = getType(tree); if (type == null || !isRelevantType(type, state)) { return false; } // Using a static final field as a sentinel is OK // TODO(cushon): revisit this assumption carried over from NumericEquality return !isStaticConstant(getSymbol(tree)); } private boolean isRelevantType(Type type, VisitorState state) { return !type.isPrimitive() && state.getTypes().unboxedType(type).isPrimitive(); } private static boolean isStaticConstant(Symbol sym) { return sym instanceof VarSymbol && isFinal(sym) && isStatic(sym); } public static boolean isFinal(Symbol s) { return (s.flags() & Flags.FINAL) == Flags.FINAL; } }
2,582
35.9
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MixedMutabilityReturnType.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.fixes.SuggestedFixes.qualifyType; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.Matchers.nothing; 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.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.methodCanBeOverridden; import com.google.auto.value.AutoValue; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; 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.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import javax.lang.model.type.TypeKind; /** * Flags methods which return mutable collections from some code paths, but immutable ones from * others. */ @BugPattern( summary = "This method returns both mutable and immutable collections or maps from different " + "paths. This may be confusing for users of the method.", severity = SeverityLevel.WARNING) public final class MixedMutabilityReturnType extends BugChecker implements CompilationUnitTreeMatcher { private static final Matcher<ExpressionTree> IMMUTABLE_FACTORY = staticMethod() .onClass("java.util.Collections") .namedAnyOf("emptyList", "emptyMap", "emptySet", "singleton", "singletonList"); private static final Matcher<ExpressionTree> EMPTY_INITIALIZER = anyOf( constructor().forClass("java.util.ArrayList").withNoParameters(), constructor().forClass("java.util.HashMap").withNoParameters(), staticMethod() .onClass("com.google.common.collect.Lists") .namedAnyOf("newArrayList", "newLinkedList") .withNoParameters(), staticMethod() .onClass("com.google.common.collect.Sets") .namedAnyOf("newHashSet", "newLinkedHashSet") .withNoParameters()); private static final Matcher<ExpressionTree> IMMUTABLE = anyOf( IMMUTABLE_FACTORY, isSubtypeOf(ImmutableCollection.class), isSubtypeOf(ImmutableMap.class)); private static final Matcher<ExpressionTree> MUTABLE = anyOf( isSubtypeOf(ArrayList.class), isSubtypeOf(LinkedHashSet.class), isSubtypeOf(LinkedHashMap.class), isSubtypeOf(LinkedList.class), isSubtypeOf(HashMap.class), isSubtypeOf(HashBiMap.class), isSubtypeOf(TreeMap.class)); private static final Matcher<Tree> RETURNS_COLLECTION = anyOf(isSubtypeOf(Collection.class), isSubtypeOf(Map.class)); private static final ImmutableMap<Matcher<Tree>, TypeDetails> REFACTORING_DETAILS = ImmutableMap.of( isSubtypeOf(BiMap.class), TypeDetails.of( "com.google.common.collect.ImmutableBiMap", instanceMethod() .onDescendantOf(BiMap.class.getName()) .namedAnyOf("put", "putAll"), nothing()), allOf(isSubtypeOf(Map.class), not(isSubtypeOf(BiMap.class))), TypeDetails.of( "com.google.common.collect.ImmutableMap", instanceMethod().onDescendantOf(Map.class.getName()).namedAnyOf("put", "putAll"), isSubtypeOf(SortedMap.class)), isSubtypeOf(List.class), TypeDetails.of( "com.google.common.collect.ImmutableList", instanceMethod().onDescendantOf(List.class.getName()).namedAnyOf("add", "addAll"), nothing()), isSubtypeOf(Set.class), TypeDetails.of( "com.google.common.collect.ImmutableSet", instanceMethod().onDescendantOf(Set.class.getName()).namedAnyOf("add", "addAll"), nothing())); @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { VariableMutabilityScanner variableMutabilityScanner = new VariableMutabilityScanner(state); variableMutabilityScanner.scan(state.getPath(), null); new ReturnTypesScanner( state, variableMutabilityScanner.immutable, variableMutabilityScanner.mutable) .scan(state.getPath(), null); return Description.NO_MATCH; } private static final class VariableMutabilityScanner extends TreePathScanner<Void, Void> { private final VisitorState state; private final Set<VarSymbol> mutable = new HashSet<>(); private final Set<VarSymbol> immutable = new HashSet<>(); private VariableMutabilityScanner(VisitorState state) { this.state = state; } @Override public Void visitVariable(VariableTree variableTree, Void unused) { VarSymbol symbol = getSymbol(variableTree); ExpressionTree initializer = variableTree.getInitializer(); if (initializer != null && getType(initializer) != null && getType(initializer).getKind() != TypeKind.NULL && RETURNS_COLLECTION.matches(initializer, state)) { if (IMMUTABLE.matches(initializer, state)) { immutable.add(symbol); } if (MUTABLE.matches(initializer, state)) { mutable.add(symbol); } } return super.visitVariable(variableTree, unused); } } private final class ReturnTypesScanner extends SuppressibleTreePathScanner<Void, Void> { private final VisitorState state; private final Set<VarSymbol> mutable; private final Set<VarSymbol> immutable; private ReturnTypesScanner( VisitorState state, Set<VarSymbol> immutable, Set<VarSymbol> mutable) { super(state); this.state = state; this.immutable = immutable; this.mutable = mutable; } @Override public Void visitMethod(MethodTree methodTree, Void unused) { if (!RETURNS_COLLECTION.matches(methodTree.getReturnType(), state)) { return super.visitMethod(methodTree, unused); } MethodScanner scanner = new MethodScanner(); scanner.scan(getCurrentPath(), null); if (!scanner.immutableReturns.isEmpty() && !scanner.mutableReturns.isEmpty()) { state.reportMatch( buildDescription(methodTree) .addAllFixes( generateFixes( ImmutableList.<ReturnTree>builder() .addAll(scanner.mutableReturns) .addAll(scanner.immutableReturns) .build(), getCurrentPath(), state)) .build()); } return super.visitMethod(methodTree, unused); } private final class MethodScanner extends TreePathScanner<Void, Void> { private final List<ReturnTree> immutableReturns = new ArrayList<>(); private final List<ReturnTree> mutableReturns = new ArrayList<>(); private boolean skipMethods = false; @Override public Void visitMethod(MethodTree node, Void unused) { if (skipMethods) { return null; } skipMethods = true; return super.visitMethod(node, null); } @Override public Void visitReturn(ReturnTree returnTree, Void unused) { if (returnTree.getExpression() instanceof IdentifierTree) { Symbol symbol = getSymbol(returnTree.getExpression()); if (mutable.contains(symbol)) { mutableReturns.add(returnTree); return super.visitReturn(returnTree, null); } if (immutable.contains(symbol)) { immutableReturns.add(returnTree); return super.visitReturn(returnTree, null); } } Type type = getType(returnTree.getExpression()); if (type == null || type.getKind() == TypeKind.NULL) { return super.visitReturn(returnTree, null); } if (IMMUTABLE.matches(returnTree.getExpression(), state)) { immutableReturns.add(returnTree); } if (MUTABLE.matches(returnTree.getExpression(), state)) { mutableReturns.add(returnTree); } return super.visitReturn(returnTree, null); } @Override public Void visitLambdaExpression(LambdaExpressionTree node, Void unused) { return null; } } } private static ImmutableList<SuggestedFix> generateFixes( List<ReturnTree> returnTrees, TreePath methodTree, VisitorState state) { SuggestedFix.Builder simpleFix = SuggestedFix.builder(); SuggestedFix.Builder fixWithBuilders = SuggestedFix.builder(); boolean anyBuilderFixes = false; Matcher<Tree> returnTypeMatcher = null; for (Map.Entry<Matcher<Tree>, TypeDetails> entry : REFACTORING_DETAILS.entrySet()) { Tree returnType = ((MethodTree) methodTree.getLeaf()).getReturnType(); Matcher<Tree> matcher = entry.getKey(); if (matcher.matches(returnType, state)) { // Only change the return type if the method is not overridable, otherwise this could // break builds. if (!methodCanBeOverridden(getSymbol((MethodTree) methodTree.getLeaf()))) { SuggestedFix.Builder fixBuilder = SuggestedFix.builder(); fixBuilder.replace( ASTHelpers.getErasedTypeTree(returnType), qualifyType(state, fixBuilder, entry.getValue().immutableType())); simpleFix.merge(fixBuilder); fixWithBuilders.merge(fixBuilder); } returnTypeMatcher = isSubtypeOf(entry.getValue().immutableType()); break; } } if (returnTypeMatcher == null) { return ImmutableList.of(); } for (ReturnTree returnTree : returnTrees) { if (returnTypeMatcher.matches(returnTree.getExpression(), state)) { break; } for (Map.Entry<Matcher<Tree>, TypeDetails> entry : REFACTORING_DETAILS.entrySet()) { Matcher<Tree> predicate = entry.getKey(); TypeDetails typeDetails = entry.getValue(); ExpressionTree expression = returnTree.getExpression(); // Skip already immutable returns. if (!predicate.matches(expression, state)) { continue; } if (expression instanceof IdentifierTree) { SuggestedFix simple = applySimpleFix(typeDetails.immutableType(), expression, state); // If we're returning an identifier of this mutable type, try to turn it into a Builder. ReturnTypeFixer returnTypeFixer = new ReturnTypeFixer(getSymbol(expression), typeDetails, state); returnTypeFixer.scan(methodTree, null); anyBuilderFixes |= !returnTypeFixer.failed; simpleFix.merge(simple); fixWithBuilders.merge(returnTypeFixer.failed ? simple : returnTypeFixer.fix.build()); break; } if (IMMUTABLE_FACTORY.matches(expression, state)) { SuggestedFix.Builder fix = SuggestedFix.builder(); fix.replace( ((MethodInvocationTree) expression).getMethodSelect(), qualifyType(state, fix, typeDetails.immutableType()) + ".of"); simpleFix.merge(fix); fixWithBuilders.merge(fix); break; } SuggestedFix simple = applySimpleFix(typeDetails.immutableType(), expression, state); simpleFix.merge(simple); fixWithBuilders.merge(simple); break; } } if (!anyBuilderFixes) { return ImmutableList.of(simpleFix.build()); } return ImmutableList.of( simpleFix.build(), fixWithBuilders .setShortDescription( "Fix using builders. Warning: this may change behaviour " + "if duplicate keys are added to ImmutableMap.Builder.") .build()); } private static SuggestedFix applySimpleFix( String immutableType, ExpressionTree expression, VisitorState state) { SuggestedFix.Builder fix = SuggestedFix.builder(); fix.replace( expression, String.format( "%s.copyOf(%s)", qualifyType(state, fix, immutableType), state.getSourceForNode(expression))); return fix.build(); } private static final class ReturnTypeFixer extends TreePathScanner<Void, Void> { private final Symbol symbol; private final TypeDetails details; private final VisitorState state; private final SuggestedFix.Builder fix = SuggestedFix.builder(); private boolean builderifiedVariable = false; private boolean failed = false; private ReturnTypeFixer(Symbol symbol, TypeDetails details, VisitorState state) { this.symbol = symbol; this.details = details; this.state = state; } @Override public Void visitVariable(VariableTree variableTree, Void unused) { if (!getSymbol(variableTree).equals(symbol)) { return super.visitVariable(variableTree, null); } if (variableTree.getInitializer() == null || !EMPTY_INITIALIZER.matches(variableTree.getInitializer(), state) || details.skipTypes().matches(variableTree.getInitializer(), state)) { failed = true; return null; } Tree erasedType = ASTHelpers.getErasedTypeTree(variableTree.getType()); // don't try to replace synthetic nodes for `var` if (ASTHelpers.getStartPosition(erasedType) != -1) { fix.replace(erasedType, qualifyType(state, fix, details.builderType())); } if (variableTree.getInitializer() != null) { fix.replace( variableTree.getInitializer(), qualifyType(state, fix, details.immutableType()) + ".builder()"); } builderifiedVariable = true; return super.visitVariable(variableTree, null); } @Override public Void visitIdentifier(IdentifierTree identifier, Void unused) { Tree parent = getCurrentPath().getParentPath().getLeaf(); if (!getSymbol(identifier).equals(symbol)) { return null; } if (parent instanceof VariableTree) { VariableTree variable = (VariableTree) parent; fix.replace(variable.getType(), qualifyType(state, fix, details.builderType())); return null; } if (parent instanceof MemberSelectTree) { Tree grandParent = getCurrentPath().getParentPath().getParentPath().getLeaf(); if (grandParent instanceof MethodInvocationTree) { if (!details.appendMethods().matches((MethodInvocationTree) grandParent, state)) { failed = true; return null; } } return null; } if (!builderifiedVariable) { failed = true; return null; } if (parent instanceof ReturnTree) { fix.postfixWith(identifier, ".build()"); } return null; } } @AutoValue abstract static class TypeDetails { abstract String immutableType(); abstract String builderType(); abstract Matcher<ExpressionTree> appendMethods(); abstract Matcher<Tree> skipTypes(); static TypeDetails of( String immutableType, Matcher<ExpressionTree> appendMethods, Matcher<Tree> skipTypes) { return new AutoValue_MixedMutabilityReturnType_TypeDetails( immutableType, immutableType + ".Builder", appendMethods, skipTypes); } } }
17,777
38.331858
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ThrowSpecificExceptions.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 com.google.auto.value.AutoValue; import com.google.common.base.VerifyException; 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.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.ThrowTree; /** Bugpattern to discourage throwing base exception classes. */ @BugPattern( summary = "Base exception classes should be treated as abstract. If the exception is intended to be" + " caught, throw a domain-specific exception. Otherwise, prefer a more specific" + " exception for clarity. Common alternatives include: AssertionError," + " IllegalArgumentException, IllegalStateException, and (Guava's) VerifyException.", explanation = "1. Defensive coding: Using a generic exception would force a caller that wishes to catch" + " it to potentially catch unrelated exceptions as well." + "\n\n" + "2. Clarity: Base exception classes offer no information on the nature of the" + " failure.", severity = WARNING) public final class ThrowSpecificExceptions extends BugChecker implements NewClassTreeMatcher { private static final ImmutableList<AbstractLikeException> ABSTRACT_LIKE_EXCEPTIONS = ImmutableList.of( AbstractLikeException.of(RuntimeException.class, VerifyException.class), AbstractLikeException.of(Throwable.class, AssertionError.class), AbstractLikeException.of(Error.class, AssertionError.class)); @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { if (tree.getClassBody() != null || !(state.getPath().getParentPath().getLeaf() instanceof ThrowTree) || state.errorProneOptions().isTestOnlyTarget()) { return Description.NO_MATCH; } for (AbstractLikeException abstractLikeException : ABSTRACT_LIKE_EXCEPTIONS) { if (abstractLikeException.matcher().matches(tree, state)) { SuggestedFix.Builder fix = SuggestedFix.builder(); String className = SuggestedFixes.qualifyType(state, fix, abstractLikeException.replacement()); return describeMatch(tree, fix.replace(tree.getIdentifier(), className).build()); } } return Description.NO_MATCH; } @AutoValue abstract static class AbstractLikeException { abstract Matcher<ExpressionTree> matcher(); abstract String replacement(); static AbstractLikeException of(Class<?> abstractLikeException, Class<?> replacement) { return new AutoValue_ThrowSpecificExceptions_AbstractLikeException( Matchers.constructor().forClass(abstractLikeException.getName()), replacement.getName()); } } }
3,834
43.08046
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CannotMockMethod.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.staticMethod; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static java.lang.String.format; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol.MethodSymbol; /** A BugPattern; see the summary */ @BugPattern( summary = "Mockito cannot mock final or static methods, and can't detect this at runtime", altNames = {"MockitoBadFinalMethod", "CannotMockFinalMethod"}, severity = WARNING) public final class CannotMockMethod extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> WHEN = staticMethod().onClass("org.mockito.Mockito").named("when"); private static final Matcher<ExpressionTree> VERIFY = staticMethod().onClass("org.mockito.Mockito").named("verify"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (WHEN.matches(tree, state)) { ExpressionTree firstArgument = tree.getArguments().get(0); if (!(firstArgument instanceof MethodInvocationTree)) { return NO_MATCH; } return describe(tree, getSymbol((MethodInvocationTree) firstArgument)); } var receiver = getReceiver(tree); if (receiver != null && VERIFY.matches(receiver, state)) { return describe(tree, getSymbol(tree)); } return NO_MATCH; } private Description describe(MethodInvocationTree tree, MethodSymbol methodSymbol) { if (methodSymbol.isStatic()) { return buildDescription(tree, "static"); } if ((methodSymbol.flags() & Flags.FINAL) == Flags.FINAL) { return buildDescription(tree, "final"); } return NO_MATCH; } private Description buildDescription(MethodInvocationTree tree, String issue) { return buildDescription(tree) .setMessage( format("Mockito cannot mock %s methods, and can't detect this at runtime", issue)) .build(); } }
3,181
38.775
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/PrimitiveAtomicReference.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.method.MethodMatchers.instanceMethod; import static com.google.errorprone.util.ASTHelpers.getReceiver; 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.sun.source.tree.ExpressionTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Type; import javax.lang.model.type.TypeKind; /** Discourages inadvertently using reference equality on boxed primitives in AtomicReference. */ @BugPattern( summary = "Using compareAndSet with boxed primitives is dangerous, as reference rather than value" + " equality is used. Consider using AtomicInteger, AtomicLong, AtomicBoolean from JDK" + " or AtomicDouble from Guava instead.", severity = WARNING) public final class PrimitiveAtomicReference extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> COMPARE_AND_SET = instanceMethod() .onDescendantOf("java.util.concurrent.atomic.AtomicReference") .namedAnyOf("compareAndSet", "weakCompareAndSet"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!COMPARE_AND_SET.matches(tree, state)) { return NO_MATCH; } ExpressionTree firstArgument = tree.getArguments().get(0); if (firstArgument instanceof LiteralTree && ((LiteralTree) firstArgument).getValue() == null) { return NO_MATCH; } Type receiverType = getType(getReceiver(tree)); if (receiverType == null) { return NO_MATCH; } // There could be no type arguments if we're seeing a raw type. if (receiverType.getTypeArguments().isEmpty()) { return NO_MATCH; } Type typeArgument = receiverType.getTypeArguments().get(0); if (state.getTypes().unboxedType(typeArgument).getKind() == TypeKind.NONE) { return NO_MATCH; } return describeMatch(tree); } }
3,053
40.27027
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ConstantField.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 com.google.common.base.Ascii; import com.google.common.base.CaseFormat; 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.util.ASTHelpers; 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.VarSymbol; 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 = "Fields with CONSTANT_CASE names should be both static and final", severity = SUGGESTION, tags = BugPattern.StandardTags.STYLE) public class ConstantField extends BugChecker implements VariableTreeMatcher { @Override public Description matchVariable(VariableTree tree, VisitorState state) { Symbol.VarSymbol sym = ASTHelpers.getSymbol(tree); if (sym.getKind() != ElementKind.FIELD) { return Description.NO_MATCH; } String name = sym.getSimpleName().toString(); if (sym.isStatic() && sym.getModifiers().contains(Modifier.FINAL)) { return Description.NO_MATCH; } if (!name.equals(Ascii.toUpperCase(name))) { return Description.NO_MATCH; } Description.Builder descriptionBuilder = buildDescription(tree); if (canBecomeStaticMember(sym)) { SuggestedFixes.addModifiers(tree, state, Modifier.FINAL, Modifier.STATIC) .map( f -> SuggestedFix.builder() .setShortDescription("make static and final") .merge(f) .build()) .ifPresent(descriptionBuilder::addFix); } return descriptionBuilder .addFix( SuggestedFix.builder() .setShortDescription("change to camelcase") .merge( SuggestedFixes.renameVariable( tree, CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name), state)) .build()) .build(); } private static boolean canBecomeStaticMember(VarSymbol sym) { // JLS 8.1.3: It is a compile-time error if an inner class declares a member that is // explicitly or implicitly static, unless the member is a constant variable (§4.12.4). // We could try and figure out if the declaration *would* be a compile time constant if made // static, but that's a bit much to keep adding this fix. ClassSymbol owningClass = sym.enclClass(); // Enum anonymous classes aren't considered isInner() even though they can't hold static fields switch (owningClass.getNestingKind()) { case LOCAL: case ANONYMOUS: return false; default: return !owningClass.isInner(); } } }
3,792
37.704082
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AutoValueBuilderDefaultsInConstructor.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.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.getType; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static java.lang.String.join; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.tree.ExpressionStatementTree; 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.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import java.util.List; import javax.lang.model.element.Modifier; /** See summary for details. */ @BugPattern( summary = "Defaults for AutoValue Builders should be set in the factory method returning Builder" + " instances, not the constructor", severity = ERROR) public final class AutoValueBuilderDefaultsInConstructor extends BugChecker implements MethodTreeMatcher { @Override public Description matchMethod(MethodTree tree, VisitorState state) { MethodSymbol symbol = getSymbol(tree); if (!symbol.isConstructor()) { return NO_MATCH; } if (!hasAnnotation(symbol.owner, "com.google.auto.value.AutoValue.Builder", state)) { return NO_MATCH; } ImmutableList<String> invocations = extractInvocations(symbol, tree.getBody().getStatements(), state); if (invocations.isEmpty()) { return NO_MATCH; } return describeMatch(tree, appendDefaultsToConstructors(tree, symbol, invocations, state)); } private static SuggestedFix appendDefaultsToConstructors( MethodTree tree, MethodSymbol symbol, ImmutableList<String> invocations, VisitorState state) { SuggestedFix.Builder fix = SuggestedFix.builder().delete(tree); String defaultSetters = "." + join(".", invocations); new TreePathScanner<Void, Void>() { @Override public Void visitNewClass(NewClassTree tree, Void unused) { if (isSubtype(getType(tree), symbol.owner.type, state)) { fix.postfixWith(tree, defaultSetters); } return super.visitNewClass(tree, null); } }.scan(state.getPath().getCompilationUnit(), null); return fix.build(); } private static ImmutableList<String> extractInvocations( MethodSymbol symbol, List<? extends StatementTree> statements, VisitorState state) { return statements.stream() .filter(t -> t instanceof ExpressionStatementTree) .map(t -> (ExpressionStatementTree) t) .filter(t -> t.getExpression() instanceof MethodInvocationTree) .map(t -> (MethodInvocationTree) t.getExpression()) .filter( t -> { Symbol calledSymbol = getSymbol(t.getMethodSelect()); return calledSymbol.owner.equals(symbol.owner) && calledSymbol.getModifiers().contains(Modifier.ABSTRACT); }) .map(t -> state.getSourceForNode(t).replaceFirst("^this\\.", "")) .collect(toImmutableList()); } }
4,277
39.358491
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/Interruption.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.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.VisitorState.memoize; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.Matchers.receiverOfInvocation; import static com.google.errorprone.matchers.Matchers.toType; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.constValue; import static com.google.errorprone.util.ASTHelpers.enclosingClass; import static com.google.errorprone.util.ASTHelpers.getSymbol; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import java.util.Objects; import javax.lang.model.element.ElementKind; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Always pass 'false' to 'Future.cancel()', unless you are propagating a" + " cancellation-with-interrupt from another caller", severity = WARNING) public class Interruption extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> CANCEL = instanceMethod() .onDescendantOfAny( "java.util.concurrent.Future", "com.google.common.util.concurrent.ClosingFuture") .named("cancel") .withParameters("boolean"); private static final Matcher<MethodInvocationTree> INTERRUPT_OTHER_THREAD = allOf( toType( MethodInvocationTree.class, instanceMethod() .onDescendantOf("java.lang.Thread") .named("interrupt") .withNoParameters()), not( receiverOfInvocation( staticMethod() .onDescendantOf("java.lang.Thread") .named("currentThread") .withNoParameters()))); private static final Matcher<ExpressionTree> WAS_INTERRUPTED = instanceMethod() .onDescendantOf("com.google.common.util.concurrent.AbstractFuture") .named("wasInterrupted") .withNoParameters(); private static final Supplier<Symbol> JAVA_UTIL_CONCURRENT_FUTURE = memoize(state -> state.getSymbolFromString("java.util.concurrent.Future")); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (state.errorProneOptions().isTestOnlyTarget()) { return NO_MATCH; } // Thread.interrupt() other than Thread.currentThread().interrupt() (handles restoring an // interrupt after catching it) if (INTERRUPT_OTHER_THREAD.matches(tree, state)) { return buildDescription(tree) .setMessage( "Thread.interrupt should not be called, except to record the interrupt status on the" + " current thread when dealing with InterruptedException") .build(); } // Future.cancel calls ... if (!CANCEL.matches(tree, state)) { return NO_MATCH; } // ... unless they pass a literal 'false' ExpressionTree argument = getOnlyElement(tree.getArguments()); if (Objects.equals(constValue(argument, Boolean.class), Boolean.FALSE)) { return NO_MATCH; } // ... OR cancel(AbstractFuture.wasInterrupted()) if (WAS_INTERRUPTED.matches(argument, state)) { return NO_MATCH; } // ... OR // // @Override // public boolean cancel(boolean mayInterruptIfRunning) { // ... // someFuture.cancel(mayInterruptIfRunning); // ... // } if (delegatingCancelMethod(state, argument)) { return NO_MATCH; } return describeMatch(tree, SuggestedFix.replace(argument, "false")); } private boolean delegatingCancelMethod(VisitorState state, ExpressionTree argument) { Symbol sym = getSymbol(argument); if (sym == null) { return false; } if (!sym.getKind().equals(ElementKind.PARAMETER)) { return false; } MethodSymbol methodSymbol = (MethodSymbol) sym.owner; if (methodSymbol.getParameters().size() != 1 || !methodSymbol.getSimpleName().contentEquals("cancel")) { return false; } Symbol.ClassSymbol classSymbol = enclosingClass(methodSymbol); if (!classSymbol.isSubClass(JAVA_UTIL_CONCURRENT_FUTURE.get(state), state.getTypes())) { return false; } return true; } }
5,845
38.768707
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/RandomModInteger.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 com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree.Kind; /** * @author Louis Wasserman */ @BugPattern( summary = "Use Random.nextInt(int). Random.nextInt() % n can have negative results", severity = SeverityLevel.ERROR) public class RandomModInteger extends BugChecker implements BinaryTreeMatcher { private static final Matcher<ExpressionTree> RANDOM_NEXT_INT = Matchers.instanceMethod() .onDescendantOf("java.util.Random") .named("nextInt") .withNoParameters(); @Override public Description matchBinary(BinaryTree tree, VisitorState state) { if (tree.getKind() == Kind.REMAINDER && tree.getLeftOperand() instanceof MethodInvocationTree && RANDOM_NEXT_INT.matches(tree.getLeftOperand(), state)) { ExpressionTree randomExpr = ASTHelpers.getReceiver(tree.getLeftOperand()); ExpressionTree modulus = tree.getRightOperand(); return describeMatch( tree, SuggestedFix.replace( tree, String.format( "%s.nextInt(%s)", state.getSourceForNode(randomExpr), state.getSourceForNode(modulus)))); } return Description.NO_MATCH; } }
2,422
36.276923
89
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AbstractPatternSyntaxChecker.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.staticMethod; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.CheckReturnValue; import com.google.errorprone.annotations.ForOverride; 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.MethodInvocationTree; /** Finds calls to regex-accepting methods with literal strings. */ @CheckReturnValue public abstract class AbstractPatternSyntaxChecker extends BugChecker implements MethodInvocationTreeMatcher { /* * Match invocations to regex-accepting methods. Subclasses will be consulted to see whether the * pattern passed to such methods are acceptable. */ private static final Matcher<MethodInvocationTree> REGEX_USAGE = anyOf( instanceMethod() .onExactClass("java.lang.String") .namedAnyOf("matches", "split") .withParameters("java.lang.String"), instanceMethod() .onExactClass("java.lang.String") .named("split") .withParameters("java.lang.String", "int"), instanceMethod() .onExactClass("java.lang.String") .namedAnyOf("replaceFirst", "replaceAll") .withParameters("java.lang.String", "java.lang.String"), staticMethod().onClass("java.util.regex.Pattern").named("matches"), staticMethod() .onClass("java.util.regex.Pattern") .named("compile") .withParameters("java.lang.String"), staticMethod().onClass("com.google.common.base.Splitter").named("onPattern")); private static final Matcher<MethodInvocationTree> REGEX_USAGE_WITH_FLAGS = anyOf( staticMethod() .onClass("java.util.regex.Pattern") .named("compile") .withParameters("java.lang.String", "int")); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (getMatcherWithoutFlags().matches(tree, state)) { String pattern = ASTHelpers.constValue(tree.getArguments().get(0), String.class); if (pattern != null) { return matchRegexLiteral(tree, state, pattern, 0); } } else if (getMatcherWithFlags().matches(tree, state)) { String pattern = ASTHelpers.constValue(tree.getArguments().get(0), String.class); Integer flags = ASTHelpers.constValue(tree.getArguments().get(1), Integer.class); if (pattern != null && flags != null) { return matchRegexLiteral(tree, state, pattern, flags); } } return NO_MATCH; } @ForOverride protected Matcher<? super MethodInvocationTree> getMatcherWithoutFlags() { return REGEX_USAGE; } @ForOverride protected Matcher<? super MethodInvocationTree> getMatcherWithFlags() { return REGEX_USAGE_WITH_FLAGS; } @ForOverride protected abstract Description matchRegexLiteral( MethodInvocationTree tree, VisitorState state, String pattern, int flags); }
4,047
39.079208
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/OrphanedFormatString.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.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.findMatchingMethods; import static com.google.errorprone.util.ASTHelpers.getReceiverType; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.FormatMethod; import com.google.errorprone.annotations.FormatString; import com.google.errorprone.bugpatterns.BugChecker.LiteralTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.predicates.TypePredicates; 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.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import java.util.IllegalFormatException; import java.util.List; import java.util.MissingFormatArgumentException; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "String literal contains format specifiers, but is not passed to a format method", severity = WARNING) public class OrphanedFormatString extends BugChecker implements LiteralTreeMatcher { /** Method calls that developers commonly incorrectly assume to accept format arguments. */ private static final Matcher<Tree> LIKELY_MISTAKE_METHOD_CALL = toType( ExpressionTree.class, anyOf( constructor().forClass("java.lang.StringBuilder"), allOf( constructor() .forClass(TypePredicates.isDescendantOf(s -> s.getSymtab().throwableType)), (tree, state) -> { Symbol sym = getSymbol(tree); return sym instanceof MethodSymbol && !((MethodSymbol) sym).isVarArgs(); }), instanceMethod() .onDescendantOfAny("java.io.PrintStream", "java.io.PrintWriter") .namedAnyOf("print", "println"), instanceMethod() .onExactClass("java.lang.StringBuilder") .named("append") .withParameters("java.lang.CharSequence", "int", "int"), staticMethod() .onClass("com.google.common.truth.Truth") .named("assertWithMessage") .withParameters("java.lang.String"), instanceMethod() .onDescendantOf("com.google.common.flogger.LoggingApi") .named("log") .withParameters("java.lang.String"), (t, s) -> t instanceof MethodInvocationTree && !findMatchingMethods( getSymbol(t).name, ms -> hasAnnotation(ms, FormatMethod.class, s) || ms.getParameters().stream() .anyMatch(vs -> hasAnnotation(vs, FormatString.class, s)), getReceiverType(t), s.getTypes()) .isEmpty())); @Override public Description matchLiteral(LiteralTree tree, VisitorState state) { Object value = tree.getValue(); if (!(value instanceof String)) { return NO_MATCH; } if (!missingFormatArgs((String) value)) { return NO_MATCH; } Tree methodInvocation = state.getPath().getParentPath().getLeaf(); if (!LIKELY_MISTAKE_METHOD_CALL.matches(methodInvocation, state)) { return NO_MATCH; } // If someone has added new API methods to a subtype of the commonly-misused classes, we can // check to see if they made it @FormatMethod and the format-string slots in correctly. if (methodInvocation.getKind() == Kind.METHOD_INVOCATION && literalIsFormatMethodArg(tree, (MethodInvocationTree) methodInvocation, state)) { return NO_MATCH; } return describeMatch(tree); } private static boolean literalIsFormatMethodArg( LiteralTree tree, MethodInvocationTree methodInvocationTree, VisitorState state) { MethodSymbol symbol = getSymbol(methodInvocationTree); if (hasAnnotation(symbol, FormatMethod.class, state)) { int indexOfParam = findIndexOfFormatStringParameter(state, symbol); if (indexOfParam != -1) { List<? extends ExpressionTree> args = methodInvocationTree.getArguments(); // This *shouldn't* be a problem, since this means that the format string is in a varargs // position in a @FormatMethod declaration and the invocation contained no varargs // arguments, but it doesn't hurt to check. return args.size() > indexOfParam && args.get(indexOfParam) == tree; } } return false; } private static int findIndexOfFormatStringParameter(VisitorState state, MethodSymbol symbol) { // Find a parameter with @FormatString, if none, use the first String parameter int indexOfFirstString = -1; List<VarSymbol> params = symbol.params(); for (int i = 0; i < params.size(); i++) { VarSymbol varSymbol = params.get(i); if (hasAnnotation(varSymbol, FormatString.class, state)) { return i; } if (indexOfFirstString == -1 && ASTHelpers.isSameType(varSymbol.type, state.getSymtab().stringType, state)) { indexOfFirstString = i; } } return indexOfFirstString; } /** Returns true for strings that contain format specifiers. */ @SuppressWarnings("StringFormatWithoutAnyParams") private static boolean missingFormatArgs(String value) { try { String unused = String.format(value); } catch (MissingFormatArgumentException e) { return true; } catch (IllegalFormatException ignored) { // we don't care about other errors (it isn't supposed to be a format string) } return false; } }
7,463
42.905882
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/EqualsNaN.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 com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCExpression; import javax.annotation.Nullable; /** * @author lowasser@google.com (Louis Wasserman) */ @BugPattern( summary = "== NaN always returns false; use the isNaN methods instead", severity = ERROR) public class EqualsNaN extends BugChecker implements BinaryTreeMatcher { @Override public Description matchBinary(BinaryTree tree, VisitorState state) { String prefix; switch (tree.getKind()) { case EQUAL_TO: prefix = ""; break; case NOT_EQUAL_TO: prefix = "!"; break; default: return Description.NO_MATCH; } JCExpression left = (JCExpression) tree.getLeftOperand(); JCExpression right = (JCExpression) tree.getRightOperand(); String leftMatch = matchNaN(left); if (leftMatch != null) { return describeMatch( tree, SuggestedFix.replace( tree, String.format("%s%s.isNaN(%s)", prefix, leftMatch, toString(right, state)))); } String rightMatch = matchNaN(right); if (rightMatch != null) { return describeMatch( tree, SuggestedFix.replace( tree, String.format("%s%s.isNaN(%s)", prefix, rightMatch, toString(left, state)))); } return Description.NO_MATCH; } @SuppressWarnings("TreeToString") private static CharSequence toString(JCTree tree, VisitorState state) { CharSequence source = state.getSourceForNode(tree); return (source == null) ? tree.toString() : source; } @Nullable private static String matchNaN(ExpressionTree tree) { Symbol sym = ASTHelpers.getSymbol(tree); if (sym != null && sym.owner != null && sym.owner.asType() != null && sym.getSimpleName().contentEquals("NaN")) { if (sym.owner.getQualifiedName().contentEquals("java.lang.Double")) { return "Double"; } else if (sym.owner.getQualifiedName().contentEquals("java.lang.Float")) { return "Float"; } } return null; } }
3,214
32.489583
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryAssignment.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.ImmutableList.toImmutableList; import static com.google.common.collect.Streams.findLast; 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.Description.NO_MATCH; 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.anyOf; import static com.google.errorprone.matchers.Matchers.hasAnnotation; import static com.google.errorprone.matchers.Matchers.hasArgumentWithValue; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.constValue; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static com.google.errorprone.util.ErrorProneTokens.getTokens; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.AssignmentTreeMatcher; 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.matchers.MultiMatcher; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.ErrorProneToken; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssignmentTree; 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; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.parser.Tokens.TokenKind; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import javax.lang.model.element.Modifier; /** * Discourage manual initialization or assignment to fields annotated with framework annotations. */ @BugPattern( summary = "Fields annotated with @Inject/@Mock should not be manually assigned to, as they should be" + " initialized by a framework. Remove the assignment if a framework is being used, or" + " the annotation if one isn't.", severity = WARNING) public final class UnnecessaryAssignment extends BugChecker implements AssignmentTreeMatcher, VariableTreeMatcher { private static final ImmutableSet<String> FRAMEWORK_ANNOTATIONS = ImmutableSet.of( "com.google.testing.junit.testparameterinjector.TestParameter", "com.google.inject.Inject", "javax.inject.Inject"); private static final Matcher<Tree> HAS_MOCK_ANNOTATION = hasAnnotation("org.mockito.Mock"); private static final Matcher<Tree> HAS_NON_MOCK_FRAMEWORK_ANNOTATION = allOf( anyOf( FRAMEWORK_ANNOTATIONS.stream() .map(Matchers::hasAnnotation) .collect(toImmutableList())), not( annotations( AT_LEAST_ONE, hasArgumentWithValue( "optional", (t, s) -> Objects.equals(constValue(t), true))))); private static final Matcher<ExpressionTree> MOCK_FACTORY = staticMethod().onClass("org.mockito.Mockito").named("mock"); private static final Matcher<ExpressionTree> INITIALIZES_MOCKS = anyOf(staticMethod().onClass("org.mockito.MockitoAnnotations").named("initMocks")); private static final MultiMatcher<ClassTree, AnnotationTree> MOCKITO_RUNNER = annotations( AT_LEAST_ONE, hasArgumentWithValue( "value", isJUnit4TestRunnerOfType(ImmutableList.of("org.mockito.junit.MockitoJUnitRunner")))); @Override public Description matchAssignment(AssignmentTree tree, VisitorState state) { if (!HAS_MOCK_ANNOTATION.matches(tree.getVariable(), state) && !HAS_NON_MOCK_FRAMEWORK_ANNOTATION.matches(tree.getVariable(), state)) { return NO_MATCH; } return describeMatch(tree, SuggestedFix.delete(tree)); } @Override public Description matchVariable(VariableTree tree, VisitorState state) { boolean hasMockAnnotation = HAS_MOCK_ANNOTATION.matches(tree, state); boolean hasInjectyAnnotation = HAS_NON_MOCK_FRAMEWORK_ANNOTATION.matches(tree, state); if (hasMockAnnotation && hasInjectyAnnotation) { return buildDescription(tree) .setMessage( "Fields shouldn't be annotated with both @Mock and another @Inject-like annotation," + " because both Mockito and the injector will assign to the field, and one of" + " the values will overwrite the other") .build(); } if (tree.getInitializer() == null) { return NO_MATCH; } if (hasMockAnnotation) { return describeMatch(tree, createMockFix(tree, state)); } if (hasInjectyAnnotation) { Description.Builder description = buildDescription(tree); if (!tree.getModifiers().getFlags().contains(Modifier.FINAL)) { String source = state .getSourceCode() .subSequence(getStartPosition(tree), getStartPosition(tree.getInitializer())) .toString(); ImmutableList<ErrorProneToken> tokens = getTokens(source, getStartPosition(tree), state.context); int equalsPos = findLast(tokens.stream().filter(t -> t.kind().equals(TokenKind.EQ))).get().pos(); description.addFix( SuggestedFix.builder() .setShortDescription("Remove the variable's initializer") .replace(equalsPos, state.getEndPosition(tree.getInitializer()), "") .build()); } AnnotationTree annotationToRemove = tree.getModifiers().getAnnotations().stream() .filter( anno -> FRAMEWORK_ANNOTATIONS.stream() .anyMatch( fanno -> isSubtype(getType(anno), state.getTypeFromString(fanno), state))) .findFirst() .get(); return description .setMessage( String.format( "Fields annotated with @%s should not be manually assigned to, as they should be" + " initialized by a framework. Remove the assignment if a framework is" + " being used, or the annotation if one isn't.", getType(annotationToRemove).tsym.getSimpleName())) .addFix( SuggestedFix.builder() .setShortDescription("Remove the annotation") .delete(annotationToRemove) .build()) .build(); } return NO_MATCH; } private static SuggestedFix createMockFix(VariableTree tree, VisitorState state) { if (MOCK_FACTORY.matches(tree.getInitializer(), state) && !classContainsInitializer(state.findEnclosing(ClassTree.class), state)) { AnnotationTree anno = ASTHelpers.getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "Mock"); return SuggestedFix.delete(anno); } int startPos = getStartPosition(tree); List<ErrorProneToken> tokens = state.getOffsetTokens(startPos, getStartPosition(tree.getInitializer())); for (ErrorProneToken token : Lists.reverse(tokens)) { if (token.kind() == TokenKind.EQ) { return SuggestedFix.replace(token.pos(), state.getEndPosition(tree.getInitializer()), ""); } } return SuggestedFix.emptyFix(); } private static boolean classContainsInitializer(ClassTree classTree, VisitorState state) { AtomicBoolean initialized = new AtomicBoolean(false); new TreeScanner<Void, Void>() { @Override public Void visitClass(ClassTree classTree, Void unused) { if (MOCKITO_RUNNER.matches(classTree, state)) { initialized.set(true); return null; } return super.visitClass(classTree, null); } @Override public Void visitMethodInvocation(MethodInvocationTree methodInvocationTree, Void unused) { if (INITIALIZES_MOCKS.matches(methodInvocationTree, state)) { initialized.set(true); return null; } return super.visitMethodInvocation(methodInvocationTree, null); } @Override public Void visitNewClass(NewClassTree newClassTree, Void unused) { if (INITIALIZES_MOCKS.matches(newClassTree, state)) { initialized.set(true); return null; } return super.visitNewClass(newClassTree, null); } }.scan(classTree, null); return initialized.get(); } }
10,068
41.665254
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MissingOverride.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 static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.streamSuperMethods; 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.MethodTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodTree; import javax.inject.Inject; import javax.lang.model.element.Modifier; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "method overrides method in supertype; expected @Override", severity = WARNING, tags = StandardTags.STYLE) public class MissingOverride extends BugChecker implements MethodTreeMatcher { /** if true, don't warn on missing {@code @Override} annotations inside interfaces */ private final boolean ignoreInterfaceOverrides; @Inject MissingOverride(ErrorProneFlags flags) { this.ignoreInterfaceOverrides = flags.getBoolean("MissingOverride:IgnoreInterfaceOverrides").orElse(false); } @Override public Description matchMethod(MethodTree tree, VisitorState state) { var sym = ASTHelpers.getSymbol(tree); if (sym.isStatic()) { return NO_MATCH; } if (hasAnnotation(sym, Override.class, state)) { return NO_MATCH; } if (ignoreInterfaceOverrides && sym.enclClass().isInterface()) { return NO_MATCH; } return streamSuperMethods(sym, state.getTypes()) .findFirst() .filter(unused -> ASTHelpers.getGeneratedBy(state).isEmpty()) // to allow deprecated methods to be removed non-atomically, we permit overrides of // @Deprecated to skip the annotation .filter(override -> !hasAnnotation(override, Deprecated.class, state)) .map( override -> buildDescription(tree) .addFix(SuggestedFix.prefixWith(tree, "@Override ")) .setMessage( String.format( "%s %s method in %s; expected @Override", sym.getSimpleName(), override.enclClass().isInterface() || override.getModifiers().contains(Modifier.ABSTRACT) ? "implements" : "overrides", override.enclClass().getSimpleName())) .build()) .orElse(NO_MATCH); } }
3,512
39.37931
91
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryTypeArgument.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.base.Verify.verify; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.tree.JCTree; import java.util.List; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Non-generic methods should not be invoked with type arguments", severity = ERROR) public class UnnecessaryTypeArgument extends BugChecker implements MethodInvocationTreeMatcher, NewClassTreeMatcher { @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return check(tree, tree.getTypeArguments(), state); } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { return check(tree, tree.getTypeArguments(), state); } private Description check(Tree tree, List<? extends Tree> arguments, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(tree); if (!(sym instanceof MethodSymbol)) { return Description.NO_MATCH; } MethodSymbol methodSymbol = (MethodSymbol) sym; int expected = methodSymbol.getTypeParameters().size(); int actual = arguments.size(); if (actual <= expected) { return Description.NO_MATCH; } for (MethodSymbol superMethod : ASTHelpers.findSuperMethods(methodSymbol, state.getTypes())) { if (!superMethod.getTypeParameters().isEmpty()) { // Exempt methods that override generic methods to preserve the substitutability of the // two types. return Description.NO_MATCH; } } return describeMatch(tree, buildFix(tree, arguments, state)); } /** Constructor a fix that deletes the set of type arguments. */ private static Fix buildFix(Tree tree, List<? extends Tree> arguments, VisitorState state) { JCTree node = (JCTree) tree; int startAbsolute = node.getStartPosition(); int lower = getStartPosition(arguments.get(0)) - startAbsolute; int upper = state.getEndPosition(arguments.get(arguments.size() - 1)) - startAbsolute; CharSequence source = state.getSourceForNode(node); while (lower >= 0 && source.charAt(lower) != '<') { lower--; } while (upper < source.length() && source.charAt(upper) != '>') { upper++; } // There's a small chance that the fix will be incorrect because there's a '<' or '>' in // a comment (e.g. `this.</*<*/T/*>*/>f()`), it should never be the case that we don't find // any angle brackets. verify(source.charAt(lower) == '<' && source.charAt(upper) == '>'); Fix fix = SuggestedFix.replace(startAbsolute + lower, startAbsolute + upper + 1, ""); return fix; } }
4,059
36.943925
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/XorPower.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 com.google.common.base.Strings; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.Tree; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "The `^` operator is binary XOR, not a power operator.", severity = ERROR) public class XorPower extends BugChecker implements BinaryTreeMatcher { @Override public Description matchBinary(BinaryTree tree, VisitorState state) { if (!tree.getKind().equals(Tree.Kind.XOR)) { return NO_MATCH; } Integer lhs = ASTHelpers.constValue(tree.getLeftOperand(), Integer.class); if (lhs == null) { return NO_MATCH; } switch (lhs.intValue()) { case 2: case 10: break; default: return NO_MATCH; } Integer rhs = ASTHelpers.constValue(tree.getRightOperand(), Integer.class); if (rhs == null) { return NO_MATCH; } if (state.getSourceForNode(tree.getRightOperand()).startsWith("0")) { // hex and octal literals return NO_MATCH; } Description.Builder description = buildDescription(tree) .setMessage( String.format( "The ^ operator is binary XOR, not a power operator, so '%s' will always" + " evaluate to %d.", state.getSourceForNode(tree), lhs ^ rhs)); switch (lhs.intValue()) { case 2: if (rhs <= 31) { description.addFix(SuggestedFix.replace(tree, String.format("1 << %d", rhs))); } break; case 10: if (rhs <= 9) { description.addFix(SuggestedFix.replace(tree, "1" + Strings.repeat("0", rhs))); } break; default: throw new AssertionError(lhs); } return description.build(); } }
2,905
34.012048
96
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NullOptional.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.fixes.SuggestedFixes.qualifyType; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.methodCallInDeclarationOfThrowingRunnable; import static com.google.errorprone.predicates.TypePredicates.anyOf; import static com.google.errorprone.predicates.TypePredicates.isDescendantOf; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasDirectAnnotationWithSimpleName; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.predicates.TypePredicate; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ArrayType; import java.util.Iterator; import java.util.List; import javax.annotation.Nullable; /** Flags passing literal null to {@code Optional}-accepting APIs. */ @BugPattern( summary = "Passing a literal null to an Optional parameter is almost certainly a mistake. Did you" + " mean to provide an empty Optional?", severity = WARNING) public final class NullOptional extends BugChecker implements MethodInvocationTreeMatcher, NewClassTreeMatcher { private static final TypePredicate GUAVA_OPTIONAL = isDescendantOf("com.google.common.base.Optional"); private static final TypePredicate OPTIONAL = anyOf(GUAVA_OPTIONAL, isDescendantOf("java.util.Optional")); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { handleMethodInvocation(getSymbol(tree), tree.getArguments(), state); return NO_MATCH; } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { handleMethodInvocation(getSymbol(tree), tree.getArguments(), state); return NO_MATCH; } private void handleMethodInvocation( @Nullable MethodSymbol symbol, List<? extends ExpressionTree> arguments, VisitorState state) { if (symbol == null) { return; } Iterator<VarSymbol> parameters = symbol.getParameters().iterator(); VarSymbol parameter = null; Type parameterType = null; for (ExpressionTree argument : arguments) { parameter = parameters.hasNext() ? parameters.next() : parameter; parameterType = parameter.type; if (symbol.isVarArgs() && !parameters.hasNext()) { parameterType = ((ArrayType) parameter.type).elemtype; } if (argument.getKind() == Kind.NULL_LITERAL && OPTIONAL.apply(parameterType, state) && !hasDirectAnnotationWithSimpleName(parameter, "Nullable")) { if (methodCallInDeclarationOfThrowingRunnable(state)) { return; } SuggestedFix.Builder fix = SuggestedFix.builder(); fix.replace( argument, String.format( "%s.%s()", qualifyType(state, fix, parameterType.tsym), GUAVA_OPTIONAL.apply(parameterType, state) ? "absent" : "empty")); state.reportMatch(describeMatch(argument, fix.build())); } } } }
4,356
40.894231
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NullableConstructor.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.MethodTree; import com.sun.tools.javac.code.Symbol; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Constructors should not be annotated with @Nullable since they cannot return null", severity = WARNING, tags = StandardTags.STYLE) public class NullableConstructor extends BugChecker implements MethodTreeMatcher { @Override public Description matchMethod(MethodTree tree, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(tree); if (!sym.isConstructor()) { return NO_MATCH; } AnnotationTree annotation = ASTHelpers.getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "Nullable"); if (annotation == null) { return NO_MATCH; } return describeMatch(annotation, SuggestedFix.delete(annotation)); } }
2,067
37.296296
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TestParametersNotInitialized.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.ChildMultiMatcher.MatchType.AT_LEAST_ONE; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.JUnitMatchers.isJUnit4TestRunnerOfType; import static com.google.errorprone.matchers.Matchers.annotations; import static com.google.errorprone.matchers.Matchers.hasArgumentWithValue; import static com.google.errorprone.util.ASTHelpers.getAnnotationWithSimpleName; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.MultiMatcher; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.Tree; /** Flags uses of parameters in non-parameterized tests. */ @BugPattern( summary = "This test has @TestParameter fields but is using the default JUnit4 runner. The" + " parameters will not be initialised beyond their default value.", severity = ERROR) public final class TestParametersNotInitialized extends BugChecker implements ClassTreeMatcher { // TestParameterInjector also exposes a @TestParameters annotation, but it's not possible to // accidentally forget the runner when using this: it's used to initialise method or constructor // parameters, and the default JUnit4 runner would throw if there are parameters in either. private static final String TEST_PARAMETER = "com.google.testing.junit.testparameterinjector.TestParameter"; private static final String RUNNER = "com.google.testing.junit.testparameterinjector.TestParameterInjector"; private static final MultiMatcher<Tree, AnnotationTree> TEST_PARAMETER_INJECTOR = annotations( AT_LEAST_ONE, hasArgumentWithValue("value", isJUnit4TestRunnerOfType(ImmutableSet.of(RUNNER)))); private static final MultiMatcher<ClassTree, AnnotationTree> JUNIT4_RUNNER = annotations( AT_LEAST_ONE, hasArgumentWithValue( "value", isJUnit4TestRunnerOfType(ImmutableSet.of("org.junit.runners.JUnit4")))); @Override public Description matchClass(ClassTree tree, VisitorState state) { if (!JUNIT4_RUNNER.matches(tree, state)) { return NO_MATCH; } if (TEST_PARAMETER_INJECTOR.matches(tree, state)) { return NO_MATCH; } if (tree.getMembers().stream().noneMatch(m -> hasAnnotation(m, TEST_PARAMETER, state))) { return NO_MATCH; } AnnotationTree annotation = getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "RunWith"); SuggestedFix.Builder fix = SuggestedFix.builder(); fix.replace( annotation, String.format("@RunWith(%s.class)", SuggestedFixes.qualifyType(state, fix, RUNNER))); return describeMatch(tree, fix.build()); } }
3,866
42.943182
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BanSerializableRead.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.bugpatterns.SerializableReads.BANNED_OBJECT_INPUT_STREAM_METHODS; 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.enclosingMethod; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import static com.google.errorprone.matchers.Matchers.methodIsNamed; import static com.google.errorprone.matchers.Matchers.not; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** A {@link BugChecker} that detects use of the unsafe {@link java.io.Serializable} API. */ @BugPattern( summary = "Deserializing user input via the `Serializable` API is extremely dangerous", severity = SeverityLevel.ERROR) public final class BanSerializableRead extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> EXEMPT = anyOf( // This is called through ObjectInputStream; a call further up the callstack will have // been exempt. allOf( enclosingClass(isSubtypeOf("java.io.Serializable")), enclosingMethod(methodIsNamed("readObject"))), allOf( enclosingClass(isSubtypeOf("java.io.ObjectInputStream")), enclosingMethod( (methodTree, state) -> BANNED_OBJECT_INPUT_STREAM_METHODS.contains( methodTree.getName().toString())))); /** Checks for unsafe deserialization calls on an ObjectInputStream in an ExpressionTree. */ private static final Matcher<ExpressionTree> OBJECT_INPUT_STREAM_DESERIALIZE_MATCHER = allOf( anyOf( // this matches calls to the ObjectInputStream to read some objects instanceMethod() .onDescendantOf("java.io.ObjectInputStream") .namedAnyOf(BANNED_OBJECT_INPUT_STREAM_METHODS), // because in the next part we exempt readObject functions, here we // check for calls to those functions instanceMethod().onDescendantOf("java.io.Serializable").named("readObject"), // we need to ban java.io.ObjectInput.readObject too, but most of the time it's called // inside java.io.Externalizable.readExternal. Also ban direct calls of readExternal, // unless it's inside another readExternal allOf( anyOf( instanceMethod().onDescendantOf("java.io.ObjectInput").named("readObject"), instanceMethod() .onDescendantOf("java.io.Externalizable") .named("readExternal")), // skip banning things inside readExternal implementation not( allOf( enclosingMethod(methodIsNamed("readExternal")), enclosingClass(isSubtypeOf("java.io.Externalizable")))))), // Java lets you override or add to the default deserialization behaviour // by defining a 'readObject' on your class. In this case, it's super common // to see calls to deserialize methods (after all, it's what *would* happen // if it *were* deserialized). We specifically want to allow such members to // be defined, but never called not(EXEMPT)); /** Checks for unsafe uses of the Java deserialization API. */ private static final Matcher<ExpressionTree> MATCHER = OBJECT_INPUT_STREAM_DESERIALIZE_MATCHER; @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (state.errorProneOptions().isTestOnlyTarget() || !MATCHER.matches(tree, state)) { return Description.NO_MATCH; } Description.Builder description = buildDescription(tree); return description.build(); } }
5,102
46.691589
101
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BareDotMetacharacter.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 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.sun.source.tree.MethodInvocationTree; /** A BugChecker; see the associated BugPattern for details. */ @BugPattern( summary = "\".\" is rarely useful as a regex, as it matches any character. To match a literal '.'" + " character, instead write \"\\\\.\".", severity = WARNING, // So that suppressions added before this check was split into two apply to both halves. altNames = {"InvalidPatternSyntax"}) public class BareDotMetacharacter extends AbstractPatternSyntaxChecker implements MethodInvocationTreeMatcher { @Override protected final Description matchRegexLiteral( MethodInvocationTree tree, VisitorState state, String regex, int flags) { if (regex.equals(".")) { return describeMatch(tree, SuggestedFix.replace(tree.getArguments().get(0), "\"\\\\.\"")); } else { return NO_MATCH; } } }
1,938
37.78
96
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DeadThread.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.method.MethodMatchers.constructor; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree.Kind; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "Thread created but not started", severity = ERROR) public class DeadThread extends BugChecker implements NewClassTreeMatcher { private static final Matcher<ExpressionTree> NEW_THREAD = constructor().forClass("java.lang.Thread"); @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { if (!NEW_THREAD.matches(tree, state)) { return NO_MATCH; } if (state.getPath().getParentPath().getLeaf().getKind() != Kind.EXPRESSION_STATEMENT) { return NO_MATCH; } return describeMatch(tree, SuggestedFix.postfixWith(tree, ".start()")); } }
2,013
38.490196
91
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/YodaCondition.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.fixes.SuggestedFixes.qualifyType; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.instanceEqualsInvocation; import static com.google.errorprone.matchers.Matchers.staticEqualsInvocation; import static com.google.errorprone.util.ASTHelpers.constValue; import static com.google.errorprone.util.ASTHelpers.getNullnessValue; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static java.lang.String.format; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import com.google.errorprone.dataflow.nullnesspropagation.NullnessAnalysis; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol.VarSymbol; import java.util.Objects; /** See the summary. */ @BugPattern( summary = "The non-constant portion of an equals check generally comes first. Prefer" + " e.equals(CONSTANT) if e is non-null or Objects.equals(e, CONSTANT) if e may be", severity = WARNING) public final class YodaCondition extends BugChecker implements BinaryTreeMatcher, MethodInvocationTreeMatcher { @Override public Description matchBinary(BinaryTree tree, VisitorState state) { switch (tree.getKind()) { case EQUAL_TO: case NOT_EQUAL_TO: return fix( tree, tree.getLeftOperand(), tree.getRightOperand(), /* provideNullSafeFix= */ false, state); default: return NO_MATCH; } } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (staticEqualsInvocation().matches(tree, state)) { return fix( tree, tree.getArguments().get(0), tree.getArguments().get(1), /* provideNullSafeFix= */ false, state); } if (instanceEqualsInvocation().matches(tree, state)) { return fix( tree, getReceiver(tree), tree.getArguments().get(0), /* provideNullSafeFix= */ true, state); } return NO_MATCH; } private Description fix( Tree tree, ExpressionTree lhs, ExpressionTree rhs, boolean provideNullSafeFix, VisitorState state) { if (seemsConstant(lhs) && !seemsConstant(rhs)) { var description = buildDescription(lhs); if (provideNullSafeFix && !getNullnessValue(rhs, state, NullnessAnalysis.instance(state.context)) .equals(Nullness.NONNULL)) { var fix = SuggestedFix.builder().setShortDescription("null-safe fix"); description.addFix( fix.replace( tree, format( "%s.equals(%s, %s)", qualifyType(state, fix, Objects.class.getName()), state.getSourceForNode(rhs), state.getSourceForNode(lhs))) .build()); } return description.addFix(SuggestedFix.swap(lhs, rhs)).build(); } return NO_MATCH; } private static boolean seemsConstant(Tree tree) { if (constValue(tree) != null) { return true; } var symbol = getSymbol(tree); return symbol instanceof VarSymbol && symbol.isEnum(); } }
4,564
35.52
96
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ProtoStringFieldReferenceEquality.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.isSameType; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.suppliers.Suppliers; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.Tree.Kind; @BugPattern( severity = ERROR, summary = "Comparing protobuf fields of type String using reference equality") public class ProtoStringFieldReferenceEquality extends BugChecker implements BinaryTreeMatcher { private static final String PROTO_SUPER_CLASS = "com.google.protobuf.GeneratedMessage"; private static final String LITE_PROTO_SUPER_CLASS = "com.google.protobuf.GeneratedMessageLite"; private static final Matcher<ExpressionTree> PROTO_STRING_METHOD = allOf( instanceMethod().onDescendantOfAny(PROTO_SUPER_CLASS, LITE_PROTO_SUPER_CLASS), isSameType(Suppliers.STRING_TYPE)); @Override public Description matchBinary(BinaryTree tree, VisitorState state) { switch (tree.getKind()) { case EQUAL_TO: case NOT_EQUAL_TO: break; default: return NO_MATCH; } ExpressionTree lhs = tree.getLeftOperand(); ExpressionTree rhs = tree.getRightOperand(); if (match(lhs, rhs, state) || match(rhs, lhs, state)) { String result = String.format("%s.equals(%s)", state.getSourceForNode(lhs), state.getSourceForNode(rhs)); if (tree.getKind() == Kind.NOT_EQUAL_TO) { result = "!" + result; } return describeMatch(tree, SuggestedFix.replace(tree, result)); } return NO_MATCH; } private static boolean match(ExpressionTree a, ExpressionTree b, VisitorState state) { return PROTO_STRING_METHOD.matches(a, state) && b.getKind() != Kind.NULL_LITERAL; } }
2,955
37.894737
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/BigDecimalEquals.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.Iterables.getLast; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.equalsMethodDeclaration; import static com.google.errorprone.matchers.Matchers.instanceEqualsInvocation; import static com.google.errorprone.matchers.Matchers.staticEqualsInvocation; import static com.google.errorprone.util.ASTHelpers.getReceiver; 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.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Type; import java.util.List; /** * Matches use of {@code BigDecimal#equals}, which compares scale as well (which is not likely to be * intended). * * @author ghm@google.com (Graeme Morgan) */ @BugPattern( summary = "BigDecimal#equals has surprising behavior: it also compares scale.", severity = WARNING) public final class BigDecimalEquals extends BugChecker implements MethodInvocationTreeMatcher { private static final String BIG_DECIMAL = "java.math.BigDecimal"; @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { Tree receiver; Tree argument; List<? extends ExpressionTree> arguments = tree.getArguments(); Type bigDecimal = JAVA_MATH_BIGDECIMAL.get(state); boolean handleNulls; if (staticEqualsInvocation().matches(tree, state)) { handleNulls = true; receiver = arguments.get(arguments.size() - 2); argument = getLast(arguments); } else if (instanceEqualsInvocation().matches(tree, state)) { handleNulls = false; receiver = getReceiver(tree); argument = arguments.get(0); } else { return NO_MATCH; } MethodTree enclosingMethod = state.findEnclosing(MethodTree.class); if (enclosingMethod != null && equalsMethodDeclaration().matches(enclosingMethod, state)) { return NO_MATCH; } boolean isReceiverBigDecimal = isSameType(getType(receiver), bigDecimal, state); boolean isTargetBigDecimal = isSameType(getType(argument), bigDecimal, state); if (!isReceiverBigDecimal && !isTargetBigDecimal) { return NO_MATCH; } // One is BigDecimal but the other isn't: report a finding without a fix. if (isReceiverBigDecimal != isTargetBigDecimal) { return describeMatch(tree); } return describe(tree, state, receiver, argument, handleNulls); } private Description describe( MethodInvocationTree tree, VisitorState state, Tree receiver, Tree argument, boolean handleNulls) { return describeMatch(tree); } private static final Supplier<Type> JAVA_MATH_BIGDECIMAL = VisitorState.memoize(state -> state.getTypeFromString(BIG_DECIMAL)); }
3,927
37.135922
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UnsafeLocaleUsage.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.Matchers.constructor; import static com.google.errorprone.matchers.Matchers.instanceMethod; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; 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.source.tree.NewClassTree; import com.sun.tools.javac.tree.JCTree.JCLiteral; /** Flags unsafe usages of the {@link java.util.Locale} constructor and class methods. */ @BugPattern( summary = "Possible unsafe operation related to the java.util.Locale library.", severity = WARNING) public final class UnsafeLocaleUsage extends BugChecker implements MethodInvocationTreeMatcher, NewClassTreeMatcher { private static final Matcher<ExpressionTree> LOCALE_TO_STRING = instanceMethod().onExactClass("java.util.Locale").named("toString"); private static final Matcher<ExpressionTree> LOCALE_CONSTRUCTOR = constructor().forClass("java.util.Locale"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (LOCALE_TO_STRING.matches(tree, state)) { return buildDescription(tree) .setMessage( "Avoid using Locale.toString() since it produces a value that" + " misleadingly looks like a locale identifier. Prefer using" + " Locale.toLanguageTag() since it produces an IETF BCP 47-formatted string that" + " can be deserialized back into a Locale.") .addFix(SuggestedFixes.renameMethodInvocation(tree, "toLanguageTag", state)) .build(); } return Description.NO_MATCH; } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { if (LOCALE_CONSTRUCTOR.matches(tree, state)) { Description.Builder descriptionBuilder = buildDescription(tree) .setMessage( "Avoid using Locale constructors, and prefer using" + " Locale.forLanguageTag(String) which takes in an IETF BCP 47-formatted" + " string or a Locale Builder."); // Only suggest a fix for constructor calls with one or two parameters since there's // too much variance in multi-parameter calls to be able to make a confident suggestion ImmutableList<ExpressionTree> constructorArguments = ImmutableList.copyOf(tree.getArguments()); if (constructorArguments.size() == 1) { // Locale.forLanguageTag() doesn't support underscores in language tags. We can replace this // ourselves when the constructor arg is a string literal. Otherwise, we can only append a // .replace() to it. ExpressionTree arg = constructorArguments.get(0); String replacementArg = arg instanceof JCLiteral ? String.format( "\"%s\"", ASTHelpers.constValue(arg, String.class).replace("_", "-")) : String.format( "%s.replace(\"_\", \"-\")", state.getSourceForNode(constructorArguments.get(0))); descriptionBuilder.addFix( SuggestedFix.replace(tree, String.format("Locale.forLanguageTag(%s)", replacementArg))); } else if (constructorArguments.size() == 2) { descriptionBuilder.addFix( SuggestedFix.replace( tree, String.format( "new Locale.Builder().setLanguage(%s).setRegion(%s).build()", state.getSourceForNode(constructorArguments.get(0)), state.getSourceForNode(constructorArguments.get(1))))); } return descriptionBuilder.build(); } return Description.NO_MATCH; } }
4,940
44.75
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ArrayAsKeyOfSetOrMap.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.sun.tools.javac.code.Type; /** * Warns that users should not have an array as a key to a Set or Map * * @author siyuanl@google.com (Siyuan Liu) * @author eleanorh@google.com (Eleanor Harris) */ @BugPattern( summary = "Arrays do not override equals() or hashCode, so comparisons will be done on" + " reference equality only. If neither deduplication nor lookup are needed, " + "consider using a List instead. Otherwise, use IdentityHashMap/Set, " + "a Map from a library that handles object arrays, or an Iterable/List of pairs.", severity = WARNING) public class ArrayAsKeyOfSetOrMap extends AbstractAsKeyOfSetOrMap { @Override protected boolean isBadType(Type type, VisitorState state) { return type instanceof Type.ArrayType; } }
1,620
35.022222
95
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/SelfAssignment.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.anyOf; import static com.google.errorprone.matchers.Matchers.staticMethod; import static com.sun.source.tree.Tree.Kind.CLASS; import static com.sun.source.tree.Tree.Kind.IDENTIFIER; import static com.sun.source.tree.Tree.Kind.MEMBER_SELECT; import static com.sun.source.tree.Tree.Kind.METHOD_INVOCATION; import static javax.lang.model.element.Modifier.STATIC; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.AssignmentTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.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.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.TypeCastTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Type; import org.checkerframework.checker.nullness.qual.Nullable; /** * TODO(eaftan): Consider cases where the parent is not a statement or there is no parent? * * @author eaftan@google.com (Eddie Aftandilian) * @author scottjohnson@google.com (Scott Johnson) */ @BugPattern(summary = "Variable assigned to itself", severity = ERROR) public class SelfAssignment extends BugChecker implements AssignmentTreeMatcher, VariableTreeMatcher { private static final Matcher<MethodInvocationTree> NON_NULL_MATCHER = anyOf( staticMethod().onClass("java.util.Objects").named("requireNonNull"), staticMethod().onClass("com.google.common.base.Preconditions").named("checkNotNull"), staticMethod() .onClass("com.google.common.time.Durations") .namedAnyOf("checkNotNegative", "checkPositive"), staticMethod() .onClass("com.google.protobuf.util.Durations") .namedAnyOf("checkNotNegative", "checkPositive", "checkValid"), staticMethod().onClass("com.google.protobuf.util.Timestamps").named("checkValid")); @Override public Description matchAssignment(AssignmentTree tree, VisitorState state) { if (!tree.getKind().equals(Kind.ASSIGNMENT)) { return Description.NO_MATCH; } // TODO(cushon): consider handling assignment expressions too, i.e. `x = y = x` ExpressionTree expression = skipCast(stripNullCheck(tree.getExpression(), state)); if (ASTHelpers.sameVariable(tree.getVariable(), expression)) { return describeForAssignment(tree, state); } return Description.NO_MATCH; } @Override public Description matchVariable(VariableTree tree, VisitorState state) { ExpressionTree initializer = stripNullCheck(tree.getInitializer(), state); Tree parent = state.getPath().getParentPath().getLeaf(); // must be a static class variable with member select initializer if (initializer == null || initializer.getKind() != MEMBER_SELECT || parent.getKind() != CLASS || !tree.getModifiers().getFlags().contains(STATIC)) { return Description.NO_MATCH; } MemberSelectTree rhs = (MemberSelectTree) initializer; Symbol rhsClass = ASTHelpers.getSymbol(rhs.getExpression()); Symbol lhsClass = ASTHelpers.getSymbol(parent); if (rhsClass != null && lhsClass != null && rhsClass.equals(lhsClass) && rhs.getIdentifier().contentEquals(tree.getName())) { return describeForVarDecl(tree, state); } return Description.NO_MATCH; } private static ExpressionTree skipCast(ExpressionTree expression) { return new SimpleTreeVisitor<ExpressionTree, Void>() { @Override public ExpressionTree visitParenthesized(ParenthesizedTree node, Void unused) { return node.getExpression().accept(this, null); } @Override public ExpressionTree visitTypeCast(TypeCastTree node, Void unused) { return node.getExpression().accept(this, null); } @Override protected @Nullable ExpressionTree defaultAction(Tree node, Void unused) { return node instanceof ExpressionTree ? (ExpressionTree) node : null; } }.visit(expression, null); } /** * If the given expression is a call to a method checking the nullity of its first parameter, and * otherwise returns that parameter. */ private static ExpressionTree stripNullCheck(ExpressionTree expression, VisitorState state) { if (expression != null && expression.getKind() == METHOD_INVOCATION) { MethodInvocationTree methodInvocation = (MethodInvocationTree) expression; if (NON_NULL_MATCHER.matches(methodInvocation, state)) { return methodInvocation.getArguments().get(0); } } return expression; } public Description describeForVarDecl(VariableTree tree, VisitorState state) { String varDeclStr = state.getSourceForNode(tree); int equalsIndex = varDeclStr.indexOf('='); if (equalsIndex < 0) { throw new IllegalStateException( "Expected variable declaration to have an initializer: " + state.getSourceForNode(tree)); } varDeclStr = varDeclStr.substring(0, equalsIndex - 1) + ";"; // Delete the initializer but still declare the variable. return describeMatch(tree, SuggestedFix.replace(tree, varDeclStr)); } /** * We expect that the lhs is a field and the rhs is an identifier, specifically a parameter to the * method. We base our suggested fixes on this expectation. * * <p>Case 1: If lhs is a field and rhs is an identifier, find a method parameter of the same type * and similar name and suggest it as the rhs. (Guess that they have misspelled the identifier.) * * <p>Case 2: If lhs is a field and rhs is not an identifier, find a method parameter of the same * type and similar name and suggest it as the rhs. * * <p>Case 3: If lhs is not a field and rhs is an identifier, find a class field of the same type * and similar name and suggest it as the lhs. * * <p>Case 4: Otherwise suggest deleting the assignment. */ public Description describeForAssignment(AssignmentTree assignmentTree, VisitorState state) { // the statement that is the parent of the self-assignment expression Tree parent = state.getPath().getParentPath().getLeaf(); // default fix is to delete assignment Fix fix = SuggestedFix.delete(parent); ExpressionTree lhs = assignmentTree.getVariable(); ExpressionTree rhs = assignmentTree.getExpression(); // if this is a method invocation, they must be calling checkNotNull() if (assignmentTree.getExpression().getKind() == METHOD_INVOCATION) { // change the default fix to be "checkNotNull(x)" instead of "x = checkNotNull(x)" fix = SuggestedFix.replace(assignmentTree, state.getSourceForNode(rhs)); // new rhs is first argument to checkNotNull() rhs = stripNullCheck(rhs, state); } rhs = skipCast(rhs); ImmutableList<Fix> exploratoryFieldFixes = ImmutableList.of(); if (lhs.getKind() == MEMBER_SELECT) { // find a method parameter of the same type and similar name and suggest it // as the rhs // rhs should be either identifier or field access Preconditions.checkState(rhs.getKind() == IDENTIFIER || rhs.getKind() == MEMBER_SELECT); Type rhsType = ASTHelpers.getType(rhs); exploratoryFieldFixes = ReplacementVariableFinder.fixesByReplacingExpressionWithMethodParameter( rhs, varDecl -> ASTHelpers.isSameType(rhsType, varDecl.type, state), state); } else if (rhs.getKind() == IDENTIFIER) { // find a field of the same type and similar name and suggest it as the lhs // lhs should be identifier Preconditions.checkState(lhs.getKind() == IDENTIFIER); Type lhsType = ASTHelpers.getType(lhs); exploratoryFieldFixes = ReplacementVariableFinder.fixesByReplacingExpressionWithLocallyDeclaredField( lhs, var -> !Flags.isStatic(var.sym) && (var.sym.flags() & Flags.FINAL) == 0 && ASTHelpers.isSameType(lhsType, var.type, state), state); } if (exploratoryFieldFixes.isEmpty()) { return describeMatch(assignmentTree, fix); } return buildDescription(assignmentTree).addAllFixes(exploratoryFieldFixes).build(); } }
9,667
41.218341
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/IncorrectMainMethod.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.getOnlyElement; 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.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; 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.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.sun.source.tree.MethodTree; 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.code.Types; import javax.lang.model.element.Modifier; /** Bugpattern for incorrect overloads of main. */ @BugPattern(summary = "'main' methods must be public, static, and void", severity = WARNING) public final class IncorrectMainMethod extends BugChecker implements MethodTreeMatcher { private static final ImmutableSet<Modifier> REQUIRED_MODIFIERS = immutableEnumSet(Modifier.PUBLIC, Modifier.STATIC); @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (!tree.getName().contentEquals("main")) { return NO_MATCH; } MethodSymbol sym = getSymbol(tree); if (sym.getParameters().size() != 1) { return NO_MATCH; } Type type = getOnlyElement(sym.getParameters()).asType(); Types types = state.getTypes(); Symtab symtab = state.getSymtab(); if (!types.isArray(type) || !types.isSameType(types.elemtype(type), symtab.stringType)) { return NO_MATCH; } if (sym.getModifiers().containsAll(REQUIRED_MODIFIERS) && types.isSameType(getType(tree.getReturnType()), symtab.voidType)) { return NO_MATCH; } SuggestedFix.Builder fix = SuggestedFix.builder().replace(tree.getReturnType(), "void"); SuggestedFixes.removeModifiers(tree, state, Modifier.PROTECTED, Modifier.PRIVATE) .ifPresent(fix::merge); SuggestedFixes.addModifiers(tree, tree.getModifiers(), state, REQUIRED_MODIFIERS) .ifPresent(fix::merge); return describeMatch(tree, fix.build()); } }
3,090
40.77027
93
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AsyncFunctionReturnsNull.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.AsyncFunction; import com.google.errorprone.BugPattern; /** Checks that {@link AsyncFunction} implementations do not directly {@code return null}. */ @BugPattern( summary = "AsyncFunction should not return a null Future, only a Future whose result is null.", severity = ERROR) public final class AsyncFunctionReturnsNull extends AbstractAsyncTypeReturnsNull { public AsyncFunctionReturnsNull() { super(AsyncFunction.class); } }
1,208
35.636364
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ModifyCollectionInEnhancedForLoop.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 static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.util.ASTHelpers.enclosingPackage; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.sameVariable; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.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.EnhancedForLoopTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.util.TreePath; import java.util.List; /** * @author anishvisaria98@gmail.com (Anish Visaria) */ @BugPattern( summary = "Modifying a collection while iterating over it in a loop may cause a" + " ConcurrentModificationException to be thrown or lead to undefined behavior.", severity = WARNING) public class ModifyCollectionInEnhancedForLoop extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> MATCHER = anyOf( instanceMethod() .onDescendantOf("java.util.Collection") .namedAnyOf("add", "addAll", "clear", "remove", "removeAll", "retainAll"), instanceMethod() .onDescendantOf("java.util.Map") .namedAnyOf( "put", "putAll", "putIfAbsent", "clear", "remove", "replace", "replaceAll", "merge")); private static final Matcher<ExpressionTree> MAP_SET_MATCHER = instanceMethod().onDescendantOf("java.util.Map").namedAnyOf("entrySet", "keySet", "values"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return NO_MATCH; } if (state.getTypes().closure(ASTHelpers.getReceiverType(tree)).stream() .anyMatch( s -> enclosingPackage(s.asElement()) .getQualifiedName() .toString() .startsWith("java.util.concurrent"))) { return NO_MATCH; } if (blockEndsInBreakOrReturn(state)) { return NO_MATCH; } ExpressionTree collection = getReceiver(tree); if (collection == null) { return NO_MATCH; } if (!enclosingLoop(state, collection)) { return NO_MATCH; } return describeMatch(tree); } private static boolean blockEndsInBreakOrReturn(VisitorState state) { TreePath statementPath = state.findPathToEnclosing(StatementTree.class); if (statementPath == null) { return false; } Tree parent = statementPath.getParentPath().getLeaf(); if (!(parent instanceof BlockTree)) { return false; } StatementTree statement = (StatementTree) statementPath.getLeaf(); List<? extends StatementTree> statements = ((BlockTree) parent).getStatements(); int idx = statements.indexOf(statement); if (idx == -1 || idx == statements.size()) { return false; } switch (getLast(statements).getKind()) { case BREAK: case RETURN: return true; default: return false; } } /** Returns true if {@code collection} is modified by an enclosing loop. */ private static boolean enclosingLoop(VisitorState state, ExpressionTree collection) { for (Tree node : state.getPath()) { switch (node.getKind()) { case METHOD: case CLASS: case LAMBDA_EXPRESSION: return false; case ENHANCED_FOR_LOOP: if (sameCollection(collection, ((EnhancedForLoopTree) node).getExpression(), state)) { return true; } break; default: // fall out } } return false; } /** * Returns true if {@code loopExpression} is defined over the same collection as {@code * collection}. */ private static boolean sameCollection( ExpressionTree collection, ExpressionTree loopExpression, VisitorState state) { if (sameVariable(collection, loopExpression)) { return true; } // Check if the loopExpression is a .keySet(), .entrySet, or .values() of the map if (loopExpression.getKind() == Kind.METHOD_INVOCATION) { ExpressionTree receiver = getReceiver(loopExpression); return receiver != null && sameVariable(collection, receiver) && MAP_SET_MATCHER.matches(loopExpression, state); } return false; } }
5,817
34.693252
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ProtoTruthMixedDescriptors.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; 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.isSubtype; import static com.google.errorprone.util.ASTHelpers.streamReceivers; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.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; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Type; import java.util.List; import java.util.Optional; /** * Checks that {@code ProtoTruth}'s {@code ignoringFields} is passed field numbers from the correct * proto. * * @author ghm@google.com (Graeme Morgan) */ @BugPattern( summary = "The arguments passed to `ignoringFields` are inconsistent with the proto which is " + "the subject of the assertion.", severity = ERROR) public final class ProtoTruthMixedDescriptors extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> IGNORING = instanceMethod() .onDescendantOfAny( "com.google.common.truth.extensions.proto.ProtoFluentAssertion", "com.google.common.truth.extensions.proto.ProtoSubject") .named("ignoringFields"); private static final Matcher<ExpressionTree> ASSERT_THAT = staticMethod() .onClass("com.google.common.truth.extensions.proto.ProtoTruth") .named("assertThat"); private static final Supplier<Type> MESSAGE = Suppliers.typeFromString("com.google.protobuf.Message"); private static final Supplier<Type> GENERATED_MESSAGE = Suppliers.typeFromString("com.google.protobuf.GeneratedMessage"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!IGNORING.matches(tree, state)) { return Description.NO_MATCH; } List<? extends ExpressionTree> arguments = tree.getArguments(); ImmutableSet<TypeSymbol> types = arguments.stream() .map(t -> protoType(t, state)) .filter(Optional::isPresent) .map(Optional::get) .collect(toImmutableSet()); if (types.size() > 1) { return describeMatch(tree); } if (types.size() != 1) { return Description.NO_MATCH; } TypeSymbol type = getOnlyElement(types); return streamReceivers(tree) .filter(t -> ASSERT_THAT.matches(t, state)) .map(t -> validateReceiver(tree, (MethodInvocationTree) t, type, state)) .findFirst() .orElse(Description.NO_MATCH); } // Tries to resolve the proto which owns the symbol at `tree`, or absent if there isn't one. private static Optional<TypeSymbol> protoType(ExpressionTree tree, VisitorState state) { Symbol symbol = getSymbol(tree); if (symbol != null && symbol.owner != null && isSubtype(symbol.owner.type, MESSAGE.get(state), state)) { return Optional.of(symbol.owner.type.tsym); } return Optional.empty(); } // Given an `assertThat()` call (`receiver`), checks that the proto matches the type `type` if it // can be resolved. private Description validateReceiver( MethodInvocationTree tree, MethodInvocationTree receiver, TypeSymbol type, VisitorState state) { if (receiver.getArguments().size() != 1) { return Description.NO_MATCH; } ExpressionTree argument = getOnlyElement(receiver.getArguments()); Type subjectType = getType(argument); if (isSubtype(subjectType, state.getSymtab().iterableType, state)) { if (subjectType.getTypeArguments().isEmpty()) { return Description.NO_MATCH; } subjectType = getOnlyElement(subjectType.getTypeArguments()); } return subjectType == null || subjectType.tsym.equals(type) || !isSubtype(subjectType, GENERATED_MESSAGE.get(state), state) ? Description.NO_MATCH : describeMatch(tree); } }
5,428
38.057554
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/EmptyCatch.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.LinkType.CUSTOM; 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.CatchTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.BlockTree; import com.sun.source.tree.CatchTree; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Caught exceptions should not be ignored", severity = WARNING, tags = BugPattern.StandardTags.STYLE, documentSuppression = false, linkType = CUSTOM, link = "https://google.github.io/styleguide/javaguide.html#s6.2-caught-exceptions") public class EmptyCatch extends BugChecker implements CatchTreeMatcher { @Override public Description matchCatch(CatchTree tree, VisitorState state) { BlockTree block = tree.getBlock(); if (!block.getStatements().isEmpty()) { return NO_MATCH; } if (state.getTokensForNode(block).stream().anyMatch(t -> !t.comments().isEmpty())) { return NO_MATCH; } if (ASTHelpers.isJUnitTestCode(state)) { return NO_MATCH; } if (ASTHelpers.isTestNgTestCode(state)) { return NO_MATCH; } return describeMatch(tree); } }
2,127
35.067797
90
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DistinctVarargsChecker.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import com.google.common.collect.ImmutableListMultimap; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * ErrorProne checker to generate warning when method expecting distinct varargs is invoked with * same variable argument. */ @BugPattern(summary = "Method expects distinct arguments at some/all positions", severity = WARNING) public final class DistinctVarargsChecker extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> IMMUTABLE_SET_VARARGS_MATCHER = anyOf( staticMethod().onClass("com.google.common.collect.ImmutableSet").named("of"), staticMethod().onClass("com.google.common.collect.ImmutableSortedSet").named("of")); private static final Matcher<ExpressionTree> ALL_DISTINCT_ARG_MATCHER = anyOf( staticMethod() .onClass("com.google.common.util.concurrent.Futures") .withSignature( "<V>whenAllSucceed(com.google.common.util.concurrent.ListenableFuture<? extends" + " V>...)"), staticMethod() .onClass("com.google.common.util.concurrent.Futures") .withSignature( "<V>whenAllComplete(com.google.common.util.concurrent.ListenableFuture<? extends" + " V>...)"), staticMethod() .onClass("com.google.common.collect.Ordering") .withSignature("<T>explicit(T,T...)")); private static final Matcher<ExpressionTree> EVEN_PARITY_DISTINCT_ARG_MATCHER = staticMethod().onClass("com.google.common.collect.ImmutableSortedMap").named("of"); private static final Matcher<ExpressionTree> EVEN_AND_ODD_PARITY_DISTINCT_ARG_MATCHER = staticMethod().onClass("com.google.common.collect.ImmutableBiMap").named("of"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { // For ImmutableSet and ImmutableSortedSet fix can be constructed. For all other methods, // non-distinct arguments will result in the runtime exceptions. if (IMMUTABLE_SET_VARARGS_MATCHER.matches(tree, state)) { return checkDistinctArgumentsWithFix(tree, state); } if (ALL_DISTINCT_ARG_MATCHER.matches(tree, state)) { return checkDistinctArguments(state, tree.getArguments()); } if (EVEN_PARITY_DISTINCT_ARG_MATCHER.matches(tree, state)) { List<ExpressionTree> arguments = new ArrayList<>(); for (int index = 0; index < tree.getArguments().size(); index += 2) { arguments.add(tree.getArguments().get(index)); } return checkDistinctArguments(state, arguments); } if (EVEN_AND_ODD_PARITY_DISTINCT_ARG_MATCHER.matches(tree, state)) { List<ExpressionTree> evenParityArguments = new ArrayList<>(); List<ExpressionTree> oddParityArguments = new ArrayList<>(); for (int index = 0; index < tree.getArguments().size(); index++) { if (index % 2 == 0) { evenParityArguments.add(tree.getArguments().get(index)); } else { oddParityArguments.add(tree.getArguments().get(index)); } } return checkDistinctArguments(state, evenParityArguments, oddParityArguments); } return Description.NO_MATCH; } private static ImmutableListMultimap<String, Integer> argumentsByString( VisitorState state, List<? extends ExpressionTree> arguments) { ImmutableListMultimap.Builder<String, Integer> result = ImmutableListMultimap.builder(); for (int i = 0; i < arguments.size(); i++) { result.put(state.getSourceForNode(arguments.get(i)), i); } return result.build(); } private Description checkDistinctArgumentsWithFix(MethodInvocationTree tree, VisitorState state) { SuggestedFix.Builder suggestedFix = SuggestedFix.builder(); List<? extends ExpressionTree> arguments = tree.getArguments(); ImmutableListMultimap<String, Integer> argumentsByString = argumentsByString(state, arguments); for (Map.Entry<String, Collection<Integer>> entry : argumentsByString.asMap().entrySet()) { entry.getValue().stream() .skip(1) .forEachOrdered( index -> suggestedFix.merge( SuggestedFix.replace( state.getEndPosition(arguments.get(index - 1)), state.getEndPosition(arguments.get(index)), ""))); } if (suggestedFix.isEmpty()) { return Description.NO_MATCH; } return describeMatch(tree, suggestedFix.build()); } private Description checkDistinctArguments( VisitorState state, List<? extends ExpressionTree>... argumentsList) { for (List<? extends ExpressionTree> arguments : argumentsList) { ImmutableListMultimap<String, Integer> argumentsByString = argumentsByString(state, arguments); for (Map.Entry<String, Collection<Integer>> entry : argumentsByString.asMap().entrySet()) { entry.getValue().stream() .skip(1) .forEachOrdered(index -> state.reportMatch(describeMatch(arguments.get(index)))); } } return Description.NO_MATCH; } }
6,509
43.896552
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/IdentityHashMapBoxing.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.method.MethodMatchers.constructor; 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.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; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Using IdentityHashMap with a boxed type as the key is risky since boxing may produce" + " distinct instances", severity = ERROR) public class IdentityHashMapBoxing extends BugChecker implements NewClassTreeMatcher, MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> NEW_IDENTITY_HASH_MAP = constructor().forClass("java.util.IdentityHashMap"); private static final Matcher<ExpressionTree> MAPS_NEW_IDENTITY_HASH_MAP = staticMethod().onClass("com.google.common.collect.Maps").named("newIdentityHashMap"); @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { if (!NEW_IDENTITY_HASH_MAP.matches(tree, state)) { return NO_MATCH; } return checkTypes(tree, state); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MAPS_NEW_IDENTITY_HASH_MAP.matches(tree, state)) { return NO_MATCH; } return checkTypes(tree, state); } private Description checkTypes(ExpressionTree tree, VisitorState state) { List<Type> argumentTypes = ASTHelpers.getResultType(tree).getTypeArguments(); if (argumentTypes.size() != 2) { return Description.NO_MATCH; } Type type = state.getTypes().unboxedType(argumentTypes.get(0)); switch (type.getKind()) { case DOUBLE: case LONG: case INT: case FLOAT: return describeMatch(tree); default: return Description.NO_MATCH; } } }
3,170
36.75
94
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NullablePrimitiveArray.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.getAnnotationsWithSimpleName; import static com.google.errorprone.util.ASTHelpers.getType; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.MoreAnnotations; import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ArrayTypeTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.Type; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeKind; import javax.lang.model.util.SimpleAnnotationValueVisitor8; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "@Nullable type annotations should not be used for primitive types since they cannot be" + " null", severity = WARNING, tags = StandardTags.STYLE) public class NullablePrimitiveArray extends BugChecker implements VariableTreeMatcher, MethodTreeMatcher { @Override public Description matchMethod(MethodTree tree, VisitorState state) { return check(tree.getReturnType(), tree.getModifiers().getAnnotations(), state); } @Override public Description matchVariable(VariableTree tree, VisitorState state) { return check(tree.getType(), tree.getModifiers().getAnnotations(), state); } // other cases of `@Nullable int[]` are covered by the existing NullablePrimitive private Description check( Tree typeTree, List<? extends AnnotationTree> annotations, VisitorState state) { Type type = getType(typeTree); if (type == null) { return NO_MATCH; } if (!type.getKind().equals(TypeKind.ARRAY)) { return NO_MATCH; } while (type.getKind().equals(TypeKind.ARRAY)) { type = state.getTypes().elemtype(type); } if (!type.isPrimitive()) { return NO_MATCH; } AnnotationTree annotation = ASTHelpers.getAnnotationWithSimpleName(annotations, "Nullable"); if (annotation == null) { return NO_MATCH; } Attribute.Compound target = ASTHelpers.getSymbol(annotation).attribute(state.getSymtab().annotationTargetType.tsym); if (!isTypeAnnotation(target)) { return NO_MATCH; } Tree dims = typeTree; while (dims instanceof ArrayTypeTree) { dims = ((ArrayTypeTree) dims).getType(); } SuggestedFix.Builder fix = SuggestedFix.builder().delete(annotation); if (!(dims instanceof AnnotatedTypeTree) || getAnnotationsWithSimpleName(((AnnotatedTypeTree) dims).getAnnotations(), "Nullable") .isEmpty()) { fix.postfixWith(dims, " " + state.getSourceForNode(annotation) + " "); } return describeMatch(annotation, fix.build()); } private static boolean isTypeAnnotation(Attribute.Compound attribute) { if (attribute == null) { return false; } Set<String> targets = new HashSet<>(); Optional<Attribute> value = MoreAnnotations.getValue(attribute, "value"); if (!value.isPresent()) { return false; } new SimpleAnnotationValueVisitor8<Void, Void>() { @Override public Void visitEnumConstant(VariableElement c, Void unused) { targets.add(c.getSimpleName().toString()); return null; } @Override public Void visitArray(List<? extends AnnotationValue> list, Void unused) { list.forEach(x -> x.accept(this, null)); return null; } }.visit(value.get(), null); for (String target : targets) { switch (target) { case "METHOD": case "FIELD": case "LOCAL_VARIABLE": case "PARAMETER": return false; default: // fall out } } return targets.contains("TYPE_USE"); } }
5,182
35.244755
96
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AbstractMockChecker.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.matchers.Description.NO_MATCH; import com.google.auto.value.AutoValue; import com.google.common.base.Strings; import com.google.common.base.Suppliers; import com.google.common.collect.Lists; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.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.VariableTree; import com.sun.tools.javac.code.Attribute.Compound; import com.sun.tools.javac.code.Symbol.CompletionFailure; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Type; import java.lang.annotation.Annotation; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; /** * Helper for enforcing Annotations that disallow mocking. * * @author amalloy@google.com (Alan Malloy) */ public abstract class AbstractMockChecker<T extends Annotation> extends BugChecker implements MethodInvocationTreeMatcher, VariableTreeMatcher { public AbstractMockChecker( TypeExtractor<VariableTree> varExtractor, TypeExtractor<MethodInvocationTree> methodExtractor, Class<T> annotationClass, Function<T, String> getValueFunction) { this.varExtractor = varExtractor; this.methodExtractor = methodExtractor; this.annotationClass = annotationClass; this.getValueFunction = getValueFunction; this.annotationName = annotationClass.getSimpleName(); } /** * A policy for determining what classes should not be mocked. * * <p>This interface's intended use is to forbid mocking of classes you don't control, for example * those in the JDK itself or in a library you use. */ public interface MockForbidder { /** * If the given type should not be mocked, provide an explanation why. * * @param type the type that is being mocked * @return the reason it should not be mocked */ Optional<Reason> forbidReason(Type type, VisitorState state); } /** An explanation of what type should not be mocked, and the reason why. */ @AutoValue public abstract static class Reason { public static Reason of(Type t, String reason) { return new AutoValue_AbstractMockChecker_Reason(t, reason); } /** A Type object representing the class that should not be mocked. */ public abstract Type unmockableClass(); /** * The reason this class should not be mocked, which may be as simple as "it is annotated to * forbid mocking" but may also provide a suggested workaround. */ public abstract String reason(); } /** * Produce a MockForbidder to use when looking for disallowed mocks, in addition to the built-in * checks for Annotations of type {@code T}. * * <p>This method will be called at most once for each instance of AbstractMockChecker, but of * course the returned object's {@link MockForbidder#forbidReason(Type, VisitorState) * forbidReason} method may be called many times. * * <p>The default implementation forbids nothing. */ protected MockForbidder forbidder() { return (type, state) -> Optional.empty(); } /** * An extension of {@link Matcher} to return, not just a boolean `matches`, but also extract some * type information about the Tree of interest. * * <p>This is used to identify what classes are being mocked in a Tree. * * @param <T> the type of Tree that this TypeExtractor operates on */ public interface TypeExtractor<T extends Tree> { /** * Investigate the provided Tree, and return type information about it if it matches. * * @return the Type of the object being mocked, if any; Optional.empty() otherwise */ Optional<Type> extract(T tree, VisitorState state); /** * Enrich this TypeExtractor with fallback behavior. * * @return a TypeExtractor which first tries {@code this.extract(t, s)}, and if that does not * match, falls back to {@code other.extract(t, s)}. */ default TypeExtractor<T> or(TypeExtractor<T> other) { return (tree, state) -> TypeExtractor.this .extract(tree, state) .map(Optional::of) .orElseGet(() -> other.extract(tree, state)); } } /** * Produces an extractor which, if the tree matches, extracts the type of that tree, as given by * {@link ASTHelpers#getType(Tree)}. */ public static <T extends Tree> TypeExtractor<T> extractType(Matcher<T> m) { return (tree, state) -> { if (m.matches(tree, state)) { return Optional.ofNullable(ASTHelpers.getType(tree)); } return Optional.empty(); }; } /** * Produces an extractor which, if the tree matches, extracts the type of the first argument to * the method invocation. */ public static TypeExtractor<MethodInvocationTree> extractFirstArg( Matcher<MethodInvocationTree> m) { return (tree, state) -> { if (!m.matches(tree, state)) { return Optional.empty(); } if (tree.getArguments().size() >= 1) { return Optional.ofNullable(ASTHelpers.getType(tree.getArguments().get(0))); } return Optional.ofNullable(ASTHelpers.targetType(state)).map(t -> t.type()); }; } /** * Produces an extractor which, if the tree matches, extracts the type of the first argument whose * type is {@link Class} (preserving its {@code <T>} type parameter, if it has one}. * * @param m the matcher to use. It is an error for this matcher to succeed on any Tree that does * not include at least one argument of type {@link Class}; if such a matcher is provided, the * behavior of the returned Extractor is undefined. */ public static TypeExtractor<MethodInvocationTree> extractClassArg( Matcher<MethodInvocationTree> m) { return (tree, state) -> { if (m.matches(tree, state)) { for (ExpressionTree argument : tree.getArguments()) { Type argumentType = ASTHelpers.getType(argument); if (ASTHelpers.isSameType(argumentType, state.getSymtab().classType, state)) { return Optional.of(argumentType); } } // It's undefined, so we could fall through - but an exception is less likely to surprise. throw new IllegalStateException(); } return Optional.empty(); }; } /** * Creates a TypeExtractor that extracts the type of a class field if that field is annotated with * any one of the given annotations. */ public static TypeExtractor<VariableTree> fieldAnnotatedWithOneOf( Stream<String> annotationClasses) { return extractType( Matchers.allOf( Matchers.isField(), Matchers.anyOf( annotationClasses.map(Matchers::hasAnnotation).collect(Collectors.toList())))); } /** * A TypeExtractor for method invocations that create a mock using Mockito.mock, Mockito.spy, or * EasyMock.create[...]Mock, extracting the type being mocked. */ public static final TypeExtractor<MethodInvocationTree> MOCKING_METHOD = extractFirstArg( Matchers.toType( MethodInvocationTree.class, Matchers.staticMethod().onClass("org.mockito.Mockito").namedAnyOf("mock", "spy"))) .or( extractClassArg( Matchers.toType( MethodInvocationTree.class, Matchers.staticMethod() .onClass("org.easymock.EasyMock") .withNameMatching(Pattern.compile("^create.*Mock(Builder)?$"))))); @Override public final Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return this.methodExtractor .extract(tree, state) .flatMap(type -> argFromClass(type, state)) .map(type -> checkMockedType(type, tree, state)) .orElse(NO_MATCH); } @Override public final Description matchVariable(VariableTree tree, VisitorState state) { return varExtractor .extract(tree, state) .map(type -> checkMockedType(type, tree, state)) .orElse(NO_MATCH); } private Description checkMockedType(Type mockedClass, Tree tree, VisitorState state) { if (ASTHelpers.isSameType(Type.noType, mockedClass, state)) { return NO_MATCH; } // We could extract this for loop to a "default" MockForbidder, but there's not much // advantage in doing so. for (Type currentType : Lists.reverse(state.getTypes().closure(mockedClass))) { TypeSymbol currentSymbol = currentType.asElement(); T doNotMock = currentSymbol.getAnnotation(annotationClass); if (doNotMock != null) { return buildDescription(tree) .setMessage(buildMessage(mockedClass, currentSymbol, doNotMock)) .build(); } for (Compound compound : currentSymbol.getAnnotationMirrors()) { TypeSymbol metaAnnotationType = (TypeSymbol) compound.getAnnotationType().asElement(); try { metaAnnotationType.complete(); } catch (CompletionFailure e) { // if the annotation isn't on the compilation classpath, we can't check it for // the annotationClass meta-annotation continue; } doNotMock = metaAnnotationType.getAnnotation(annotationClass); if (doNotMock != null) { return buildDescription(tree) .setMessage(buildMessage(mockedClass, currentSymbol, metaAnnotationType, doNotMock)) .build(); } } } return forbidder .get() .forbidReason(mockedClass, state) .map( reason -> buildDescription(tree) .setMessage( buildMessage(mockedClass, reason.unmockableClass().tsym, reason.reason())) .build()) .orElse(NO_MATCH); } /** * If type is Class<T>, returns the erasure of T. Otherwise, returns type unmodified. Returns * empty() when provided a raw Class as argument. */ private static Optional<Type> argFromClass(Type type, VisitorState state) { if (ASTHelpers.isSameType(type, state.getSymtab().classType, state)) { if (type.getTypeArguments().isEmpty()) { return Optional.empty(); } return Optional.of(state.getTypes().erasure(getOnlyElement(type.getTypeArguments()))); } return Optional.of(type); } private String buildMessage(Type mockedClass, TypeSymbol forbiddenType, T doNotMock) { return buildMessage(mockedClass, forbiddenType, null, doNotMock); } private String buildMessage( Type mockedClass, TypeSymbol forbiddenType, @Nullable TypeSymbol metaAnnotationType, T doNotMock) { return String.format( "%s; %s is annotated as @%s%s: %s.", buildMessage(mockedClass, forbiddenType), forbiddenType, metaAnnotationType == null ? annotationName : metaAnnotationType, (metaAnnotationType == null ? "" : String.format(" (which is annotated as @%s)", annotationName)), Optional.ofNullable(Strings.emptyToNull(getValueFunction.apply(doNotMock))) .orElseGet(() -> String.format("It is annotated as %s.", annotationName))); } private static String buildMessage(Type mockedClass, TypeSymbol forbiddenType) { return String.format( "Do not mock '%s'%s", mockedClass, (mockedClass.asElement().equals(forbiddenType) ? "" : " (which is-a '" + forbiddenType + "')")); } private static String buildMessage(Type mockedClass, TypeSymbol forbiddenType, String reason) { return String.format("%s: %s.", buildMessage(mockedClass, forbiddenType), reason); } private final TypeExtractor<VariableTree> varExtractor; private final TypeExtractor<MethodInvocationTree> methodExtractor; private final Class<T> annotationClass; private final String annotationName; private final Function<T, String> getValueFunction; private final Supplier<MockForbidder> forbidder = Suppliers.memoize(this::forbidder); }
13,384
36.917847
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LoopOverCharArray.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.method.MethodMatchers.instanceMethod; import static com.google.errorprone.util.ASTHelpers.getStartPosition; 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.BlockTree; import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree; import com.sun.source.util.TreeScanner; import java.util.List; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "toCharArray allocates a new array, using charAt is more efficient", severity = WARNING) public class LoopOverCharArray extends BugChecker implements BugChecker.EnhancedForLoopTreeMatcher { private static final Matcher<ExpressionTree> TO_CHAR_ARRAY = instanceMethod().onExactClass("java.lang.String").named("toCharArray"); @Override public Description matchEnhancedForLoop(EnhancedForLoopTree tree, VisitorState state) { if (!TO_CHAR_ARRAY.matches(tree.getExpression(), state)) { return NO_MATCH; } ExpressionTree receiver = ASTHelpers.getReceiver(tree.getExpression()); if (!(receiver instanceof IdentifierTree)) { return NO_MATCH; } StatementTree body = tree.getStatement(); if (!(body instanceof BlockTree)) { return NO_MATCH; } List<? extends StatementTree> statements = ((BlockTree) body).getStatements(); if (statements.isEmpty()) { return NO_MATCH; } Description.Builder description = buildDescription(tree); // The fix uses `i` as the loop index variable, so give up if there's already an `i` in scope if (!alreadyDefinesIdentifier(tree)) { description.addFix( SuggestedFix.replace( getStartPosition(tree), getStartPosition(statements.get(0)), String.format( "for (int i = 0; i < %s.length(); i++) { char %s = %s.charAt(i);", state.getSourceForNode(receiver), tree.getVariable().getName(), state.getSourceForNode(receiver)))); } return description.build(); } private static boolean alreadyDefinesIdentifier(Tree tree) { boolean[] result = {false}; new TreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree node, Void unused) { if (node.getName().contentEquals("i")) { result[0] = true; } return super.visitIdentifier(node, unused); } }.scan(tree, null); return result[0]; } }
3,672
37.663158
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ReplacementVariableFinder.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.sun.source.tree.Tree.Kind.IDENTIFIER; import static com.sun.source.tree.Tree.Kind.MEMBER_SELECT; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.errorprone.VisitorState; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.names.LevenshteinEditDistance; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import java.util.Collections; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collector; import java.util.stream.Collectors; /** Utility methods to find replacement variables with similar names. */ public final class ReplacementVariableFinder { private ReplacementVariableFinder() {} /** * Suggest replacing {@code input} with a qualified reference to a locally declared field with a * similar or the same name as the {@code input} expression. * * @param input a MEMBER_SELECT or IDENTIFIER expression which should be replaced. * @param validFieldPredicate Predicate used to decide which locally declared fields are * appropriate candidates for replacement (e.g.: is the appropriate type) */ public static ImmutableList<Fix> fixesByReplacingExpressionWithLocallyDeclaredField( ExpressionTree input, Predicate<JCVariableDecl> validFieldPredicate, VisitorState state) { Preconditions.checkState(input.getKind() == IDENTIFIER || input.getKind() == MEMBER_SELECT); ImmutableMultimap<Integer, JCVariableDecl> potentialReplacements = ASTHelpers.findEnclosingNode(state.getPath(), JCClassDecl.class).getMembers().stream() .filter(JCVariableDecl.class::isInstance) .map(JCVariableDecl.class::cast) .filter(validFieldPredicate) .collect(collectByEditDistanceTo(simpleNameOfIdentifierOrMemberAccess(input))); return buildValidReplacements( potentialReplacements, var -> SuggestedFix.replace(input, "this." + var.sym)); } /** * Suggest replacing {@code input} with a reference to a method parameter in the nearest enclosing * method declaration with a similar or the same name as the {@code input} expression. * * @param input a MEMBER_SELECT or IDENTIFIER expression which should be replaced. * @param validParameterPredicate Predicate used to decide which method parameters are appropriate * candidates for replacement (e.g.: is the appropriate type) */ public static ImmutableList<Fix> fixesByReplacingExpressionWithMethodParameter( ExpressionTree input, Predicate<JCVariableDecl> validParameterPredicate, VisitorState state) { Preconditions.checkState(input.getKind() == IDENTIFIER || input.getKind() == MEMBER_SELECT); // find a method parameter matching the input predicate and similar name and suggest it // as the new argument ImmutableMultimap<Integer, JCVariableDecl> potentialReplacements = ASTHelpers.findEnclosingNode(state.getPath(), JCMethodDecl.class).getParameters().stream() .filter(validParameterPredicate) .collect(collectByEditDistanceTo(simpleNameOfIdentifierOrMemberAccess(input))); return buildValidReplacements( potentialReplacements, var -> SuggestedFix.replace(input, var.sym.toString())); } private static ImmutableList<Fix> buildValidReplacements( Multimap<Integer, JCVariableDecl> potentialReplacements, Function<JCVariableDecl, Fix> replacementFunction) { if (potentialReplacements.isEmpty()) { return ImmutableList.of(); } // Take all of the potential edit-distance replacements with the same minimum distance, // then suggest them as individual fixes. return potentialReplacements.get(Collections.min(potentialReplacements.keySet())).stream() .map(replacementFunction) .collect(toImmutableList()); } private static Collector<JCVariableDecl, ?, ImmutableMultimap<Integer, JCVariableDecl>> collectByEditDistanceTo(String baseName) { return Collectors.collectingAndThen( Multimaps.toMultimap( (JCVariableDecl varDecl) -> LevenshteinEditDistance.getEditDistance(baseName, varDecl.name.toString()), varDecl -> varDecl, LinkedHashMultimap::create), ImmutableMultimap::copyOf); } private static String simpleNameOfIdentifierOrMemberAccess(ExpressionTree tree) { String name = null; if (tree.getKind() == IDENTIFIER) { name = ((JCIdent) tree).name.toString(); } else if (tree.getKind() == MEMBER_SELECT) { name = ((JCFieldAccess) tree).name.toString(); } return name; } }
5,902
44.061069
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LiteProtoToString.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.Streams.stream; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.predicates.TypePredicates.allOf; import static com.google.errorprone.predicates.TypePredicates.isDescendantOf; import static com.google.errorprone.predicates.TypePredicates.isExactType; import static com.google.errorprone.predicates.TypePredicates.not; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.fixes.Fix; import com.google.errorprone.predicates.TypePredicate; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Type; import java.util.Optional; /** Flags calls to {@code toString} on lite protos. */ @BugPattern( summary = "toString() on lite protos will not generate a useful representation of the proto from" + " optimized builds. Consider whether using some subset of fields instead would" + " provide useful information.", severity = WARNING) public final class LiteProtoToString extends AbstractToString { private static final String LITE_ENUM_MESSAGE = "toString() on lite proto enums will generate different representations of the value from" + " development and optimized builds. Consider using #getNumber if you only need a" + " serialized representation of the value, or #name if you really need the name." + ""; private static final TypePredicate IS_LITE_PROTO = allOf( isDescendantOf("com.google.protobuf.MessageLite"), not(isDescendantOf("com.google.protobuf.Message")), not(isExactType("com.google.protobuf.UnknownFieldSet"))); private static final TypePredicate IS_LITE_ENUM = allOf( isDescendantOf("com.google.protobuf.Internal.EnumLite"), not(isDescendantOf("com.google.protobuf.ProtocolMessageEnum")), not(isDescendantOf("com.google.protobuf.Descriptors.EnumValueDescriptor")), not(isDescendantOf("com.google.protobuf.AbstractMessageLite.InternalOneOfEnum"))); private static final ImmutableSet<String> METHODS_STRIPPED_BY_OPTIMIZER = ImmutableSet.<String>builder() .add("atVerbose", "atFine", "atFiner", "atFinest", "atDebug", "atConfig", "atInfo") .add("v", "d", "i") .build(); @Override protected TypePredicate typePredicate() { return LiteProtoToString::matches; } private static boolean matches(Type type, VisitorState state) { if (state.errorProneOptions().isTestOnlyTarget()) { return false; } if (isStrippedLogMessage(state)) { return false; } return IS_LITE_PROTO.apply(type, state) || IS_LITE_ENUM.apply(type, state); } private static boolean isStrippedLogMessage(VisitorState state) { return stream(state.getPath()).anyMatch(LiteProtoToString::isStrippedLogMessage); } private static boolean isStrippedLogMessage(Tree tree) { for (; tree instanceof MethodInvocationTree; tree = getReceiver((MethodInvocationTree) tree)) { if (METHODS_STRIPPED_BY_OPTIMIZER.contains(getSymbol(tree).getSimpleName().toString())) { return true; } } return false; } @Override protected Optional<String> descriptionMessageForDefaultMatch(Type type, VisitorState state) { return Optional.of(IS_LITE_ENUM.apply(type, state) ? LITE_ENUM_MESSAGE : message()); } @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(); } }
4,621
39.191304
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/InputStreamSlowMultibyteRead.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.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.hasAnnotation; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import static com.google.errorprone.matchers.Matchers.methodHasArity; import static com.google.errorprone.matchers.Matchers.methodIsNamed; import static com.google.errorprone.matchers.Matchers.methodReturns; import static com.google.errorprone.suppliers.Suppliers.INT_TYPE; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.JUnitMatchers; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.util.TreePath; 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.util.Name; import java.io.InputStream; import javax.lang.model.element.ElementKind; /** Checks that InputStreams should override int read(byte[], int, int); */ @BugPattern( summary = "Please also override int read(byte[], int, int), otherwise multi-byte reads from this " + "input stream are likely to be slow.", severity = WARNING, tags = StandardTags.PERFORMANCE) public class InputStreamSlowMultibyteRead extends BugChecker implements ClassTreeMatcher { private static final Matcher<ClassTree> IS_INPUT_STREAM = isSubtypeOf(InputStream.class); private static final Matcher<MethodTree> READ_INT_METHOD = allOf(methodIsNamed("read"), methodReturns(INT_TYPE), methodHasArity(0)); @Override public Description matchClass(ClassTree classTree, VisitorState state) { if (!IS_INPUT_STREAM.matches(classTree, state)) { return Description.NO_MATCH; } TypeSymbol thisClassSymbol = ASTHelpers.getSymbol(classTree); if (thisClassSymbol.getKind() != ElementKind.CLASS) { return Description.NO_MATCH; } // Find the method that overrides the single-byte read. It should also override the multibyte // read. MethodTree readByteMethod = classTree.getMembers().stream() .filter(MethodTree.class::isInstance) .map(MethodTree.class::cast) .filter(m -> READ_INT_METHOD.matches(m, state)) .findFirst() .orElse(null); if (readByteMethod == null) { return Description.NO_MATCH; } Type byteArrayType = state.arrayTypeForType(state.getSymtab().byteType); Type intType = state.getSymtab().intType; MethodSymbol multiByteReadMethod = ASTHelpers.resolveExistingMethod( state, thisClassSymbol, READ.get(state), ImmutableList.of(byteArrayType, intType, intType), ImmutableList.of()); return multiByteReadMethod.owner.equals(thisClassSymbol) ? Description.NO_MATCH : maybeMatchReadByte(readByteMethod, state); } private static final Matcher<MethodTree> RETURNS_CONSTANT = Matchers.singleStatementReturnMatcher((e, s) -> ASTHelpers.constValue(e) != null); private Description maybeMatchReadByte(MethodTree readByteMethod, VisitorState state) { // Methods that return a constant expression are likely to be 'dummy streams', for which // the multibyte read is OK. if (RETURNS_CONSTANT.matches(readByteMethod, state)) { return Description.NO_MATCH; } // Streams within JUnit test cases are likely to be OK as well. TreePath enclosingPath = ASTHelpers.findPathFromEnclosingNodeToTopLevel(state.getPath(), ClassTree.class); while (enclosingPath != null) { ClassTree klazz = (ClassTree) enclosingPath.getLeaf(); if (JUnitMatchers.isTestCaseDescendant.matches(klazz, state) || hasAnnotation(JUnitMatchers.JUNIT4_RUN_WITH_ANNOTATION).matches(klazz, state)) { return Description.NO_MATCH; } enclosingPath = ASTHelpers.findPathFromEnclosingNodeToTopLevel(enclosingPath, ClassTree.class); } return describeMatch(readByteMethod); } private static final Supplier<Name> READ = VisitorState.memoize(state -> state.getName("read")); }
5,321
39.318182
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ThrowNull.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.sun.source.tree.Tree.Kind.NULL_LITERAL; 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.sun.source.tree.ThrowTree; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Throwing 'null' always results in a NullPointerException being thrown.", severity = ERROR) public class ThrowNull extends BugChecker implements ThrowTreeMatcher { @Override public Description matchThrow(ThrowTree tree, VisitorState state) { return (tree.getExpression().getKind() == NULL_LITERAL) ? describeMatch( tree, SuggestedFix.replace(tree.getExpression(), "new NullPointerException()")) : NO_MATCH; } }
1,711
38.813953
91
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/UseCorrectAssertInTests.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.method.MethodMatchers.instanceMethod; import static com.sun.source.tree.Tree.Kind.LOGICAL_COMPLEMENT; import static com.sun.source.tree.Tree.Kind.NULL_LITERAL; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AssertTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCUnary; import com.sun.tools.javac.tree.TreeInfo; /** * @author galitch@google.com (Anton Galitch) */ @BugPattern( summary = "Java assert is used in testing code. For testing purposes, prefer using Truth-based" + " assertions.", severity = SeverityLevel.ERROR) public class UseCorrectAssertInTests extends BugChecker implements MethodTreeMatcher { private static final String STATIC_ASSERT_THAT_IMPORT = "static com.google.common.truth.Truth.assertThat"; private static final String STATIC_ASSERT_WITH_MESSAGE_IMPORT = "static com.google.common.truth.Truth.assertWithMessage"; private static final String IS_TRUE = "isTrue();"; private static final String IS_FALSE = "isFalse();"; private static final String IS_NULL = "isNull();"; private static final String IS_NOT_NULL = "isNotNull();"; private static final String IS_EQUAL_TO = "isEqualTo(%s);"; private static final String IS_NOT_EQUAL_TO = "isNotEqualTo(%s);"; private static final String IS_SAME_AS = "isSameInstanceAs(%s);"; private static final String IS_NOT_SAME_AS = "isNotSameInstanceAs(%s);"; public UseCorrectAssertInTests() {} @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { if (methodTree.getBody() == null) { // Method is not implemented (i.e. it's abstract). return Description.NO_MATCH; } // Match either JUnit tests or test-only code. if (!(ASTHelpers.isJUnitTestCode(state) || state.errorProneOptions().isTestOnlyTarget())) { return Description.NO_MATCH; } ImmutableList<AssertTree> assertions = scanAsserts(methodTree); if (assertions.isEmpty()) { return Description.NO_MATCH; } SuggestedFix.Builder fix = SuggestedFix.builder(); for (AssertTree foundAssert : assertions) { replaceAssert(fix, foundAssert, state); } // Emit finding on the first assertion rather than on the method (b/175575632). return describeMatch(assertions.get(0), fix.build()); } private static void replaceAssert( SuggestedFix.Builder fix, AssertTree foundAssert, VisitorState state) { ExpressionTree expr = foundAssert.getCondition(); expr = (ExpressionTree) TreeInfo.skipParens((JCTree) expr); // case: "assert !expr" if (expr.getKind().equals(LOGICAL_COMPLEMENT)) { addFix(fix, ((JCUnary) expr).getExpression(), foundAssert, state, IS_FALSE); return; } // case: "assert expr1.equals(expr2)" if (instanceMethod().anyClass().named("equals").matches(expr, state)) { JCMethodInvocation equalsCall = ((JCMethodInvocation) expr); JCExpression expr1 = ((JCFieldAccess) ((JCMethodInvocation) expr).meth).selected; JCExpression expr2 = equalsCall.getArguments().get(0); addFix( fix, expr1, foundAssert, state, String.format(IS_EQUAL_TO, normalizedSourceForExpression(expr2, state))); return; } // case: "assert expr1 == expr2" or "assert expr1 != expr2" if (expr.getKind().equals(Kind.EQUAL_TO) || expr.getKind().equals(Kind.NOT_EQUAL_TO)) { suggestFixForEquality(fix, foundAssert, state, expr.getKind().equals(Kind.EQUAL_TO)); return; } // case: "assert expr", which didn't match any of the previous cases. addFix(fix, (JCExpression) expr, foundAssert, state, IS_TRUE); } private static void addFix( SuggestedFix.Builder fix, JCExpression expr, AssertTree foundAssert, VisitorState state, String isMethod) { String assertToUse; if (foundAssert.getDetail() == null) { fix.addImport(STATIC_ASSERT_THAT_IMPORT); assertToUse = String.format("assertThat(%s).", normalizedSourceForExpression(expr, state)); } else { fix.addImport(STATIC_ASSERT_WITH_MESSAGE_IMPORT); assertToUse = String.format( "assertWithMessage(%s).that(%s).", convertToString(foundAssert.getDetail(), state), normalizedSourceForExpression(expr, state)); } fix.replace(foundAssert, assertToUse + isMethod); } /** Handles the case "expr1 == expr2" */ private static void suggestFixForEquality( SuggestedFix.Builder fix, AssertTree foundAssert, VisitorState state, boolean isEqual) { BinaryTree equalityTree = (BinaryTree) TreeInfo.skipParens((JCTree) foundAssert.getCondition()); ExpressionTree expr1 = equalityTree.getLeftOperand(); ExpressionTree expr2 = equalityTree.getRightOperand(); if (expr1.getKind() == NULL_LITERAL) { // case: "assert null [op] expr" addFix(fix, (JCExpression) expr2, foundAssert, state, isEqual ? IS_NULL : IS_NOT_NULL); } else if (expr2.getKind() == NULL_LITERAL) { // case: "assert expr [op] null" addFix(fix, (JCExpression) expr1, foundAssert, state, isEqual ? IS_NULL : IS_NOT_NULL); } else if (ASTHelpers.getType(expr1).isPrimitive() || ASTHelpers.getType(expr2).isPrimitive()) { // case: eg. "assert expr == 1" addFix( fix, (JCExpression) expr1, foundAssert, state, String.format(isEqual ? IS_EQUAL_TO : IS_NOT_EQUAL_TO, state.getSourceForNode(expr2))); } else { // case: "assert expr1 [op] expr2" addFix( fix, (JCExpression) expr1, foundAssert, state, String.format(isEqual ? IS_SAME_AS : IS_NOT_SAME_AS, state.getSourceForNode(expr2))); } } private static String normalizedSourceForExpression(JCExpression expression, VisitorState state) { return state.getSourceForNode(TreeInfo.skipParens(expression)); } /* Appends .toString() if the expression is not of type String. */ private static String convertToString(ExpressionTree detail, VisitorState state) { return state.getSourceForNode(detail) + (ASTHelpers.isSameType(ASTHelpers.getType(detail), state.getSymtab().stringType, state) ? "" : ".toString()"); } /** Returns all the "assert" expressions in the tree. */ private static ImmutableList<AssertTree> scanAsserts(Tree tree) { ImmutableList.Builder<AssertTree> assertTrees = ImmutableList.builder(); tree.accept( new TreeScanner<Void, VisitorState>() { @Override public Void visitAssert(AssertTree assertTree, VisitorState visitorState) { assertTrees.add(assertTree); return null; } }, null); return assertTrees.build(); } }
8,300
36.731818
100
java