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/FunctionalInterfaceMethodChanged.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.ImmutableSet.toImmutableSet; import static com.google.errorprone.suppliers.Suppliers.JAVA_LANG_VOID_TYPE; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; 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.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.BlockTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.LiteralTree; 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.TreeVisitor; import com.sun.source.util.SimpleTreeVisitor; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; import java.util.Collections; import javax.lang.model.element.Modifier; /** * @author Louis Wasserman */ @BugPattern( summary = "Casting a lambda to this @FunctionalInterface can cause a behavior change from casting to" + " a functional superinterface, which is surprising to users. Prefer decorator" + " methods to this surprising behavior.", severity = SeverityLevel.ERROR) public class FunctionalInterfaceMethodChanged extends BugChecker implements MethodTreeMatcher { private static final Matcher<Tree> IS_FUNCTIONAL_INTERFACE = Matchers.symbolHasAnnotation(FunctionalInterface.class); @Override public Description matchMethod(MethodTree tree, VisitorState state) { ClassTree enclosingClazz = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class); if (tree.getModifiers().getFlags().contains(Modifier.DEFAULT) && IS_FUNCTIONAL_INTERFACE.matches(enclosingClazz, state)) { Types types = state.getTypes(); ImmutableSet<Symbol> functionalSuperInterfaceSams = enclosingClazz.getImplementsClause().stream() .filter(t -> IS_FUNCTIONAL_INTERFACE.matches(t, state)) .map(ASTHelpers::getSymbol) .map(TypeSymbol.class::cast) .map(types::findDescriptorSymbol) // TypeSymbol to single abstract method of the type .collect(toImmutableSet()); // We designate an override of a superinterface SAM "behavior preserving" if it just // calls the SAM of this interface. Symbol thisInterfaceSam = types.findDescriptorSymbol(ASTHelpers.getSymbol(enclosingClazz)); // relatively crude: doesn't verify that the same args are passed in the same order // so it can get false positives for behavior-preservingness (false negatives for the check) TreeVisitor<Boolean, VisitorState> behaviorPreserving = new BehaviorPreservingChecker(thisInterfaceSam); if (!Collections.disjoint( ASTHelpers.findSuperMethods(ASTHelpers.getSymbol(tree), types), functionalSuperInterfaceSams) && !tree.accept(behaviorPreserving, state)) { return describeMatch(tree); } } return Description.NO_MATCH; } private static class BehaviorPreservingChecker extends SimpleTreeVisitor<Boolean, VisitorState> { private boolean inBoxedVoidReturningMethod = false; private final Symbol methodToCall; public BehaviorPreservingChecker(Symbol methodToCall) { super(false); this.methodToCall = methodToCall; } @Override public Boolean visitMethod(MethodTree node, VisitorState state) { boolean prevInBoxedVoidReturningMethod = inBoxedVoidReturningMethod; Type returnType = ASTHelpers.getType(node.getReturnType()); Type boxedVoidType = JAVA_LANG_VOID_TYPE.get(state); if (ASTHelpers.isSameType(returnType, boxedVoidType, state)) { inBoxedVoidReturningMethod = true; } boolean result = node.getBody() != null && node.getBody().accept(this, state); inBoxedVoidReturningMethod = prevInBoxedVoidReturningMethod; return result; } @Override public Boolean visitBlock(BlockTree node, VisitorState state) { if (inBoxedVoidReturningMethod) { // Must have exactly 2 statements if (node.getStatements().size() != 2) { return false; } // Where the first one is a call to the methodToCall if (!node.getStatements().get(0).accept(this, state)) { return false; } // And the second one is "return null;" if (node.getStatements().get(1) instanceof ReturnTree) { ReturnTree returnTree = (ReturnTree) node.getStatements().get(1); if (returnTree.getExpression() instanceof LiteralTree) { Object returnValue = ((LiteralTree) returnTree.getExpression()).getValue(); return returnValue == null; } } return false; } else { return node.getStatements().size() == 1 && Iterables.getOnlyElement(node.getStatements()).accept(this, state); } } @Override public Boolean visitExpressionStatement(ExpressionStatementTree node, VisitorState state) { return node.getExpression().accept(this, state); } @Override public Boolean visitReturn(ReturnTree node, VisitorState state) { return node.getExpression().accept(this, state); } @Override public Boolean visitMethodInvocation(MethodInvocationTree node, VisitorState state) { return ASTHelpers.getSymbol(node) == methodToCall; } } }
6,519
39.246914
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/StreamToIterable.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.BugPattern.StandardTags.FRAGILE_CODE; import static com.google.errorprone.fixes.SuggestedFixes.qualifyStaticImport; 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.getSymbol; 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.LambdaExpressionTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.LambdaExpressionTree.BodyKind; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.TypeCastTree; import com.sun.tools.javac.code.Symbol.VarSymbol; /** Discourage {@code stream::iterator} to create {@link Iterable}s. */ @BugPattern( summary = "Using stream::iterator creates a one-shot Iterable, which may cause surprising failures.", severity = WARNING, tags = FRAGILE_CODE, documentSuppression = false) public final class StreamToIterable extends BugChecker implements LambdaExpressionTreeMatcher, MemberReferenceTreeMatcher { private static final Matcher<ExpressionTree> STREAM_ITERATOR = instanceMethod().onDescendantOf("java.util.stream.Stream").named("iterator"); @Override public Description matchLambdaExpression(LambdaExpressionTree tree, VisitorState state) { if (!isSameType(getType(tree), state.getSymtab().iterableType, state)) { return NO_MATCH; } if (!tree.getBodyKind().equals(BodyKind.EXPRESSION)) { return NO_MATCH; } ExpressionTree body = (ExpressionTree) tree.getBody(); if (!STREAM_ITERATOR.matches(body, state)) { return NO_MATCH; } // Only match variables, which we can be sure aren't being re-created. if (!(getSymbol(getReceiver(body)) instanceof VarSymbol)) { return NO_MATCH; } return describeMatch(tree, body, state); } @Override public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) { if (!STREAM_ITERATOR.matches(tree, state)) { return NO_MATCH; } if (!isSameType(getType(tree), state.getSymtab().iterableType, state)) { return NO_MATCH; } return describeMatch(tree, tree, state); } private Description describeMatch( ExpressionTree tree, ExpressionTree invocation, VisitorState state) { if (state.getPath().getParentPath().getLeaf() instanceof TypeCastTree && state.getPath().getParentPath().getParentPath().getLeaf() instanceof EnhancedForLoopTree) { return NO_MATCH; } SuggestedFix.Builder fix = SuggestedFix.builder() .setShortDescription( "Collect to an ImmutableList (caveat: this materializes the contents into memory" + " at once)"); fix.replace( tree, String.format( "%s.collect(%s())", state.getSourceForNode(getReceiver(invocation)), qualifyStaticImport( "com.google.common.collect.ImmutableList.toImmutableList", fix, state))); return describeMatch(tree, fix.build()); } }
4,430
40.411215
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ByteBufferBackingArray.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.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.matchers.Matchers.staticMethod; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import java.nio.ByteBuffer; import java.util.Optional; /** * Checks when ByteBuffer.array() is used without calling .arrayOffset() to know the offset of the * array, or when the buffer wasn't initialized using ByteBuffer.wrap() or ByteBuffer.allocate(). */ @BugPattern( summary = "ByteBuffer.array() shouldn't be called unless ByteBuffer.arrayOffset() is used or " + "if the ByteBuffer was initialized using ByteBuffer.wrap() or ByteBuffer.allocate().", severity = WARNING) public class ByteBufferBackingArray extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> BYTE_BUFFER_ARRAY_MATCHER = anyOf(instanceMethod().onDescendantOf(ByteBuffer.class.getName()).named("array")); private static final Matcher<ExpressionTree> BYTE_BUFFER_ARRAY_OFFSET_MATCHER = anyOf(instanceMethod().onDescendantOf(ByteBuffer.class.getName()).named("arrayOffset")); private static final Matcher<ExpressionTree> BYTE_BUFFER_ALLOWED_INITIALIZERS_MATCHER = staticMethod().onClass(ByteBuffer.class.getName()).namedAnyOf("allocate", "wrap"); private static final Matcher<ExpressionTree> BYTE_BUFFER_MATCHER = isSameType(ByteBuffer.class); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!BYTE_BUFFER_ARRAY_MATCHER.matches(tree, state)) { return Description.NO_MATCH; } // Checks for validating use on method call chain. ExpressionTree receiver = tree; do { receiver = ASTHelpers.getReceiver(receiver); if (isValidInitializerOrNotAByteBuffer(receiver, state)) { return Description.NO_MATCH; } } while (receiver instanceof MethodInvocationTree); Symbol bufferSymbol = ASTHelpers.getSymbol(receiver); if (bufferSymbol == null) { return Description.NO_MATCH; } // Checks for validating use on method scope. if (bufferSymbol.owner instanceof MethodSymbol) { MethodTree enclosingMethod = ASTHelpers.findMethod((MethodSymbol) bufferSymbol.owner, state); if (enclosingMethod == null || ValidByteBufferArrayScanner.scan(enclosingMethod, state, bufferSymbol)) { return Description.NO_MATCH; } } // Checks for validating use on fields. if (bufferSymbol.owner instanceof ClassSymbol) { ClassTree enclosingClass = ASTHelpers.findClass((ClassSymbol) bufferSymbol.owner, state); if (enclosingClass == null) { return Description.NO_MATCH; } Optional<? extends Tree> validMemberTree = enclosingClass.getMembers().stream() .filter( memberTree -> ValidByteBufferArrayScanner.scan(memberTree, state, bufferSymbol)) .findFirst(); if (validMemberTree.isPresent()) { return Description.NO_MATCH; } } return describeMatch(tree); } private static boolean isValidInitializerOrNotAByteBuffer( ExpressionTree receiver, VisitorState state) { return BYTE_BUFFER_ALLOWED_INITIALIZERS_MATCHER.matches(receiver, state) || !BYTE_BUFFER_MATCHER.matches(receiver, state); } /** * Scan for a call to ByteBuffer.arrayOffset() or check if buffer was initialized with either * ByteBuffer.wrap() or ByteBuffer.allocate(). */ private static class ValidByteBufferArrayScanner extends TreeScanner<Void, VisitorState> { private final Symbol searchedBufferSymbol; private boolean visited; private boolean valid; static boolean scan(Tree tree, VisitorState state, Symbol searchedBufferSymbol) { ValidByteBufferArrayScanner visitor = new ValidByteBufferArrayScanner(searchedBufferSymbol); tree.accept(visitor, state); return visitor.valid; } private ValidByteBufferArrayScanner(Symbol searchedBufferSymbol) { this.searchedBufferSymbol = searchedBufferSymbol; } @Override public Void visitVariable(VariableTree tree, VisitorState state) { checkForInitializer(ASTHelpers.getSymbol(tree), tree.getInitializer(), state); return super.visitVariable(tree, state); } @Override public Void visitAssignment(AssignmentTree tree, VisitorState state) { checkForInitializer(ASTHelpers.getSymbol(tree.getVariable()), tree.getExpression(), state); return super.visitAssignment(tree, state); } @Override public Void visitMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (valid) { return null; } Symbol bufferSymbol = ASTHelpers.getSymbol(ASTHelpers.getReceiver(tree)); if (searchedBufferSymbol.equals(bufferSymbol)) { if (BYTE_BUFFER_ARRAY_MATCHER.matches(tree, state)) { visited = true; } else if (BYTE_BUFFER_ARRAY_OFFSET_MATCHER.matches(tree, state)) { valid = true; } } return super.visitMethodInvocation(tree, state); } private void checkForInitializer( Symbol foundSymbol, ExpressionTree expression, VisitorState state) { if (visited || valid) { return; } if (!searchedBufferSymbol.equals(foundSymbol)) { return; } if (expression == null) { return; } if (ValidByteBufferInitializerScanner.scan(expression, state)) { valid = true; } } } /** Scan for a call to ByteBuffer.wrap() or ByteBuffer.allocate(). */ private static class ValidByteBufferInitializerScanner extends TreeScanner<Boolean, VisitorState> { static Boolean scan(ExpressionTree tree, VisitorState state) { ValidByteBufferInitializerScanner visitor = new ValidByteBufferInitializerScanner(); return firstNonNull(tree.accept(visitor, state), false); } private ValidByteBufferInitializerScanner() {} @Override public Boolean visitMethodInvocation(MethodInvocationTree tree, VisitorState state) { boolean b1 = BYTE_BUFFER_ALLOWED_INITIALIZERS_MATCHER.matches(tree, state); boolean b2 = super.visitMethodInvocation(tree, state); return b1 || b2; } @Override public Boolean reduce(Boolean r1, Boolean r2) { return firstNonNull(r1, false) || firstNonNull(r2, false); } } }
8,067
37.236967
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MixedDescriptors.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.enclosingPackage; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isSubtype; import com.google.errorprone.BugPattern; import com.google.errorprone.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.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.TypeSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import java.util.List; import java.util.Optional; /** * Checks for calls to {@code Descriptor#findFieldByNumber} with field numbers from a different * proto. * * @author ghm@google.com (Graeme Morgan) */ @BugPattern( summary = "The field number passed into #findFieldByNumber belongs to a different proto" + " to the Descriptor.", severity = ERROR) public final class MixedDescriptors extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> GET_DESCRIPTOR = staticMethod().onDescendantOf("com.google.protobuf.Message").named("getDescriptor"); private static final Matcher<ExpressionTree> FIND_FIELD = instanceMethod() .onDescendantOf("com.google.protobuf.Descriptors.Descriptor") .named("findFieldByNumber"); private static final Supplier<Type> MESSAGE = Suppliers.typeFromString("com.google.protobuf.Message"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!FIND_FIELD.matches(tree, state)) { return Description.NO_MATCH; } ExpressionTree receiver = getReceiver(tree); if (!GET_DESCRIPTOR.matches(receiver, state)) { return Description.NO_MATCH; } List<? extends ExpressionTree> arguments = tree.getArguments(); if (arguments.size() != 1) { return Description.NO_MATCH; } Symbol argumentSymbol = getSymbol(getOnlyElement(arguments)); if (!(argumentSymbol instanceof VarSymbol) || !argumentSymbol.getSimpleName().toString().endsWith("_FIELD_NUMBER")) { return Description.NO_MATCH; } Optional<TypeSymbol> descriptorType = protoType(getOnlyElement(arguments), state); Optional<TypeSymbol> receiverType = protoType(receiver, state); return typesDiffer( descriptorType.filter(MixedDescriptors::shouldConsider), receiverType.filter(MixedDescriptors::shouldConsider)) ? describeMatch(tree) : Description.NO_MATCH; } /** Ignore packages specifically qualified as proto1 or proto2. */ private static boolean shouldConsider(TypeSymbol symbol) { String packge = enclosingPackage(symbol).toString(); return !(packge.contains(".proto1api") || packge.contains(".proto2api")); } private static boolean typesDiffer(Optional<TypeSymbol> a, Optional<TypeSymbol> b) { return a.isPresent() && b.isPresent() && !a.get().equals(b.get()); } private static Optional<TypeSymbol> protoType(Tree tree, VisitorState state) { Symbol symbol = getSymbol(tree); if (symbol != null && symbol.owner instanceof ClassSymbol && isSubtype(symbol.owner.type, MESSAGE.get(state), state)) { return Optional.of(symbol.owner.type.tsym); } return Optional.empty(); } }
4,748
39.589744
95
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/CatchingUnchecked.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isCheckedExceptionType; import static com.google.errorprone.util.ASTHelpers.isSameType; import static com.google.errorprone.util.ASTHelpers.isSubtype; 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.TryTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers.ScanThrownTypes; import com.sun.source.tree.CatchTree; import com.sun.source.tree.TryTree; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.UnionClassType; import java.util.HashSet; import java.util.Set; import javax.annotation.Nullable; /** * Flags code which catches {@link RuntimeException}s under the guise of catching {@link Exception}. */ @BugPattern( summary = "This catch block catches `Exception`, but can only catch unchecked exceptions. Consider" + " catching RuntimeException (or something more specific) instead so it is more" + " apparent that no checked exceptions are being handled.", severity = SeverityLevel.WARNING) public final class CatchingUnchecked extends BugChecker implements TryTreeMatcher { @Override public Description matchTry(TryTree tree, VisitorState state) { ScanThrownTypes scanner = new ScanThrownTypes(state); scanner.scanResources(tree); scanner.scan(tree.getBlock(), null); Set<Type> thrownExceptions = new HashSet<>(scanner.getThrownTypes()); for (CatchTree catchTree : tree.getCatches()) { if (isSameType(getType(catchTree.getParameter()), state.getSymtab().exceptionType, state)) { if (thrownExceptions.stream().noneMatch(t -> isCheckedExceptionType(t, state))) { state.reportMatch( describeMatch( catchTree, SuggestedFix.replace(catchTree.getParameter().getType(), "RuntimeException"))); } } ImmutableList<Type> caughtTypes = extractTypes(getType(catchTree.getParameter())); thrownExceptions.removeIf(t -> caughtTypes.stream().anyMatch(ct -> isSubtype(t, ct, state))); } return NO_MATCH; } private static ImmutableList<Type> extractTypes(@Nullable Type type) { if (type == null) { return ImmutableList.of(); } if (type.isUnion()) { return ImmutableList.copyOf(((UnionClassType) type).getAlternativeTypes()); } return ImmutableList.of(type); } }
3,415
39.666667
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/DirectInvocationOnMock.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.Streams.stream; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.fixes.SuggestedFixes.qualifyStaticImport; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyMethod; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.receiverOfInvocation; import static com.google.errorprone.matchers.Matchers.staticMethod; import static com.google.errorprone.suppliers.Suppliers.OBJECT_TYPE; import static com.google.errorprone.suppliers.Suppliers.arrayOf; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.MoreAnnotations.getAnnotationValue; import static java.lang.String.format; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeCastTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import java.util.HashSet; import java.util.Set; /** A bugpattern; see the description. */ @BugPattern( summary = "Methods should not be directly invoked on mocks. Should this be part of a verify(..)" + " call?", severity = WARNING) public final class DirectInvocationOnMock extends BugChecker implements CompilationUnitTreeMatcher { @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { ImmutableSet<VarSymbol> mocks = findMocks(state); Set<MethodSymbol> methodsCallingRealImplementations = new HashSet<>(); new SuppressibleTreePathScanner<Void, Void>(state) { @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { if (THEN_CALL_REAL_METHOD.matches(tree, state)) { var receiver = getReceiver(tree); if (receiver != null && WHEN.matches(receiver, state)) { ExpressionTree firstArgument = ((MethodInvocationTree) receiver).getArguments().get(0); var firstArgumentSymbol = getSymbol(firstArgument); if (firstArgumentSymbol instanceof MethodSymbol) { methodsCallingRealImplementations.add((MethodSymbol) firstArgumentSymbol); } } return super.visitMethodInvocation(tree, null); } if (DO_CALL_REAL_METHOD.matches(tree, state)) { var methodSymbol = getSymbol(getCurrentPath().getParentPath().getParentPath().getLeaf()); if (methodSymbol instanceof MethodSymbol) { methodsCallingRealImplementations.add((MethodSymbol) methodSymbol); } return super.visitMethodInvocation(tree, null); } if (methodsCallingRealImplementations.contains(getSymbol(tree))) { return super.visitMethodInvocation(tree, null); } if ((getSymbol(tree).flags() & Flags.FINAL) != 0) { return null; } Tree parent = stream(getCurrentPath()) .skip(1) .filter(t -> !(t instanceof TypeCastTree)) .findFirst() .get(); var receiver = getReceiver(tree); if (isMock(receiver) && !(parent instanceof ExpressionTree && WHEN.matches((ExpressionTree) parent, state))) { var description = buildDescription(tree) .setMessage( format( "Methods should not be directly invoked on the mock `%s`. Should this be" + " part of a verify(..) call?", getSymbol(receiver).getSimpleName())); if (getCurrentPath().getParentPath().getLeaf() instanceof ExpressionStatementTree) { var fix = SuggestedFix.builder(); String verify = qualifyStaticImport("org.mockito.Mockito.verify", fix, state); description.addFix( fix.replace(receiver, format("%s(%s)", verify, state.getSourceForNode(receiver))) .setShortDescription("turn into verify() call") .build()); description.addFix( SuggestedFix.builder() .delete(tree) .setShortDescription("delete redundant invocation") .build()); } state.reportMatch(description.build()); } return super.visitMethodInvocation(tree, null); } private boolean isMock(ExpressionTree tree) { var symbol = getSymbol(tree); return symbol != null && (mocks.contains(symbol) || symbol.getAnnotationMirrors().stream() .filter(am -> am.type.tsym.getQualifiedName().contentEquals("org.mockito.Mock")) .findFirst() .filter(am -> getAnnotationValue(am, "answer").isEmpty()) .isPresent()); } }.scan(state.getPath(), null); return NO_MATCH; } private ImmutableSet<VarSymbol> findMocks(VisitorState state) { ImmutableSet.Builder<VarSymbol> mocks = ImmutableSet.builder(); new TreeScanner<Void, Void>() { @Override public Void visitVariable(VariableTree tree, Void unused) { if (tree.getInitializer() != null && MOCK.matches(tree.getInitializer(), state)) { mocks.add(getSymbol(tree)); } return super.visitVariable(tree, null); } @Override public Void visitAssignment(AssignmentTree tree, Void unused) { if (MOCK.matches(tree.getExpression(), state)) { var symbol = getSymbol(tree.getVariable()); if (symbol instanceof VarSymbol) { mocks.add((VarSymbol) symbol); } } return super.visitAssignment(tree, null); } }.scan(state.getPath().getCompilationUnit(), null); return mocks.build(); } private static final Matcher<ExpressionTree> MOCK = anyOf( staticMethod() .onClass("org.mockito.Mockito") .named("mock") .withParameters("java.lang.Class"), staticMethod() .onClass("org.mockito.Mockito") .named("mock") .withParametersOfType(ImmutableList.of(arrayOf(OBJECT_TYPE)))); private static final Matcher<MethodInvocationTree> DO_CALL_REAL_METHOD = anyOf( allOf( instanceMethod().onDescendantOf("org.mockito.stubbing.Stubber").named("when"), receiverOfInvocation( staticMethod().onClass("org.mockito.Mockito").named("doCallRealMethod"))), allOf( instanceMethod().onDescendantOf("org.mockito.BDDMockito.BDDStubber").named("given"), receiverOfInvocation( staticMethod().onClass("org.mockito.BDDMockito").named("willCallRealMethod")))); private static final Matcher<ExpressionTree> WHEN = anyMethod().anyClass().namedAnyOf("when", "given"); private static final Matcher<ExpressionTree> THEN_CALL_REAL_METHOD = anyOf( instanceMethod() .onDescendantOf("org.mockito.stubbing.OngoingStubbing") .named("thenCallRealMethod"), instanceMethod() .onDescendantOf("org.mockito.BDDMockito.BDDMyOngoingStubbing") .named("willCallRealMethod")); }
9,019
42.574879
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/VarTypeName.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.TypeParameterTreeMatcher; import com.google.errorprone.matchers.Description; import com.sun.source.tree.ClassTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeParameterTree; import javax.lang.model.element.Name; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "`var` should not be used as a type name.", severity = ERROR) public class VarTypeName extends BugChecker implements ClassTreeMatcher, TypeParameterTreeMatcher { @Override public Description matchClass(ClassTree tree, VisitorState state) { return check(tree, tree.getSimpleName()); } @Override public Description matchTypeParameter(TypeParameterTree tree, VisitorState state) { return check(tree, tree.getName()); } private Description check(Tree tree, Name name) { return name.contentEquals("var") ? describeMatch(tree) : NO_MATCH; } }
1,909
37.2
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/IntLongMath.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.BugPattern.StandardTags.FRAGILE_CODE; 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.AssignmentTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.code.Type; import javax.lang.model.type.TypeKind; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Expression of type int may overflow before being assigned to a long", severity = WARNING, tags = FRAGILE_CODE) public class IntLongMath extends BugChecker implements VariableTreeMatcher, AssignmentTreeMatcher, ReturnTreeMatcher { @Override public Description matchReturn(ReturnTree tree, VisitorState state) { if (tree.getExpression() == null) { return NO_MATCH; } Type type = null; outer: for (Tree parent : state.getPath()) { switch (parent.getKind()) { case METHOD: type = ASTHelpers.getType(((MethodTree) parent).getReturnType()); break outer; case LAMBDA_EXPRESSION: type = state.getTypes().findDescriptorType(ASTHelpers.getType(parent)).getReturnType(); break outer; default: // fall out } } if (type == null) { return NO_MATCH; } return check(type, tree.getExpression()); } @Override public Description matchAssignment(AssignmentTree tree, VisitorState state) { return check(ASTHelpers.getType(tree), tree.getExpression()); } @Override public Description matchVariable(VariableTree tree, VisitorState state) { return check(ASTHelpers.getType(tree), tree.getInitializer()); } Description check(Type targetType, ExpressionTree init) { if (init == null || targetType == null) { return NO_MATCH; } if (ASTHelpers.constValue(init) != null) { return NO_MATCH; } if (targetType.getKind() != TypeKind.LONG) { return NO_MATCH; } // Note that we don't care about boxing as int isn't assignable to Long; // primitive widening conversions can't be combined with autoboxing. if (ASTHelpers.getType(init).getKind() != TypeKind.INT) { return NO_MATCH; } BinaryTree innerMost = null; ExpressionTree nested = init; while (true) { nested = ASTHelpers.stripParentheses(nested); if (!(nested instanceof BinaryTree)) { break; } switch (nested.getKind()) { case DIVIDE: case REMAINDER: case AND: case XOR: case OR: case RIGHT_SHIFT: // Skip binops that can't overflow; it doesn't matter whether they're performed on // longs or ints. break; default: innerMost = (BinaryTree) nested; } nested = ((BinaryTree) nested).getLeftOperand(); } if (innerMost == null) { return NO_MATCH; } if (innerMost.getLeftOperand().getKind() == Kind.INT_LITERAL) { return describeMatch(init, SuggestedFix.postfixWith(innerMost.getLeftOperand(), "L")); } if (innerMost.getRightOperand().getKind() == Kind.INT_LITERAL) { return describeMatch(init, SuggestedFix.postfixWith(innerMost.getRightOperand(), "L")); } return describeMatch(init, SuggestedFix.prefixWith(innerMost.getLeftOperand(), "(long) ")); } }
4,731
34.578947
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/Finalize.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isVoidType; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.matchers.Description; import com.sun.source.tree.MethodTree; import java.util.Set; import javax.lang.model.element.Modifier; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "Do not override finalize", severity = WARNING, documentSuppression = false) public class Finalize extends BugChecker implements MethodTreeMatcher { @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (!tree.getName().contentEquals("finalize")) { return NO_MATCH; } if (!tree.getParameters().isEmpty()) { return NO_MATCH; } if (!isVoidType(getType(tree.getReturnType()), state)) { return NO_MATCH; } Set<Modifier> modifiers = getSymbol(tree).getModifiers(); if (!modifiers.contains(Modifier.PROTECTED) && !modifiers.contains(Modifier.PUBLIC)) { return NO_MATCH; } return describeMatch(tree); } }
2,100
37.2
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ProtoBuilderReturnValueIgnored.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.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.streamReceivers; import static com.google.errorprone.util.SideEffectAnalysis.hasSideEffect; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.predicates.type.DescendantOf; import com.google.errorprone.suppliers.Suppliers; 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 javax.inject.Inject; /** Highlights cases where a proto's build method has its return value ignored. */ @BugPattern( summary = "Unnecessary call to proto's #build() method. If you don't consume the return value of " + "#build(), the result is discarded and the only effect is to verify that all " + "required fields are set, which can be expressed more directly with " + "#isInitialized().", severity = ERROR) public final class ProtoBuilderReturnValueIgnored extends AbstractReturnValueIgnored { private static final Matcher<ExpressionTree> BUILDER = instanceMethod() .onDescendantOf("com.google.protobuf.MessageLite.Builder") .namedAnyOf("build", "buildPartial"); public static final Matcher<ExpressionTree> MATCHER = allOf( BUILDER, // Don't match expressions beginning with a newBuilder call; these should be covered by // ModifiedButNotUsed. ProtoBuilderReturnValueIgnored::doesNotTerminateInNewBuilder); private static final Matcher<ExpressionTree> ROOT_INVOCATIONS_TO_IGNORE = anyOf( staticMethod() .onClass( new DescendantOf(Suppliers.typeFromString("com.google.protobuf.MessageLite"))) .namedAnyOf("newBuilder"), instanceMethod() .onDescendantOf("com.google.protobuf.MessageLite") .namedAnyOf("toBuilder")); @Inject ProtoBuilderReturnValueIgnored(ConstantExpressions constantExpressions) { super(constantExpressions); } @Override public Matcher<? super ExpressionTree> specializedMatcher() { return MATCHER; } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { Description description = super.matchMethodInvocation(tree, state); if (description.equals(Description.NO_MATCH)) { return Description.NO_MATCH; } return buildDescription(tree).addAllFixes(generateFixes(tree, state)).build(); } private static ImmutableList<SuggestedFix> generateFixes( MethodInvocationTree tree, VisitorState state) { SuggestedFix.Builder simpleFixBuilder = SuggestedFix.builder() .setShortDescription( "Remove the call to #build. Note that this will not validate the presence " + "of required fields."); ExpressionTree receiver = getReceiver(tree); if (receiver instanceof IdentifierTree || receiver instanceof MemberSelectTree) { simpleFixBuilder.replace(state.getPath().getParentPath().getLeaf(), ""); if (hasSideEffect(receiver)) { simpleFixBuilder.setShortDescription( "Remove the call to #build. Note that this will not validate the presence " + "of required fields, and removes any side effects of the receiver expression."); } } else { simpleFixBuilder.replace(state.getEndPosition(receiver), state.getEndPosition(tree), ""); } SuggestedFix simpleFix = simpleFixBuilder.build(); SuggestedFix withRequiredFieldCheck = SuggestedFix.builder() .setShortDescription( "Replace the call to #build with an explicit check that required " + "fields are present.") .addStaticImport("com.google.common.base.Preconditions.checkState") .prefixWith(tree, "checkState(") .replace( state.getEndPosition(receiver), state.getEndPosition(tree), ".isInitialized())") .build(); return ImmutableList.of(simpleFix, withRequiredFieldCheck); } private static boolean doesNotTerminateInNewBuilder(ExpressionTree tree, VisitorState state) { return streamReceivers(tree).noneMatch(t -> ROOT_INVOCATIONS_TO_IGNORE.matches(t, state)); } }
5,693
42.8
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerStringConcatenation.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.flogger; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.flogger.FloggerHelpers.inferFormatSpecifier; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.constValue; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSameType; import static java.util.stream.Collectors.joining; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.method.MethodMatchers; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.util.SimpleTreeVisitor; import java.util.ArrayList; import java.util.List; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Prefer string formatting using printf placeholders (e.g. %s) instead of string" + " concatenation", severity = WARNING) public class FloggerStringConcatenation extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> MATCHER = MethodMatchers.instanceMethod() .onDescendantOf("com.google.common.flogger.LoggingApi") .named("log") .withParameters("java.lang.String"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return NO_MATCH; } ExpressionTree argument = getOnlyElement(tree.getArguments()); if (!(argument instanceof BinaryTree)) { return NO_MATCH; } if (constValue(argument, String.class) != null) { return NO_MATCH; } List<Tree> pieces = new ArrayList<>(); argument.accept( new SimpleTreeVisitor<Void, Void>() { @Override public Void visitBinary(BinaryTree tree, Void unused) { if (tree.getKind().equals(Kind.PLUS) && isSameType(getType(tree), state.getSymtab().stringType, state)) { // + yielding a String is concatenation, and should use placeholders for each part. tree.getLeftOperand().accept(this, null); return tree.getRightOperand().accept(this, null); } else { // Otherwise it's not concatenation, and should be its own placeholder return defaultAction(tree, null); } } @Override public Void visitParenthesized(ParenthesizedTree node, Void unused) { return node.getExpression().accept(this, null); } @Override protected Void defaultAction(Tree tree, Void unused) { pieces.add(tree); return null; } }, null); StringBuilder formatString = new StringBuilder(); List<Tree> formatArguments = new ArrayList<>(); for (Tree piece : pieces) { if (piece.getKind().equals(Kind.STRING_LITERAL)) { formatString.append((String) ((LiteralTree) piece).getValue()); } else { formatString.append('%').append(inferFormatSpecifier(piece, state)); formatArguments.add(piece); } } return describeMatch( tree, SuggestedFix.replace( argument, state.getConstantExpression(formatString.toString()) + ", " + formatArguments.stream().map(state::getSourceForNode).collect(joining(", ")))); } }
4,778
38.825
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerWithCause.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.flogger; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import static com.google.errorprone.matchers.method.MethodMatchers.constructor; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.LinkType; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.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.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.tree.JCTree.JCNewClass; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; /** Flogger's withCause(Throwable) method checks */ @BugPattern( summary = "Calling withCause(Throwable) with an inline allocated Throwable is discouraged." + " Consider using withStackTrace(StackSize) instead, and specifying a reduced" + " stack size (e.g. SMALL, MEDIUM or LARGE) instead of FULL, to improve" + " performance.", linkType = LinkType.CUSTOM, link = "https://google.github.io/flogger/best_practice#stack-trace", severity = WARNING) public class FloggerWithCause extends BugChecker implements MethodInvocationTreeMatcher { private static final String STACK_SIZE_MEDIUM_IMPORT = "com.google.common.flogger.StackSize.MEDIUM"; private static final Matcher<ExpressionTree> WITH_CAUSE_MATCHER = instanceMethod().onDescendantOf("com.google.common.flogger.LoggingApi").named("withCause"); private static final Matcher<ExpressionTree> FIXABLE_THROWABLE_MATCHER = constructor() .forClass( TypePredicates.isExactTypeAny( ImmutableList.of( "java.lang.AssertionError", "java.lang.Error", "java.lang.Exception", "java.lang.IllegalArgumentException", "java.lang.IllegalStateException", "java.lang.RuntimeException", "java.lang.Throwable", "com.google.photos.be.util.StackTraceLoggerException"))) .withParameters(ImmutableList.of()); private static final Matcher<Tree> THROWABLE_MATCHER = isSubtypeOf("java.lang.Throwable"); private static final Matcher<ExpressionTree> THROWABLE_STRING_MATCHER = Matchers.anyOf( instanceMethod().onDescendantOf("java.lang.Throwable").named("getMessage"), instanceMethod().onDescendantOf("java.lang.Throwable").named("toString")); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!WITH_CAUSE_MATCHER.matches(tree, state)) { return Description.NO_MATCH; } ExpressionTree cause = Iterables.getOnlyElement(tree.getArguments()); if (cause.getKind() == Kind.NEW_CLASS) { Optional<ExpressionTree> throwableArgument = getThrowableArgument(cause, state); if (throwableArgument.isPresent() || FIXABLE_THROWABLE_MATCHER.matches(cause, state)) { List<Fix> fixes = getFixes(tree, state, throwableArgument.orElse(null)); return getDescription(tree, fixes); } } return Description.NO_MATCH; } private Description getDescription(MethodInvocationTree tree, List<Fix> fixes) { Description.Builder description = buildDescription(tree); for (Fix fix : fixes) { description.addFix(fix); } return description.build(); } private static List<Fix> getFixes( MethodInvocationTree tree, VisitorState state, ExpressionTree throwableArgument) { if (throwableArgument != null) { String withCauseReplacement = ".withCause(" + state.getSourceForNode(throwableArgument) + ")"; String withStackTraceAndWithCauseReplacement = ".withStackTrace(MEDIUM)" + withCauseReplacement; return Arrays.asList( getFix(tree, state, withCauseReplacement), getFix(tree, state, withStackTraceAndWithCauseReplacement, STACK_SIZE_MEDIUM_IMPORT)); } return Collections.singletonList( getFix(tree, state, ".withStackTrace(MEDIUM)", STACK_SIZE_MEDIUM_IMPORT)); } private static Optional<ExpressionTree> getThrowableArgument( ExpressionTree cause, VisitorState state) { for (ExpressionTree argument : ((JCNewClass) cause).getArguments()) { if (THROWABLE_MATCHER.matches(argument, state)) { return Optional.of(argument); } if (THROWABLE_STRING_MATCHER.matches(argument, state)) { return Optional.ofNullable(ASTHelpers.getReceiver(argument)); } } return Optional.empty(); } /** * Returns fix that has current method replaced with provided method replacement string and * provided static import added to it */ private static Fix getFix( MethodInvocationTree tree, VisitorState state, String replacement, String importString) { return getFixBuilder(tree, state, replacement).addStaticImport(importString).build(); } /** Returns fix that has current method replaced with provided method replacement string */ private static Fix getFix(MethodInvocationTree tree, VisitorState state, String replacement) { return getFixBuilder(tree, state, replacement).build(); } private static SuggestedFix.Builder getFixBuilder( MethodInvocationTree tree, VisitorState state, String methodReplacement) { int methodStart = getMethodStart(tree, state); int methodEnd = getMethodEnd(tree, state); return SuggestedFix.builder().replace(methodStart, methodEnd, methodReplacement); } private static int getMethodStart(MethodInvocationTree tree, VisitorState state) { return state.getEndPosition(ASTHelpers.getReceiver(tree)); } private static int getMethodEnd(MethodInvocationTree tree, VisitorState state) { return state.getEndPosition(tree); } }
7,186
40.784884
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerMessageFormat.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.flogger; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.instanceMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import java.util.List; import java.util.regex.Pattern; /** * @author cushon@google.com (Liam Miller-Cushon) */ @BugPattern( summary = "Invalid message format-style format specifier ({0}), expected printf-style (%s)", explanation = "Flogger uses printf-style format specifiers, such as %s and %d. Message format-style" + " specifiers like {0} don't work.", severity = WARNING) public class FloggerMessageFormat extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> LOG_MATCHER = instanceMethod().onDescendantOf("com.google.common.flogger.LoggingApi").named("log"); private static final Pattern MESSAGE_FORMAT_SPECIFIER = Pattern.compile("\\{[0-9]\\}"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!LOG_MATCHER.matches(tree, state)) { return NO_MATCH; } List<? extends ExpressionTree> arguments = tree.getArguments(); // There's a 0-arg 'log' method for terminating complex chains, with no format string if (arguments.isEmpty()) { return NO_MATCH; } ExpressionTree formatArg = arguments.get(0); String formatString = ASTHelpers.constValue(formatArg, String.class); if (formatString == null) { return NO_MATCH; } if (!MESSAGE_FORMAT_SPECIFIER.matcher(formatString).find()) { return NO_MATCH; } Description.Builder description = buildDescription(tree); String source = state.getSourceForNode(formatArg); String fixed = MESSAGE_FORMAT_SPECIFIER.matcher(source).replaceAll("%s"); if (!source.equals(fixed)) { description.addFix(SuggestedFix.replace(formatArg, fixed)); } return description.build(); } }
3,137
38.225
96
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerFormatString.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.flogger; import static com.google.common.collect.Iterables.getLast; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.formatstring.FormatStringValidation; import com.google.errorprone.bugpatterns.formatstring.FormatStringValidation.ValidationResult; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol.MethodSymbol; import java.util.List; import javax.annotation.Nullable; /** * @author cushon@google.com (Liam Miller-Cushon) */ @BugPattern( altNames = "FormatString", summary = "Invalid printf-style format string", severity = ERROR) public class FloggerFormatString extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> FORMAT_METHOD = instanceMethod().onDescendantOf("com.google.common.flogger.LoggingApi").named("log"); private static final Matcher<ExpressionTree> WITH_CAUSE = instanceMethod().onDescendantOf("com.google.common.flogger.LoggingApi").named("withCause"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!FORMAT_METHOD.matches(tree, state)) { return NO_MATCH; } List<? extends ExpressionTree> args = tree.getArguments(); if (args.size() <= 1) { // log(String)'s argument isn't a format string, see FloggerLogString // we also warn on mistakes like `log("hello %s")` in OrphanedFormatString return NO_MATCH; } MethodSymbol sym = ASTHelpers.getSymbol(tree); FormatStringValidation.ValidationResult result = FormatStringValidation.validate(sym, tree.getArguments(), state); if (result == null) { return NO_MATCH; } Description.Builder description = buildDescription(tree).setMessage(result.message()); Fix fix = withCauseFix(result, tree, state); if (fix != null) { description.addFix(fix); } return description.build(); } /** * If there were more arguments than format specifiers and the last argument is an exception, * suggest using {@code withCause(e)} instead of adding a format specifier. */ @Nullable private Fix withCauseFix(ValidationResult result, MethodInvocationTree tree, VisitorState state) { if (!result.message().startsWith("extra format arguments")) { return null; } ExpressionTree last = getLast(tree.getArguments()); if (!ASTHelpers.isSubtype(ASTHelpers.getType(last), state.getSymtab().throwableType, state)) { return null; } // if there's already a call to withCause, don't suggest adding another one boolean[] withCause = {false}; tree.accept( new TreeScanner<Void, Void>() { @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { if (WITH_CAUSE.matches(tree, state)) { withCause[0] = true; } return super.visitMethodInvocation(tree, null); } }, null); if (withCause[0]) { return null; } return SuggestedFix.builder() .replace( state.getEndPosition(tree.getArguments().get(tree.getArguments().size() - 2)), state.getEndPosition(last), "") .postfixWith( ASTHelpers.getReceiver(tree), String.format(".withCause(%s)", state.getSourceForNode(last))) .build(); } }
4,777
37.532258
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerHelpers.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.flogger; import static com.google.errorprone.util.ASTHelpers.getType; import com.google.errorprone.VisitorState; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Type; /** Analysis helpers for flogger. */ final class FloggerHelpers { private static final char STRING_FORMAT = 's'; static char inferFormatSpecifier(Tree piece, VisitorState state) { Type type = getType(piece); return inferFormatSpecifier(type, state); } static char inferFormatSpecifier(Type type, VisitorState state) { if (type == null) { return STRING_FORMAT; } switch (state.getTypes().unboxedTypeOrType(type).getKind()) { case INT: case LONG: return 'd'; case FLOAT: case DOUBLE: return 'g'; case BOOLEAN: // %b is identical to %s in Flogger, but not in String.format, so it might be risky // to train people to prefer it. (In format() a Boolean "null" becomes "false",) return STRING_FORMAT; default: return STRING_FORMAT; } } private FloggerHelpers() {} }
1,728
29.333333
91
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerWithoutCause.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.flogger; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import com.google.common.collect.Lists; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; 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.util.TreeScanner; import com.sun.tools.javac.code.Type; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nullable; import javax.lang.model.type.TypeKind; /** * Detects Flogger log statements that pass Exceptions to the log method instead of using withCause. */ @BugPattern( summary = "Use withCause to associate Exceptions with log statements", severity = BugPattern.SeverityLevel.WARNING) public class FloggerWithoutCause extends BugChecker implements BugChecker.MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> LOG_METHOD = instanceMethod().onDescendantOf("com.google.common.flogger.LoggingApi").named("log"); private static final Matcher<ExpressionTree> WITH_CAUSE = instanceMethod().onDescendantOf("com.google.common.flogger.LoggingApi").named("withCause"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!LOG_METHOD.matches(tree, state)) { return Description.NO_MATCH; } Tree exception = getExceptionArg(tree, state); if (exception == null) { return Description.NO_MATCH; } AtomicBoolean withCause = new AtomicBoolean(false); tree.accept( new TreeScanner<Void, Void>() { @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { if (WITH_CAUSE.matches(tree, state)) { withCause.set(true); } return super.visitMethodInvocation(tree, null); } }, null); if (withCause.get()) { return Description.NO_MATCH; } return describeMatch( tree, SuggestedFix.postfixWith( ASTHelpers.getReceiver(tree), String.format(".withCause(%s)", state.getSourceForNode(exception)))); } @Nullable private static Tree getExceptionArg(MethodInvocationTree tree, VisitorState state) { for (Tree arg : Lists.reverse(tree.getArguments())) { try { Type argType = ASTHelpers.getType(arg); if (argType != null && argType.getKind() != TypeKind.NULL && ASTHelpers.isSubtype(argType, state.getSymtab().throwableType, state)) { return arg; } } catch (RuntimeException t) { // ignore completion failures } } return null; } }
3,637
33.980769
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerRedundantIsEnabled.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.flogger; 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.instanceMethod; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.sun.source.tree.Tree.Kind.BLOCK; import static com.sun.source.tree.Tree.Kind.EXPRESSION_STATEMENT; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; 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.sun.source.tree.BinaryTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IfTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree; import com.sun.source.tree.UnaryTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import java.util.List; import java.util.Optional; import org.checkerframework.checker.nullness.qual.Nullable; /** * @author mariasam@google.com (Maria Sam) */ @BugPattern( summary = "Logger level check is already implied in the log() call. " + "An explicit at[Level]().isEnabled() check is redundant.", severity = WARNING) public class FloggerRedundantIsEnabled extends BugChecker implements IfTreeMatcher { private static final String FLOGGER = "com.google.common.flogger.FluentLogger"; private static final String FLOGGER_API = "com.google.common.flogger.FluentLogger.Api"; private static final Matcher<ExpressionTree> AT_LEVEL = instanceMethod() .onDescendantOf(FLOGGER) .namedAnyOf( "atInfo", "atConfig", "atFine", "atFiner", "atFinest", "atWarning", "atSevere") .withNoParameters(); private static final Matcher<ExpressionTree> IS_ENABLED = instanceMethod().onDescendantOf(FLOGGER_API).named("isEnabled").withNoParameters(); private static final Matcher<ExpressionTree> LOG = instanceMethod().onDescendantOf(FLOGGER_API).named("log"); @Override public Description matchIf(IfTree ifTree, VisitorState state) { // No else-statement. if (ifTree.getElseStatement() != null) { return NO_MATCH; } // If then-block contains exactly one expression and it is a `log` invocation, extract it. Optional<MethodInvocationTree> methodCall = extractLoneLogInvocation(ifTree, state); if (!methodCall.isPresent()) { return NO_MATCH; } MethodInvocationTree logInvocation = methodCall.get(); ExpressionTree ifCondition = ifTree.getCondition(); // The if-condition is just a call to `.isEnabled()` (possibly negated). ExpressionTree unwrappedIfCondition = unwrap(ifCondition); if (IS_ENABLED.matches(unwrappedIfCondition, state) && sameLoggerAtSameLevel(unwrappedIfCondition, logInvocation, state)) { // Replace entire if-tree with just the `.log()` call. return describeMatch( ifTree, SuggestedFix.replace(ifTree, state.getSourceForNode(logInvocation) + ";")); } // Remove `.isEnabled()` call from complex if-condition. return fixBinaryIfCondition(ifCondition, logInvocation, state) .map(fix -> describeMatch(ifTree, fix)) .orElse(NO_MATCH); } /** * Examines the then-block of the given if-tree. If the then-block contains exactly one statement, * and that one statement is a Flogger `log` method invocation, then returns that statement as a * {@link MethodInvocationTree}. Else returns an empty Optional. * * <p>Adapted from {@link com.google.errorprone.bugpatterns.ImplementAssertionWithChaining}. */ private static Optional<MethodInvocationTree> extractLoneLogInvocation( IfTree ifTree, VisitorState state) { // Get lone statement from then-block. StatementTree thenStatement = ifTree.getThenStatement(); while (thenStatement.getKind() == BLOCK) { List<? extends StatementTree> statements = ((BlockTree) thenStatement).getStatements(); if (statements.size() != 1) { return Optional.empty(); } thenStatement = getOnlyElement(statements); } // Check if that lone statement is a Flogger `log` method invocation, and cast. if (thenStatement.getKind() == EXPRESSION_STATEMENT) { ExpressionTree thenExpression = ((ExpressionStatementTree) thenStatement).getExpression(); if (LOG.matches(thenExpression, state)) { return Optional.of((MethodInvocationTree) thenExpression); } } return Optional.empty(); } /** Strip any parentheses or `!` from the given expression. */ private static ExpressionTree unwrap(ExpressionTree expr) { return expr.accept( new SimpleTreeVisitor<ExpressionTree, Void>() { @Override protected @Nullable ExpressionTree defaultAction(Tree tree, Void unused) { return tree instanceof ExpressionTree ? (ExpressionTree) tree : null; } @Override public ExpressionTree visitParenthesized( ParenthesizedTree parenthesizedTree, Void unused) { return parenthesizedTree.getExpression().accept(this, null); } @Override public ExpressionTree visitUnary(UnaryTree unaryTree, Void unused) { return unaryTree.getExpression().accept(this, null); } }, null); } /** * Determines whether the two given logger invocations are operations on the same logger, at the * same level. */ private static boolean sameLoggerAtSameLevel( ExpressionTree expr1, ExpressionTree expr2, VisitorState state) { ExpressionTree atLevel1 = getReceiver(expr1); ExpressionTree atLevel2 = getReceiver(expr2); if (!AT_LEVEL.matches(atLevel1, state) || !AT_LEVEL.matches(atLevel2, state)) { return false; } Symbol atLevelSym1 = getSymbol(atLevel1); Symbol atLevelSym2 = getSymbol(atLevel2); if (atLevelSym1 == null || !atLevelSym1.equals(atLevelSym2)) { return false; } Symbol logger1 = getSymbol(getReceiver(atLevel1)); Symbol logger2 = getSymbol(getReceiver(atLevel2)); return logger1 != null && logger1.equals(logger2); } private static Optional<SuggestedFix> fixBinaryIfCondition( ExpressionTree ifCondition, MethodInvocationTree logInvocation, VisitorState state) { LoggerIsEnabledBinaryIfConditionScanner scanner = new LoggerIsEnabledBinaryIfConditionScanner(logInvocation, state); scanner.scan(ifCondition, null); return scanner.fix; } private static class LoggerIsEnabledBinaryIfConditionScanner extends TreeScanner<Void, Void> { private final ExpressionTree logInvocation; private final VisitorState state; public Optional<SuggestedFix> fix; public LoggerIsEnabledBinaryIfConditionScanner( ExpressionTree logInvocation, VisitorState state) { this.logInvocation = logInvocation; this.state = state; this.fix = Optional.empty(); } @Override public Void visitBinary(BinaryTree binaryTree, Void unused) { ExpressionTree left = unwrap(binaryTree.getLeftOperand()); ExpressionTree right = unwrap(binaryTree.getRightOperand()); if (IS_ENABLED.matches(left, state) && sameLoggerAtSameLevel(logInvocation, left, state)) { // `isEnabled` on left. Replace binary condition with just the right side. this.fix = Optional.of( SuggestedFix.replace( binaryTree, state.getSourceForNode(binaryTree.getRightOperand()))); return null; } if (IS_ENABLED.matches(right, state) && sameLoggerAtSameLevel(logInvocation, right, state)) { // `isEnabled` on right. Replace binary condition with just the left side. this.fix = Optional.of( SuggestedFix.replace( binaryTree, state.getSourceForNode(binaryTree.getLeftOperand()))); return null; } return super.visitBinary(binaryTree, null); } } }
9,195
39.871111
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerLogWithCause.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.flogger; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.fixes.SuggestedFix.postfixWith; 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.getSymbol; import static java.lang.Boolean.TRUE; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.CatchTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.CatchTree; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.StatementTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import java.util.List; /** * Flags cases where there is an exception available that could be set as the cause in a log * message. */ @BugPattern( summary = "Setting the caught exception as the cause of the log message may provide more context for" + " anyone debugging errors.", severity = WARNING) public final class FloggerLogWithCause extends BugChecker implements CatchTreeMatcher { private static final Matcher<ExpressionTree> LOG_MATCHER = instanceMethod().onDescendantOf("com.google.common.flogger.LoggingApi").named("log"); private static final Matcher<ExpressionTree> WITH_CAUSE = instanceMethod().onDescendantOf("com.google.common.flogger.LoggingApi").named("withCause"); private static final Matcher<ExpressionTree> HIGH_LEVEL = instanceMethod() .onDescendantOf("com.google.common.flogger.AbstractLogger") .namedAnyOf("atWarning", "atSevere"); @Override public Description matchCatch(CatchTree tree, VisitorState state) { if (isSuppressed(tree.getParameter(), state)) { return Description.NO_MATCH; } List<? extends StatementTree> statements = tree.getBlock().getStatements(); if (statements.size() != 1) { return NO_MATCH; } StatementTree statementTree = statements.get(0); if (!(statementTree instanceof ExpressionStatementTree)) { return NO_MATCH; } ExpressionTree expressionTree = ((ExpressionStatementTree) statementTree).getExpression(); if (!LOG_MATCHER.matches(expressionTree, state)) { return NO_MATCH; } boolean isHighLevelLog = false; for (ExpressionTree receiver = expressionTree; receiver instanceof MethodInvocationTree; receiver = getReceiver(receiver)) { if (WITH_CAUSE.matches(receiver, state)) { return NO_MATCH; } if (HIGH_LEVEL.matches(receiver, state)) { isHighLevelLog = true; } } if (!isHighLevelLog) { return NO_MATCH; } Symbol parameter = getSymbol(tree.getParameter()); boolean exceptionUsed = new TreeScanner<Boolean, Void>() { @Override public Boolean visitIdentifier(IdentifierTree node, Void unused) { return parameter.equals(getSymbol(node)); } @Override public Boolean reduce(Boolean a, Boolean b) { return TRUE.equals(a) || TRUE.equals(b); } }.scan(tree.getBlock(), null); if (exceptionUsed) { return NO_MATCH; } String withCause = String.format(".withCause(%s)", tree.getParameter().getName()); return describeMatch(expressionTree, postfixWith(getReceiver(expressionTree), withCause)); } }
4,457
37.431034
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerRequiredModifiers.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.flogger; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.fixes.SuggestedFixes.addModifiers; import static com.google.errorprone.fixes.SuggestedFixes.removeModifiers; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.isStatic; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PROTECTED; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.google.common.base.Joiner; import com.google.common.base.Verify; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.LinkType; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.IdentifierTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.fixes.SuggestedFixes.AdditionPosition; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.suppliers.Suppliers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ModifiersTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.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 java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.inject.Inject; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; /** Ensures that class-level FluentLogger objects are private static final. */ @BugPattern( summary = "FluentLogger.forEnclosingClass should always be saved to a private static final field.", link = "https://google.github.io/flogger/best_practice#modifiers", linkType = LinkType.CUSTOM, severity = WARNING) public final class FloggerRequiredModifiers extends BugChecker implements MethodInvocationTreeMatcher, IdentifierTreeMatcher, MemberSelectTreeMatcher, VariableTreeMatcher { private static final String GOOGLE_LOGGER = "com.google.common.flogger.FluentLogger"; private static final Supplier<Type> LOGGER_TYPE = Suppliers.typeFromString(GOOGLE_LOGGER); private static final Matcher<ExpressionTree> INIT_LOGGER = staticMethod().onClass(LOGGER_TYPE).named("forEnclosingClass").withNoParameters(); private static final ImmutableList<Modifier> EXPECTED_MODIFIERS = ImmutableList.of(Modifier.PRIVATE, STATIC, FINAL); /** A list of names we could give to new fields of type Logger, in descending preference order. */ private static final ImmutableList<String> REASONABLE_LOGGER_NAMES = ImmutableList.of("logger", "flogger", "googleLogger", "myLogger"); private static final String NESTED_LOGGER_CLASSNAME = "Private"; private static final String NESTED_LOGGER_FIELDNAME = "logger"; private static final String NESTED_LOGGER_DEFINITION = Joiner.on('\n') .join( "/** Do not use. Exists only to hide implementation details of this interface. */", String.format("public static final class %s {", NESTED_LOGGER_CLASSNAME), String.format(" private %s() {}", NESTED_LOGGER_CLASSNAME), String.format( " private static final FluentLogger %s = FluentLogger.forEnclosingClass();", NESTED_LOGGER_FIELDNAME), "}"); private final Map<String, LocalLogger> localLogger = new HashMap<>(); private static final Matcher<Tree> CONTAINS_INIT_LOGGER = Matchers.contains(ExpressionTree.class, INIT_LOGGER); @Inject FloggerRequiredModifiers() {} @Override public Description matchVariable(VariableTree tree, VisitorState state) { Type loggerType = LOGGER_TYPE.get(state); if (!ASTHelpers.isSameType(loggerType, ASTHelpers.getType(tree), state)) { return NO_MATCH; } VarSymbol sym = ASTHelpers.getSymbol(tree); if (!(sym.owner instanceof ClassSymbol)) { return NO_MATCH; } ExpressionTree initializer = tree.getInitializer(); // Static fields with no initializer, or fields initialized to a constant FluentLogger if (initializer == null ? sym.isStatic() : isConstantLogger(initializer, (ClassSymbol) sym.owner, state) && !sym.owner.isInterface()) { return fixModifier(tree, (ClassTree) state.getPath().getParentPath().getLeaf(), state); } return NO_MATCH; } private static boolean isConstantLogger( ExpressionTree initializer, ClassSymbol owner, VisitorState state) { if (initializer instanceof MethodInvocationTree) { Type loggerType = LOGGER_TYPE.get(state); MethodInvocationTree method = (MethodInvocationTree) initializer; MethodSymbol methodSym = ASTHelpers.getSymbol(method); if (methodSym.isStatic() && methodSym.owner.equals(owner) && ASTHelpers.isSameType(loggerType, methodSym.getReturnType(), state)) { return true; } // Fall through to search for FluentLogger.forEnclosingClass() } return CONTAINS_INIT_LOGGER.matches(initializer, state); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!INIT_LOGGER.matches(tree, state)) { return NO_MATCH; } Type loggerType = LOGGER_TYPE.get(state); if (loggerType == null) { return NO_MATCH; } // An expression should always be inside a method or a variable (initializer blocks count as // a method), but just in case we use class as a final backstop. TreePath owner = state.findPathToEnclosing(ClassTree.class, MethodTree.class, VariableTree.class); Tree parent = owner.getLeaf(); Tree grandparent = owner.getParentPath().getLeaf(); boolean isLoggerField = parent instanceof VariableTree && grandparent instanceof ClassTree && ASTHelpers.isSameType(loggerType, ASTHelpers.getType(parent), state); if (isLoggerField) { // Declared as a class member - matchVariable will already have fixed the modifiers, and we // allow calls to forEnclosingClass() in initializer context, so we can just quit here return NO_MATCH; } // See if they're defining a static method that produces a FluentLogger. If so, we assume they // are using it to initialize their FluentLogger instance, and we don't stop them from calling // FluentLogger.forEnclosingClass() inside the method. MethodTree owningMethod = state.findEnclosing(MethodTree.class); if (owningMethod != null) { MethodSymbol methodSym = ASTHelpers.getSymbol(owningMethod); Type returnType = methodSym.getReturnType(); // Could be null for initializer blocks if (ASTHelpers.isSameType(loggerType, returnType, state)) { return NO_MATCH; } } // They're using forEnclosingClass inside a method that doesn't produce a logger, or in the // initializer for some variable that's not a logger. We'll replace this with a reference to a // class-level logger. state.incrementCounter(this, parent instanceof VariableTree ? "local-variable" : "inline"); return replaceWithFieldLookup(tree, state); } private Description fixModifier(VariableTree field, ClassTree owningClass, VisitorState state) { ModifiersTree modifiers = field.getModifiers(); Set<Modifier> flags = modifiers.getFlags(); if (flags.containsAll(EXPECTED_MODIFIERS)) { return NO_MATCH; } updateModifierCounters(state, flags); // We have to add all the modifiers as a single SuggestedFix or they conflict ImmutableSet.Builder<Modifier> toAdd = ImmutableSet.builder(); SuggestedFix.Builder fix = SuggestedFix.builder(); removeModifiers(field, state, PUBLIC, PROTECTED).ifPresent(fix::merge); toAdd.add(PRIVATE); toAdd.add(Modifier.FINAL); if (flags.contains(FINAL) && canHaveStaticFields(ASTHelpers.getSymbol(owningClass))) { // We only add static to fields which are already final, or that we're also making final. // It's a bit dangerous to quietly make something static if it might be getting reassigned. toAdd.add(STATIC); } ImmutableSet<Modifier> newModifiers = toAdd.build(); if (!newModifiers.isEmpty()) { addModifiers(field, modifiers, state, newModifiers).ifPresent(fix::merge); } if (fix.isEmpty()) { // They're missing some modifiers, but not the ones we've been instructed to change today. // This is instead of blindly using fix.build(), which would insert a comment if empty. return NO_MATCH; } return describeMatch(field, fix.build()); } private Description replaceWithFieldLookup(ExpressionTree expr, VisitorState state) { SuggestedFix.Builder fix = SuggestedFix.builder(); LocalLogger logger = findOrDefineLogger(state, fix); /* Sometimes people assign to the logger in, e.g., a static initializer. We don't want to rewrite this to { logger = logger; }, so we search up the tree to see if we are part of any assignment to the logger that we're planning to replace this with a reference to. */ if (logger.provenance == LocalLogger.Provenance.ALREADY_PRESENT && logger.sym.isPresent()) { // There should always be a symbol for ALREADY_PRESENT, but we check just in case. Symbol target = logger.sym.get(); Tree e = expr; TreePath path = state.getPath(); do { if (e instanceof AssignmentTree) { AssignmentTree assignment = (AssignmentTree) e; if (ASTHelpers.getSymbol(assignment.getVariable()).equals(target)) { state.incrementCounter(this, "skip-self-assignment"); return NO_MATCH; } } path = path.getParentPath(); e = path.getLeaf(); } while (e instanceof ExpressionTree); } String loggerName = logger.name; Tree parent = state.getPath().getParentPath().getLeaf(); if (parent instanceof VariableTree && ((VariableTree) parent).getName().contentEquals(loggerName)) { // Instead of making a local shadow of a class member, just use the class member. return describeMatch(expr, fix.delete(parent).build()); } if (loggerName.equals(state.getSourceForNode(expr))) { // Don't rewrite `logger` to `logger`, which runs the formatter over an "unchanged" // line. if (fix.isEmpty()) { // The logger field we want to refer to already exists, and we don't need to // change this // line, so there's actually no work to do. return NO_MATCH; } // Produce a fix that inserts the new logger field without changing this line. return describeMatch(expr, fix.build()); } return describeMatch(expr, fix.replace(expr, loggerName).build()); } private void updateModifierCounters(VisitorState state, Set<Modifier> flags) { // We expect to see all of these, so note when we don't for (Modifier modifier : ImmutableList.of(STATIC, FINAL)) { if (!flags.contains(modifier)) { state.incrementCounter(this, "missing-" + modifier); } } // These we expect to see at most one of, so log whichever is there (or package otherwise) boolean explicitVisibility = false; for (Modifier visibility : ImmutableList.of(PUBLIC, Modifier.PRIVATE, PROTECTED)) { if (flags.contains(visibility)) { state.incrementCounter(this, "visibility-" + visibility); explicitVisibility = true; break; } } if (!explicitVisibility) { state.incrementCounter(this, "visibility-package"); } } private static final class LocalLogger { LocalLogger(Provenance provenance, Optional<Symbol> sym, String name) { this.provenance = provenance; this.sym = sym; this.name = name; } enum Provenance { ALREADY_PRESENT, DEFINED_BY_FIX } final Provenance provenance; final Optional<Symbol> sym; final String name; } private LocalLogger findOrDefineLogger(VisitorState state, SuggestedFix.Builder fix) { return localLogger.computeIfAbsent( ASTHelpers.getFileName(state.getPath().getCompilationUnit()), s -> computeLocalLogger(state, fix)); } private LocalLogger computeLocalLogger(VisitorState state, SuggestedFix.Builder fix) { Type loggerType = LOGGER_TYPE.get(state); if (loggerType == null) { throw new AssertionError("Attempting to define new logger in a file without loggers"); } ImmutableSet<Symbol> ignoredFields = fieldsToIgnore(state); ClassTree topLevelClassInFile = outermostClassTree(state.getPath()); ClassSymbol targetClassSym = ASTHelpers.getSymbol(topLevelClassInFile); for (Tree member : topLevelClassInFile.getMembers()) { Symbol memberSym = ASTHelpers.getSymbol(member); if (memberSym instanceof VarSymbol && ASTHelpers.isSubtype(memberSym.type, loggerType, state) && !ignoredFields.contains(memberSym)) { // Found some logger defined, let's just use that, unless it needs to be moved. if (!targetClassSym.isInterface()) { state.incrementCounter(this, "found-existing"); return new LocalLogger( LocalLogger.Provenance.ALREADY_PRESENT, Optional.of(memberSym), memberSym.getSimpleName().toString()); } /* This logger belongs to an interface, which means it is public. We'll create a new static nested class to hold the logger, and make the logger a private member of that class. */ fix.delete(member); return defineNestedClassWithLogger(topLevelClassInFile, state, fix); } } fix.addImport(GOOGLE_LOGGER); if (targetClassSym.isInterface()) { // Interfaces should get a nested class, not a normal field. return defineNestedClassWithLogger(topLevelClassInFile, state, fix); } String name = REASONABLE_LOGGER_NAMES.stream() .filter( candidate -> Iterables.isEmpty( targetClassSym.members().getSymbolsByName(state.getName(candidate)))) .findFirst() .orElseThrow(IllegalStateException::new); String newMember = String.format( "private static final FluentLogger %s =" + " FluentLogger.forEnclosingClass();", name); fix.merge( SuggestedFixes.addMembers(topLevelClassInFile, state, AdditionPosition.FIRST, newMember)); return new LocalLogger(LocalLogger.Provenance.DEFINED_BY_FIX, Optional.empty(), name); } private static LocalLogger defineNestedClassWithLogger( ClassTree topLevelClassInFile, VisitorState state, SuggestedFix.Builder fix) { fix.merge(SuggestedFixes.addMembers(topLevelClassInFile, state, NESTED_LOGGER_DEFINITION)); return new LocalLogger( LocalLogger.Provenance.DEFINED_BY_FIX, Optional.empty(), String.format("%s.%s", NESTED_LOGGER_CLASSNAME, NESTED_LOGGER_FIELDNAME)); } private static ClassTree outermostClassTree(TreePath path) { ClassTree result = null; while (path != null) { Tree leaf = path.getLeaf(); if (leaf instanceof ClassTree) { result = (ClassTree) leaf; } path = path.getParentPath(); } Verify.verifyNotNull(result, "No enclosing class"); return result; } private static boolean canHaveStaticFields(ClassSymbol enclosingClassSym) { return enclosingClassSym.getNestingKind() == NestingKind.TOP_LEVEL || enclosingClassSym.getNestingKind() == NestingKind.MEMBER && ((enclosingClassSym.flags() & Flags.STATIC) != 0); } @Override public Description matchIdentifier(IdentifierTree tree, VisitorState state) { return rehomeLogger(tree, state); } @Override public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) { return rehomeLogger(tree, state); } /** * If the expression refers to a FluentLogger owned by a class in another file, rewrites it to * refer to a logger in this file, defining one if necessary. */ private Description rehomeLogger(ExpressionTree tree, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(tree); if (sym == null) { return NO_MATCH; } Type type = sym.type; if (!ASTHelpers.isSameType(type, LOGGER_TYPE.get(state), state)) { return NO_MATCH; } Symbol owner = sym.owner; if (!(owner instanceof ClassSymbol)) { // This may be looking up FluentLogger itself, as a member of its package, or reading a local. return NO_MATCH; } if (!(isStatic(sym) || tree instanceof IdentifierTree)) { // We can only be referring to another class's logger statically, or implicitly through a // superclass as an identifier. This early exit avoids flagging instance field lookups. return NO_MATCH; } /* Loggers owned by public interfaces should be moved regardless of whether they're defined in the current file, because fields in interfaces must be public, but loggers should be private. */ boolean needsMoveFromInterface = owner.isInterface(); Symbol outermostClassOfLogger = findUltimateOwningClass(owner); ClassTree outermostClassOfFile = null; for (Tree parent : state.getPath()) { Symbol ownerSym = ASTHelpers.getSymbol(parent); if (outermostClassOfLogger.equals(ownerSym)) { /* Seems to be a logger owned by a class in this file. */ if (!needsMoveFromInterface) { return NO_MATCH; } } if (parent instanceof ClassTree) { outermostClassOfFile = (ClassTree) parent; } } if (outermostClassOfFile == null) { // Impossible, I think? state.incrementCounter(this, "error-no-outermost-class"); return NO_MATCH; } return replaceWithFieldLookup(tree, state); } private static Symbol findUltimateOwningClass(Symbol sym) { Symbol result = sym; while (sym instanceof ClassSymbol) { result = sym; sym = sym.owner; } return result; } /** * Fields which we should not use to replace the current expression, because we are in the middle * of defining them. */ private static ImmutableSet<Symbol> fieldsToIgnore(VisitorState state) { Tree t = state.findEnclosing(VariableTree.class, ClassTree.class); return t instanceof VariableTree ? ImmutableSet.of(ASTHelpers.getSymbol(t)) : ImmutableSet.of(); } }
20,517
40.366935
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerLogString.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.flogger; import static com.google.errorprone.BugPattern.LinkType.NONE; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Matchers.instanceMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.CompileTimeConstantExpressionMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** * Detects invocations of {@code LoggingApi.log(String)} for which the argument is not a * compile-time constant and provides suggested alternatives. * * <p>Currently the suggestions are only made in the error message; eventually most of these things * should be actual suggested fixes. */ @BugPattern( summary = "Arguments to log(String) must be compile-time constants or parameters annotated with" + " @CompileTimeConstant. If possible, use Flogger's formatting log methods instead.", linkType = NONE, severity = ERROR) public class FloggerLogString extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> LOG_STRING = instanceMethod() .onDescendantOf("com.google.common.flogger.LoggingApi") .named("log") .withParameters("java.lang.String"); private static final Matcher<ExpressionTree> COMPILE_TIME_CONSTANT = CompileTimeConstantExpressionMatcher.instance(); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return LOG_STRING.matches(tree, state) && !COMPILE_TIME_CONSTANT.matches(tree.getArguments().get(0), state) ? describeMatch(tree) : Description.NO_MATCH; } }
2,645
39.707692
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerLogVarargs.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.flogger; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.argument; import static com.google.errorprone.matchers.Matchers.isSameType; 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; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.suppliers.Suppliers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; /** * @author Graeme Morgan (ghm@google.com) */ @BugPattern( summary = "logVarargs should be used to pass through format strings and arguments.", severity = ERROR) public final class FloggerLogVarargs extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<MethodInvocationTree> MATCHER = allOf( instanceMethod().onDescendantOf("com.google.common.flogger.LoggingApi").named("log"), argument(0, isSameType(Suppliers.STRING_TYPE)), argument(1, isSameType(Suppliers.arrayOf(Suppliers.OBJECT_TYPE)))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return NO_MATCH; } MethodTree enclosingMethod = state.findEnclosing(MethodTree.class); if (enclosingMethod == null) { return NO_MATCH; } // Heuristically, a compile time constant format string might be intended to be used with an // actual array, but a non-CTC probably isn't. return ASTHelpers.constValue(tree.getArguments().get(0)) == null ? describeMatch(tree, SuggestedFixes.renameMethodInvocation(tree, "logVarargs", state)) : NO_MATCH; } }
2,852
41.58209
96
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerArgumentToString.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.flogger; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.flogger.FloggerHelpers.inferFormatSpecifier; 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.instanceMethod; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getType; import static java.util.Arrays.stream; import com.google.common.base.Ascii; import com.google.common.collect.ImmutableMap; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ArrayType; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.annotation.Nullable; import javax.lang.model.type.TypeKind; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Use Flogger's printf-style formatting instead of explicitly converting arguments to" + " strings", severity = WARNING) public class FloggerArgumentToString extends BugChecker implements MethodInvocationTreeMatcher { /** * Match any unescaped '%' and capture probable terms (including the '%'). Note that this * expression also captures "%n" (newline) which we convert in-place to an escaped "\n". * * <p>Printf terms do not currently support specifying an index (e.g. {@code "%1$d"}) as this is * used incredibly rarely and not worth automating. */ private static final Pattern PRINTF_TERM_CAPTURE_PATTERN = // TODO(amalloy): I think this can be done without possessive quantifiers: // (?:^|[^%])(?:%%)*(%[^%a-zA-Z]*[a-zA-Z]) // I think this also means we no longer need the special-case "at current position" check, // since skipping % characters can't cause it to match. Pattern.compile( // Skip escaped pairs of '%' before the next term. "[^%]*+(?:%%[^%]*+)*+" // Capture an unescaped '%' and anything up to the first letter. + "(%[^%a-zA-Z]*[a-zA-Z])"); /** * Validate captured printf terms (minus the leading '%'). This expression MUST NOT risk having * false positives and anything we match (other than "%n") must be 100% legal in Flogger. */ private static final Pattern PRINTF_TERM_VALIDATION_PATTERN = Pattern.compile( // Simple: %c, %b and %n (newline) "[cCbBn]|" // String: %s, %20s, %S, %#s + "#?(?:[1-9][0-9]*)?[sS]|" // Integral: %d, %12d, %,d (numeric grouping) + ",?(?:[1-9][0-9]*)?d|" // Zero padded Integral: %05d (not allowed with grouping) + "0[1-9][0-9]*d|" // Hex: %x, %#x, %#016X (%0x is not legal) + "#?(?:0[1-9][0-9]*)?[xX]|" // Float: %f, %,f, %8e, %12.6G + ",?(?:[1-9][0-9]*)?(?:\\.[0-9]+)?[feEgG]"); private static final Character STRING_FORMAT = 's'; private static final Character UPPER_STRING_FORMAT = 'S'; private static final Character HEX_FORMAT = 'x'; private static final Character UPPER_HEX_FORMAT = 'X'; static class Parameter { final Supplier<String> source; final Type type; @Nullable final Character placeholder; private Parameter(ExpressionTree expression, char placeholder) { this(s -> s.getSourceForNode(expression), getType(expression), placeholder); } private Parameter(Supplier<String> source, Type type, char placeholder) { this.source = source; this.type = type; this.placeholder = placeholder; } private static Parameter receiver(MethodInvocationTree invocation, char placeholder) { ExpressionTree receiver = getReceiver(invocation); if (receiver != null) { return new Parameter(getReceiver(invocation), placeholder); } return new Parameter(s -> "this", null, placeholder); } } private enum Unwrapper { // Unwrap any instance call to toString(). TO_STRING(instanceMethod().anyClass().named("toString").withNoParameters()) { @Override Parameter unwrap(MethodInvocationTree invocation, char placeholder) { return Parameter.receiver(invocation, placeholder); } }, // Unwrap things like: String.valueOf(x) --> x // Consider carefully if it's worth doing the char[] variant (Will we format char[] exactly // as the corresponding String? How often is it used?) STRING_VALUE_OF( anyOf( Stream.of( "valueOf(boolean)", "valueOf(char)", "valueOf(int)", "valueOf(long)", "valueOf(float)", "valueOf(double)", "valueOf(java.lang.Object)") .map( signature -> instanceMethod().onExactClass("java.lang.String").withSignature(signature)) .collect(toImmutableList()))) { @Override Parameter unwrap(MethodInvocationTree invocation, char placeholder) { return Parameter.receiver(invocation, placeholder); } }, // Unwrap things like: Integer.toString(n) --> n STATIC_TO_STRING( anyOf( ImmutableMap.<Class<?>, String>builder() .put(Boolean.class, "toString(boolean)") .put(Character.class, "toString(char)") .put(Byte.class, "toString(byte)") .put(Short.class, "toString(short)") .put(Integer.class, "toString(int)") .put(Long.class, "toString(long)") .put(Float.class, "toString(float)") .put(Double.class, "toString(double)") .buildOrThrow() .entrySet() .stream() .map(e -> staticMethod().onClass(e.getKey().getName()).withSignature(e.getValue())) .collect(toImmutableList()))) { @Override Parameter unwrap(MethodInvocationTree invocation, char placeholder) { return new Parameter(getOnlyArgument(invocation), placeholder); } }, // Unwrap any inline manual auto-boxing (good for cases where flogger does not auto-box). // Note that we could also unwrap unboxing, but this has the effect of removing a null check. STATIC_VALUE_OF( anyOf( ImmutableMap.<Class<?>, String>builder() .put(Boolean.class, "valueOf(boolean)") .put(Character.class, "valueOf(char)") .put(Byte.class, "valueOf(byte)") .put(Short.class, "valueOf(short)") .put(Integer.class, "valueOf(int)") .put(Long.class, "valueOf(long)") .put(Float.class, "valueOf(float)") .put(Double.class, "valueOf(double)") .buildOrThrow() .entrySet() .stream() .map(e -> staticMethod().onClass(e.getKey().getName()).withSignature(e.getValue())) .collect(toImmutableList()))) { @Override Parameter unwrap(MethodInvocationTree invocation, char placeholder) { return new Parameter(getOnlyArgument(invocation), placeholder); } }, // Check that the output format safe to unwrap (it could be log("%b", x.toString()) which // cannot be unwrapped). STRING_TO_UPPER_CASE( instanceMethod().onExactClass("java.lang.String").named("toUpperCase").withNoParameters()) { @Override Parameter unwrap(MethodInvocationTree invocation, char placeholder) { return new Parameter(getReceiver(invocation), UPPER_STRING_FORMAT); } }, ASCII_TO_UPPER_CASE( anyOf( Stream.of("java.lang.String", "java.lang.CharSequence") .map( param -> staticMethod() .onClass("com.google.common.base.Ascii") .named("toUpperCase") .withParameters(param)) .collect(toImmutableList()))) { @Override Parameter unwrap(MethodInvocationTree invocation, char placeholder) { return new Parameter(getOnlyArgument(invocation), UPPER_STRING_FORMAT); } }, STATIC_TO_HEX_STRING( anyOf( ImmutableMap.<Class<?>, String>builder() .put(Integer.class, "toHexString(int)") .put(Long.class, "toHexString(long)") .buildOrThrow() .entrySet() .stream() .map(e -> staticMethod().onClass(e.getKey().getName()).withSignature(e.getValue())) .collect(toImmutableList()))) { @Override Parameter unwrap(MethodInvocationTree invocation, char placeholder) { return new Parameter( getOnlyArgument(invocation), Ascii.isUpperCase(placeholder) ? UPPER_HEX_FORMAT : HEX_FORMAT); } }, ARRAYS_AS_LIST_OR_TO_STRING( allOf( staticMethod().onClass("java.util.Arrays").namedAnyOf("asList", "toString"), toType( MethodInvocationTree.class, FloggerArgumentToString::hasSingleVarargsCompatibleArgument))) { @Override Parameter unwrap(MethodInvocationTree invocation, char placeholder) { return new Parameter(getOnlyArgument(invocation), placeholder); } }; abstract Parameter unwrap(MethodInvocationTree tree, char placeholder); @SuppressWarnings("Immutable") // all implementations are immutable private final Matcher<ExpressionTree> matcher; Unwrapper(Matcher<ExpressionTree> matcher) { this.matcher = matcher; } } private static ExpressionTree getOnlyArgument(MethodInvocationTree invocation) { return getOnlyElement(invocation.getArguments()); } private static final Matcher<ExpressionTree> LOG_MATCHER = instanceMethod().onDescendantOf("com.google.common.flogger.LoggingApi").named("log"); static final Matcher<ExpressionTree> UNWRAPPABLE = anyOf(stream(Unwrapper.values()).map(u -> u.matcher).collect(toImmutableList())); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!LOG_MATCHER.matches(tree, state)) { return NO_MATCH; } List<? extends ExpressionTree> arguments = tree.getArguments(); if (arguments.isEmpty()) { return NO_MATCH; } String formatString = ASTHelpers.constValue(arguments.get(0), String.class); if (formatString == null) { return NO_MATCH; } arguments = arguments.subList(1, arguments.size()); if (arguments.stream().noneMatch(argument -> UNWRAPPABLE.matches(argument, state))) { return NO_MATCH; } return unwrapArguments(formatString, tree, arguments, state); } Description unwrapArguments( String formatString, MethodInvocationTree tree, List<? extends ExpressionTree> arguments, VisitorState state) { SuggestedFix.Builder fix = SuggestedFix.builder(); int start = 0; java.util.regex.Matcher matcher = PRINTF_TERM_CAPTURE_PATTERN.matcher(formatString); StringBuilder sb = new StringBuilder(); int idx = 0; boolean fixed = false; // NOTE: Not only must we find() a next term, the match must start at our current position // otherwise we can unexpectedly match things like "%%s" (by skipping the first '%'). while (matcher.find() && matcher.start() == start) { String term = matcher.group(1); // Validate the term (minus the leading '%'). if (!PRINTF_TERM_VALIDATION_PATTERN.matcher(term.substring(1)).matches()) { return NO_MATCH; } if (term.equals("%n")) { // Replace "%n" with "\n" everywhere (Flogger does not recognize %n and it's // potentially confusing if people mistake it for a placeholder). term = "\\n"; } else { // Only unwrap existing printf parameters if the placeholder has no additional formatting. if (term.length() == 2) { ExpressionTree argument = arguments.get(idx); char placeholder = term.charAt(1); Parameter unwrapped = unwrap(argument, placeholder, state); if (unwrapped != null) { fix.replace(argument, unwrapped.source.get(state)); placeholder = firstNonNull(unwrapped.placeholder, 's'); if (placeholder == STRING_FORMAT) { placeholder = inferFormatSpecifier(unwrapped.type, state); } term = "%" + placeholder; fixed = true; } } idx++; } sb.append(formatString, start, matcher.start(1)).append(term); start = matcher.end(1); } sb.append(formatString, start, formatString.length()); if (!fixed) { return NO_MATCH; } fix.replace(tree.getArguments().get(0), state.getConstantExpression(sb.toString())); return describeMatch(tree, fix.build()); } @Nullable private static Parameter unwrap(ExpressionTree argument, char placeholder, VisitorState state) { for (Unwrapper unwrapper : Unwrapper.values()) { if (unwrapper.matcher.matches(argument, state)) { return unwrapper.unwrap((MethodInvocationTree) argument, placeholder); } } return null; } private static boolean hasSingleVarargsCompatibleArgument( MethodInvocationTree tree, VisitorState state) { if (tree.getArguments().size() != 1) { return false; } Type type = getType(getOnlyArgument(tree)); if (type == null) { return false; } if (!type.getKind().equals(TypeKind.ARRAY)) { return false; } return ASTHelpers.isSameType( ((ArrayType) type).getComponentType(), state.getSymtab().objectType, state); } }
15,584
39.585938
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerSplitLogStatement.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.flogger; import static com.google.errorprone.BugPattern.LinkType.CUSTOM; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.enclosingClass; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import static com.google.errorprone.matchers.Matchers.methodReturns; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.Matchers.variableType; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; /** Bugpattern to prevent splitting flogger log invocations into multiple statements. */ @BugPattern( summary = "Splitting log statements and using Api instances directly breaks logging.", linkType = CUSTOM, link = "https://google.github.io/flogger/best_practice#no-split", severity = ERROR) public final class FloggerSplitLogStatement extends BugChecker implements MethodTreeMatcher, VariableTreeMatcher { private static final Matcher<Tree> IS_LOGGER_API = isSubtypeOf("com.google.common.flogger.LoggingApi"); private static final Matcher<Tree> CLASS_MATCHES = not( anyOf( enclosingClass(isSubtypeOf("com.google.common.flogger.AbstractLogger")), enclosingClass(isSubtypeOf("com.google.common.flogger.LoggingApi")))); private static final Matcher<MethodTree> METHOD_MATCHES = allOf(methodReturns(IS_LOGGER_API), CLASS_MATCHES); private static final Matcher<VariableTree> VARIABLE_MATCHES = allOf(variableType(IS_LOGGER_API), CLASS_MATCHES); @Override public Description matchMethod(MethodTree tree, VisitorState state) { return METHOD_MATCHES.matches(tree, state) ? describeMatch(tree) : NO_MATCH; } @Override public Description matchVariable(VariableTree tree, VisitorState state) { return VARIABLE_MATCHES.matches(tree, state) ? describeMatch(tree) : NO_MATCH; } }
3,192
41.573333
90
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/overloading/ParameterTree.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.overloading; import com.google.auto.value.AutoValue; import com.google.common.base.Preconditions; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import java.util.Set; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; /** * A simpler version of standard {@link VariableTree} used to distinguish between real variable * declarations and method parameters. * * <p>{@link VariableTree} is in a sense "too rich" to represent method parameters. For example, it * is allowed to have an initializer or arbitrary modifiers. This class is a much simpler version of * variable tree used to distinguish actual real {@link VariableTree} (variable declarations) from * simple method parameters. During construction it is validated that the underlying {@link * VariableTree} can really be used as method parameter. * * <p>It also provides slightly more sensible (for our purposes) {@link Object#toString()} * implementation. * * @author hanuszczak@google.com (Łukasz Hanuszczak) */ @AutoValue abstract class ParameterTree { public abstract Name getName(); public abstract Tree getType(); public abstract boolean isVarArgs(); public static ParameterTree create(VariableTree variableTree) { Preconditions.checkArgument(isValidParameterTree(variableTree)); Name name = variableTree.getName(); Tree type = variableTree.getType(); boolean isVarargs = isVariableTreeVarArgs(variableTree); return new AutoValue_ParameterTree(name, type, isVarargs); } private static boolean isValidParameterTree(VariableTree variableTree) { // A valid parameter has no initializer. if (variableTree.getInitializer() != null) { return false; } // A valid parameter either has no modifiers or has only `final` keyword. Set<Modifier> flags = variableTree.getModifiers().getFlags(); return flags.isEmpty() || (flags.size() == 1 && flags.contains(Modifier.FINAL)); } @Override public final String toString() { String type = getType().toString(); String name = getName().toString(); // Hacky fix to improve pretty-printing of varargs (otherwise they are printed as Type[]). if (isVarArgs()) { type = type.substring(0, type.length() - 2) + "..."; } return type + " " + name; } // TODO(hanuszczak): This should probably be moved to ASTHelpers. private static boolean isVariableTreeVarArgs(VariableTree variableTree) { Symbol sym = ASTHelpers.getSymbol(variableTree); Preconditions.checkArgument( sym.owner instanceof MethodSymbol, "sym must be a parameter to a method"); MethodSymbol method = (MethodSymbol) sym.owner; return method.isVarArgs() && method.getParameters().last() == sym; } }
3,547
35.958333
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/overloading/InconsistentOverloads.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.overloading; import static com.google.common.collect.ImmutableList.sortedCopyOf; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static java.util.Comparator.comparingInt; import static java.util.stream.Collectors.groupingBy; import com.google.common.base.Preconditions; 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; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.tree.JCTree; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Optional; /** * A {@link BugChecker} that detects inconsistently overloaded methods in Java classes. * * <p>The bug checker works in several stages. First, it group the class methods by name. Then each * group is processed separately (and violations are reported on per-group basis). * * <p>The group is processed by building a {@link ParameterTrie}. This trie is an archetype built * from methods of lower arity used to determine ordering of methods of higher arity. After ordering * of arguments of particular method has been determined (using the archetype) it is then added to * the trie and serves as basis for methods of even higher arity. * * <p>If the determined ordering is different the original parameter ordering a {@link * ParameterOrderingViolation} is reported. It is essentially a list of expected parameter and list * of actual parameters then used to build a {@link SuggestedFix} object. * * @author hanuszczak@google.com (Łukasz Hanuszczak) */ @BugPattern( summary = "The ordering of parameters in overloaded methods should be as consistent as possible (when" + " viewed from left to right)", severity = SeverityLevel.WARNING) public final class InconsistentOverloads extends BugChecker implements ClassTreeMatcher { @Override public Description matchClass(ClassTree classTree, VisitorState state) { processClassMethods(getClassTreeMethods(classTree, state), state); /* * We want to report inconsistencies per method group. There is no "method group" unit in the * Java AST, so we match on the class, group its methods to method groups and process each group * separately. * * Because of this we return no match for the class itself but we report policy violations for * each group after it is processed. */ return Description.NO_MATCH; } private void processClassMethods(List<MethodTree> classMethodTrees, VisitorState state) { for (List<MethodTree> groupMethods : getMethodGroups(classMethodTrees)) { processGroupMethods(groupMethods, state); } } private void processGroupMethods(List<MethodTree> groupMethodTrees, VisitorState state) { Preconditions.checkArgument(!groupMethodTrees.isEmpty()); for (ParameterOrderingViolation violation : getViolations(groupMethodTrees)) { MethodSymbol methodSymbol = getSymbol(violation.methodTree()); if (ASTHelpers.findSuperMethods(methodSymbol, state.getTypes()).isEmpty()) { Description.Builder description = buildDescription(violation.methodTree()); description.setMessage(violation.getDescription()); state.reportMatch(description.build()); } } } private static ImmutableList<ParameterOrderingViolation> getViolations( List<MethodTree> groupMethodTrees) { ImmutableList.Builder<ParameterOrderingViolation> result = ImmutableList.builder(); ParameterTrie trie = new ParameterTrie(); for (MethodTree methodTree : sortedByArity(groupMethodTrees)) { Optional<ParameterOrderingViolation> violation = trie.extendAndComputeViolation(methodTree); violation.ifPresent(result::add); } return result.build(); } private static ImmutableList<MethodTree> sortedByArity(Iterable<MethodTree> methodTrees) { return sortedCopyOf(comparingArity().thenComparing(comparingPositions()), methodTrees); } private static Comparator<MethodTree> comparingPositions() { return comparingInt(InconsistentOverloads::getStartPosition); } private static Comparator<MethodTree> comparingArity() { return comparingInt(ParameterTrie::getMethodTreeArity); } /** * Returns a collection of method groups for given list of {@code classMethods}. * * <p>A <i>method group</i> is a list of methods with the same name. * * <p>It is assumed that given {@code classMethods} really do belong to the same class. The * returned collection does not guarantee any particular group ordering. */ private static Collection<List<MethodTree>> getMethodGroups(List<MethodTree> classMethods) { return classMethods.stream().collect(groupingBy(MethodTree::getName)).values(); } /** * Returns a list of {@link MethodTree} declared in the given {@code classTree}. * * <p>Only method trees that belong to the {@code classTree} are returned, so methods declared in * nested classes are not going to be considered. */ private ImmutableList<MethodTree> getClassTreeMethods(ClassTree classTree, VisitorState state) { List<? extends Tree> members = classTree.getMembers(); return members.stream() .filter(MethodTree.class::isInstance) .map(MethodTree.class::cast) .filter(m -> !isSuppressed(m, state)) .collect(toImmutableList()); } /** * Returns a start position of given {@code tree}. * * <p>The only purpose of this method is to avoid doing a hacky casting to {@link JCTree}. */ private static int getStartPosition(Tree tree) { return ASTHelpers.getStartPosition(tree); } }
6,811
40.791411
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/overloading/ParameterTrie.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.overloading; import static java.util.Comparator.comparingInt; import com.google.auto.value.AutoValue; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.sun.source.tree.MethodTree; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Optional; import java.util.TreeSet; import javax.lang.model.element.Name; /** * A simple <a href="https://en.wikipedia.org/wiki/Trie">trie</a> implementation. * * <p>Edges between trie nodes represent method parameters and each path represents some method * signature. This trie is an archetype that next method signatures must follow - we extend the trie * with new signatures reporting all ordering violations along the way. * * @author hanuszczak@google.com (Łukasz Hanuszczak) */ class ParameterTrie { private final Map<Name, ParameterTrie> children; public ParameterTrie() { this.children = new HashMap<>(); } /** * Extends the trie with parameters of {@code methodTree}. * * <p>If any ordering {@link ParameterOrderingViolation} is discovered during extension procedure, * they are reported in the result. * * <p>The method signature is considered to violate the consistency if there exists a path in the * archetype (the trie) that could be used but would require parameter reordering. The extension * algorithm simply walks down the trie as long as possible until the signature has parameters * matching existing edges in the trie. Once this is no longer possible, new nodes are the trie is * extended with remaining parameters. */ public Optional<ParameterOrderingViolation> extendAndComputeViolation(MethodTree methodTree) { return new ParameterTrieExtender(methodTree).execute(this); } /** * A convenience class used by {@link ParameterTrie#extendAndComputeViolation(MethodTree)} method. * * <p>The extension algorithm is inherently stateful. Because threading three state arguments in * every recursive function invocation is inconvenient, we use this class to keep track of the * state in class members. * * <p>The violation detection works like this: first a method signature (i.e. all the method * parameters) is added to the trie. As long as it is possible the algorithm tries to find a * parameter that can be followed using existing edges in the trie. When no such parameter is * found, the trie extension procedure begins where remaining parameters are added to the trie in * order in which they appear in the initial list. This whole procedure (a path that was followed * during the process) determines a "correct", "consistent" ordering of the parameters. If the * original input list of parameters has a different order that the one determined by the * algorithm a violation is reported. */ private static class ParameterTrieExtender { private final MethodTree methodTree; private final NavigableSet<Parameter> inputParameters; private final List<Parameter> outputParameters; public ParameterTrieExtender(MethodTree methodTree) { this.methodTree = methodTree; this.inputParameters = new TreeSet<>(comparingInt(Parameter::position)); this.outputParameters = new ArrayList<>(); } /** * Extends given {@code trie} with initial {@link MethodTree}. * * <p>If any {@link ParameterOrderingViolation} is found during the extension procedure, it is * reported in the result. */ public Optional<ParameterOrderingViolation> execute(ParameterTrie trie) { Preconditions.checkArgument(trie != null); initialize(); walk(trie); return validate(); } /** * Initializes the input and output parameter collections. * * <p>After initialization, the input parameters should be equal to parameters of the given * {@link MethodTree} and output parameters should be empty. After processing this should be * reversed: input parameters list should be empty and output parameters should be an ordered * version of parameters of the given {@link MethodTree}. */ private void initialize() { for (int i = 0; i < getMethodTreeArity(methodTree); i++) { inputParameters.add(Parameter.create(methodTree, i)); } outputParameters.clear(); } /** * Processes input parameters by walking along the trie as long as there is a path. * * <p>Once the walk is no longer possible (there is no trie child that matches one of the input * parameters) the extender begins expansion procedure (see {@link * ParameterTrieExtender#execute(ParameterTrie)}). */ private void walk(ParameterTrie trie) { Preconditions.checkArgument(trie != null); for (Parameter parameter : inputParameters) { if (parameter.tree().isVarArgs() || !trie.children.containsKey(parameter.name())) { continue; } inputParameters.remove(parameter); outputParameters.add(parameter); walk(trie.children.get(parameter.name())); return; } // Walking not possible anymore, start expansion. expand(trie); } /** * Expands the trie with leftover input parameters. * * <p>It is assumed that given {@code trie} does not have a key corresponding to any input * parameter which should happen only if {@link ParameterTrieExtender#walk(ParameterTrie)} has * nowhere else to go. * * <p>Only non-varargs parameters are added to the trie. Any varargs parameters should always be * placed at the end of the method signature so it makes no sense to include them in the * archetype. */ private void expand(ParameterTrie trie) { Preconditions.checkArgument(trie != null); if (inputParameters.isEmpty()) { return; } Parameter parameter = inputParameters.first(); inputParameters.remove(parameter); outputParameters.add(parameter); ParameterTrie allocatedTrie = new ParameterTrie(); if (!parameter.tree().isVarArgs()) { trie.children.put(parameter.name(), allocatedTrie); } expand(allocatedTrie); } /** * Reports {@link ParameterOrderingViolation} if output parameters are not ordered as in input * file. * * <p>This method simply goes through the list of output parameters (input parameters ordered by * trie traversal algorithm). If a parameter at particular position differs from its original * position a violation is reported. * * <p>If the ordering is consistent then there is no violation and an empty optional is * returned. */ private Optional<ParameterOrderingViolation> validate() { ImmutableList.Builder<ParameterTree> actual = ImmutableList.builder(); ImmutableList.Builder<ParameterTree> expected = ImmutableList.builder(); boolean valid = true; for (int i = 0; i < outputParameters.size(); i++) { Parameter parameter = outputParameters.get(i); if (parameter.position() != i) { valid = false; } actual.add(parameter.tree()); expected.add(getParameterTree(parameter.position())); } if (valid) { return Optional.empty(); } else { ParameterOrderingViolation violation = ParameterOrderingViolation.builder() .setMethodTree(methodTree) .setActual(actual.build()) .setExpected(expected.build()) .build(); return Optional.of(violation); } } /** Returns a {@link ParameterTree} at {@code position} in the associated method. */ private ParameterTree getParameterTree(int position) { return ParameterTree.create(methodTree.getParameters().get(position)); } } /** * A class used to represent a {@link ParameterTree} (which is essentially just a {@link * com.sun.source.tree.VariableTree} and its original position within the {@link MethodTree}. */ @AutoValue abstract static class Parameter { public abstract ParameterTree tree(); public abstract int position(); public Name name() { return tree().getName(); } public static Parameter create(MethodTree methodTree, int position) { ParameterTree parameterTree = ParameterTree.create(methodTree.getParameters().get(position)); return new AutoValue_ParameterTrie_Parameter(parameterTree, position); } } /** Returns arity (number of parameters) of given {@code methodTree}. */ static int getMethodTreeArity(MethodTree methodTree) { return methodTree.getParameters().size(); } }
9,408
36.486056
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/overloading/ParameterOrderingViolation.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.overloading; import static java.util.stream.Collectors.joining; import com.google.auto.value.AutoValue; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.errorprone.fixes.SuggestedFix; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; /** * A class used to represent ordering violations within a {@link MethodTree}. * * <p>It is a triplet of three things: an original {@link MethodTree}, List<{@link VariableTree}> of * expected parameters, and a List<{@link VariableTree}> of actual parameters. Violations are * reported by using {@link ParameterTrie#extendAndComputeViolation(MethodTree)}. * * @author hanuszczak@google.com (Łukasz Hanuszczak) */ @AutoValue abstract class ParameterOrderingViolation { public abstract MethodTree methodTree(); public abstract ImmutableList<ParameterTree> actual(); public abstract ImmutableList<ParameterTree> expected(); @AutoValue.Builder abstract static class Builder { abstract Builder setMethodTree(MethodTree methodTree); abstract Builder setActual(ImmutableList<ParameterTree> actual); abstract Builder setExpected(ImmutableList<ParameterTree> expected); abstract ParameterOrderingViolation autoBuild(); public ParameterOrderingViolation build() { ParameterOrderingViolation orderingViolation = autoBuild(); int actualParametersCount = orderingViolation.actual().size(); int expectedParameterCount = orderingViolation.expected().size(); Preconditions.checkState(actualParametersCount == expectedParameterCount); return orderingViolation; } } public static ParameterOrderingViolation.Builder builder() { return new AutoValue_ParameterOrderingViolation.Builder(); } /** * Provides a violation description with suggested parameter ordering. * * <p>An automated {@link SuggestedFix} is not returned with the description because it is not * safe: reordering the parameters can break the build (if we are lucky) or - in case of * reordering parameters with the same types - break runtime behaviour of the program. */ public String getDescription() { return "The parameters of this method are inconsistent with other overloaded versions." + " A consistent order would be: " + getSuggestedSignature(); } private String getSuggestedSignature() { return String.format("%s(%s)", methodTree().getName(), getSuggestedParameters()); } private String getSuggestedParameters() { return expected().stream().map(ParameterTree::toString).collect(joining(", ")); } }
3,291
34.397849
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/TimeUnitMismatch.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.time; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.names.NamingConventions.splitToLowercaseTerms; import static com.google.errorprone.suppliers.Suppliers.DOUBLE_TYPE; import static com.google.errorprone.suppliers.Suppliers.INT_TYPE; import static com.google.errorprone.suppliers.Suppliers.LONG_TYPE; import static com.google.errorprone.util.ASTHelpers.enclosingClass; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isSameType; import static com.sun.source.tree.Tree.Kind.MEMBER_SELECT; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; 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.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.IdentifierTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeCastTree; 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.Type; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** Checker that detects likely time-unit mismatches by looking at identifier names. */ @BugPattern( summary = "An value that appears to be represented in one unit is used where another appears to be " + "required (e.g., seconds where nanos are needed)", severity = WARNING) public final class TimeUnitMismatch extends BugChecker implements AssignmentTreeMatcher, MethodInvocationTreeMatcher, NewClassTreeMatcher, VariableTreeMatcher { @Override public Description matchAssignment(AssignmentTree tree, VisitorState state) { String formalName = extractArgumentName(tree.getVariable()); if (formalName != null) { check(formalName, tree.getExpression(), state); } return ANY_MATCHES_WERE_ALREADY_REPORTED; } @Override public Description matchVariable(VariableTree tree, VisitorState state) { if (tree.getInitializer() != null) { check(tree.getName().toString(), tree.getInitializer(), state); } return ANY_MATCHES_WERE_ALREADY_REPORTED; } /* * TODO(cpovirk): Hardcode a list of methods that are very common or have surprising return types * or argument types, and consult that list when matching method/constructor calls. (Maybe even * hardcode some methods whose parameters have meaningful types if we fear that some people will * compile against .class files that were compiled without parameter names?) e.g., * SystemClock.elapsedRealtime is millis. And how about Stopwatch.elapsed(TimeUnit) and perhaps * similar methods? */ /* * TODO(cpovirk): Check `return` statements against the type suggested by the method name (or from * the hardcoded list, since mismatches there seem more likely -- e.g., Ticker.read() that returns * elapsedRealtime()). */ /* * TODO(cpovirk): Write a separate check that looks for methods whose units are unclear from the * method+parameter names. Identify that they are in fact time-unit methods by the fact that * people are passing parameters whose units we can detect (in which case we can give a * suggestion!) or from generic names like "now"/"time"/"instant." In addition to giving a * suggested fix that is a rename, also say in prose that it's better to use Duration, etc. */ @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { MethodSymbol symbol = getSymbol(tree); checkAll(symbol.getParameters(), tree.getArguments(), state); return ANY_MATCHES_WERE_ALREADY_REPORTED; } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { MethodSymbol symbol = getSymbol(tree); checkTimeUnitToUnit(tree, symbol, state); boolean setterMethodReported = checkSetterStyleMethod(tree, symbol, state); if (!setterMethodReported) { checkAll(symbol.getParameters(), tree.getArguments(), state); } return ANY_MATCHES_WERE_ALREADY_REPORTED; } // check for setTimeoutInSecs(int timeout) where the callsite is millis private boolean checkSetterStyleMethod( MethodInvocationTree tree, MethodSymbol symbol, VisitorState state) { if (symbol.params().length() == 1 && ASTHelpers.isVoidType(symbol.getReturnType(), state) && tree.getArguments().size() == 1) { return check(symbol.name.toString(), tree.getArguments().get(0), state); } return false; } /* * TODO(cpovirk): Match addition, subtraction, and division in which args are of different types? * I wonder if division will have weird edge cases in which people are trying to write * conversions?? I think I'm confusing myself, though: The check will probably be correct if it * uses the same mismatch rules for division as for the other two. */ /** * Checks whether this call is a call to {@code TimeUnit.to*} and, if so, whether the units of its * parameter and its receiver disagree. */ private boolean checkTimeUnitToUnit( MethodInvocationTree tree, MethodSymbol methodSymbol, VisitorState state) { if (tree.getMethodSelect().getKind() != MEMBER_SELECT) { return false; } MemberSelectTree memberSelect = (MemberSelectTree) tree.getMethodSelect(); Symbol receiverSymbol = getSymbol(memberSelect.getExpression()); if (receiverSymbol == null) { return false; } if (isTimeUnit(receiverSymbol, state) && receiverSymbol.isEnum() && TIME_UNIT_TO_UNIT_METHODS.containsValue(methodSymbol.getSimpleName().toString()) && tree.getArguments().size() == 1) { return check( receiverSymbol.getSimpleName().toString(), getOnlyElement(tree.getArguments()), state); } return false; } private static boolean isTimeUnit(Symbol receiverSymbol, VisitorState state) { return isSameType(JAVA_UTIL_CONCURRENT_TIMEUNIT.get(state), receiverSymbol.type, state); } private static final ImmutableBiMap<TimeUnit, String> TIME_UNIT_TO_UNIT_METHODS = new ImmutableBiMap.Builder<TimeUnit, String>() .put(NANOSECONDS, "toNanos") .put(MICROSECONDS, "toMicros") .put(MILLISECONDS, "toMillis") .put(SECONDS, "toSeconds") .put(MINUTES, "toMinutes") .put(HOURS, "toHours") .put(DAYS, "toDays") .buildOrThrow(); private boolean checkAll( List<VarSymbol> formals, List<? extends ExpressionTree> actuals, VisitorState state) { if (formals.size() != actuals.size()) { // varargs? weird usages of inner classes? TODO(cpovirk): Handle those correctly. return false; } /* * TODO(cpovirk): Look for calls with a bad TimeUnit parameter: "foo(timeoutMillis, SECONDS)." * This is the kind of thing that DurationToLongTimeUnit covers but more generic. */ boolean hasFinding = false; for (int i = 0; i < formals.size(); i++) { hasFinding |= check(formals.get(i).getSimpleName().toString(), actuals.get(i), state); } return hasFinding; } private boolean check(String formalName, ExpressionTree actualTree, VisitorState state) { /* * Sometimes people name a Duration parameter something like "durationMs." Then we falsely * report a problem if the value comes from Duration.ofSeconds(). Let's stick to numeric types. * * TODO(cpovirk): But consider looking at List<Integer> and even String, for which I've seen * possible mistakes. */ if (!NUMERIC_TIME_TYPE.matches(actualTree, state)) { return false; } /* * TODO(cpovirk): Is it worth assuming, e.g., that a literal "60" is likely to be a number of * seconds? */ String actualName = extractArgumentName(actualTree); if (actualName == null) { /* * TODO(cpovirk): Look for other assignments to a variable in the method to guess its type. * (Maybe even guess the type returned by a method by looking at other calls in the file?) Of * course, that may be slow. */ // TODO(cpovirk): Look for multiplication/division operations that are meant to change units. // TODO(cpovirk): ...even if they include casts! return false; } TimeUnit formalUnit = unitSuggestedByName(formalName); TimeUnit actualUnit = unitSuggestedByName(actualName); if (formalUnit == null || actualUnit == null || formalUnit == actualUnit) { return false; } String message = String.format( "Possible unit mismatch: expected %s but was %s. Before accepting this change, make " + "sure that there is a true unit mismatch and not just an identifier whose name " + "contains the wrong unit. (If there is, correct that instead!)", formalUnit.toString().toLowerCase(Locale.ROOT), actualUnit.toString().toLowerCase(Locale.ROOT)); if ((actualUnit == MICROSECONDS || actualUnit == MILLISECONDS) && (formalUnit == MICROSECONDS || formalUnit == MILLISECONDS)) { // TODO(cpovirk): Display this only if the code contained one of the ambiguous terms. message += " WARNING: This checker considers \"ms\" and \"msec\" to always refer to *milli*seconds. " + "Occasionally, code uses them for *micro*seconds. If this error involves " + "identifiers with those terms, be sure to check that it does mean milliseconds " + "before accepting this fix. If it instead means microseconds, consider renaming to " + "\"us\" or \"usec\" (or just \"micros\")."; // TODO(cpovirk): More ambitiously, suggest an edit to rename the identifier to "micros," etc. } else if (formalUnit == SECONDS && (actualUnit != HOURS && actualUnit != DAYS)) { message += " WARNING: The suggested replacement truncates fractional seconds, so a value " + "like 999ms becomes 0."; message += "Consider performing a floating-point division instead."; // TODO(cpovirk): Offer this as a suggested fix. } /* * TODO(cpovirk): I saw two instances in which the fix needs to be "backward" because the value * is a rate. For example, to convert "queries per second" to "queries per millisecond," we need * to _multiply_ by 1000, rather than divide as we would if we were converting seconds to * milliseconds. */ SuggestedFix.Builder fix = SuggestedFix.builder(); // TODO(cpovirk): This can conflict with constants with names like "SECONDS." fix.addStaticImport(TimeUnit.class.getName() + "." + actualUnit); // TODO(cpovirk): This won't work for `double` and won't work if the output needs to be `int`. fix.prefixWith( actualTree, String.format("%s.%s(", actualUnit, TIME_UNIT_TO_UNIT_METHODS.get(formalUnit))); fix.postfixWith(actualTree, ")"); /* * TODO(cpovirk): Often a better fix would be Duration.ofMillis(...).toNanos(). However, that * implies that the values are durations rather than instants, and it requires Java 8 (and some * utility methods in the case of micros). Maybe we should suggest a number of possible fixes? */ state.reportMatch(buildDescription(actualTree).setMessage(message).addFix(fix.build()).build()); /* * TODO(cpovirk): Supply a different fix in the matchTimeUnitToUnit case (or the similar case in * which someone is calling, say, toMillis() but should be calling toDays(). The current fix * produces nested toFoo(...) calls. A better fix would be to replace the existing call with a * corrected call. */ return true; } /** * Extracts the "argument name," as defined in section 2.1 of "Nomen est Omen," from the * expression. This translates a potentially complex expression into a simple name that can be * used by the similarity metric. * * <p>"Nomen est Omen: Exploring and Exploiting Similarities between Argument and Parameter * Names," ICSE 2016 */ @Nullable private static String extractArgumentName(ExpressionTree expr) { switch (expr.getKind()) { case TYPE_CAST: return extractArgumentName(((TypeCastTree) expr).getExpression()); case MEMBER_SELECT: { // If we have a field or method access, we use the name of the field/method. (We ignore // the name of the receiver object.) Exception: If the method is named "get" (Optional, // Flag, etc.), we use the name of the object or class that it's called on. MemberSelectTree memberSelect = (MemberSelectTree) expr; String member = memberSelect.getIdentifier().toString(); return member.equals("get") ? extractArgumentName(memberSelect.getExpression()) : member; } case METHOD_INVOCATION: { // If we have a 'call expression' we use the name of the method we are calling. Exception: // If the method is named "get," we use the object or class instead. (See above.) Symbol sym = getSymbol(expr); if (sym == null) { return null; } String methodName = sym.getSimpleName().toString(); return methodName.equals("get") ? extractArgumentName(((MethodInvocationTree) expr).getMethodSelect()) : methodName; } case IDENTIFIER: { IdentifierTree idTree = (IdentifierTree) expr; if (idTree.getName().contentEquals("this")) { // for the 'this' keyword the argument name is the name of the object's class Symbol sym = getSymbol(idTree); return (sym == null) ? null : enclosingClass(sym).getSimpleName().toString(); } else { // if we have a variable, just extract its name return ((IdentifierTree) expr).getName().toString(); } } default: return null; } } // TODO(cpovirk): Theoretically we'd want to handle byte, float, and short, too. private static final Matcher<Tree> NUMERIC_TIME_TYPE = anyOf( isSameType(INT_TYPE), isSameType(LONG_TYPE), isSameType(DOUBLE_TYPE), isSameType("java.lang.Integer"), isSameType("java.lang.Long"), isSameType("java.lang.Double")); @Nullable @VisibleForTesting static TimeUnit unitSuggestedByName(String name) { // Tuple types, especially Pair, trip us up. Skip APIs that might be from them. // This check is somewhat redundant with the "second" check below. // TODO(cpovirk): Skip APIs only if they're from a type that also declares a first/getFirst()? if (name.equals("second") || name.equals("getSecond")) { return null; } // http://grepcode.com/file/repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.33/com/mysql/jdbc/TimeUtil.java#336 if (name.equals("secondsPart")) { return NANOSECONDS; } // The name of a Google-internal method, but I see other methods with this name externally. if (name.equals("msToS")) { return SECONDS; } ImmutableList<String> words = fixUnitCamelCase(splitToLowercaseTerms(name)); // People use variable names like "firstTimestamp" and "secondTimestamp." // This check is somewhat redundant with the "second" check above. if (words.get(0).equals("second")) { return null; } /* * Sometimes people write a method like "fromNanos()." Whatever unit that might return, it's * very unlikely to be nanos, so we give up. */ if (hasNameOfFromUnits(words)) { return null; } /* * Sometimes people write "final int TWO_SECONDS = 2 * 1000." Whatever unit that might be in, * it's very unlikely to be seconds, so we give up. * * TODO(cpovirk): We could probably guess the unit correctly most of the time if we wanted. */ if (isNamedForNumberOfUnits(words)) { return null; } Set<TimeUnit> units = timeUnits(words); /* * TODO(cpovirk): If the name has multiple units, like "millisToNanos," attempt to determine * which is the output. We can look not only at the method name but also at its parameter: If * the parameter is named "millis," then the output is presumably nanos. */ return units.size() == 1 ? getOnlyElement(units) : null; } /** Returns true if the input looks like [from, seconds]. */ private static boolean hasNameOfFromUnits(List<String> words) { return words.size() == 2 && words.get(0).equals("from") && UNIT_FOR_SUFFIX.containsKey(words.get(1)); } /** Returns true if the input looks like [five, seconds]. */ private static boolean isNamedForNumberOfUnits(List<String> words) { return words.size() == 2 && NUMBER_WORDS.contains(words.get(0)) && UNIT_FOR_SUFFIX.containsKey(words.get(1)); } // TODO(cpovirk): Maybe there's some test we could use in ICU4J? RuleBasedNumberFormat.SPELLOUT? private static final ImmutableSet<String> NUMBER_WORDS = ImmutableSet.of( "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "twenty", "thirty", "forty", "fifty", "sixty"); /** * Converts "MS"/"MSec"/etc. to "Ms"/etc. and "microSeconds"/"MicroSeconds"/etc. to * "microseconds"/"Microseconds"/etc. */ private static ImmutableList<String> fixUnitCamelCase(List<String> words) { ImmutableList.Builder<String> out = ImmutableList.builderWithExpectedSize(words.size()); int i = 0; for (i = 0; i < words.size() - 1; i++) { String current = words.get(i); String next = words.get(i + 1); String together = current + next; if (UNIT_FOR_SUFFIX.containsKey(together)) { out.add(together); i++; // Move past `next`, as well. } else { out.add(current); } } if (i == words.size() - 1) { out.add(words.get(i)); } return out.build(); } private static ImmutableSet<TimeUnit> timeUnits(List<String> wordsLists) { return wordsLists.stream() .map(UNIT_FOR_SUFFIX::get) .filter(x -> x != null) .collect(toImmutableSet()); } // TODO(cpovirk): Unify with UNITS_TO_LOOK_FOR in other checkers. That also adds hours and days. // TODO(cpovirk): Maybe also add things like "weeks?" private static final ImmutableMap<String, TimeUnit> UNIT_FOR_SUFFIX = ImmutableMap.copyOf( new ImmutableSetMultimap.Builder<TimeUnit, String>() .putAll(SECONDS, "sec", "secs", "second", "seconds") .putAll( MILLISECONDS, // "milli", "millis", "mills", "ms", "msec", "msecs", "millisec", "millisecs", "millisecond", "milliseconds") // TODO(cpovirk): milis, milisecond, etc.? (i.e., misspellings) .putAll( MICROSECONDS, // "micro", "micros", "us", "usec", "usecs", "microsec", "microsecs", "microsecond", "microseconds") .putAll( NANOSECONDS, // "nano", "nanos", "ns", "nsec", "nsecs", "nanosec", "nanosecs", "nanosecond", "nanoseconds") .build() .inverse() .entries()); /** * {@link Description#NO_MATCH}, returned by all our {@code match*} methods because any matches * have already been reported by manual calls to {@link VisitorState#reportMatch}. */ private static final Description ANY_MATCHES_WERE_ALREADY_REPORTED = Description.NO_MATCH; private static final Supplier<Type> JAVA_UTIL_CONCURRENT_TIMEUNIT = VisitorState.memoize(state -> state.getTypeFromString("java.util.concurrent.TimeUnit")); }
22,895
40.403255
121
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JodaNewPeriod.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.time; 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.constructor; import static com.google.errorprone.matchers.Matchers.receiverOfInvocation; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isSameType; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.tools.javac.code.Symbol.MethodSymbol; import java.util.List; /** Match possibly incorrect use of Period to obtain a number of (e.g.) days between two dates. */ @BugPattern( summary = "This may have surprising semantics, e.g. new Period(LocalDate.parse(\"1970-01-01\"), " + "LocalDate.parse(\"1970-02-02\")).getDays() == 1, not 32.", severity = WARNING) public final class JodaNewPeriod extends BugChecker implements MethodInvocationTreeMatcher { private static final String READABLE_PARTIAL = "org.joda.time.ReadablePartial"; private static final String READABLE_INSTANT = "org.joda.time.ReadableInstant"; private static final Matcher<MethodInvocationTree> MATCHER = allOf( instanceMethod() .onDescendantOf("org.joda.time.Period") .namedAnyOf( "getMonths", "getWeeks", "getDays", "getHours", "getMinutes", "getSeconds"), receiverOfInvocation( anyOf( constructor().forClass("org.joda.time.Period").withParameters("long", "long"), constructor() .forClass("org.joda.time.Period") .withParameters(READABLE_PARTIAL, READABLE_PARTIAL), constructor() .forClass("org.joda.time.Period") .withParameters(READABLE_INSTANT, READABLE_INSTANT)))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return MATCHER.matches(tree, state) ? describeMatch(tree, generateFix(tree, state)) : Description.NO_MATCH; } private static SuggestedFix generateFix(MethodInvocationTree tree, VisitorState state) { NewClassTree receiver = (NewClassTree) getReceiver(tree); List<? extends ExpressionTree> arguments = receiver.getArguments(); MethodSymbol methodSymbol = getSymbol(receiver); String unit = ((MemberSelectTree) tree.getMethodSelect()).getIdentifier().toString().replace("get", ""); SuggestedFix.Builder fixBuilder = SuggestedFix.builder(); // new Period(long, long).getUnits() -> new Duration(long, long).getStandardUnits(); if (isSameType( state.getTypes().unboxedTypeOrType(methodSymbol.params().get(0).type), state.getSymtab().longType, state)) { String duration = SuggestedFixes.qualifyType(state, fixBuilder, "org.joda.time.Duration"); return fixBuilder .replace( tree, String.format( "new %s(%s, %s).getStandard%s()", duration, state.getSourceForNode(arguments.get(0)), state.getSourceForNode(arguments.get(1)), unit)) .build(); } // new Period(ReadableFoo, ReadableFoo).getUnits() -> Units.unitsBetween(RF, RF).getUnits(); String unitImport = SuggestedFixes.qualifyType(state, fixBuilder, "org.joda.time." + unit); return fixBuilder .replace( tree, String.format( "%s.%sBetween(%s, %s).get%s()", unitImport, unit.toLowerCase(), state.getSourceForNode(arguments.get(0)), state.getSourceForNode(arguments.get(1)), unit)) .build(); } }
5,210
42.789916
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JavaInstantGetSecondsGetNano.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.time.NearbyCallers.containsCallToSameReceiverNearby; import static com.google.errorprone.matchers.Matchers.allOf; 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; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** * This checker warns about calls to {@code instant.getNano()} without a corresponding "nearby" call * to {@code instant.getEpochSecond()}. * * @author kak@google.com (Kurt Alfred Kluever) */ @BugPattern( summary = "instant.getNano() only accesses the underlying nanosecond adjustment from the whole " + "second.", explanation = "If you call instant.getNano(), you must also call instant.getEpochSecond() in 'nearby' " + "code. If you are trying to convert this instant to nanoseconds, you probably meant " + "to use Instants.toEpochNanos(instant) instead.", severity = WARNING) public final class JavaInstantGetSecondsGetNano extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> GET_EPOCH_SECOND = instanceMethod().onExactClass("java.time.Instant").named("getEpochSecond"); private static final Matcher<ExpressionTree> GET_NANO = allOf( instanceMethod().onExactClass("java.time.Instant").named("getNano"), Matchers.not(Matchers.packageStartsWith("java."))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (GET_NANO.matches(tree, state)) { if (!containsCallToSameReceiverNearby( tree, GET_EPOCH_SECOND, state, /* checkProtoChains= */ false)) { return describeMatch(tree); } } return Description.NO_MATCH; } }
2,909
41.173913
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JodaConstructors.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.time; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.constructor; import static com.google.errorprone.matchers.Matchers.packageStartsWith; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; 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; /** * Check for calls to bad JodaTime constructors. * * <ul> * <li>{@code org.joda.time.Duration#Duration(long)} * <li>{@code org.joda.time.Instant#Instant()} * <li>{@code org.joda.time.Instant#Instant(long)} * <li>{@code org.joda.time.DateTime#DateTime()} * <li>{@code org.joda.time.DateTime#DateTime(org.joda.time.Chronology)} * <li>{@code org.joda.time.DateTime#DateTime(org.joda.time.DateTimeZone)} * </ul> */ @BugPattern( summary = "Use of certain JodaTime constructors are not allowed.", explanation = "Use JodaTime's static factories instead of the ambiguous constructors.", severity = WARNING) public final class JodaConstructors extends BugChecker implements NewClassTreeMatcher { private static final Matcher<ExpressionTree> SELF_USAGE = packageStartsWith("org.joda.time"); private static final Matcher<ExpressionTree> DURATION_CTOR = constructor().forClass("org.joda.time.Duration").withParameters("long"); private static final Matcher<ExpressionTree> INSTANT_CTOR_NO_ARG = constructor().forClass("org.joda.time.Instant").withNoParameters(); private static final Matcher<ExpressionTree> INSTANT_CTOR_LONG_ARG = constructor().forClass("org.joda.time.Instant").withParameters("long"); private static final Matcher<ExpressionTree> DATE_TIME_CTOR_NO_ARG = constructor().forClass("org.joda.time.DateTime").withNoParameters(); private static final Matcher<ExpressionTree> DATE_TIME_CTORS_ONE_ARG = anyOf( constructor() .forClass("org.joda.time.DateTime") .withParameters("org.joda.time.Chronology"), constructor() .forClass("org.joda.time.DateTime") .withParameters("org.joda.time.DateTimeZone")); @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { // Allow usage by JodaTime itself if (SELF_USAGE.matches(tree, state)) { return Description.NO_MATCH; } // ban new Duration(long) if (DURATION_CTOR.matches(tree, state)) { SuggestedFix fix = SuggestedFix.replace( getStartPosition(tree), getStartPosition(getOnlyElement(tree.getArguments())), state.getSourceForNode(tree.getIdentifier()) + ".millis("); return describeMatch(tree, fix); } // ban new Instant() if (INSTANT_CTOR_NO_ARG.matches(tree, state)) { SuggestedFix fix = SuggestedFix.replace(tree, getIdentifierSource(tree, state) + ".now()"); return describeMatch(tree, fix); } // ban new Instant(long) if (INSTANT_CTOR_LONG_ARG.matches(tree, state)) { SuggestedFix fix = SuggestedFix.replace( getStartPosition(tree), getStartPosition(getOnlyElement(tree.getArguments())), getIdentifierSource(tree, state) + ".ofEpochMilli("); return describeMatch(tree, fix); } // ban new DateTime() if (DATE_TIME_CTOR_NO_ARG.matches(tree, state)) { SuggestedFix fix = SuggestedFix.replace(tree, getIdentifierSource(tree, state) + ".now()"); return describeMatch(tree, fix); } // ban new DateTime(DateTimeZone) and new DateTime(Chronology) if (DATE_TIME_CTORS_ONE_ARG.matches(tree, state)) { SuggestedFix fix = SuggestedFix.replace( getStartPosition(tree), getStartPosition(getOnlyElement(tree.getArguments())), getIdentifierSource(tree, state) + ".now("); return describeMatch(tree, fix); } // otherwise, no match return Description.NO_MATCH; } private static String getIdentifierSource(NewClassTree tree, VisitorState state) { return state.getSourceForNode(tree.getIdentifier()); } }
5,251
38.787879
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/DurationToLongTimeUnit.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.staticMethod; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import com.google.common.base.Enums; import com.google.common.collect.ImmutableMap; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Type; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; /** * Reports an error when a Duration or Instant is incorrectly decomposed in order to call an API * which accepts a {@code <long, TimeUnit>} pair. */ @BugPattern( summary = "Unit mismatch when decomposing a Duration or Instant to call a <long, TimeUnit> API", severity = ERROR) // TODO(kak): we should probably rename this as it works for Instants/Timestamps too public final class DurationToLongTimeUnit extends BugChecker implements MethodInvocationTreeMatcher { private static final String JAVA_DURATION = "java.time.Duration"; private static final String JAVA_INSTANT = "java.time.Instant"; private static final String JAVA_DURATIONS = "com.google.common.time.Durations"; private static final String JAVA_INSTANTS = "com.google.common.time.Instants"; private static final String JODA_DURATION = "org.joda.time.Duration"; private static final String JODA_RDURATION = "org.joda.time.ReadableDuration"; private static final String JODA_RINSTANT = "org.joda.time.ReadableInstant"; private static final String PROTO_DURATION = "com.google.protobuf.Duration"; private static final String PROTO_TIMESTAMP = "com.google.protobuf.Timestamp"; private static final String TIME_UNIT = "java.util.concurrent.TimeUnit"; private static final ImmutableMap<Matcher<ExpressionTree>, TimeUnit> MATCHERS = new ImmutableMap.Builder<Matcher<ExpressionTree>, TimeUnit>() // JavaTime .put(instanceMethod().onExactClass(JAVA_DURATION).named("toNanos"), NANOSECONDS) .put(instanceMethod().onExactClass(JAVA_DURATION).named("toMillis"), MILLISECONDS) .put(instanceMethod().onExactClass(JAVA_DURATION).named("getSeconds"), SECONDS) .put(instanceMethod().onExactClass(JAVA_DURATION).named("toMinutes"), MINUTES) .put(instanceMethod().onExactClass(JAVA_DURATION).named("toHours"), HOURS) .put(instanceMethod().onExactClass(JAVA_DURATION).named("toDays"), DAYS) .put(instanceMethod().onExactClass(JAVA_INSTANT).named("toEpochMilli"), MILLISECONDS) .put(instanceMethod().onExactClass(JAVA_INSTANT).named("getEpochSecond"), SECONDS) // com.google.common.time APIs .put(staticMethod().onClass(JAVA_DURATIONS).named("toNanosSaturated"), NANOSECONDS) .put(staticMethod().onClass(JAVA_DURATIONS).named("toMicros"), MICROSECONDS) .put(staticMethod().onClass(JAVA_DURATIONS).named("toMicrosSaturated"), MICROSECONDS) .put(staticMethod().onClass(JAVA_DURATIONS).named("toMillisSaturated"), MILLISECONDS) .put(staticMethod().onClass(JAVA_INSTANTS).named("toEpochNanos"), NANOSECONDS) .put(staticMethod().onClass(JAVA_INSTANTS).named("toEpochNanosSaturated"), NANOSECONDS) .put(staticMethod().onClass(JAVA_INSTANTS).named("toEpochMicros"), MICROSECONDS) .put(staticMethod().onClass(JAVA_INSTANTS).named("toEpochMicrosSaturated"), MICROSECONDS) .put(staticMethod().onClass(JAVA_INSTANTS).named("toEpochMillisSaturated"), MILLISECONDS) // JodaTime .put(instanceMethod().onExactClass(JODA_DURATION).named("getStandardSeconds"), SECONDS) .put(instanceMethod().onExactClass(JODA_DURATION).named("getStandardMinutes"), MINUTES) .put(instanceMethod().onExactClass(JODA_DURATION).named("getStandardHours"), HOURS) .put(instanceMethod().onExactClass(JODA_DURATION).named("getStandardDays"), DAYS) .put(instanceMethod().onDescendantOf(JODA_RDURATION).named("getMillis"), MILLISECONDS) .put(instanceMethod().onDescendantOf(JODA_RINSTANT).named("getMillis"), MILLISECONDS) // ProtoTime .put(instanceMethod().onExactClass(PROTO_DURATION).named("getSeconds"), SECONDS) .put(instanceMethod().onExactClass(PROTO_TIMESTAMP).named("getSeconds"), SECONDS) .buildOrThrow(); private static final Matcher<ExpressionTree> TIME_UNIT_DECOMPOSITION = instanceMethod().onExactClass(TIME_UNIT).named("convert").withParameters(JAVA_DURATION); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { List<? extends ExpressionTree> arguments = tree.getArguments(); if (arguments.size() >= 2) { // TODO(kak): Do we want to check varargs as well? Type longType = state.getSymtab().longType; Type timeUnitType = JAVA_UTIL_CONCURRENT_TIMEUNIT.get(state); for (int i = 0; i < arguments.size() - 1; i++) { ExpressionTree arg0 = arguments.get(i); ExpressionTree timeUnitTree = arguments.get(i + 1); Type type0 = ASTHelpers.getType(arg0); Type type1 = ASTHelpers.getType(timeUnitTree); if (ASTHelpers.isSameType(type0, longType, state) && ASTHelpers.isSameType(type1, timeUnitType, state)) { Optional<TimeUnit> timeUnitInArgument = getTimeUnit(timeUnitTree); if (timeUnitInArgument.isPresent()) { for (Map.Entry<Matcher<ExpressionTree>, TimeUnit> entry : MATCHERS.entrySet()) { TimeUnit timeUnitExpressedInConversion = entry.getValue(); if (entry.getKey().matches(arg0, state) && timeUnitInArgument.get() != timeUnitExpressedInConversion) { return describeTimeUnitConversionFix( tree, timeUnitTree, timeUnitExpressedInConversion); } } // Look for TimeUnit.convert(Duration), dynamically looking for the source time unit // to convert from. if (TIME_UNIT_DECOMPOSITION.matches(arg0, state)) { Optional<TimeUnit> sourceTimeUnit = getTimeUnit(ASTHelpers.getReceiver(arg0)); if (sourceTimeUnit.isPresent() && !sourceTimeUnit.get().equals(timeUnitInArgument.get())) { return describeTimeUnitConversionFix(tree, timeUnitTree, sourceTimeUnit.get()); } } } } } } return Description.NO_MATCH; } private Description describeTimeUnitConversionFix( MethodInvocationTree tree, ExpressionTree timeUnitTree, TimeUnit timeUnitExpressedInConversion) { SuggestedFix fix = SuggestedFix.builder() // TODO(kak): Do we want to use static imports here? .addImport(TIME_UNIT) .replace(timeUnitTree, "TimeUnit." + timeUnitExpressedInConversion) .build(); return describeMatch(tree, fix); } /** * Given that this ExpressionTree's type is a {@link java.util.concurrent.TimeUnit}, return the * TimeUnit it likely represents. */ static Optional<TimeUnit> getTimeUnit(ExpressionTree timeUnit) { if (timeUnit instanceof IdentifierTree) { // e.g., SECONDS return Enums.getIfPresent(TimeUnit.class, ((IdentifierTree) timeUnit).getName().toString()) .toJavaUtil(); } if (timeUnit instanceof MemberSelectTree) { // e.g., TimeUnit.SECONDS return Enums.getIfPresent( TimeUnit.class, ((MemberSelectTree) timeUnit).getIdentifier().toString()) .toJavaUtil(); } return Optional.empty(); } private static final Supplier<Type> JAVA_UTIL_CONCURRENT_TIMEUNIT = VisitorState.memoize(state -> state.getTypeFromString(TIME_UNIT)); }
9,392
48.962766
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/DurationTemporalUnit.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.time; import static com.google.common.collect.Sets.toImmutableEnumSet; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.bugpatterns.time.DurationGetTemporalUnit.getInvalidChronoUnit; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import java.time.temporal.ChronoUnit; import java.util.Arrays; /** * Bans calls to {@code Duration} APIs where the {@link java.time.temporal.TemporalUnit} is not * {@link ChronoUnit#DAYS} or it has an estimated duration (which is guaranteed to throw an {@code * DateTimeException}). */ @BugPattern( summary = "Duration APIs only work for DAYS or exact durations.", explanation = "Duration APIs only work for TemporalUnits with exact durations or" + " ChronoUnit.DAYS. E.g., Duration.of(1, ChronoUnit.YEARS) is guaranteed to throw a" + " DateTimeException.", severity = ERROR) public final class DurationTemporalUnit extends BugChecker implements MethodInvocationTreeMatcher { private static final String DURATION = "java.time.Duration"; private static final String TEMPORAL_UNIT = "java.time.temporal.TemporalUnit"; private static final Matcher<ExpressionTree> DURATION_OF_LONG_TEMPORAL_UNIT = allOf( anyOf( staticMethod().onClass(DURATION).named("of").withParameters("long", TEMPORAL_UNIT), instanceMethod() .onExactClass(DURATION) .named("minus") .withParameters("long", TEMPORAL_UNIT), instanceMethod() .onExactClass(DURATION) .named("plus") .withParameters("long", TEMPORAL_UNIT)), Matchers.not(Matchers.packageStartsWith("java."))); private static final ImmutableSet<ChronoUnit> INVALID_TEMPORAL_UNITS = Arrays.stream(ChronoUnit.values()) .filter(c -> c.isDurationEstimated()) .filter(c -> !c.equals(ChronoUnit.DAYS)) // DAYS is explicitly allowed .collect(toImmutableEnumSet()); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (DURATION_OF_LONG_TEMPORAL_UNIT.matches(tree, state)) { if (getInvalidChronoUnit(tree.getArguments().get(1), INVALID_TEMPORAL_UNITS).isPresent()) { return describeMatch(tree); } } return Description.NO_MATCH; } }
3,791
43.093023
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/ProtoTimestampGetSecondsGetNano.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.time.NearbyCallers.containsCallToSameReceiverNearby; 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; 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; /** * This checker warns about accessing the underlying nanosecond-adjustment field of a protobuf * timestamp without a "nearby" access of the underlying seconds field. * * @author kak@google.com (Kurt Alfred Kluever) */ @BugPattern( summary = "getNanos() only accesses the underlying nanosecond-adjustment of the instant.", explanation = "If you call timestamp.getNanos(), you must also call timestamp.getSeconds() in 'nearby' " + "code. If you are trying to convert this timestamp to nanoseconds, " + "you probably meant to use Timestamps.toNanos(timestamp) instead.", severity = WARNING) public final class ProtoTimestampGetSecondsGetNano extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> GET_SECONDS = instanceMethod().onExactClass("com.google.protobuf.Timestamp").named("getSeconds"); private static final Matcher<ExpressionTree> GET_NANOS = instanceMethod().onExactClass("com.google.protobuf.Timestamp").named("getNanos"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (GET_NANOS.matches(tree, state)) { if (!containsCallToSameReceiverNearby( tree, GET_SECONDS, state, /* checkProtoChains= */ true)) { return describeMatch(tree); } } return Description.NO_MATCH; } }
2,725
42.269841
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/StronglyTypeTime.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.constructor; import static com.google.errorprone.matchers.Matchers.staticMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher; import com.google.errorprone.bugpatterns.StronglyType; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import java.util.regex.Pattern; /** Flags fields which would be better expressed as time types rather than primitive integers. */ @BugPattern( summary = "This primitive integral type is only used to construct time types. It would be clearer to" + " strongly type the field instead.", severity = WARNING) public final class StronglyTypeTime extends BugChecker implements CompilationUnitTreeMatcher { private static final Matcher<ExpressionTree> TIME_FACTORY = anyOf( // Java time. staticMethod() .onClass("java.time.Duration") .namedAnyOf("ofNanos", "ofMillis", "ofSeconds", "ofMinutes", "ofHours", "ofDays") .withParameters("long"), staticMethod() .onClass("java.time.Instant") .namedAnyOf("ofEpochMilli", "ofEpochSecond") .withParameters("long"), // Proto time. staticMethod() .onClass("com.google.protobuf.util.Timestamps") .namedAnyOf("fromNanos", "fromMicros", "fromMillis", "fromSeconds"), staticMethod() .onClass("com.google.protobuf.util.Durations") .namedAnyOf( "fromNanos", "fromMicros", "fromMillis", "fromSeconds", "fromMinutes", "fromHours", "fromDays"), // Joda time. staticMethod() .onClass("org.joda.time.Duration") .namedAnyOf( "millis", "standardSeconds", "standardMinutes", "standardHours", "standardDays") .withParameters("long"), constructor().forClass("org.joda.time.Instant").withParameters("long"), staticMethod() .onClass("org.joda.time.Instant") .namedAnyOf("ofEpochMilli", "ofEpochSecond") .withParameters("long"), constructor().forClass("org.joda.time.DateTime").withParameters("long")); private static final Pattern TIME_UNIT_REMOVER = Pattern.compile( "((_?IN)?_?(NANO|NANOSECOND|NSEC|_NS|MICRO|MSEC|USEC|MICROSECOND|MILLI|MILLISECOND|_MS|SEC|SECOND|MINUTE|MIN|HOUR|DAY)S?)?$", Pattern.CASE_INSENSITIVE); @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { return StronglyType.forCheck(this) .addType(state.getSymtab().intType) .addType(state.getSymtab().longType) .addType(state.getSymtab().floatType) .addType(state.getSymtab().doubleType) .setFactoryMatcher(TIME_FACTORY) .setRenameFunction(StronglyTypeTime::createNewName) .build() .match(tree, state); } /** Tries to strip any time-related suffix off the field name. */ private static final String createNewName(String fieldName) { String newName = TIME_UNIT_REMOVER.matcher(fieldName).replaceAll(""); // Guard against field names that *just* contain the unit. Not much we can do here. return newName.isEmpty() ? fieldName : newName; } }
4,492
41.790476
135
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JodaPlusMinusLong.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.matchers.method.MethodMatchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import java.util.ArrayList; import java.util.List; /** * Check for calls to JodaTime's {@code type.plus(long)} and {@code type.minus(long)} where {@code * <type> = {Duration,Instant,DateTime,DateMidnight}}. */ @BugPattern( summary = "Use of JodaTime's type.plus(long) or type.minus(long) is not allowed (where <type> = " + "{Duration,Instant,DateTime,DateMidnight}). Please use " + "type.plus(Duration.millis(long)) or type.minus(Duration.millis(long)) instead.", explanation = "JodaTime's type.plus(long) and type.minus(long) methods are often a source of bugs " + "because the units of the parameters are ambiguous. Please use " + "type.plus(Duration.millis(long)) or type.minus(Duration.millis(long)) instead.", severity = WARNING) public final class JodaPlusMinusLong extends BugChecker implements MethodInvocationTreeMatcher { private static final ImmutableSet<String> TYPES = ImmutableSet.of("DateMidnight", "DateTime", "Duration", "Instant"); private static final ImmutableSet<String> METHODS = ImmutableSet.of("plus", "minus"); private static final Matcher<ExpressionTree> MATCHER = Matchers.allOf( buildMatcher(), // Allow usage by JodaTime itself Matchers.not(Matchers.packageStartsWith("org.joda.time"))); private static final Matcher<ExpressionTree> DURATION_GET_MILLIS_MATCHER = MethodMatchers.instanceMethod() .onDescendantOf("org.joda.time.ReadableDuration") .named("getMillis"); private static Matcher<ExpressionTree> buildMatcher() { List<Matcher<ExpressionTree>> matchers = new ArrayList<>(); for (String type : TYPES) { for (String method : METHODS) { matchers.add( Matchers.instanceMethod() .onExactClass("org.joda.time." + type) .named(method) .withParameters("long")); } } return Matchers.anyOf(matchers); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return Description.NO_MATCH; } SuggestedFix.Builder builder = SuggestedFix.builder(); ExpressionTree firstArgumentTree = tree.getArguments().get(0); String firstArgumentReplacement; if (DURATION_GET_MILLIS_MATCHER.matches(firstArgumentTree, state)) { // This is passing {@code someDuration.getMillis()} as the parameter. we can replace this // with {@code someDuration}. firstArgumentReplacement = state.getSourceForNode(ASTHelpers.getReceiver(firstArgumentTree)); } else { // Wrap the long as a Duration. firstArgumentReplacement = SuggestedFixes.qualifyType(state, builder, "org.joda.time.Duration") + ".millis(" + state.getSourceForNode(firstArgumentTree) + ")"; } builder.replace(firstArgumentTree, firstArgumentReplacement); return describeMatch(tree, builder.build()); } }
4,482
40.12844
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/PreferJavaTimeOverload.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.constructor; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasOverloadWithOnlyOneParameter; import static com.google.errorprone.util.ASTHelpers.isSameType; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import com.google.common.collect.ImmutableMap; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import javax.inject.Inject; /** This check suggests the use of {@code java.time}-based APIs, when available. */ @BugPattern( altNames = {"PreferDurationOverload"}, summary = "Prefer using java.time-based APIs when available. Note that this checker does" + " not and cannot guarantee that the overloads have equivalent semantics, but that is" + " generally the case with overloaded methods.", severity = WARNING) public final class PreferJavaTimeOverload extends BugChecker implements MethodInvocationTreeMatcher { private static final String JAVA_DURATION = "java.time.Duration"; private static final String JODA_DURATION = "org.joda.time.Duration"; private static final ImmutableMap<Matcher<ExpressionTree>, TimeUnit> JODA_DURATION_FACTORY_MATCHERS = new ImmutableMap.Builder<Matcher<ExpressionTree>, TimeUnit>() .put(constructor().forClass(JODA_DURATION).withParameters("long"), MILLISECONDS) .put(staticMethod().onClass(JODA_DURATION).named("millis"), MILLISECONDS) .put(staticMethod().onClass(JODA_DURATION).named("standardSeconds"), SECONDS) .put(staticMethod().onClass(JODA_DURATION).named("standardMinutes"), MINUTES) .put(staticMethod().onClass(JODA_DURATION).named("standardHours"), HOURS) .put(staticMethod().onClass(JODA_DURATION).named("standardDays"), DAYS) .buildOrThrow(); private static final ImmutableMap<TimeUnit, String> TIMEUNIT_TO_DURATION_FACTORY = new ImmutableMap.Builder<TimeUnit, String>() .put(NANOSECONDS, "%s.ofNanos(%s)") .put(MICROSECONDS, "%s.of(%s, %s)") .put(MILLISECONDS, "%s.ofMillis(%s)") .put(SECONDS, "%s.ofSeconds(%s)") .put(MINUTES, "%s.ofMinutes(%s)") .put(HOURS, "%s.ofHours(%s)") .put(DAYS, "%s.ofDays(%s)") .buildOrThrow(); private static final String JAVA_INSTANT = "java.time.Instant"; private static final String JODA_INSTANT = "org.joda.time.Instant"; private static final Matcher<ExpressionTree> JODA_INSTANT_CONSTRUCTOR_MATCHER = constructor().forClass(JODA_INSTANT).withParameters("long"); private static final String TIME_SOURCE = "com.google.common.time.TimeSource"; private static final String JODA_CLOCK = "com.google.common.time.Clock"; private static final String JAVA_TIME_CONVERSIONS = "com.google.thirdparty.jodatime.JavaTimeConversions"; private static final Matcher<ExpressionTree> TO_JODA_DURATION = staticMethod().onClass(JAVA_TIME_CONVERSIONS).named("toJodaDuration"); private static final Matcher<ExpressionTree> TO_JODA_INSTANT = staticMethod().onClass(JAVA_TIME_CONVERSIONS).named("toJodaInstant"); private static final Matcher<ExpressionTree> IGNORED_APIS = anyOf( staticMethod().onClass("org.jooq.impl.DSL").withAnyName(), // any static method under org.assertj.* staticMethod() .onClass((type, state) -> type.toString().startsWith("org.assertj.")) .withAnyName(), // any instance method on Reactor's Flux API instanceMethod().onDescendantOf("reactor.core.publisher.Flux").withAnyName()); private static final Matcher<ExpressionTree> JAVA_DURATION_DECOMPOSITION_MATCHER = instanceMethod() .onExactClass(JAVA_DURATION) .namedAnyOf("toNanos", "toMillis", "getSeconds", "toMinutes", "toHours", "toDays"); private final boolean hasJava8LibSupport; @Inject PreferJavaTimeOverload(ErrorProneFlags flags) { this.hasJava8LibSupport = flags.getBoolean("Android:Java8Libs").orElse(false); } // TODO(kak): Add support for constructors that accept a <long, TimeUnit> or JodaTime Duration @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { // don't fire for Android code that doesn't have Java8 library support (b/138965731) if (state.isAndroidCompatible() && !hasJava8LibSupport) { return Description.NO_MATCH; } // we return no match for a set of explicitly ignored APIs if (IGNORED_APIS.matches(tree, state)) { return Description.NO_MATCH; } List<? extends ExpressionTree> arguments = tree.getArguments(); // TODO(glorioso): Add support for methods with > 2 parameters. E.g., // foo(String, long, TimeUnit, Frobber) -> foo(String, Duration, Frobber) if (isNumericMethodCall(tree, state)) { if (hasJavaTimeOverload(tree, JAVA_DURATION_TYPE.get(state), state)) { return buildDescriptionForNumericPrimitive(tree, state, arguments, "Duration"); } if (hasJavaTimeOverload(tree, JAVA_INSTANT_TYPE.get(state), state)) { return buildDescriptionForNumericPrimitive(tree, state, arguments, "Instant"); } } if (isLongTimeUnitMethodCall(tree, state)) { Optional<TimeUnit> optionalTimeUnit = DurationToLongTimeUnit.getTimeUnit(arguments.get(1)); if (optionalTimeUnit.isPresent()) { if (hasJavaTimeOverload(tree, JAVA_DURATION_TYPE.get(state), state)) { String durationFactory = TIMEUNIT_TO_DURATION_FACTORY.get(optionalTimeUnit.get()); if (durationFactory != null) { SuggestedFix.Builder fix = SuggestedFix.builder(); String qualifiedDuration = SuggestedFixes.qualifyType(state, fix, JAVA_DURATION); String value = state.getSourceForNode(arguments.get(0)); String replacement = null; // rewrite foo(javaDuration.getSeconds(), SECONDS) -> foo(javaDuration) if (arguments.get(0) instanceof MethodInvocationTree) { MethodInvocationTree maybeDurationDecomposition = (MethodInvocationTree) arguments.get(0); if (JAVA_DURATION_DECOMPOSITION_MATCHER.matches(maybeDurationDecomposition, state)) { if (isSameType( ASTHelpers.getReceiverType(maybeDurationDecomposition), JAVA_DURATION_TYPE.get(state), state)) { replacement = state.getSourceForNode(ASTHelpers.getReceiver(maybeDurationDecomposition)); } } } // handle microseconds separately, since there is no Duration factory for micros if (optionalTimeUnit.get() == MICROSECONDS) { String qualifiedChronoUnit = SuggestedFixes.qualifyType(state, fix, "java.time.temporal.ChronoUnit"); replacement = String.format( durationFactory, qualifiedDuration, value, qualifiedChronoUnit + ".MICROS"); } // Otherwise, just use the normal replacement if (replacement == null) { replacement = String.format(durationFactory, qualifiedDuration, value); } fix.replace( getStartPosition(arguments.get(0)), state.getEndPosition(arguments.get(1)), replacement); return describeMatch(tree, fix.build()); } } } } if (isMethodCallWithSingleParameter(tree, state, "org.joda.time.ReadableDuration")) { ExpressionTree arg0 = arguments.get(0); if (hasJavaTimeOverload(tree, JAVA_DURATION_TYPE.get(state), state)) { SuggestedFix.Builder fix = SuggestedFix.builder(); // TODO(kak): Maybe only emit a match if Duration doesn't have to be fully qualified? String qualifiedDuration = SuggestedFixes.qualifyType(state, fix, JAVA_DURATION); // TODO(kak): Add support for org.joda.time.Duration.ZERO -> java.time.Duration.ZERO // If the Joda Duration is being constructed inline, then unwrap it. for (Map.Entry<Matcher<ExpressionTree>, TimeUnit> entry : JODA_DURATION_FACTORY_MATCHERS.entrySet()) { if (entry.getKey().matches(arg0, state)) { String value = null; if (arg0 instanceof MethodInvocationTree) { MethodInvocationTree jodaDurationCreation = (MethodInvocationTree) arg0; value = state.getSourceForNode(jodaDurationCreation.getArguments().get(0)); } if (arg0 instanceof NewClassTree) { NewClassTree jodaDurationCreation = (NewClassTree) arg0; value = state.getSourceForNode(jodaDurationCreation.getArguments().get(0)); } if (value != null) { String durationFactory = TIMEUNIT_TO_DURATION_FACTORY.get(entry.getValue()); if (durationFactory != null) { String replacement = String.format(durationFactory, qualifiedDuration, value); fix.replace(arg0, replacement); return describeMatch(tree, fix.build()); } } } } // If we're converting to a JodaTime Duration (from a java.time Duration) to call the // JodaTime overload, just unwrap it! if (TO_JODA_DURATION.matches(arg0, state)) { fix.replace( arg0, state.getSourceForNode(((MethodInvocationTree) arg0).getArguments().get(0))); return describeMatch(tree, fix.build()); } fix.replace( arg0, String.format( "%s.ofMillis(%s.getMillis())", qualifiedDuration, state.getSourceForNode(arg0))); return describeMatch(tree, fix.build()); } } if (isMethodCallWithSingleParameter(tree, state, "org.joda.time.ReadableInstant")) { ExpressionTree arg0 = arguments.get(0); if (hasJavaTimeOverload(tree, JAVA_INSTANT_TYPE.get(state), state)) { SuggestedFix.Builder fix = SuggestedFix.builder(); // TODO(kak): Maybe only emit a match if Instant doesn't have to be fully qualified? String qualifiedInstant = SuggestedFixes.qualifyType(state, fix, JAVA_INSTANT); // TODO(kak): Add support for org.joda.time.Instant.EPOCH -> java.time.Instant.EPOCH // If the Joda Instant is being constructed inline, then unwrap it. if (JODA_INSTANT_CONSTRUCTOR_MATCHER.matches(arg0, state)) { if (arg0 instanceof NewClassTree) { NewClassTree jodaInstantCreation = (NewClassTree) arg0; String value = state.getSourceForNode(jodaInstantCreation.getArguments().get(0)); fix.replace(arg0, String.format("%s.ofEpochMilli(%s)", qualifiedInstant, value)); return describeMatch(tree, fix.build()); } } // If we're converting to a JodaTime Instant (from a java.time Instant) to call the JodaTime // overload, just unwrap it! if (TO_JODA_INSTANT.matches(arg0, state)) { fix.replace( arg0, state.getSourceForNode(((MethodInvocationTree) arg0).getArguments().get(0))); return describeMatch(tree, fix.build()); } fix.replace( arg0, String.format( "%s.ofEpochMilli(%s.getMillis())", qualifiedInstant, state.getSourceForNode(arg0))); return describeMatch(tree, fix.build()); } } return Description.NO_MATCH; } private Description buildDescriptionForNumericPrimitive( MethodInvocationTree tree, VisitorState state, List<? extends ExpressionTree> arguments, String javaTimeType) { // we don't know what units to use, but we can still warn the user! return buildDescription(tree) .setMessage( String.format( "If the numeric primitive (%s) represents a %s, please call %s(%s) instead.", state.getSourceForNode(arguments.get(0)), javaTimeType, state.getSourceForNode(tree.getMethodSelect()), javaTimeType)) .build(); } private static boolean isNumericMethodCall(MethodInvocationTree tree, VisitorState state) { List<VarSymbol> params = getSymbol(tree).getParameters(); if (params.size() == 1) { Type type0 = params.get(0).asType(); return isSameType(type0, state.getSymtab().intType, state) || isSameType(type0, state.getSymtab().longType, state) || isSameType(type0, state.getSymtab().doubleType, state); } return false; } private static boolean isMethodCallWithSingleParameter( MethodInvocationTree tree, VisitorState state, String typeName) { Type type = state.getTypeFromString(typeName); List<VarSymbol> params = getSymbol(tree).getParameters(); return (params.size() == 1) && isSubtype(params.get(0).asType(), type, state); } private static boolean isLongTimeUnitMethodCall(MethodInvocationTree tree, VisitorState state) { Type longType = state.getSymtab().longType; Type timeUnitType = TIME_UNIT_TYPE.get(state); List<VarSymbol> params = getSymbol(tree).getParameters(); if (params.size() == 2) { return isSameType(params.get(0).asType(), longType, state) && isSameType(params.get(1).asType(), timeUnitType, state); } return false; } private static boolean hasJavaTimeOverload( MethodInvocationTree tree, Type type, VisitorState state) { MethodSymbol calledMethod = getSymbol(tree); return hasOverloadWithOnlyOneParameter(calledMethod, calledMethod.name, type, state); } private static boolean hasTimeSourceMethod(MethodInvocationTree tree, VisitorState state) { MethodSymbol calledMethod = getSymbol(tree); String timeSourceBasedName = calledMethod.name.toString().replace("Clock", "TimeSource"); return hasOverloadWithOnlyOneParameter( calledMethod, state.getName(timeSourceBasedName), TIME_SOURCE_TYPE.get(state), state); } private static final Supplier<Type> JAVA_DURATION_TYPE = VisitorState.memoize(state -> state.getTypeFromString(JAVA_DURATION)); private static final Supplier<Type> JAVA_INSTANT_TYPE = VisitorState.memoize(state -> state.getTypeFromString(JAVA_INSTANT)); private static final Supplier<Type> TIME_UNIT_TYPE = VisitorState.memoize(state -> state.getTypeFromString("java.util.concurrent.TimeUnit")); private static final Supplier<Type> TIME_SOURCE_TYPE = VisitorState.memoize(state -> state.getTypeFromString(TIME_SOURCE)); }
17,037
44.678284
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JavaDurationGetSecondsGetNano.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.time.NearbyCallers.containsCallToSameReceiverNearby; import static com.google.errorprone.matchers.Matchers.allOf; 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; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** * This checker warns about calls to {@code duration.getNano()} without a corresponding "nearby" * call to {@code duration.getSeconds()}. * * @author kak@google.com (Kurt Alfred Kluever) */ @BugPattern( summary = "duration.getNano() only accesses the underlying nanosecond adjustment from the whole " + "second.", explanation = "If you call duration.getNano(), you must also call duration.getSeconds() in 'nearby' code." + " If you are trying to convert this duration to nanoseconds, you probably meant to" + " use duration.toNanos() instead.", severity = WARNING) public final class JavaDurationGetSecondsGetNano extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> GET_SECONDS = instanceMethod().onExactClass("java.time.Duration").named("getSeconds"); private static final Matcher<ExpressionTree> GET_NANO = allOf( instanceMethod().onExactClass("java.time.Duration").named("getNano"), Matchers.not(Matchers.packageStartsWith("java."))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (GET_NANO.matches(tree, state)) { if (!containsCallToSameReceiverNearby( tree, GET_SECONDS, state, /* checkProtoChains= */ false)) { return describeMatch(tree); } } return Description.NO_MATCH; } }
2,884
40.811594
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/NearbyCallers.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.time; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import com.google.common.collect.ImmutableList; import com.google.errorprone.VisitorState; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.google.protobuf.GeneratedMessage; import com.google.protobuf.GeneratedMessageLite; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import java.util.Optional; import java.util.regex.Pattern; /** * Utility class to find calls "nearby" other calls. * * <p>TODO(glorioso): Coalesce this with ByteBufferBackingArray since they have similar aims? */ public class NearbyCallers { private NearbyCallers() {} // lifted from com.google.devtools.javatools.refactory.refaster.cleanups.proto.ProtoMatchers private static final Matcher<ExpressionTree> IS_IMMUTABLE_PROTO_GETTER = instanceMethod() .onDescendantOfAny(GeneratedMessage.class.getName(), GeneratedMessageLite.class.getName()) .withNameMatching(Pattern.compile("get(?!CachedSize$|SerializedSize$).+")) .withNoParameters(); /** * Returns whether or not there is a call matching {@code secondaryMethodMatcher} with the same * receiver as the method call represented by {@code primaryMethod} in "nearby" code. * * <p>This is generally used to ensure that developers calling {@code primaryMethod} should likely * also be checking {@code secondaryMethodMatcher} (as a signal that they understand the * edge-cases of {@code primaryMethod}). * * @param primaryMethod the tree that contains the primary method call (e.g.: what might have * weird edge-cases). * @param secondaryMethodMatcher A matcher to identify the secondary method call (e.g.: that shows * a demonstration of the knowledge of the edge-cases in {@code primaryMethod}) * @param state the visitor state of this matcher * @param checkProtoChains whether or not to check a chain of protobuf getter methods to see if * it's the 'same receiver' (e.g., {@code a.getB().getC().getSeconds()} and {@code * a.getB().getC().getNanos()} */ static boolean containsCallToSameReceiverNearby( MethodInvocationTree primaryMethod, Matcher<ExpressionTree> secondaryMethodMatcher, VisitorState state, boolean checkProtoChains) { ExpressionTree primaryMethodReceiver = ASTHelpers.getReceiver(primaryMethod); TreeScanner<Boolean, Void> scanner = new TreeScanner<Boolean, Void>() { @Override public Boolean reduce(Boolean r1, Boolean r2) { return firstNonNull(r1, Boolean.FALSE) || firstNonNull(r2, Boolean.FALSE); } @Override public Boolean visitLambdaExpression(LambdaExpressionTree node, Void unused) { return false; } @Override public Boolean visitMethodInvocation(MethodInvocationTree secondaryMethod, Void unused) { if (super.visitMethodInvocation(secondaryMethod, unused)) { return true; } if (secondaryMethod == null || !secondaryMethodMatcher.matches(secondaryMethod, state)) { return false; } ExpressionTree secondaryMethodReceiver = ASTHelpers.getReceiver(secondaryMethod); if (secondaryMethodReceiver == null) { return false; } // if the methods are being invoked directly on the same variable... if (primaryMethodReceiver != null && ASTHelpers.sameVariable(primaryMethodReceiver, secondaryMethodReceiver)) { return true; } // If we're checking proto chains, look for the root variables and see if they're the // same. return checkProtoChains && protoChainsMatch(primaryMethod, secondaryMethod); } private boolean protoChainsMatch( MethodInvocationTree primaryMethod, MethodInvocationTree secondaryMethod) { ExpressionTree primaryRootAssignable = ASTHelpers.getRootAssignable(primaryMethod); ExpressionTree secondaryRootAssignable = ASTHelpers.getRootAssignable(secondaryMethod); if (primaryRootAssignable == null || secondaryRootAssignable == null || !ASTHelpers.sameVariable(primaryRootAssignable, secondaryRootAssignable)) { return false; } // build up a list of method invocations for both invocations return buildProtoGetterChain(primaryMethod, state) .flatMap( primaryChain -> buildProtoGetterChain(secondaryMethod, state).map(primaryChain::equals)) .orElse(false); } }; ImmutableList<Tree> treesToScan = getNearbyTreesToScan(state); return !treesToScan.isEmpty() && scanner.scan(treesToScan, null); } // Return the chain of receivers from expr (intended to be a MethodInvocation) so long // as it's entirely composed of proto getters, followed by a terminal identifier, e.g.: // // FooProto x = ...; // String value = x.getA().getB().getC().expr() // // the chain would be [getC(), getB(), getA(), x] private static Optional<ImmutableList<Symbol>> buildProtoGetterChain( ExpressionTree expr, VisitorState state) { ImmutableList.Builder<Symbol> symbolChain = ImmutableList.builder(); while (expr instanceof JCMethodInvocation) { expr = ((JCMethodInvocation) expr).getMethodSelect(); // if the method isn't an immutable protobuf getter, return false if (!IS_IMMUTABLE_PROTO_GETTER.matches(expr, state)) { return Optional.empty(); } if (expr instanceof JCFieldAccess) { expr = ((JCFieldAccess) expr).getExpression(); } symbolChain.add(ASTHelpers.getSymbol(expr)); } return Optional.of(symbolChain.build()); } private static ImmutableList<Tree> getNearbyTreesToScan(VisitorState state) { for (Tree parent : state.getPath()) { switch (parent.getKind()) { case BLOCK: // if we reach a block tree, then _only_ scan that block return ImmutableList.of(parent); case LAMBDA_EXPRESSION: // if we reach a lambda tree, then don't scan anything since we don't know where/when that // lambda will actually be executed. // TODO(glorioso): for simple expression lambdas, consider looking for use sites and scan // *those* sites, but binding the lambda variable to its use site might be rough :( // e.g.: // Function<Duration, Long> NANOS = d -> d.getNano(); // Function<Duration, Long> SECONDS = d -> d.getSeconds(); // ... // long nanos = NANOS.apply(myDuration) + SECONDS.apply(myDuration) * 1_000_000L; // // how do we track myDuration through both layers? return ImmutableList.of(); case CLASS: // if we get all the way up to the class tree, then _only_ scan the other class-level // fields ImmutableList.Builder<Tree> treesToScan = ImmutableList.builder(); for (Tree member : ((ClassTree) parent).getMembers()) { if (member instanceof VariableTree) { ExpressionTree expressionTree = ((VariableTree) member).getInitializer(); if (expressionTree != null) { treesToScan.add(expressionTree); } } } return treesToScan.build(); default: // fall out, continue searching up the tree } } return ImmutableList.of(); } }
8,829
42.073171
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/ZoneIdOfZ.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; 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.not; import static com.google.errorprone.matchers.Matchers.packageStartsWith; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.constValue; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; 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; /** * This checker bans calls to {@code ZoneId.of("Z")} in favor of {@link java.time.ZoneOffset#UTC}. * * @author kak@google.com (Kurt Alfred Kluever) */ @BugPattern( summary = "Use ZoneOffset.UTC instead of ZoneId.of(\"Z\").", explanation = "Avoid the magic constant (ZoneId.of(\"Z\")) in favor of a more descriptive API: " + " ZoneOffset.UTC", severity = ERROR) public final class ZoneIdOfZ extends BugChecker implements MethodInvocationTreeMatcher { private static final String ZONE_OFFSET = "java.time.ZoneOffset"; private static final Matcher<ExpressionTree> ZONE_ID_OF = allOf( staticMethod().onClass("java.time.ZoneId").named("of"), not(anyOf(packageStartsWith("java."), packageStartsWith("tck.java.")))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (ZONE_ID_OF.matches(tree, state)) { String zone = constValue(tree.getArguments().get(0), String.class); if (zone != null && zone.equals("Z")) { SuggestedFix.Builder fix = SuggestedFix.builder().addImport(ZONE_OFFSET); fix.replace(tree, String.format("%s.UTC", qualifyType(state, fix, ZONE_OFFSET))); return describeMatch(tree, fix.build()); } } return Description.NO_MATCH; } }
2,975
42.130435
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JavaTimeDefaultTimeZone.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Symbol.MethodSymbol; /** Check for calls to {@code java.time} APIs that silently use the default system time-zone. */ @BugPattern( summary = "java.time APIs that silently use the default system time-zone are not allowed.", explanation = "Using APIs that silently use the default system time-zone is dangerous. " + "The default system time-zone can vary from machine to machine or JVM to JVM. " + "You must choose an explicit ZoneId.", severity = WARNING) public final class JavaTimeDefaultTimeZone extends BugChecker implements MethodInvocationTreeMatcher { private static final ImmutableSet<String> NOW_STATIC = ImmutableSet.of( "java.time.LocalDate", "java.time.LocalDateTime", "java.time.LocalTime", "java.time.MonthDay", "java.time.OffsetDateTime", "java.time.OffsetTime", "java.time.Year", "java.time.YearMonth", "java.time.ZonedDateTime", "java.time.chrono.JapaneseDate", "java.time.chrono.MinguoDate", "java.time.chrono.HijrahDate", "java.time.chrono.ThaiBuddhistDate"); private static final ImmutableSet<String> DATE_NOW_INSTANCE = ImmutableSet.of( "java.time.chrono.Chronology", "java.time.chrono.HijrahChronology", "java.time.chrono.IsoChronology", "java.time.chrono.JapaneseChronology", "java.time.chrono.MinguoChronology", "java.time.chrono.ThaiBuddhistChronology"); private static final Matcher<ExpressionTree> CLOCK_MATCHER = Matchers.staticMethod() .onClass("java.time.Clock") .named("systemDefaultZone") .withNoParameters(); private static final Matcher<ExpressionTree> IN_JAVA_TIME = Matchers.packageStartsWith("java.time"); private static boolean matches(MethodInvocationTree tree) { if (!tree.getArguments().isEmpty()) { return false; } MethodSymbol symbol = ASTHelpers.getSymbol(tree); switch (symbol.getSimpleName().toString()) { case "now": return symbol.isStatic() && NOW_STATIC.contains(symbol.owner.getQualifiedName().toString()); case "dateNow": return !symbol.isStatic() && DATE_NOW_INSTANCE.contains(symbol.owner.getQualifiedName().toString()); case "systemDefaultZone": return symbol.isStatic() && symbol.owner.getQualifiedName().contentEquals("java.time.Clock"); default: return false; } } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!matches(tree) || IN_JAVA_TIME.matches(tree, state)) { return Description.NO_MATCH; } String idealReplacementCode = "ZoneId.of(\"America/Los_Angeles\")"; SuggestedFix.Builder fixBuilder = SuggestedFix.builder(); String zoneIdName = SuggestedFixes.qualifyType(state, fixBuilder, "java.time.ZoneId"); String replacementCode = zoneIdName + ".systemDefault()"; // The method could be statically imported and have no receiver: if so, just swap out the whole // tree as opposed to surgically replacing the post-receiver part.. ExpressionTree receiver = ASTHelpers.getReceiver(tree); // we special case Clock because the replacement isn't just an overload, but a new API entirely boolean systemDefaultZoneClockMethod = CLOCK_MATCHER.matches(tree, state); String replacementMethod = systemDefaultZoneClockMethod ? "system" : ASTHelpers.getSymbol(tree).name.toString(); if (receiver != null) { fixBuilder.replace( state.getEndPosition(receiver), state.getEndPosition(tree), "." + replacementMethod + "(" + replacementCode + ")"); } else { if (systemDefaultZoneClockMethod) { fixBuilder.addStaticImport("java.time.Clock.systemDefaultZone"); } fixBuilder.replace(tree, replacementMethod + "(" + replacementCode + ")"); } return buildDescription(tree) .setMessage( String.format( "%s.%s is not allowed because it silently uses the system default time-zone. You " + "must pass an explicit time-zone (e.g., %s) to this method.", ASTHelpers.getSymbol(tree).owner.getSimpleName(), ASTHelpers.getSymbol(tree), idealReplacementCode)) .addFix(fixBuilder.build()) .build(); } }
5,879
40.118881
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JavaDurationWithNanos.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.Matchers.packageStartsWith; 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; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** Check for calls to {@code duration.withNanos(int)}. */ @BugPattern( summary = "Use of java.time.Duration.withNanos(int) is not allowed.", explanation = "Duration's withNanos(int) method is often a source of bugs because it returns a copy of " + "the current Duration instance, but _only_ the nano field is mutated (the seconds " + "field is copied directly). Use Duration.ofSeconds(duration.getSeconds(), nanos) " + "instead.", severity = WARNING) public final class JavaDurationWithNanos extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> MATCHER = allOf( Matchers.instanceMethod() .onExactClass("java.time.Duration") .named("withNanos") .withParameters("int"), // Allow usage by java.time itself not(packageStartsWith("java.time"))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return Description.NO_MATCH; } SuggestedFix.Builder builder = SuggestedFix.builder(); ExpressionTree nanosArg = Iterables.getOnlyElement(tree.getArguments()); ExpressionTree receiver = ASTHelpers.getReceiver(tree); String replacement = SuggestedFixes.qualifyType(state, builder, "java.time.Duration") + ".ofSeconds(" + state.getSourceForNode(receiver) + ".getSeconds(), "; builder.replace(getStartPosition(tree), getStartPosition(nanosArg), replacement); return describeMatch(tree, builder.build()); } }
3,301
41.883117
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/InvalidJavaTimeConstant.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.time; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.packageStartsWith; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.temporal.ChronoField.DAY_OF_YEAR; import static java.time.temporal.ChronoField.EPOCH_DAY; import static java.time.temporal.ChronoField.HOUR_OF_DAY; import static java.time.temporal.ChronoField.MINUTE_OF_HOUR; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.NANO_OF_DAY; import static java.time.temporal.ChronoField.NANO_OF_SECOND; import static java.time.temporal.ChronoField.SECOND_OF_DAY; import static java.time.temporal.ChronoField.SECOND_OF_MINUTE; import static java.time.temporal.ChronoField.YEAR; import static java.util.Arrays.stream; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.bugpatterns.BugChecker; 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.Type; import java.time.DateTimeException; import java.time.temporal.ChronoField; import java.util.List; /** * This checker errors on calls to {@code java.time} methods using values that are guaranteed to * throw a {@link DateTimeException}. * * @author kak@google.com (Kurt Alfred Kluever) */ @BugPattern( summary = "This checker errors on calls to java.time methods using values that are guaranteed to " + "throw a DateTimeException.", severity = ERROR) public final class InvalidJavaTimeConstant extends BugChecker implements MethodInvocationTreeMatcher { @AutoValue abstract static class MatcherWithUnits { abstract Matcher<ExpressionTree> matcher(); abstract ImmutableList<ChronoField> units(); } @AutoValue abstract static class Param { abstract String type(); abstract ChronoField unit(); } private static Param intP(ChronoField unit) { return new AutoValue_InvalidJavaTimeConstant_Param("int", unit); } private static Param longP(ChronoField unit) { return new AutoValue_InvalidJavaTimeConstant_Param("long", unit); } private static Param monthP(ChronoField unit) { return new AutoValue_InvalidJavaTimeConstant_Param("java.time.Month", unit); } @AutoValue abstract static class JavaTimeType { abstract String className(); abstract ImmutableList<MatcherWithUnits> methods(); public static Builder builder() { return new AutoValue_InvalidJavaTimeConstant_JavaTimeType.Builder(); } @AutoValue.Builder public abstract static class Builder { public abstract Builder setClassName(String className); abstract String className(); abstract ImmutableList.Builder<MatcherWithUnits> methodsBuilder(); @CanIgnoreReturnValue public Builder addStaticMethod(String methodName, Param... params) { methodsBuilder() .add( new AutoValue_InvalidJavaTimeConstant_MatcherWithUnits( staticMethod() .onClass(className()) .named(methodName) .withParameters(getParameterTypes(params)), getParameterUnits(params))); return this; } @CanIgnoreReturnValue public Builder addInstanceMethod(String methodName, Param... params) { methodsBuilder() .add( new AutoValue_InvalidJavaTimeConstant_MatcherWithUnits( instanceMethod() .onExactClass(className()) .named(methodName) .withParameters(getParameterTypes(params)), getParameterUnits(params))); return this; } private static ImmutableList<ChronoField> getParameterUnits(Param... params) { return stream(params).map(p -> p.unit()).collect(toImmutableList()); } private static ImmutableList<String> getParameterTypes(Param... params) { return stream(params).map(p -> p.type()).collect(toImmutableList()); } public abstract JavaTimeType build(); } } private static final JavaTimeType DAY_OF_WEEK_APIS = JavaTimeType.builder() .setClassName("java.time.DayOfWeek") .addStaticMethod("of", intP(DAY_OF_WEEK)) .build(); private static final JavaTimeType MONTH_APIS = JavaTimeType.builder() .setClassName("java.time.Month") .addStaticMethod("of", intP(MONTH_OF_YEAR)) .build(); private static final JavaTimeType YEAR_APIS = JavaTimeType.builder() .setClassName("java.time.Year") .addStaticMethod("of", intP(YEAR)) .addInstanceMethod("atDay", intP(DAY_OF_YEAR)) .addInstanceMethod("atMonth", intP(MONTH_OF_YEAR)) .build(); private static final JavaTimeType YEAR_MONTH_APIS = JavaTimeType.builder() .setClassName("java.time.YearMonth") .addStaticMethod("of", intP(YEAR), intP(MONTH_OF_YEAR)) .addStaticMethod("of", intP(YEAR), monthP(MONTH_OF_YEAR)) .addInstanceMethod("atDay", intP(DAY_OF_MONTH)) .addInstanceMethod("withMonth", intP(MONTH_OF_YEAR)) .addInstanceMethod("withYear", intP(YEAR)) .build(); private static final JavaTimeType MONTH_DAY_APIS = JavaTimeType.builder() .setClassName("java.time.MonthDay") .addStaticMethod("of", intP(MONTH_OF_YEAR), intP(DAY_OF_MONTH)) .addStaticMethod("of", monthP(MONTH_OF_YEAR), intP(DAY_OF_MONTH)) .addInstanceMethod("atYear", intP(YEAR)) .addInstanceMethod("withDayOfMonth", intP(DAY_OF_MONTH)) .addInstanceMethod("withMonth", intP(MONTH_OF_YEAR)) .build(); private static final JavaTimeType LOCAL_TIME_APIS = JavaTimeType.builder() .setClassName("java.time.LocalTime") .addStaticMethod("of", intP(HOUR_OF_DAY), intP(MINUTE_OF_HOUR)) .addStaticMethod("of", intP(HOUR_OF_DAY), intP(MINUTE_OF_HOUR), intP(SECOND_OF_MINUTE)) .addStaticMethod( "of", intP(HOUR_OF_DAY), intP(MINUTE_OF_HOUR), intP(SECOND_OF_MINUTE), intP(NANO_OF_SECOND)) .addStaticMethod("ofNanoOfDay", longP(NANO_OF_DAY)) .addStaticMethod("ofSecondOfDay", longP(SECOND_OF_DAY)) .addInstanceMethod("withHour", intP(HOUR_OF_DAY)) .addInstanceMethod("withMinute", intP(MINUTE_OF_HOUR)) .addInstanceMethod("withNano", intP(NANO_OF_SECOND)) .addInstanceMethod("withSecond", intP(SECOND_OF_MINUTE)) .build(); private static final JavaTimeType LOCAL_DATE_APIS = JavaTimeType.builder() .setClassName("java.time.LocalDate") .addStaticMethod("of", intP(YEAR), intP(MONTH_OF_YEAR), intP(DAY_OF_MONTH)) .addStaticMethod("of", intP(YEAR), monthP(MONTH_OF_YEAR), intP(DAY_OF_MONTH)) .addStaticMethod("ofEpochDay", longP(EPOCH_DAY)) .addStaticMethod("ofYearDay", intP(YEAR), intP(DAY_OF_YEAR)) .addInstanceMethod("withDayOfMonth", intP(DAY_OF_MONTH)) .addInstanceMethod("withDayOfYear", intP(DAY_OF_YEAR)) .addInstanceMethod("withMonth", intP(MONTH_OF_YEAR)) .addInstanceMethod("withYear", intP(YEAR)) .build(); private static final JavaTimeType LOCAL_DATE_TIME_APIS = JavaTimeType.builder() .setClassName("java.time.LocalDateTime") .addStaticMethod( "of", intP(YEAR), intP(MONTH_OF_YEAR), intP(DAY_OF_MONTH), intP(HOUR_OF_DAY), intP(MINUTE_OF_HOUR)) .addStaticMethod( "of", intP(YEAR), monthP(MONTH_OF_YEAR), intP(DAY_OF_MONTH), intP(HOUR_OF_DAY), intP(MINUTE_OF_HOUR)) .addStaticMethod( "of", intP(YEAR), intP(MONTH_OF_YEAR), intP(DAY_OF_MONTH), intP(HOUR_OF_DAY), intP(MINUTE_OF_HOUR), intP(SECOND_OF_MINUTE)) .addStaticMethod( "of", intP(YEAR), monthP(MONTH_OF_YEAR), intP(DAY_OF_MONTH), intP(HOUR_OF_DAY), intP(MINUTE_OF_HOUR), intP(SECOND_OF_MINUTE)) .addStaticMethod( "of", intP(YEAR), intP(MONTH_OF_YEAR), intP(DAY_OF_MONTH), intP(HOUR_OF_DAY), intP(MINUTE_OF_HOUR), intP(SECOND_OF_MINUTE), intP(NANO_OF_SECOND)) .addStaticMethod( "of", intP(YEAR), monthP(MONTH_OF_YEAR), intP(DAY_OF_MONTH), intP(HOUR_OF_DAY), intP(MINUTE_OF_HOUR), intP(SECOND_OF_MINUTE), intP(NANO_OF_SECOND)) .addInstanceMethod("withDayOfMonth", intP(DAY_OF_MONTH)) .addInstanceMethod("withDayOfYear", intP(DAY_OF_YEAR)) .addInstanceMethod("withHour", intP(HOUR_OF_DAY)) .addInstanceMethod("withMinute", intP(MINUTE_OF_HOUR)) .addInstanceMethod("withMonth", intP(MONTH_OF_YEAR)) .addInstanceMethod("withNano", intP(NANO_OF_SECOND)) .addInstanceMethod("withSecond", intP(SECOND_OF_MINUTE)) .addInstanceMethod("withYear", intP(YEAR)) .build(); private static final ImmutableMap<String, JavaTimeType> APIS = Maps.uniqueIndex( ImmutableList.of( LOCAL_TIME_APIS, LOCAL_DATE_APIS, LOCAL_DATE_TIME_APIS, DAY_OF_WEEK_APIS, MONTH_APIS, YEAR_APIS, MONTH_DAY_APIS, YEAR_MONTH_APIS), JavaTimeType::className); private static final Matcher<ExpressionTree> JAVA_MATCHER = anyOf(packageStartsWith("java."), packageStartsWith("tck.java.")); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { // Allow the JDK to do whatever it wants (unit tests, etc.) if (JAVA_MATCHER.matches(tree, state)) { return Description.NO_MATCH; } // Get the receiver of the method invocation and make sure it's not null Type receiverType = ASTHelpers.getReceiverType(tree); if (receiverType == null) { return Description.NO_MATCH; } // If the receiver is not one of our java.time types, then return early JavaTimeType type = APIS.get(receiverType.toString()); if (type == null) { return Description.NO_MATCH; } // Otherwise, check the method matchers we have for that type for (MatcherWithUnits matcherWithUnits : type.methods()) { if (matcherWithUnits.matcher().matches(tree, state)) { List<? extends ExpressionTree> arguments = tree.getArguments(); for (int i = 0; i < arguments.size(); i++) { ExpressionTree argument = arguments.get(i); Number constant = ASTHelpers.constValue(argument, Number.class); if (constant != null) { try { matcherWithUnits.units().get(i).checkValidValue(constant.longValue()); } catch (DateTimeException invalid) { return buildDescription(argument).setMessage(invalid.getMessage()).build(); } } } // we short-circuit the loop here; only 1 method matcher will ever match, so there's no // sense in checking the rest of them return Description.NO_MATCH; } } return Description.NO_MATCH; } }
13,283
37.842105
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JavaLocalTimeGetNano.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.time.NearbyCallers.containsCallToSameReceiverNearby; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.Matchers.packageStartsWith; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; 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 java.time.LocalTime; /** * This checker warns about calls to {@link LocalTime#getNano} without a corresponding "nearby" call * to {@link LocalTime#getSecond}. */ @BugPattern( summary = "localTime.getNano() only accesses the nanos-of-second field." + " It's rare to only use getNano() without a nearby getSecond() call.", severity = WARNING) public final class JavaLocalTimeGetNano extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> GET_SECOND = instanceMethod().onExactClass("java.time.LocalTime").named("getSecond"); private static final Matcher<ExpressionTree> GET_NANO = allOf( instanceMethod().onExactClass("java.time.LocalTime").named("getNano"), not(packageStartsWith("java."))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (GET_NANO.matches(tree, state)) { if (!containsCallToSameReceiverNearby( tree, GET_SECOND, state, /* checkProtoChains= */ false)) { return describeMatch(tree); } } return Description.NO_MATCH; } }
2,678
40.859375
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/FromTemporalAccessor.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.time; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.matchers.Matchers.packageStartsWith; import static com.google.errorprone.matchers.Matchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.getReceiverType; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSameType; import com.google.common.collect.ImmutableMap; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Type; import java.time.DayOfWeek; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import java.time.MonthDay; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.Year; import java.time.YearMonth; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Map; /** * Bans calls to {@code javaTimeType.from(temporalAmount)} where the call is guaranteed to either: * * <ul> * <li>throw a {@code DateTimeException} at runtime (e.g., {@code LocalDate.from(month)}) * <li>return the same parameter (e.g., {@code Instant.from(instant)}) * </ul> * * @author kak@google.com (Kurt Alfred Kluever) */ @BugPattern( summary = "Certain combinations of javaTimeType.from(TemporalAccessor) will always throw a" + " DateTimeException or return the parameter directly.", explanation = "Not all java.time types can be created via from(TemporalAccessor). For example, you can" + " create a Month from a LocalDate (Month.from(localDate)) because a LocalDate" + " consists of a year, month, and day. However, you cannot create a LocalDate from a" + " Month (since it doesn't have the year or day information). Instead of throwing a" + " DateTimeException at runtime, this checker validates the type transformations at" + " compile time using static type information.", severity = ERROR) public final class FromTemporalAccessor extends BugChecker implements MethodInvocationTreeMatcher { private static final String TEMPORAL_ACCESSOR = "java.time.temporal.TemporalAccessor"; private static final Matcher<ExpressionTree> FROM_MATCHER = staticMethod().anyClass().named("from").withParameters(TEMPORAL_ACCESSOR); private static final Matcher<ExpressionTree> PACKAGE_MATCHER = anyOf( packageStartsWith("java.time"), packageStartsWith("org.threeten.extra"), packageStartsWith("tck.java.time")); private static final ImmutableMap<Matcher<Tree>, Matcher<ExpressionTree>> BAD_VALUE_FROM_KEY = new ImmutableMap.Builder<Matcher<Tree>, Matcher<ExpressionTree>>() .put( isSameType(DayOfWeek.class), makeValue( Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), Month.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), Year.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.AmPm", "org.threeten.extra.DayOfMonth", "org.threeten.extra.DayOfYear", "org.threeten.extra.Quarter", "org.threeten.extra.YearQuarter", "org.threeten.extra.YearWeek")) .put( isSameType(Instant.class), makeValue( DayOfWeek.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), Month.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), Year.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.AmPm", "org.threeten.extra.DayOfMonth", "org.threeten.extra.DayOfYear", "org.threeten.extra.Quarter", "org.threeten.extra.YearQuarter", "org.threeten.extra.YearWeek")) .put( isSameType(LocalDate.class), makeValue( Instant.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.AmPm")) .put( isSameType(LocalDateTime.class), makeValue( Instant.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName())) .put( isSameType(LocalTime.class), makeValue( DayOfWeek.class.getName(), Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), Month.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), Year.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.DayOfMonth", "org.threeten.extra.DayOfYear", "org.threeten.extra.Quarter", "org.threeten.extra.YearQuarter", "org.threeten.extra.YearWeek")) .put( isSameType(Month.class), makeValue( DayOfWeek.class.getName(), Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), Year.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.AmPm", "org.threeten.extra.DayOfMonth", "org.threeten.extra.DayOfYear", "org.threeten.extra.YearQuarter", "org.threeten.extra.YearWeek")) .put( isSameType(MonthDay.class), makeValue( DayOfWeek.class.getName(), Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), Year.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.AmPm", "org.threeten.extra.DayOfYear", "org.threeten.extra.YearQuarter", "org.threeten.extra.YearWeek")) .put(isSameType(OffsetDateTime.class), makeValue()) .put( isSameType(OffsetTime.class), makeValue( DayOfWeek.class.getName(), Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), Month.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), Year.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), "org.threeten.extra.DayOfMonth", "org.threeten.extra.DayOfYear", "org.threeten.extra.Quarter", "org.threeten.extra.YearQuarter", "org.threeten.extra.YearWeek")) .put( isSameType(Year.class), makeValue( DayOfWeek.class.getName(), Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), Month.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.AmPm", "org.threeten.extra.DayOfMonth", "org.threeten.extra.DayOfYear", "org.threeten.extra.Quarter", "org.threeten.extra.YearQuarter", "org.threeten.extra.YearWeek")) .put( isSameType(YearMonth.class), makeValue( DayOfWeek.class.getName(), Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.AmPm", "org.threeten.extra.DayOfMonth", "org.threeten.extra.DayOfYear", "org.threeten.extra.YearWeek")) .put(isSameType(ZonedDateTime.class), makeValue()) .put( isSameType(ZoneOffset.class), makeValue( DayOfWeek.class.getName(), Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), Month.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), Year.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), "org.threeten.extra.AmPm", "org.threeten.extra.DayOfMonth", "org.threeten.extra.DayOfYear", "org.threeten.extra.Quarter", "org.threeten.extra.YearQuarter", "org.threeten.extra.YearWeek")) .put( isSameType("org.threeten.extra.AmPm"), makeValue( DayOfWeek.class.getName(), Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), Month.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), Year.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.DayOfMonth", "org.threeten.extra.DayOfYear", "org.threeten.extra.Quarter", "org.threeten.extra.YearQuarter", "org.threeten.extra.YearWeek")) .put( isSameType("org.threeten.extra.DayOfMonth"), makeValue( DayOfWeek.class.getName(), Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), Month.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), Year.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.AmPm", "org.threeten.extra.DayOfYear", "org.threeten.extra.Quarter", "org.threeten.extra.YearQuarter", "org.threeten.extra.YearWeek")) .put( isSameType("org.threeten.extra.DayOfYear"), makeValue( DayOfWeek.class.getName(), Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), Month.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), Year.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.AmPm", "org.threeten.extra.DayOfMonth", "org.threeten.extra.Quarter", "org.threeten.extra.YearQuarter", "org.threeten.extra.YearWeek")) .put( isSameType("org.threeten.extra.Quarter"), makeValue( DayOfWeek.class.getName(), Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), Month.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), Year.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.AmPm", "org.threeten.extra.DayOfMonth", "org.threeten.extra.DayOfYear", "org.threeten.extra.YearQuarter", "org.threeten.extra.YearWeek")) .put( isSameType("org.threeten.extra.YearQuarter"), makeValue( DayOfWeek.class.getName(), Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), Month.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.AmPm", "org.threeten.extra.DayOfMonth", "org.threeten.extra.DayOfYear", "org.threeten.extra.YearWeek")) .put( isSameType("org.threeten.extra.YearWeek"), makeValue( DayOfWeek.class.getName(), Instant.class.getName(), LocalDate.class.getName(), LocalDateTime.class.getName(), LocalTime.class.getName(), Month.class.getName(), MonthDay.class.getName(), OffsetDateTime.class.getName(), OffsetTime.class.getName(), Year.class.getName(), YearMonth.class.getName(), ZonedDateTime.class.getName(), ZoneOffset.class.getName(), "org.threeten.extra.AmPm", "org.threeten.extra.DayOfMonth", "org.threeten.extra.DayOfYear", "org.threeten.extra.Quarter", "org.threeten.extra.YearQuarter")) .buildOrThrow(); private static Matcher<ExpressionTree> makeValue(String... classes) { return staticMethod().onClassAny(classes).named("from").withParameters(TEMPORAL_ACCESSOR); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { // exit early if we're not in a `from(TemporalAccessor)` method // this should be a large performance win since nearly all MITs will short-circuit here if (!FROM_MATCHER.matches(tree, state)) { return Description.NO_MATCH; } // exit early if we're inside java.time or ThreeTen-Extra if (PACKAGE_MATCHER.matches(tree, state)) { return Description.NO_MATCH; } // exit early if the receiver isn't a java.time or ThreeTen-Extra type String receiverType = getReceiverType(tree).toString(); if (!receiverType.startsWith("java.time") && !receiverType.startsWith("org.threeten.extra")) { return Description.NO_MATCH; } ExpressionTree arg0 = getOnlyElement(tree.getArguments()); Type type0 = getType(arg0); // exit early if the parameter is statically typed as a TemporalAccessor if (isSameType(type0, JAVA_TIME_TEMPORAL_TEMPORALACCESSOR.get(state), state)) { return Description.NO_MATCH; } // prevent `Instant.from(instant)` and similar if (isSameType(getType(tree), type0, state)) { SuggestedFix.Builder builder = SuggestedFix.builder(); builder.replace(tree, state.getSourceForNode(arg0)); return describeMatch(tree, builder.build()); } for (Map.Entry<Matcher<Tree>, Matcher<ExpressionTree>> entry : BAD_VALUE_FROM_KEY.entrySet()) { Matcher<ExpressionTree> fromMatcher = entry.getValue(); // matches Type.from(TemporalAccessor) Matcher<Tree> argumentMatcher = entry.getKey(); // ensures the arg0 is a "bad type" if (fromMatcher.matches(tree, state) && argumentMatcher.matches(arg0, state)) { return describeMatch(tree); } } return Description.NO_MATCH; } private static final Supplier<Type> JAVA_TIME_TEMPORAL_TEMPORALACCESSOR = VisitorState.memoize(state -> state.getTypeFromString(TEMPORAL_ACCESSOR)); }
20,463
42.820128
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/DurationGetTemporalUnit.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import java.time.temporal.ChronoUnit; import java.util.EnumSet; import java.util.Optional; /** * Bans calls to {@code Duration.get(temporalUnit)} where {@code temporalUnit} is not {@code * SECONDS} or {@code NANOS}. */ @BugPattern( summary = "Duration.get() only works with SECONDS or NANOS.", explanation = "`Duration.get(TemporalUnit)` only works when passed `ChronoUnit.SECONDS` or " + "`ChronoUnit.NANOS`. All other values are guaranteed to throw a " + "`UnsupportedTemporalTypeException`. In general, you should avoid " + "`duration.get(ChronoUnit)`. Instead, please use `duration.toNanos()`, " + "`Durations.toMicros(duration)`, `duration.toMillis()`, `duration.getSeconds()`, " + "`duration.toMinutes()`, `duration.toHours()`, or `duration.toDays()`.", severity = ERROR) public final class DurationGetTemporalUnit extends BugChecker implements MethodInvocationTreeMatcher { private static final ImmutableSet<ChronoUnit> INVALID_TEMPORAL_UNITS = ImmutableSet.copyOf(EnumSet.complementOf(EnumSet.of(ChronoUnit.SECONDS, ChronoUnit.NANOS))); private static final ImmutableMap<ChronoUnit, String> SUGGESTIONS = ImmutableMap.<ChronoUnit, String>builder() .put(ChronoUnit.DAYS, ".toDays()") .put(ChronoUnit.HOURS, ".toHours()") .put(ChronoUnit.MINUTES, ".toMinutes()") // SECONDS is omitted because it's a valid parameter .put(ChronoUnit.MILLIS, ".toMillis()") .buildOrThrow(); private static final Matcher<ExpressionTree> MATCHER = Matchers.instanceMethod() .onExactClass("java.time.Duration") .named("get") .withParameters("java.time.temporal.TemporalUnit"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (MATCHER.matches(tree, state)) { Optional<ChronoUnit> invalidUnit = getInvalidChronoUnit( Iterables.getOnlyElement(tree.getArguments()), INVALID_TEMPORAL_UNITS); if (invalidUnit.isPresent()) { if (SUGGESTIONS.containsKey(invalidUnit.get())) { SuggestedFix.Builder builder = SuggestedFix.builder(); builder.replace( tree, state.getSourceForNode(ASTHelpers.getReceiver(tree)) + SUGGESTIONS.get(invalidUnit.get())); return describeMatch(tree, builder.build()); } return describeMatch(tree); } } return Description.NO_MATCH; } // used by PeriodGetTemporalUnit and DurationOfLongTemporalUnit static Optional<ChronoUnit> getInvalidChronoUnit( ExpressionTree tree, Iterable<ChronoUnit> invalidUnits) { Optional<String> constant = getEnumName(tree); if (constant.isPresent()) { for (ChronoUnit invalidTemporalUnit : invalidUnits) { if (constant.get().equals(invalidTemporalUnit.name())) { return Optional.of(invalidTemporalUnit); } } } return Optional.empty(); } private static Optional<String> getEnumName(ExpressionTree temporalUnit) { if (temporalUnit instanceof IdentifierTree) { // e.g., SECONDS return Optional.of(((IdentifierTree) temporalUnit).getName().toString()); } if (temporalUnit instanceof MemberSelectTree) { // e.g., ChronoUnit.SECONDS return Optional.of(((MemberSelectTree) temporalUnit).getIdentifier().toString()); } return Optional.empty(); } }
4,994
40.97479
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/ProtoDurationGetSecondsGetNano.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.time.NearbyCallers.containsCallToSameReceiverNearby; 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; 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; /** * This checker warns about accessing the underlying nanosecond-adjustment field of a duration * without a "nearby" access of the underlying seconds field. * * @author kak@google.com (Kurt Alfred Kluever) */ @BugPattern( summary = "getNanos() only accesses the underlying nanosecond-adjustment of the duration.", explanation = "If you call duration.getNanos(), you must also call duration.getSeconds() in 'nearby' " + "code. If you are trying to convert this duration to nanoseconds, " + "you probably meant to use Durations.toNanos(duration) instead.", severity = WARNING) public final class ProtoDurationGetSecondsGetNano extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> GET_SECONDS = instanceMethod().onExactClass("com.google.protobuf.Duration").named("getSeconds"); private static final Matcher<ExpressionTree> GET_NANOS = instanceMethod().onExactClass("com.google.protobuf.Duration").named("getNanos"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (GET_NANOS.matches(tree, state)) { if (!containsCallToSameReceiverNearby( tree, GET_SECONDS, state, /* checkProtoChains= */ true)) { return describeMatch(tree); } } return Description.NO_MATCH; } }
2,708
42
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/TimeUnitConversionChecker.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.instanceMethod; import com.google.common.base.Enums; import com.google.common.base.Optional; import com.google.common.primitives.Longs; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; 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 java.util.concurrent.TimeUnit; /** Check for problematic or suspicious TimeUnit conversion calls. */ @BugPattern( summary = "This TimeUnit conversion looks buggy: converting from a smaller unit to a larger unit " + "(and passing a constant), converting to/from the same TimeUnit, or converting " + "TimeUnits where the result is statically known to be 0 or 1 are all buggy patterns.", explanation = "This checker flags potential problems with TimeUnit conversions: " + "1) conversions that are statically known to be equal to 0 or 1; " + "2) conversions that are converting from a given unit back to the same unit; " + "3) conversions that are converting from a smaller unit to a larger unit and passing " + "a constant value", severity = WARNING) public final class TimeUnitConversionChecker extends BugChecker implements MethodInvocationTreeMatcher { // TODO(kak): We should probably also extend this to recognize TimeUnit.convertTo() invocations private static final Matcher<ExpressionTree> MATCHER = instanceMethod() .onExactClass("java.util.concurrent.TimeUnit") .namedAnyOf( "toDays", "toHours", "toMinutes", "toSeconds", "toMillis", "toMicros", "toNanos"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return Description.NO_MATCH; } Tree receiverOfConversion = ASTHelpers.getReceiver(tree); if (receiverOfConversion == null) { // Usage inside TimeUnit itself, no changes we can make here. return Description.NO_MATCH; } // This trips up on code like: // TimeUnit SECONDS = TimeUnit.MINUTES; // long about2500 = SECONDS.toSeconds(42); // but... I think that's bad enough to ignore here :) String timeUnitName = ASTHelpers.getSymbol(receiverOfConversion).getSimpleName().toString(); Optional<TimeUnit> receiver = Enums.getIfPresent(TimeUnit.class, timeUnitName); if (!receiver.isPresent()) { return Description.NO_MATCH; } String methodName = ASTHelpers.getSymbol(tree).getSimpleName().toString(); TimeUnit convertTo = methodNameToTimeUnit(methodName); ExpressionTree arg0 = tree.getArguments().get(0); // if we have a constant and can Long-parse it... Long constant = Longs.tryParse(String.valueOf(state.getSourceForNode(arg0))); if (constant != null) { long converted = invokeConversion(receiver.get(), methodName, constant); // ... and the conversion results in 0 or 1, just inline it! if (converted == 0 || converted == 1 || constant == converted) { SuggestedFix fix = replaceTreeWith(tree, convertTo, converted + "L"); return describeMatch(tree, fix); } // otherwise we have a suspect case: SMALLER_UNIT.toLargerUnit(constantValue) // because: "people usually don't like to have constants like 60_000_000 and use" // "libraries to turn them into smaller numbers" if (receiver.get().compareTo(convertTo) < 0) { // We can't suggest a replacement here, so we just have to error out. return describeMatch(tree); } } // if we're trying to convert the unit to itself, just return the arg if (receiver.get().equals(convertTo)) { SuggestedFix fix = replaceTreeWith(tree, convertTo, state.getSourceForNode(arg0)); return describeMatch(tree, fix); } return Description.NO_MATCH; } private static SuggestedFix replaceTreeWith( MethodInvocationTree tree, TimeUnit units, String replacement) { return SuggestedFix.builder() .postfixWith(tree, " /* " + units.toString().toLowerCase() + " */") .replace(tree, replacement) .build(); } private static long invokeConversion(TimeUnit timeUnit, String methodName, long duration) { switch (methodName) { case "toDays": return timeUnit.toDays(duration); case "toHours": return timeUnit.toHours(duration); case "toMinutes": return timeUnit.toMinutes(duration); case "toSeconds": return timeUnit.toSeconds(duration); case "toMillis": return timeUnit.toMillis(duration); case "toMicros": return timeUnit.toMicros(duration); case "toNanos": return timeUnit.toNanos(duration); default: throw new IllegalArgumentException(); } } private static TimeUnit methodNameToTimeUnit(String methodName) { switch (methodName) { case "toDays": return TimeUnit.DAYS; case "toHours": return TimeUnit.HOURS; case "toMinutes": return TimeUnit.MINUTES; case "toSeconds": return TimeUnit.SECONDS; case "toMillis": return TimeUnit.MILLISECONDS; case "toMicros": return TimeUnit.MICROSECONDS; case "toNanos": return TimeUnit.NANOSECONDS; default: throw new IllegalArgumentException(); } } }
6,536
38.859756
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JodaToSelf.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.time; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Streams; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.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.NewClassTree; /** Check for calls to Joda-Time's {@code foo.toFoo()} and {@code new Foo(foo)}. */ @BugPattern( summary = "Use of Joda-Time's DateTime.toDateTime(), Duration.toDuration(), Instant.toInstant(), " + "Interval.toInterval(), and Period.toPeriod() are not allowed.", explanation = "Joda-Time's DateTime.toDateTime(), Duration.toDuration(), Instant.toInstant(), " + "Interval.toInterval(), and Period.toPeriod() are always unnecessary, since they " + "simply 'return this'. There is no reason to ever call them.", severity = ERROR) public final class JodaToSelf extends BugChecker implements MethodInvocationTreeMatcher, NewClassTreeMatcher { private static final ImmutableSet<String> TYPE_NAMES = ImmutableSet.of("DateTime", "Duration", "Instant", "Interval", "Period"); private static final ImmutableSet<String> TYPES_WITHOUT_METHOD = ImmutableSet.of("LocalDate", "LocalDateTime", "LocalTime"); private static final Matcher<ExpressionTree> MATCHER = Matchers.allOf( Matchers.anyOf( TYPE_NAMES.stream() .map( typeName -> Matchers.instanceMethod() .onExactClass("org.joda.time." + typeName) .named("to" + typeName) .withNoParameters()) .collect(toImmutableList())), // Allow usage by JodaTime itself Matchers.not(Matchers.packageStartsWith("org.joda.time"))); private static final Matcher<ExpressionTree> CONSTRUCTOR_MATCHER = Matchers.allOf( Matchers.anyOf( Streams.concat(TYPE_NAMES.stream(), TYPES_WITHOUT_METHOD.stream()) .map( typeName -> Matchers.constructor() .forClass("org.joda.time." + typeName) .withParameters("java.lang.Object")) .collect(toImmutableList())), // Allow usage by JodaTime itself Matchers.not(Matchers.packageStartsWith("org.joda.time"))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return Description.NO_MATCH; } return buildDescription(tree) .setMessage( String.format("Use of %s is a no-op and is not allowed.", ASTHelpers.getSymbol(tree))) .addFix( SuggestedFix.replace( state.getEndPosition(ASTHelpers.getReceiver(tree)), state.getEndPosition(tree), "")) .build(); } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { if (!CONSTRUCTOR_MATCHER.matches(tree, state)) { return Description.NO_MATCH; } ExpressionTree argument = getOnlyElement(tree.getArguments()); if (!ASTHelpers.isSameType( ASTHelpers.getType(argument), ASTHelpers.getType(tree.getIdentifier()), state)) { return Description.NO_MATCH; } return buildDescription(tree) .setMessage( String.format("Use of %s is a no-op and is not allowed.", ASTHelpers.getSymbol(tree))) .addFix(SuggestedFix.replace(tree, state.getSourceForNode(argument))) .build(); } }
4,977
41.186441
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/PeriodTimeMath.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.argument; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.matchers.Matchers.not; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; 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 javax.inject.Inject; /** Bans calls to {@code Period#plus/minus(TemporalAmount)} where the argument is a Duration. */ @BugPattern( summary = "When adding or subtracting from a Period, Duration is incompatible.", explanation = "Period.(plus|minus)(TemporalAmount) will always throw a DateTimeException when passed a " + "Duration.", severity = ERROR) public final class PeriodTimeMath extends BugChecker implements MethodInvocationTreeMatcher { private final Matcher<MethodInvocationTree> matcherToCheck; private static final Matcher<ExpressionTree> PERIOD_MATH = instanceMethod().onExactClass("java.time.Period").namedAnyOf("plus", "minus"); private static final Matcher<ExpressionTree> DURATION = isSameType("java.time.Duration"); private static final Matcher<ExpressionTree> PERIOD = isSameType("java.time.Period"); @Inject PeriodTimeMath(ErrorProneFlags flags) { boolean requireStrictCompatibility = flags.getBoolean("PeriodTimeMath:RequireStaticPeriodArgument").orElse(false); matcherToCheck = allOf(PERIOD_MATH, argument(0, requireStrictCompatibility ? not(PERIOD) : DURATION)); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return matcherToCheck.matches(tree, state) ? describeMatch(tree) : Description.NO_MATCH; } }
2,878
42.621212
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JodaDurationWithMillis.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; 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; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** Check for calls to {@code duration.withMillis(long)}. */ @BugPattern( summary = "Use of duration.withMillis(long) is not allowed. Please use Duration.millis(long) " + "instead.", explanation = "Joda-Time's 'duration.withMillis(long)' method is often a source of bugs because it " + "doesn't mutate the current instance but rather returns a new immutable Duration " + "instance." + "Please use Duration.millis(long) instead. If your Duration is better expressed in " + "terms of other units, use standardSeconds(long), standardMinutes(long), " + "standardHours(long), or standardDays(long) instead.", severity = WARNING) public final class JodaDurationWithMillis extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> MATCHER = Matchers.allOf( Matchers.instanceMethod() .onExactClass("org.joda.time.Duration") .named("withMillis") .withParameters("long"), // Allow usage by JodaTime itself Matchers.not(Matchers.packageStartsWith("org.joda.time"))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return Description.NO_MATCH; } SuggestedFix.Builder builder = SuggestedFix.builder(); String replacement = SuggestedFixes.qualifyType(state, builder, "org.joda.time.Duration") + ".millis("; ExpressionTree millisArg = Iterables.getOnlyElement(tree.getArguments()); builder.replace(getStartPosition(tree), getStartPosition(millisArg), replacement); return describeMatch(tree, builder.build()); } }
3,170
42.438356
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/LocalDateTemporalAmount.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.argument; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.Matchers.packageStartsWith; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.MethodInvocationTree; /** * Bans calls to {@code LocalDate.plus(TemporalAmount)} and {@code LocalDate.minus(TemporalAmount)} * where the {@link java.time.temporal.TemporalAmount} is a non-zero {@link java.time.Duration}. */ @BugPattern( summary = "LocalDate.plus() and minus() does not work with Durations. LocalDate represents civil" + " time (years/months/days), so java.time.Period is the appropriate thing to add or" + " subtract instead.", severity = ERROR) public final class LocalDateTemporalAmount extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<MethodInvocationTree> MATCHER = allOf( instanceMethod() .onExactClass("java.time.LocalDate") .namedAnyOf("plus", "minus") .withParameters("java.time.temporal.TemporalAmount"), // TODO(kak): If the parameter is equal to Duration.ZERO, then technically this call will // work, but that's a very small corner case to worry about. argument(0, isSameType("java.time.Duration")), not(packageStartsWith("java."))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return MATCHER.matches(tree, state) ? describeMatch(tree) : Description.NO_MATCH; } }
2,824
43.84127
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/DateChecker.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.time; import static com.google.common.base.Verify.verify; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.constructor; import static com.google.errorprone.matchers.Matchers.instanceMethod; import com.google.common.base.Joiner; import com.google.common.collect.Range; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; 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.LiteralTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import java.time.DateTimeException; import java.time.Month; import java.util.ArrayList; import java.util.List; /** * Warns against suspect looking calls to {@link java.util.Date} APIs. Noteably, {@code Date} uses: * * <ul> * <li>1900-based years (negative values permitted) * <li>0-based months (with rollover and negative values permitted) * <li>1-based days (with rollover and negative values permitted) * <li>0-based hours (with rollover and negative values permitted) * <li>0-based minutes (with rollover and negative values permitted) * <li>0-based seconds (with rollover and negative values permitted) * </ul> * * @author kak@google.com (Kurt Alfred Kluever) */ @BugPattern( summary = "Warns against suspect looking calls to java.util.Date APIs", explanation = "java.util.Date uses 1900-based years, 0-based months, 1-based days, and 0-based" + " hours/minutes/seconds. Additionally, it allows for negative values or very large" + " values (which rollover).", severity = WARNING) public final class DateChecker extends BugChecker implements MethodInvocationTreeMatcher, NewClassTreeMatcher { private static final String DATE = "java.util.Date"; private static final Matcher<ExpressionTree> CONSTRUCTORS = anyOf( constructor().forClass(DATE).withParameters("int", "int", "int"), constructor().forClass(DATE).withParameters("int", "int", "int", "int", "int"), constructor().forClass(DATE).withParameters("int", "int", "int", "int", "int", "int")); private static final Matcher<ExpressionTree> SET_YEAR = instanceMethod().onExactClass(DATE).named("setYear"); private static final Matcher<ExpressionTree> SET_MONTH = instanceMethod().onExactClass(DATE).named("setMonth"); private static final Matcher<ExpressionTree> SET_DAY = instanceMethod().onExactClass(DATE).named("setDate"); private static final Matcher<ExpressionTree> SET_HOUR = instanceMethod().onExactClass(DATE).named("setHours"); private static final Matcher<ExpressionTree> SET_MIN = instanceMethod().onExactClass(DATE).named("setMinutes"); private static final Matcher<ExpressionTree> SET_SEC = instanceMethod().onExactClass(DATE).named("setSeconds"); // permits years [1901, 2050] which seems ~reasonable private static final Range<Integer> YEAR_RANGE = Range.closed(1, 150); private static final Range<Integer> MONTH_RANGE = Range.closed(0, 11); private static final Range<Integer> DAY_RANGE = Range.closed(1, 31); private static final Range<Integer> HOUR_RANGE = Range.closed(0, 23); private static final Range<Integer> SEC_MIN_RANGE = Range.closed(0, 59); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { List<String> errors = new ArrayList<>(); if (tree.getArguments().size() == 1) { ExpressionTree arg0 = tree.getArguments().get(0); if (SET_YEAR.matches(tree, state)) { checkYear(arg0, errors); } else if (SET_MONTH.matches(tree, state)) { checkMonth(arg0, errors); } else if (SET_DAY.matches(tree, state)) { checkDay(arg0, errors); } else if (SET_HOUR.matches(tree, state)) { checkHours(arg0, errors); } else if (SET_MIN.matches(tree, state)) { checkMinutes(arg0, errors); } else if (SET_SEC.matches(tree, state)) { checkSeconds(arg0, errors); } } return buildDescription(tree, errors); } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { List<String> errors = new ArrayList<>(); if (CONSTRUCTORS.matches(tree, state)) { List<? extends ExpressionTree> args = tree.getArguments(); int numArgs = args.size(); verify( numArgs >= 3 && numArgs <= 6, "Expected the constructor to have at least 3 and at most 6 arguments, but it had %s", numArgs); checkYear(args.get(0), errors); checkMonth(args.get(1), errors); checkDay(args.get(2), errors); if (numArgs > 4) { checkHours(args.get(3), errors); checkMinutes(args.get(4), errors); } if (numArgs > 5) { checkSeconds(args.get(5), errors); } } return buildDescription(tree, errors); } private Description buildDescription(ExpressionTree tree, List<String> errors) { return errors.isEmpty() ? Description.NO_MATCH : buildDescription(tree) .setMessage( "This Date usage looks suspect for the following reason(s): " + Joiner.on(" ").join(errors)) .build(); } private static void checkYear(ExpressionTree tree, List<String> errors) { checkBounds(tree, "1900-based year", YEAR_RANGE, errors); } private static void checkMonth(ExpressionTree tree, List<String> errors) { checkBounds(tree, "0-based month", MONTH_RANGE, errors); if (tree instanceof LiteralTree) { int monthValue = (int) ((LiteralTree) tree).getValue(); try { errors.add( String.format( "Use Calendar.%s instead of %s to represent the month.", Month.of(monthValue + 1), monthValue)); } catch (DateTimeException badMonth) { // this is an out of bounds month, and thus already caught by the checkBounds() call above! } } } private static void checkDay(ExpressionTree tree, List<String> errors) { // TODO(kak): we should also consider checking if the given day is valid for the given // month/year. E.g., Feb 30th is never valid, Feb 29th is sometimes valid, and Feb 28th is // always valid. checkBounds(tree, "day", DAY_RANGE, errors); } private static void checkHours(ExpressionTree tree, List<String> errors) { checkBounds(tree, "hours", HOUR_RANGE, errors); } private static void checkMinutes(ExpressionTree tree, List<String> errors) { checkBounds(tree, "minutes", SEC_MIN_RANGE, errors); } private static void checkSeconds(ExpressionTree tree, List<String> errors) { checkBounds(tree, "seconds", SEC_MIN_RANGE, errors); } private static void checkBounds( ExpressionTree tree, String type, Range<Integer> range, List<String> errors) { Integer value = ASTHelpers.constValue(tree, Integer.class); if (value != null && !range.contains(value)) { errors.add(String.format("The %s value (%s) is out of bounds %s.", type, value, range)); } } }
8,170
39.855
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JodaDateTimeConstants.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.time; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.FieldMatchers.staticField; import static com.google.errorprone.matchers.Matchers.anyOf; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.IdentifierTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher; 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.MemberSelectTree; import java.util.stream.Stream; /** Checks for usages of dangerous {@code DateTimeConstants} constants. */ @BugPattern( summary = "Using the `_PER_` constants in `DateTimeConstants` is problematic because they encourage" + " manual date/time math.", explanation = "Manual date/time math leads to overflows, unit mismatches, and weak typing. Prefer to use" + " strong types (e.g., `java.time.Duration` or `java.time.Instant`) and their APIs to" + " perform date/time math.", severity = WARNING) public final class JodaDateTimeConstants extends BugChecker implements MemberSelectTreeMatcher, IdentifierTreeMatcher { private static final Matcher<ExpressionTree> DATE_TIME_CONSTANTS_MATCHER = anyOf( Stream.of( "HOURS_PER_DAY", "HOURS_PER_WEEK", "MILLIS_PER_DAY", "MILLIS_PER_HOUR", "MILLIS_PER_MINUTE", "MILLIS_PER_SECOND", "MILLIS_PER_WEEK", "MINUTES_PER_DAY", "MINUTES_PER_HOUR", "MINUTES_PER_WEEK", "SECONDS_PER_DAY", "SECONDS_PER_HOUR", "SECONDS_PER_MINUTE", "SECONDS_PER_WEEK") .map(constant -> staticField("org.joda.time.DateTimeConstants", constant)) .collect(toImmutableSet())); @Override public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) { return match(tree, state); } @Override public Description matchIdentifier(IdentifierTree tree, VisitorState state) { return match(tree, state); } private Description match(ExpressionTree tree, VisitorState state) { return DATE_TIME_CONSTANTS_MATCHER.matches(tree, state) ? describeMatch(tree) : NO_MATCH; } }
3,399
39.963855
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/TemporalAccessorGetChronoField.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; 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; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.util.Name; import java.time.DayOfWeek; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import java.time.MonthDay; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.Year; import java.time.YearMonth; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.chrono.HijrahDate; import java.time.chrono.HijrahEra; import java.time.chrono.IsoEra; import java.time.chrono.JapaneseDate; import java.time.chrono.JapaneseEra; import java.time.chrono.MinguoDate; import java.time.chrono.MinguoEra; import java.time.chrono.ThaiBuddhistDate; import java.time.chrono.ThaiBuddhistEra; import java.time.temporal.ChronoField; import java.time.temporal.TemporalAccessor; import java.util.List; import java.util.Optional; /** * Bans calls to {@code TemporalAccessor.get(ChronoField)} where the implementation is guaranteed to * throw an {@code UnsupportedTemporalTypeException}. */ @BugPattern( summary = "TemporalAccessor.get() only works for certain values of ChronoField.", explanation = "TemporalAccessor.get(ChronoField) only works for certain values of ChronoField. E.g., " + "DayOfWeek only supports DAY_OF_WEEK. All other values are guaranteed to throw an " + "UnsupportedTemporalTypeException.", severity = ERROR) public final class TemporalAccessorGetChronoField extends BugChecker implements MethodInvocationTreeMatcher { private static final ZoneId ARBITRARY_ZONE = ZoneId.of("America/Los_Angeles"); private static final ImmutableList<TemporalAccessor> TEMPORAL_ACCESSOR_INSTANCES = ImmutableList.of( DayOfWeek.MONDAY, HijrahDate.now(ARBITRARY_ZONE), HijrahEra.AH, Instant.now(), IsoEra.CE, JapaneseDate.now(ARBITRARY_ZONE), JapaneseEra.SHOWA, LocalDate.now(ARBITRARY_ZONE), LocalDateTime.now(ARBITRARY_ZONE), LocalTime.now(ARBITRARY_ZONE), MinguoDate.now(ARBITRARY_ZONE), MinguoEra.ROC, Month.MAY, MonthDay.now(ARBITRARY_ZONE), OffsetDateTime.now(ARBITRARY_ZONE), OffsetTime.now(ARBITRARY_ZONE), ThaiBuddhistDate.now(ARBITRARY_ZONE), ThaiBuddhistEra.BE, Year.now(ARBITRARY_ZONE), YearMonth.now(ARBITRARY_ZONE), ZonedDateTime.now(ARBITRARY_ZONE), ZoneOffset.ofHours(8)); private static final ImmutableListMultimap<String, ChronoField> UNSUPPORTED = buildUnsupported(); private static ImmutableListMultimap<String, ChronoField> buildUnsupported() { ImmutableListMultimap.Builder<String, ChronoField> builder = ImmutableListMultimap.builder(); for (TemporalAccessor temporalAccessor : TEMPORAL_ACCESSOR_INSTANCES) { for (ChronoField chronoField : ChronoField.values()) { if (!temporalAccessor.isSupported(chronoField)) { builder.put(temporalAccessor.getClass().getCanonicalName(), chronoField); } } } return builder.build(); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { MethodSymbol sym = ASTHelpers.getSymbol(tree); Name methodName = sym.name; if (!(methodName.contentEquals("get") || methodName.contentEquals("getLong"))) { return Description.NO_MATCH; } List<VarSymbol> params = sym.params(); if (params.size() != 1) { return Description.NO_MATCH; } Name argType = params.get(0).type.tsym.getQualifiedName(); if (!argType.contentEquals("java.time.temporal.TemporalField")) { return Description.NO_MATCH; } String declaringType = sym.owner.getQualifiedName().toString(); ImmutableList<ChronoField> invalidChronoFields = UNSUPPORTED.get(declaringType); if (invalidChronoFields != null && isDefinitelyInvalidChronoField(tree, invalidChronoFields)) { return describeMatch(tree); } return Description.NO_MATCH; } private static boolean isDefinitelyInvalidChronoField( MethodInvocationTree tree, Iterable<ChronoField> invalidChronoFields) { return getEnumName(Iterables.getOnlyElement(tree.getArguments())) .map( /* TODO(amalloy): We could pre-index chronoFields instead of iterating over it. * However, it's fairly rare to get to this point, so it's not a big deal if * it's relatively slow. */ constant -> Streams.stream(invalidChronoFields).map(Enum::name).anyMatch(constant::equals)) .orElse(false); } private static Optional<String> getEnumName(ExpressionTree chronoField) { if (chronoField instanceof IdentifierTree) { // e.g., SECOND_OF_DAY return Optional.of(((IdentifierTree) chronoField).getName().toString()); } if (chronoField instanceof MemberSelectTree) { // e.g., ChronoField.SECOND_OF_DAY return Optional.of(((MemberSelectTree) chronoField).getIdentifier().toString()); } return Optional.empty(); } }
6,641
38.772455
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JodaInstantWithMillis.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.fixes.SuggestedFixes.qualifyType; 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; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** Check for calls to {@code instant.withMillis(long)}. */ @BugPattern( summary = "Use of instant.withMillis(long) is not allowed. Use Instant.ofEpochMilli(long) instead.", explanation = "Joda-Time's 'instant.withMillis(long)' method is often a source of bugs because it " + "doesn't mutate the current instance but rather returns a new immutable Instant " + "instance. Please use Instant.ofEpochMilli(long) instead.", severity = WARNING) public final class JodaInstantWithMillis extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> MATCHER = Matchers.allOf( Matchers.instanceMethod() .onExactClass("org.joda.time.Instant") .named("withMillis") .withParameters("long"), // Allow usage by JodaTime itself Matchers.not(Matchers.packageStartsWith("org.joda.time"))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return Description.NO_MATCH; } SuggestedFix.Builder builder = SuggestedFix.builder(); String replacement = qualifyType(state, builder, "org.joda.time.Instant") + ".ofEpochMilli("; ExpressionTree millisArg = Iterables.getOnlyElement(tree.getArguments()); builder.replace(getStartPosition(tree), getStartPosition(millisArg), replacement); return describeMatch(tree, builder.build()); } }
2,933
42.791045
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JavaPeriodGetDays.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.time.NearbyCallers.containsCallToSameReceiverNearby; import static com.google.errorprone.matchers.Matchers.allOf; 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; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** * This checker warns about calls to {@code period.getDays()} without a corresponding "nearby" call * to {@code period.getYears(), period.getMonths(), or period.getTotalMonths()}. * * @author glorioso@google.com (Nick Glorioso) */ @BugPattern( summary = "period.getDays() only accesses the \"days\" portion of the Period, and doesn't represent" + " the total span of time of the period. Consider using org.threeten.extra.Days to" + " extract the difference between two civil dates if you want the whole time.", severity = WARNING) public final class JavaPeriodGetDays extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> PERIOD_LOOK_AT_OTHERS = instanceMethod() .onExactClass("java.time.Period") .namedAnyOf("getMonths", "getYears", "getTotalMonths"); private static final Matcher<ExpressionTree> PERIOD_GET_DAYS = allOf( instanceMethod().onExactClass("java.time.Period").named("getDays"), Matchers.not(Matchers.packageStartsWith("java."))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (PERIOD_GET_DAYS.matches(tree, state)) { if (!containsCallToSameReceiverNearby( tree, PERIOD_LOOK_AT_OTHERS, state, /* checkProtoChains= */ false)) { return describeMatch(tree); } } return Description.NO_MATCH; } }
2,896
42.238806
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/PeriodGetTemporalUnit.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.bugpatterns.time.DurationGetTemporalUnit.getInvalidChronoUnit; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import java.time.temporal.ChronoUnit; import java.util.EnumSet; /** * Bans calls to {@code Period.get(temporalUnit)} where {@code temporalUnit} is not {@code YEARS}, * {@code MONTHS}, or {@code DAYS}. */ @BugPattern( summary = "Period.get() only works with YEARS, MONTHS, or DAYS.", explanation = "`Period.get(TemporalUnit)` only works when passed `ChronoUnit.YEARS`, `ChronoUnit.MONTHS`," + " or `ChronoUnit.DAYS`. All other values are guaranteed to throw an" + " `UnsupportedTemporalTypeException`.", severity = ERROR) public final class PeriodGetTemporalUnit extends BugChecker implements MethodInvocationTreeMatcher { private static final ImmutableSet<ChronoUnit> INVALID_TEMPORAL_UNITS = ImmutableSet.copyOf( EnumSet.complementOf(EnumSet.of(ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.DAYS))); private static final Matcher<ExpressionTree> MATCHER = Matchers.instanceMethod() .onExactClass("java.time.Period") .named("get") .withParameters("java.time.temporal.TemporalUnit"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return MATCHER.matches(tree, state) && getInvalidChronoUnit( Iterables.getOnlyElement(tree.getArguments()), INVALID_TEMPORAL_UNITS) .isPresent() ? describeMatch(tree) : Description.NO_MATCH; } }
2,831
41.268657
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/PeriodFrom.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.matchers.Matchers.staticMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; import java.time.Duration; /** * Bans calls to {@code Period.from(temporalAmount)} where {@code temporalAmount} is a {@link * Duration}. * * @author kak@google.com (Kurt Alfred Kluever) */ @BugPattern( summary = "Period.from(Period) returns itself; from(Duration) throws a runtime exception.", explanation = "Period.from(TemporalAmount) will always throw a DateTimeException when " + "passed a Duration and return itself when passed a Period.", severity = ERROR) public final class PeriodFrom extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> PERIOD_FROM = staticMethod().onClass("java.time.Period").named("from"); private static final Matcher<Tree> DURATION = isSameType("java.time.Duration"); private static final Matcher<Tree> PERIOD = isSameType("java.time.Period"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (PERIOD_FROM.matches(tree, state)) { ExpressionTree arg0 = tree.getArguments().get(0); if (DURATION.matches(arg0, state)) { return describeMatch(tree); } if (PERIOD.matches(arg0, state)) { return describeMatch(tree, SuggestedFix.replace(tree, state.getSourceForNode(arg0))); } } return Description.NO_MATCH; } }
2,709
38.275362
95
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/InstantTemporalUnit.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.time; import static com.google.common.collect.Sets.toImmutableEnumSet; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.bugpatterns.time.DurationGetTemporalUnit.getInvalidChronoUnit; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import java.time.temporal.ChronoUnit; import java.util.Arrays; /** * Bans calls to {@code Instant} APIs where the {@link java.time.temporal.TemporalUnit} is not one * of: {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS}, {@code MINUTES}, {@code * HOURS}, {@code HALF_DAYS}, or {@code DAYS}. */ @BugPattern( summary = "Instant APIs only work for NANOS, MICROS, MILLIS, SECONDS, MINUTES, HOURS, HALF_DAYS and" + " DAYS.", severity = ERROR) public final class InstantTemporalUnit extends BugChecker implements MethodInvocationTreeMatcher { private static final String INSTANT = "java.time.Instant"; private static final String TEMPORAL_UNIT = "java.time.temporal.TemporalUnit"; private static final Matcher<ExpressionTree> INSTANT_OF_LONG_TEMPORAL_UNIT = allOf( anyOf( instanceMethod() .onExactClass(INSTANT) .named("minus") .withParameters("long", TEMPORAL_UNIT), instanceMethod() .onExactClass(INSTANT) .named("plus") .withParameters("long", TEMPORAL_UNIT), instanceMethod() .onExactClass(INSTANT) .named("until") .withParameters("java.time.temporal.Temporal", TEMPORAL_UNIT)), Matchers.not(Matchers.packageStartsWith("java."))); // This definition comes from Instant.isSupported(TemporalUnit) static final ImmutableSet<ChronoUnit> INVALID_TEMPORAL_UNITS = Arrays.stream(ChronoUnit.values()) .filter(c -> !c.isTimeBased()) .filter(c -> !c.equals(ChronoUnit.DAYS)) // DAYS is explicitly allowed .collect(toImmutableEnumSet()); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (INSTANT_OF_LONG_TEMPORAL_UNIT.matches(tree, state)) { if (getInvalidChronoUnit(tree.getArguments().get(1), INVALID_TEMPORAL_UNITS).isPresent()) { return describeMatch(tree); } } return Description.NO_MATCH; } }
3,703
41.574713
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JodaWithDurationAddedLong.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.time; 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.instanceMethod; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.Matchers.packageStartsWith; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.method.MethodMatchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** * Check for calls to JodaTime's {@code type.withDurationAdded(long, int)} where {@code <type> = * {Duration,Instant,DateTime}}. */ @BugPattern( summary = "Use of JodaTime's type.withDurationAdded(long, int) (where <type> = " + "{Duration,Instant,DateTime}). Please use " + "type.withDurationAdded(Duration.millis(long), int) instead.", explanation = "JodaTime's type.withDurationAdded(long, int) is often a source of bugs " + "because the units of the parameters are ambiguous. Please use " + "type.withDurationAdded(Duration.millis(long), int) instead.", severity = WARNING) public final class JodaWithDurationAddedLong extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> MATCHER = allOf( anyOf( instanceMethod() .onExactClass("org.joda.time.DateTime") .named("withDurationAdded") .withParameters("long", "int"), instanceMethod() .onExactClass("org.joda.time.Duration") .named("withDurationAdded") .withParameters("long", "int"), instanceMethod() .onExactClass("org.joda.time.Instant") .named("withDurationAdded") .withParameters("long", "int")), // Allow usage by JodaTime itself not(packageStartsWith("org.joda.time"))); private static final Matcher<ExpressionTree> DURATION_GET_MILLIS_MATCHER = MethodMatchers.instanceMethod() .onDescendantOf("org.joda.time.ReadableDuration") .named("getMillis"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return Description.NO_MATCH; } String receiver = state.getSourceForNode(ASTHelpers.getReceiver(tree)); // Get the constant scalar, if there is one. Integer scalar = ASTHelpers.constValue(tree.getArguments().get(1), Integer.class); SuggestedFix.Builder builder = SuggestedFix.builder(); if (Integer.valueOf(0).equals(scalar)) { // This is adding zero times a duration to the receiver: we can replace this with just the // receiver. builder.replace(tree, receiver); } else { ExpressionTree firstArgumentTree = tree.getArguments().get(0); String firstArgumentReplacement; if (DURATION_GET_MILLIS_MATCHER.matches(firstArgumentTree, state)) { // This is passing {@code someDuration.getMillis()} as the parameter. we can replace this // with {@code someDuration}. firstArgumentReplacement = state.getSourceForNode(ASTHelpers.getReceiver(firstArgumentTree)); } else { // Wrap the long as a Duration. firstArgumentReplacement = SuggestedFixes.qualifyType(state, builder, "org.joda.time.Duration") + ".millis(" + state.getSourceForNode(firstArgumentTree) + ")"; } if (Integer.valueOf(1).equals(scalar)) { // Use plus instead of adding 1 times the duration. builder.replace(tree, receiver + ".plus(" + firstArgumentReplacement + ")"); } else if (Integer.valueOf(-1).equals(scalar)) { // Use minus instead of adding -1 times the duration. builder.replace(tree, receiver + ".minus(" + firstArgumentReplacement + ")"); } else { builder.replace(firstArgumentTree, firstArgumentReplacement); } } return describeMatch(tree, builder.build()); } }
5,331
41.656
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JavaLocalDateTimeGetNano.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.time.NearbyCallers.containsCallToSameReceiverNearby; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.Matchers.packageStartsWith; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; 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 java.time.LocalDateTime; /** * This checker warns about calls to {@link LocalDateTime#getNano} without a corresponding "nearby" * call to {@link LocalDateTime#getSecond}. */ @BugPattern( summary = "localDateTime.getNano() only accesss the nanos-of-second field." + " It's rare to only use getNano() without a nearby getSecond() call.", severity = WARNING) public final class JavaLocalDateTimeGetNano extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> GET_SECOND = instanceMethod().onExactClass("java.time.LocalDateTime").named("getSecond"); private static final Matcher<ExpressionTree> GET_NANO = allOf( instanceMethod().onExactClass("java.time.LocalDateTime").named("getNano"), not(packageStartsWith("java."))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (GET_NANO.matches(tree, state)) { if (!containsCallToSameReceiverNearby( tree, GET_SECOND, state, /* checkProtoChains= */ false)) { return describeMatch(tree); } } return Description.NO_MATCH; } }
2,709
40.692308
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JavaDurationWithSeconds.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import com.google.common.collect.Iterables; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** Check for calls to {@code duration.withSeconds(long)}. */ @BugPattern( summary = "Use of java.time.Duration.withSeconds(long) is not allowed.", explanation = "Duration's withSeconds(long) method is often a source of bugs because it returns a copy " + "of the current Duration instance, but _only_ the seconds field is mutated (the " + "nanos field is copied directly). Use Duration.ofSeconds(seconds, " + "duration.getNano()) instead.", severity = WARNING) public final class JavaDurationWithSeconds extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> MATCHER = Matchers.allOf( Matchers.instanceMethod() .onExactClass("java.time.Duration") .named("withSeconds") .withParameters("long"), // Allow usage by java.time itself Matchers.not(Matchers.packageStartsWith("java.time"))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return Description.NO_MATCH; } SuggestedFix.Builder builder = SuggestedFix.builder(); ExpressionTree secondsArg = Iterables.getOnlyElement(tree.getArguments()); ExpressionTree receiver = ASTHelpers.getReceiver(tree); String replacement = SuggestedFixes.qualifyType(state, builder, "java.time.Duration") + ".ofSeconds(" + state.getSourceForNode(secondsArg) + ", " + state.getSourceForNode(receiver) + ".getNano())"; builder.replace(tree, replacement); return describeMatch(tree, builder.build()); } }
3,102
40.373333
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/JodaTimeConverterManager.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.Matchers.staticMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** Ban usage of Joda's {@code ConverterManager}. */ @BugPattern( summary = "Joda-Time's ConverterManager makes the semantics of DateTime/Instant/etc construction" + " subject to global static state. If you need to define your own converters, use" + " a helper.", severity = WARNING) public final class JodaTimeConverterManager extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> MATCHER = allOf( staticMethod().onClass("org.joda.time.convert.ConverterManager").named("getInstance"), // Allow usage by JodaTime itself. not(Matchers.packageStartsWith("org.joda.time"))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return MATCHER.matches(tree, state) ? describeMatch(tree) : Description.NO_MATCH; } }
2,276
41.166667
96
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/time/DurationFrom.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.time; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.matchers.Matchers.staticMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; import java.time.Period; /** * Bans calls to {@code Duration.from(temporalAmount)} where {@code temporalAmount} is a {@link * Period}. * * @author kak@google.com (Kurt Alfred Kluever) */ @BugPattern( summary = "Duration.from(Duration) returns itself; from(Period) throws a runtime exception.", explanation = "Duration.from(TemporalAmount) will always throw a UnsupportedTemporalTypeException when " + "passed a Period and return itself when passed a Duration.", severity = ERROR) public final class DurationFrom extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> DURATION_FROM = staticMethod().onClass("java.time.Duration").named("from"); private static final Matcher<Tree> DURATION = isSameType("java.time.Duration"); private static final Matcher<Tree> PERIOD = isSameType("java.time.Period"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (DURATION_FROM.matches(tree, state)) { ExpressionTree arg0 = tree.getArguments().get(0); if (PERIOD.matches(arg0, state)) { return describeMatch(tree); } if (DURATION.matches(arg0, state)) { return describeMatch(tree, SuggestedFix.replace(tree, state.getSourceForNode(arg0))); } } return Description.NO_MATCH; } }
2,734
38.637681
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/apidiff/Java8ApiChecker.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.apidiff; import static com.google.common.collect.ImmutableSetMultimap.toImmutableSetMultimap; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.io.Resources; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.bugpatterns.apidiff.ApiDiff.ClassMemberKey; import com.google.protobuf.ExtensionRegistry; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Map; import java.util.regex.Pattern; import javax.inject.Inject; /** Checks for uses of classes, fields, or methods that are not compatible with JDK 8 */ @BugPattern( name = "Java8ApiChecker", summary = "Use of class, field, or method that is not compatible with JDK 8", explanation = "Code that needs to be compatible with Java 8 cannot use types or members" + " that are only present in newer class libraries", severity = ERROR) public class Java8ApiChecker extends ApiDiffChecker { private static ApiDiff loadApiDiff(ErrorProneFlags errorProneFlags) { try { byte[] diffData = Resources.toByteArray(Resources.getResource(Java8ApiChecker.class, "8to11diff.binarypb")); ApiDiff diff = ApiDiff.fromProto( ApiDiffProto.Diff.newBuilder() .mergeFrom(diffData, ExtensionRegistry.getEmptyRegistry()) .build()); boolean checkBuffer = errorProneFlags.getBoolean("Java8ApiChecker:checkBuffer").orElse(true); boolean checkChecksum = errorProneFlags.getBoolean("Java8ApiChecker:checkChecksum").orElse(true); if (checkBuffer && checkChecksum) { return diff; } ImmutableSetMultimap<String, ClassMemberKey> unsupportedMembers = diff.unsupportedMembersByClass().entries().stream() .filter(e -> checkBuffer || !BUFFER.matcher(e.getKey()).matches()) .filter(e -> checkChecksum || !e.getKey().equals(CHECKSUM)) .collect(toImmutableSetMultimap(Map.Entry::getKey, Map.Entry::getValue)); return ApiDiff.fromMembers(diff.unsupportedClasses(), unsupportedMembers); } catch (IOException e) { throw new UncheckedIOException(e); } } private static final Pattern BUFFER = Pattern.compile("java/nio/.*Buffer"); private static final String CHECKSUM = "java/util/zip/Checksum"; @Inject Java8ApiChecker(ErrorProneFlags errorProneFlags) { super(loadApiDiff(errorProneFlags)); } }
3,210
39.64557
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/apidiff/ApiDiffChecker.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.apidiff; import static com.google.errorprone.util.ASTHelpers.getSymbol; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.IdentifierTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher; import com.google.errorprone.bugpatterns.apidiff.ApiDiff.ClassMemberKey; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.Signatures; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.ImportTree; import com.sun.source.tree.MemberSelectTree; import com.sun.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.lang.annotation.Annotation; import java.util.Optional; import org.checkerframework.checker.nullness.qual.Nullable; /** A base Error Prone check implementation to enforce compliance with a given API diff. */ public abstract class ApiDiffChecker extends BugChecker implements IdentifierTreeMatcher, MemberSelectTreeMatcher { private final ApiDiff apiDiff; private final Optional<Class<? extends Annotation>> alsoForbidApisAnnotated; protected ApiDiffChecker(ApiDiff apiDiff) { this.apiDiff = apiDiff; this.alsoForbidApisAnnotated = Optional.empty(); } protected ApiDiffChecker(ApiDiff apiDiff, Class<? extends Annotation> alsoForbidApisAnnotated) { this.apiDiff = apiDiff; this.alsoForbidApisAnnotated = Optional.of(alsoForbidApisAnnotated); } @Override public Description matchIdentifier(IdentifierTree tree, VisitorState state) { return check(tree, state); } @Override public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) { return check(tree, state); } protected Description check(ExpressionTree tree, VisitorState state) { if (state.findEnclosing(ImportTree.class) != null) { return Description.NO_MATCH; } Symbol sym = getSymbol(tree); if (sym == null) { return Description.NO_MATCH; } ClassSymbol receiver = getReceiver(tree, sym); if (receiver == null) { // e.g. package symbols return Description.NO_MATCH; } Types types = state.getTypes(); // check for information associated with the class if (apiDiff.isClassUnsupported(Signatures.classDescriptor(receiver.type, types)) || classOrEnclosingClassIsForbiddenByAnnotation(receiver, state)) { return buildDescription(tree) .setMessage(String.format("%s is not available", receiver)) .build(); } // check for fields and methods that are not present in the old API if (!(sym instanceof VarSymbol || sym instanceof MethodSymbol)) { return Description.NO_MATCH; } ClassMemberKey memberKey = ClassMemberKey.create( sym.getSimpleName().toString(), Signatures.descriptor(sym.type, types)); ClassSymbol owner = sym.owner.enclClass(); if (apiDiff.isMemberUnsupported(Signatures.classDescriptor(owner.type, types), memberKey) || hasAnnotationForbiddingUse(sym, state)) { return buildDescription(tree) .setMessage(String.format("%s#%s is not available in %s", owner, sym, receiver)) .build(); } return Description.NO_MATCH; } private boolean classOrEnclosingClassIsForbiddenByAnnotation(Symbol clazz, VisitorState state) { if (!alsoForbidApisAnnotated.isPresent()) { return false; } for (; clazz instanceof ClassSymbol; clazz = clazz.owner) { if (hasAnnotationForbiddingUse(clazz, state)) { return true; } } return false; } private boolean hasAnnotationForbiddingUse(Symbol sym, VisitorState state) { return alsoForbidApisAnnotated.isPresent() && ASTHelpers.hasAnnotation(sym, alsoForbidApisAnnotated.get(), state); } /** * Finds the class of the expression's receiver: the declaring class of a static member access, or * the type that an instance member is accessed on. */ private static @Nullable ClassSymbol getReceiver(ExpressionTree tree, Symbol sym) { if (ASTHelpers.isStatic(sym) || sym instanceof ClassSymbol) { return sym.enclClass(); } switch (tree.getKind()) { case MEMBER_SELECT: case METHOD_INVOCATION: Type receiver = ASTHelpers.getType(ASTHelpers.getReceiver(tree)); if (receiver == null) { return null; } return receiver.tsym.enclClass(); case IDENTIFIER: // Simple names are implicitly qualified by an enclosing instance, so if we get here // we're inside the compilation unit that declares the receiver, and the diff doesn't // contain accurate information. return null; default: return null; } } }
5,702
36.768212
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/apidiff/ApiDiff.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.apidiff; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Multimap; import com.google.errorprone.bugpatterns.apidiff.ApiDiffProto.Diff; import java.util.Set; /** The difference between two APIs. */ @AutoValue public abstract class ApiDiff { /** A per class unique identifier for a field or method. */ @AutoValue public abstract static class ClassMemberKey { /** The simple name of the member. */ public abstract String identifier(); /** The JVMS 4.3 member descriptor. */ public abstract String descriptor(); public static ClassMemberKey create(String identifier, String descriptor) { return new AutoValue_ApiDiff_ClassMemberKey(identifier, descriptor); } @Override public final String toString() { return String.format("%s:%s", identifier(), descriptor()); } } /** Binary names of classes only present in the new API. */ public abstract ImmutableSet<String> unsupportedClasses(); /** Members only present in the new API, grouped by binary name of their declaring class. */ public abstract ImmutableSetMultimap<String, ClassMemberKey> unsupportedMembersByClass(); /** Returns true if the class with the given binary name is unsupported. */ boolean isClassUnsupported(String className) { return unsupportedClasses().contains(className); } /** Returns true if the member with the given declaring class is unsupported. */ boolean isMemberUnsupported(String className, ClassMemberKey memberKey) { return unsupportedMembersByClass().containsEntry(className, memberKey) || unsupportedMembersByClass() .containsEntry(className, ClassMemberKey.create(memberKey.identifier(), "")); } public static ApiDiff fromMembers( Set<String> unsupportedClasses, Multimap<String, ClassMemberKey> unsupportedMembersByClass) { return new AutoValue_ApiDiff( ImmutableSet.copyOf(unsupportedClasses), ImmutableSetMultimap.copyOf(unsupportedMembersByClass)); } /** Converts a {@link Diff} to a {@link ApiDiff}. */ public static ApiDiff fromProto(Diff diff) { ImmutableSet.Builder<String> unsupportedClasses = ImmutableSet.builder(); ImmutableSetMultimap.Builder<String, ClassMemberKey> unsupportedMembersByClass = ImmutableSetMultimap.builder(); for (ApiDiffProto.ClassDiff c : diff.getClassDiffList()) { switch (c.getDiffCase()) { case EVERYTHING_DIFF: unsupportedClasses.add(c.getEverythingDiff().getClassName()); break; case MEMBER_DIFF: ApiDiffProto.MemberDiff memberDiff = c.getMemberDiff(); for (ApiDiffProto.ClassMember member : memberDiff.getMemberList()) { unsupportedMembersByClass.put( memberDiff.getClassName(), ClassMemberKey.create(member.getIdentifier(), member.getMemberDescriptor())); } break; default: throw new AssertionError(c.getDiffCase()); } } return new AutoValue_ApiDiff(unsupportedClasses.build(), unsupportedMembersByClass.build()); } /** Converts a {@link ApiDiff} to a {@link ApiDiffProto.Diff}. */ public Diff toProto() { ApiDiffProto.Diff.Builder builder = ApiDiffProto.Diff.newBuilder(); for (String className : unsupportedClasses()) { builder.addClassDiff( ApiDiffProto.ClassDiff.newBuilder() .setEverythingDiff(ApiDiffProto.EverythingDiff.newBuilder().setClassName(className))); } for (String className : unsupportedMembersByClass().keySet()) { ApiDiffProto.MemberDiff.Builder memberDiff = ApiDiffProto.MemberDiff.newBuilder().setClassName(className); for (ClassMemberKey member : unsupportedMembersByClass().get(className)) { memberDiff.addMember( ApiDiffProto.ClassMember.newBuilder() .setIdentifier(member.identifier()) .setMemberDescriptor(member.descriptor())); } builder.addClassDiff(ApiDiffProto.ClassDiff.newBuilder().setMemberDiff(memberDiff)); } return builder.build(); } }
4,846
38.729508
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/apidiff/Java7ApiChecker.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.apidiff; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import com.google.common.io.Resources; import com.google.errorprone.BugPattern; import java.io.IOException; import java.io.UncheckedIOException; /** Checks for uses of classes, fields, or methods that are not compatible with JDK 7 */ @BugPattern( name = "Java7ApiChecker", summary = "Use of class, field, or method that is not compatible with JDK 7", explanation = "Code that needs to be compatible with Java 7 cannot use types or members" + " that are only present in the JDK 8 class libraries", severity = ERROR) public class Java7ApiChecker extends ApiDiffChecker { public static final ApiDiff API_DIFF = loadApiDiff(); private static ApiDiff loadApiDiff() { try { ApiDiffProto.Diff.Builder diffBuilder = ApiDiffProto.Diff.newBuilder(); byte[] diffData = Resources.toByteArray(Resources.getResource(Java7ApiChecker.class, "7to11diff.binarypb")); diffBuilder .mergeFrom(diffData) .addClassDiff( ApiDiffProto.ClassDiff.newBuilder() .setMemberDiff( ApiDiffProto.MemberDiff.newBuilder() .setClassName("com/google/common/base/Predicate") .addMember( ApiDiffProto.ClassMember.newBuilder() .setIdentifier("test") .setMemberDescriptor("(Ljava/lang/Object;)Z")))) .addClassDiff( ApiDiffProto.ClassDiff.newBuilder() .setMemberDiff( ApiDiffProto.MemberDiff.newBuilder() .setClassName("com/google/common/base/BinaryPredicate") .addMember( ApiDiffProto.ClassMember.newBuilder() .setIdentifier("test") .setMemberDescriptor( "(Ljava/lang/Object;Ljava/lang/Object;)Z")))); return ApiDiff.fromProto(diffBuilder.build()); } catch (IOException e) { throw new UncheckedIOException(e); } } public Java7ApiChecker() { super(API_DIFF); } }
2,932
38.635135
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/apidiff/AndroidJdkLibsChecker.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.apidiff; 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.io.Resources; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.protobuf.ExtensionRegistry; import com.sun.source.tree.ExpressionTree; import java.io.IOException; import java.io.UncheckedIOException; import javax.inject.Inject; /** * Checks for uses of classes, fields, or methods that are not compatible with legacy Android * devices. As of Android N, that includes all of JDK8 (which is only supported on Nougat) except * type and repeated annotations, which are compiled in a backwards compatible way. */ @BugPattern( name = "AndroidJdkLibsChecker", altNames = "AndroidApiChecker", summary = "Use of class, field, or method that is not compatible with legacy Android devices", severity = ERROR) // TODO(b/32513850): Allow Android N+ APIs, e.g., by computing API diff using android.jar public class AndroidJdkLibsChecker extends ApiDiffChecker { private static ApiDiff loadApiDiff(boolean allowJava8) { try { byte[] diffData = Resources.toByteArray( Resources.getResource( AndroidJdkLibsChecker.class, allowJava8 ? "android_java8.binarypb" : "android.binarypb")); ApiDiffProto.Diff diff = ApiDiffProto.Diff.newBuilder() .mergeFrom(diffData, ExtensionRegistry.getEmptyRegistry()) .build(); return ApiDiff.fromProto(diff); } catch (IOException e) { throw new UncheckedIOException(e); } } private final boolean allowJava8; @Inject AndroidJdkLibsChecker(ErrorProneFlags flags) { this(flags.getBoolean("Android:Java8Libs").orElse(false)); } public AndroidJdkLibsChecker() { this(false); } private AndroidJdkLibsChecker(boolean allowJava8) { super(loadApiDiff(allowJava8)); this.allowJava8 = allowJava8; } private static final Matcher<ExpressionTree> FOREACH_ON_COLLECTION = instanceMethod() .onDescendantOf("java.util.Collection") .named("forEach") .withParameters("java.util.function.Consumer"); @Override protected Description check(ExpressionTree tree, VisitorState state) { Description description = super.check(tree, state); if (description.equals(NO_MATCH)) { return NO_MATCH; } if (allowJava8 && FOREACH_ON_COLLECTION.matches(tree, state)) { return NO_MATCH; } return description; } }
3,468
34.040404
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/collectionincompatibletype/CollectionIncompatibleType.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.collectionincompatibletype; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.fixes.SuggestedFixes.addSuppressWarnings; import static com.google.errorprone.matchers.Description.NO_MATCH; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.TypeCompatibilityUtils; import com.google.errorprone.bugpatterns.TypeCompatibilityUtils.TypeCompatibilityReport; import com.google.errorprone.bugpatterns.collectionincompatibletype.AbstractCollectionIncompatibleTypeMatcher.MatchResult; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.Signatures; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Types; import java.util.Collection; import java.util.List; import java.util.Map; import javax.inject.Inject; /** * Checker for calling Object-accepting methods with types that don't match the type arguments of * their container types. Currently this checker detects problems with the following methods on all * their subtypes and subinterfaces: * * <ul> * <li>{@link Collection#contains} * <li>{@link Collection#remove} * <li>{@link List#indexOf} * <li>{@link List#lastIndexOf} * <li>{@link Map#get} * <li>{@link Map#containsKey} * <li>{@link Map#remove} * <li>{@link Map#containsValue} * </ul> */ @BugPattern( summary = "Incompatible type as argument to Object-accepting Java collections method", severity = ERROR) public class CollectionIncompatibleType extends BugChecker implements MethodInvocationTreeMatcher, MemberReferenceTreeMatcher { private enum FixType { NONE, CAST, PRINT_TYPES_AS_COMMENT, SUPPRESS_WARNINGS, } private final FixType fixType; private final TypeCompatibilityUtils typeCompatibilityUtils; @Inject CollectionIncompatibleType(ErrorProneFlags flags) { this.fixType = flags.getEnum("CollectionIncompatibleType:FixType", FixType.class).orElse(FixType.NONE); this.typeCompatibilityUtils = TypeCompatibilityUtils.fromFlags(flags); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return match(tree, state); } @Override public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) { return match(tree, state); } public Description match(ExpressionTree tree, VisitorState state) { MatchResult result = ContainmentMatchers.firstNonNullMatchResult(tree, state); if (result == null) { return NO_MATCH; } Types types = state.getTypes(); TypeCompatibilityReport compatibilityReport = typeCompatibilityUtils.compatibilityOfTypes( result.targetType(), result.sourceType(), state); if (compatibilityReport.isCompatible()) { return NO_MATCH; } String sourceType = Signatures.prettyType(result.sourceType()); String targetType = Signatures.prettyType(result.targetType()); if (sourceType.equals(targetType)) { sourceType = result.sourceType().toString(); targetType = result.targetType().toString(); } Description.Builder description = buildDescription(tree) .setMessage(result.message(sourceType, targetType) + compatibilityReport.extraReason()); switch (fixType) { case PRINT_TYPES_AS_COMMENT: description.addFix( SuggestedFix.prefixWith( tree, String.format( "/* expected: %s, actual: %s */", ASTHelpers.getUpperBound(result.targetType(), types), result.sourceType()))); break; case CAST: result.buildFix().ifPresent(description::addFix); break; case SUPPRESS_WARNINGS: SuggestedFix.Builder builder = SuggestedFix.builder(); builder.prefixWith( result.sourceTree(), String.format("/* expected: %s, actual: %s */ ", targetType, sourceType)); addSuppressWarnings(builder, state, "CollectionIncompatibleType"); description.addFix(builder.build()); break; case NONE: break; } return description.build(); } }
5,332
35.77931
122
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/collectionincompatibletype/CompatibleWithMisuse.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.collectionincompatibletype; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.CompatibleWith; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssignmentTree; 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.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.TypeVariableSymbol; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; /** * @author glorioso@google.com (Nick Glorioso) */ @BugPattern( name = "CompatibleWithAnnotationMisuse", summary = "@CompatibleWith's value is not a type argument.", severity = ERROR) public class CompatibleWithMisuse extends BugChecker implements AnnotationTreeMatcher { private static final Matcher<AnnotationTree> IS_COMPATIBLE_WITH_ANNOTATION = Matchers.isType(CompatibleWith.class.getCanonicalName()); @Override public Description matchAnnotation(AnnotationTree annoTree, VisitorState state) { if (!IS_COMPATIBLE_WITH_ANNOTATION.matches(annoTree, state)) { return Description.NO_MATCH; } // Hunt for type args on the declared method // TODO(glorioso): Once annotation is TYPE_USE, make sure that the node is actually a method // parameter MethodTree methodTree = ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class); MethodSymbol declaredMethod = ASTHelpers.getSymbol(methodTree); // If this method overrides other methods, ensure that none of them have @CompatibleWith. // This restriction may need to be removed to allow more complex declaration hierarchies. for (MethodSymbol methodSymbol : ASTHelpers.findSuperMethods(declaredMethod, state.getTypes())) { if (methodSymbol.params().stream() .anyMatch(p -> ASTHelpers.hasAnnotation(p, CompatibleWith.class, state))) { return describeWithMessage( annoTree, String.format( "This method overrides a method in %s that already has @CompatibleWith", methodSymbol.owner.getSimpleName())); } } List<TypeVariableSymbol> potentialTypeVars = new ArrayList<>(declaredMethod.getTypeParameters()); // Check enclosing types (not superclasses) ClassSymbol cs = (ClassSymbol) declaredMethod.owner; do { potentialTypeVars.addAll(cs.getTypeParameters()); cs = cs.isInner() ? cs.owner.enclClass() : null; } while (cs != null); if (potentialTypeVars.isEmpty()) { return describeWithMessage( annoTree, "There are no type arguments in scope to match against."); } ImmutableSet<String> validNames = potentialTypeVars.stream() .map(TypeVariableSymbol::getSimpleName) .map(Object::toString) .collect(toImmutableSet()); String constValue = valueArgumentFromCompatibleWithAnnotation(annoTree); if (isNullOrEmpty(constValue)) { return describeWithMessage( annoTree, String.format( "The value of @CompatibleWith must not be empty (valid arguments are %s)", printTypeArgs(validNames))); } return validNames.contains(constValue) ? Description.NO_MATCH : describeWithMessage( annoTree, String.format( "%s is not a valid type argument. Valid arguments are: %s", constValue, printTypeArgs(validNames))); } // @CompatibleWith("X"), @CompatibleWith(value = "X"), // @CompatibleWith(SOME_FIELD_WHOSE_CONSTANT_VALUE_IS_X) // => X // This function assumes the annotation tree will only have one argument, of type String, that // is required. private static @Nullable String valueArgumentFromCompatibleWithAnnotation(AnnotationTree tree) { ExpressionTree argumentValue = Iterables.getOnlyElement(tree.getArguments()); if (argumentValue.getKind() != Kind.ASSIGNMENT) { // :-| Annotation symbol broken. Punt? return null; } return ASTHelpers.constValue(((AssignmentTree) argumentValue).getExpression(), String.class); } private static String printTypeArgs(Set<String> validNames) { return Joiner.on(", ").join(validNames); } private Description describeWithMessage(Tree tree, String message) { return buildDescription(tree).setMessage(message).build(); } }
5,887
38.516779
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/collectionincompatibletype/ContainmentMatchers.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.collectionincompatibletype; import com.google.common.collect.ImmutableList; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.collectionincompatibletype.AbstractCollectionIncompatibleTypeMatcher.MatchResult; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.ExpressionTree; import javax.annotation.Nullable; /** Matchers for methods which express containment, like {@link java.util.Collection#contains}. */ public final class ContainmentMatchers { /** * The least-common ancestor of all of the types of {@link #DIRECT_MATCHERS} and {@link * #TYPE_ARG_MATCHERS}. */ private static final Matcher<ExpressionTree> FIRST_ORDER_MATCHER = Matchers.anyMethod() .onDescendantOfAny( "java.util.Collection", "java.util.Dictionary", "java.util.Map", "java.util.Collections", "com.google.common.collect.Sets"); /** The "normal" case of extracting the type of a method argument */ private static final ImmutableList<MethodArgMatcher> DIRECT_MATCHERS = ImmutableList.of( // "Normal" cases, e.g. Collection#remove(Object) // Make sure to keep that the type or one of its supertype should be present in // FIRST_ORDER_MATCHER new MethodArgMatcher("java.util.Collection", "contains(java.lang.Object)", 0, 0), new MethodArgMatcher("java.util.Collection", "remove(java.lang.Object)", 0, 0), new MethodArgMatcher("java.util.Deque", "removeFirstOccurrence(java.lang.Object)", 0, 0), new MethodArgMatcher("java.util.Deque", "removeLastOccurrence(java.lang.Object)", 0, 0), new MethodArgMatcher("java.util.Dictionary", "get(java.lang.Object)", 0, 0), new MethodArgMatcher("java.util.Dictionary", "remove(java.lang.Object)", 0, 0), new MethodArgMatcher("java.util.List", "indexOf(java.lang.Object)", 0, 0), new MethodArgMatcher("java.util.List", "lastIndexOf(java.lang.Object)", 0, 0), new MethodArgMatcher("java.util.Map", "containsKey(java.lang.Object)", 0, 0), new MethodArgMatcher("java.util.Map", "containsValue(java.lang.Object)", 1, 0), new MethodArgMatcher("java.util.Map", "get(java.lang.Object)", 0, 0), new MethodArgMatcher("java.util.Map", "getOrDefault(java.lang.Object,V)", 0, 0), new MethodArgMatcher("java.util.Map", "remove(java.lang.Object)", 0, 0), new MethodArgMatcher("java.util.Stack", "search(java.lang.Object)", 0, 0), new MethodArgMatcher("java.util.Vector", "indexOf(java.lang.Object,int)", 0, 0), new MethodArgMatcher("java.util.Vector", "lastIndexOf(java.lang.Object,int)", 0, 0), new MethodArgMatcher("java.util.Vector", "removeElement(java.lang.Object)", 0, 0)); /** * Cases where we need to extract the type argument from a method argument, e.g. * Collection#containsAll(Collection<?>) */ private static final ImmutableList<TypeArgOfMethodArgMatcher> TYPE_ARG_MATCHERS = ImmutableList.of( // Make sure to keep that the type or one of its supertype should be present in // FIRST_ORDER_MATCHER new TypeArgOfMethodArgMatcher( "java.util.Collection", // class that defines the method "containsAll(java.util.Collection<?>)", // method signature 0, // index of the owning class's type argument to extract 0, // index of the method argument whose type argument to extract "java.util.Collection", // type of the method argument 0), // index of the method argument's type argument to extract new TypeArgOfMethodArgMatcher( "java.util.Collection", // class that defines the method "removeAll(java.util.Collection<?>)", // method signature 0, // index of the owning class's type argument to extract 0, // index of the method argument whose type argument to extract "java.util.Collection", // type of the method argument 0), // index of the method argument's type argument to extract new TypeArgOfMethodArgMatcher( "java.util.Collection", // class that defines the method "retainAll(java.util.Collection<?>)", // method signature 0, // index of the owning class's type argument to extract 0, // index of the method argument whose type argument to extract "java.util.Collection", // type of the method argument 0)); // index of the method argument's type argument to extract private static final ImmutableList<BinopMatcher> STATIC_MATCHERS = ImmutableList.of( new BinopMatcher("java.util.Collection", "java.util.Collections", "disjoint"), new BinopMatcher("java.util.Set", "com.google.common.collect.Sets", "difference")); private static final ImmutableList<AbstractCollectionIncompatibleTypeMatcher> ALL_MATCHERS = ImmutableList.<AbstractCollectionIncompatibleTypeMatcher>builder() .addAll(DIRECT_MATCHERS) .addAll(TYPE_ARG_MATCHERS) .addAll(STATIC_MATCHERS) .build(); @Nullable public static MatchResult firstNonNullMatchResult(ExpressionTree tree, VisitorState state) { if (!FIRST_ORDER_MATCHER.matches(tree, state)) { return null; } for (AbstractCollectionIncompatibleTypeMatcher matcher : ContainmentMatchers.ALL_MATCHERS) { MatchResult result = matcher.matches(tree, state); if (result != null) { return result; } } return null; } private ContainmentMatchers() {} }
6,398
49.785714
122
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/collectionincompatibletype/AbstractCollectionIncompatibleTypeMatcher.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.collectionincompatibletype; import com.google.auto.value.AutoValue; import com.google.errorprone.VisitorState; import com.google.errorprone.fixes.Fix; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; import java.util.Collection; import java.util.Map; import java.util.Optional; import javax.annotation.Nullable; /** * Extracts the necessary information from a {@link MethodInvocationTree} to check whether calls to * a method are using incompatible types and to emit a helpful error message. */ public abstract class AbstractCollectionIncompatibleTypeMatcher { /** * Returns a matcher for the appropriate method invocation for this matcher. For example, this * might match {@link Collection#remove(Object)} or {@link Map#containsKey(Object)}. */ abstract Matcher<ExpressionTree> methodMatcher(); /** * Extracts the source type that must be castable to the target type. For example, in this code * sample: * * <pre>{@code * Collection<Integer> collection; * collection.contains("foo"); * }</pre> * * The source type is String. * * @return the source type or null if not available */ @Nullable abstract Type extractSourceType(MethodInvocationTree tree, VisitorState state); @Nullable abstract Type extractSourceType(MemberReferenceTree tree, VisitorState state); /** * Returns the AST node from which the source type was extracted. Needed to produce readable error * messages. For example, in this code sample: * * <pre>{@code * Collection<Integer> collection; * collection.contains("foo"); * }</pre> * * The source tree is "foo". * * @return the source AST node or null if not available */ @Nullable abstract ExpressionTree extractSourceTree(MethodInvocationTree tree, VisitorState state); @Nullable abstract ExpressionTree extractSourceTree(MemberReferenceTree tree, VisitorState state); /** * Extracts the target type to which the source type must be castable. For example, in this code * sample: * * <pre>{@code * Collection<Integer> collection; * collection.contains("foo"); * }</pre> * * The target type is Integer. * * @return the target type or null if not available */ @Nullable abstract Type extractTargetType(MethodInvocationTree tree, VisitorState state); @Nullable abstract Type extractTargetType(MemberReferenceTree tree, VisitorState state); /** * Encapsulates the result of matching a {@link Collection#contains}-like call, including the * source and target types. */ @AutoValue public abstract static class MatchResult { public abstract ExpressionTree sourceTree(); public abstract Type sourceType(); public abstract Type targetType(); public abstract AbstractCollectionIncompatibleTypeMatcher matcher(); public static MatchResult create( ExpressionTree sourceTree, Type sourceType, Type targetType, AbstractCollectionIncompatibleTypeMatcher matcher) { return new AutoValue_AbstractCollectionIncompatibleTypeMatcher_MatchResult( sourceTree, sourceType, targetType, matcher); } public String message(String sourceType, String targetType) { return matcher().message(this, sourceType, targetType); } public Optional<Fix> buildFix() { return matcher().buildFix(this); } } @Nullable public final MatchResult matches(ExpressionTree tree, VisitorState state) { if (!methodMatcher().matches(tree, state)) { return null; } return new SimpleTreeVisitor<MatchResult, Void>() { @Override public MatchResult visitMethodInvocation( MethodInvocationTree methodInvocationTree, Void unused) { return getMatchResult( extractSourceTree(methodInvocationTree, state), extractSourceType(methodInvocationTree, state), extractTargetType(methodInvocationTree, state)); } @Override public MatchResult visitMemberReference( MemberReferenceTree memberReferenceTree, Void unused) { return getMatchResult( extractSourceTree(memberReferenceTree, state), extractSourceType(memberReferenceTree, state), extractTargetType(memberReferenceTree, state)); } }.visit(tree, null); } @Nullable private MatchResult getMatchResult( @Nullable ExpressionTree sourceTree, @Nullable Type sourceType, @Nullable Type targetType) { if (sourceTree == null || sourceType == null || targetType == null) { return null; } return MatchResult.create(sourceTree, sourceType, targetType, this); } /** * Extracts the appropriate type argument from a specific supertype of the given {@code type}. * This handles the case when a subtype has different type arguments than the expected type. For * example, {@code ClassToInstanceMap<T>} implements {@code Map<Class<? extends T>, T>}. * * @param type the (sub)type from which to extract the type argument * @param superTypeSym the symbol of the supertype on which the type parameter is defined * @param typeArgIndex the index of the type argument to extract from the supertype * @param types the {@link Types} utility class from the {@link VisitorState} * @return the type argument, if defined, or null otherwise */ @Nullable protected static Type extractTypeArgAsMemberOfSupertype( Type type, Symbol superTypeSym, int typeArgIndex, Types types) { Type collectionType = types.asSuper(type, superTypeSym); if (collectionType == null) { return null; } com.sun.tools.javac.util.List<Type> tyargs = collectionType.getTypeArguments(); if (tyargs.size() <= typeArgIndex) { // Collection is raw, nothing we can do. return null; } return tyargs.get(typeArgIndex); } Optional<Fix> buildFix(MatchResult result) { return Optional.empty(); } protected String message(MatchResult result, String sourceType, String targetType) { return String.format( "Argument '%s' should not be passed to this method; its type %s is not compatible with %s", result.sourceTree(), sourceType, targetType); } }
7,151
33.057143
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/collectionincompatibletype/BinopMatcher.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.collectionincompatibletype; import static com.google.errorprone.util.ASTHelpers.getType; import com.google.errorprone.VisitorState; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Type; import javax.annotation.Nullable; final class BinopMatcher extends AbstractCollectionIncompatibleTypeMatcher { private final Matcher<ExpressionTree> matcher; private final String collectionType; BinopMatcher(String collectionType, String className, String methodName) { this.collectionType = collectionType; matcher = Matchers.staticMethod().onClass(className).named(methodName); } @Override Matcher<ExpressionTree> methodMatcher() { return matcher; } @Nullable @Override Type extractSourceType(MethodInvocationTree tree, VisitorState state) { return extractTypeArgAsMemberOfSupertype( getType(tree.getArguments().get(0)), state.getSymbolFromString(collectionType), 0, state.getTypes()); } @Nullable @Override Type extractSourceType(MemberReferenceTree tree, VisitorState state) { Type descriptorType = state.getTypes().findDescriptorType(getType(tree)); return extractTypeArgAsMemberOfSupertype( descriptorType.getParameterTypes().get(0), state.getSymbolFromString(collectionType), 0, state.getTypes()); } @Nullable @Override ExpressionTree extractSourceTree(MethodInvocationTree tree, VisitorState state) { return tree.getArguments().get(0); } @Nullable @Override ExpressionTree extractSourceTree(MemberReferenceTree tree, VisitorState state) { return tree; } @Nullable @Override Type extractTargetType(MethodInvocationTree tree, VisitorState state) { return extractTypeArgAsMemberOfSupertype( getType(tree.getArguments().get(1)), state.getSymbolFromString(collectionType), 0, state.getTypes()); } @Nullable @Override Type extractTargetType(MemberReferenceTree tree, VisitorState state) { Type descriptorType = state.getTypes().findDescriptorType(getType(tree)); return extractTypeArgAsMemberOfSupertype( descriptorType.getParameterTypes().get(1), state.getSymbolFromString(collectionType), 0, state.getTypes()); } @Override protected String message(MatchResult result, String sourceType, String targetType) { return String.format( "Argument '%s' should not be passed to this method; its type %s is not compatible with" + " %s", result.sourceTree(), sourceType, targetType); } }
3,422
30.990654
95
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/collectionincompatibletype/IncompatibleArgumentType.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.collectionincompatibletype; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.bugpatterns.collectionincompatibletype.AbstractCollectionIncompatibleTypeMatcher.extractTypeArgAsMemberOfSupertype; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableListMultimap; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.CheckReturnValue; import com.google.errorprone.annotations.CompatibleWith; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.TypeCompatibilityUtils; import com.google.errorprone.bugpatterns.TypeCompatibilityUtils.TypeCompatibilityReport; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.Signatures; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.TypeVariableSymbol; 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.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import javax.inject.Inject; import javax.lang.model.element.Parameterizable; import javax.lang.model.element.TypeParameterElement; /** * @author glorioso@google.com (Nick Glorioso) */ @BugPattern( summary = "Passing argument to a generic method with an incompatible type.", severity = ERROR) public class IncompatibleArgumentType extends BugChecker implements MethodInvocationTreeMatcher { private final TypeCompatibilityUtils typeCompatibilityUtils; @Inject IncompatibleArgumentType(ErrorProneFlags flags) { this.typeCompatibilityUtils = TypeCompatibilityUtils.fromFlags(flags); } // Nonnull requiredType: The type I need is bound, in requiredType // null requiredType: I found the type variable, but I can't bind it to any type @AutoValue abstract static class RequiredType { @Nullable abstract Type type(); static RequiredType create(Type type) { return new AutoValue_IncompatibleArgumentType_RequiredType(type); } } @Override public Description matchMethodInvocation( MethodInvocationTree methodInvocationTree, VisitorState state) { // example: // class Foo<A> { // <B> void bar(@CompatibleWith("A") Object o, @CompatibleWith("B") Object o2) {} // } // new Foo<Integer>().<String>bar(1, "a'); // A Type substitution capturing <Integer> on Foo and <String> on bar(Object,Object); Type calledMethodType = ASTHelpers.getType(methodInvocationTree.getMethodSelect()); // A Type substitution capturing <Integer> on Foo Type calledClazzType = ASTHelpers.getReceiverType(methodInvocationTree); List<? extends ExpressionTree> arguments = methodInvocationTree.getArguments(); // The unbound MethodSymbol for bar(), with type parameters <A> and <B> MethodSymbol declaredMethod = ASTHelpers.getSymbol(methodInvocationTree); if (arguments.isEmpty()) { return Description.NO_MATCH; } List<RequiredType> requiredTypesAtCallSite = new ArrayList<>(Collections.nCopies(arguments.size(), null)); Types types = state.getTypes(); if (!populateTypesToEnforce( declaredMethod, calledMethodType, calledClazzType, requiredTypesAtCallSite, state)) { // No annotations on this method, try the supers; for (MethodSymbol method : ASTHelpers.findSuperMethods(declaredMethod, types)) { if (populateTypesToEnforce( method, calledMethodType, calledClazzType, requiredTypesAtCallSite, state)) { break; } } } reportAnyViolations(arguments, requiredTypesAtCallSite, state); // We manually report ourselves, so we don't pass any errors up the chain. return Description.NO_MATCH; } private void reportAnyViolations( List<? extends ExpressionTree> arguments, List<RequiredType> requiredArgumentTypes, VisitorState state) { Types types = state.getTypes(); for (int i = 0; i < requiredArgumentTypes.size(); i++) { RequiredType requiredType = requiredArgumentTypes.get(i); if (requiredType == null) { continue; } ExpressionTree argument = arguments.get(i); Type argType = ASTHelpers.getType(argument); if (requiredType.type() != null) { // Report a violation for this type TypeCompatibilityReport report = typeCompatibilityUtils.compatibilityOfTypes(requiredType.type(), argType, state); if (!report.isCompatible()) { state.reportMatch( describeViolation(argument, argType, requiredType.type(), types, state)); } } } } private Description describeViolation( ExpressionTree argument, Type argType, Type requiredType, Types types, VisitorState state) { // For the error message, use simple names instead of fully qualified names unless they are // identical. String sourceType = Signatures.prettyType(argType); String targetType = Signatures.prettyType(ASTHelpers.getUpperBound(requiredType, types)); if (sourceType.equals(targetType)) { sourceType = argType.toString(); targetType = requiredType.toString(); } String msg = String.format( "Argument '%s' should not be passed to this method. Its type %s is not" + " compatible with the required type: %s.", state.getSourceForNode(argument), sourceType, targetType); return buildDescription(argument).setMessage(msg).build(); } // Return whether this method contains any @CompatibleWith annotations. If there are none, the // caller should explore super-methods. @CheckReturnValue private static boolean populateTypesToEnforce( MethodSymbol declaredMethod, Type calledMethodType, Type calledReceiverType, List<RequiredType> argumentTypeRequirements, VisitorState state) { boolean foundAnyTypeToEnforce = false; List<VarSymbol> params = declaredMethod.params(); for (int i = 0; i < params.size(); i++) { VarSymbol varSymbol = params.get(i); CompatibleWith anno = ASTHelpers.getAnnotation(varSymbol, CompatibleWith.class); if (anno != null) { foundAnyTypeToEnforce = true; // Now we try and resolve the generic type argument in the annotation against the current // method call's projection of this generic type. RequiredType requiredType = resolveRequiredTypeForThisCall( state, calledMethodType, calledReceiverType, declaredMethod, anno.value()); // @CW is on the varags parameter if (declaredMethod.isVarArgs() && i == params.size() - 1) { if (i >= argumentTypeRequirements.size()) { // varargs method with 0 args passed from the caller side, no arguments to enforce // void foo(String...); foo(); break; } else { // Set this required type for all of the arguments in the varargs position. for (int j = i; j < argumentTypeRequirements.size(); j++) { argumentTypeRequirements.set(j, requiredType); } } } else { argumentTypeRequirements.set(i, requiredType); } } } return foundAnyTypeToEnforce; } @Nullable @CheckReturnValue // From calledReceiverType private static RequiredType resolveRequiredTypeForThisCall( VisitorState state, Type calledMethodType, Type calledReceiverType, MethodSymbol declaredMethod, String typeArgName) { RequiredType requiredType = resolveTypeFromGenericMethod(calledMethodType, declaredMethod, typeArgName); if (requiredType == null) { requiredType = resolveTypeFromClass( calledReceiverType, (ClassSymbol) declaredMethod.owner, typeArgName, state); } return requiredType; } @Nullable private static RequiredType resolveTypeFromGenericMethod( Type calledMethodType, MethodSymbol declaredMethod, String typeArgName) { int tyargIndex = findTypeArgInList(declaredMethod, typeArgName); return tyargIndex == -1 ? null : RequiredType.create( getTypeFromTypeMapping(calledMethodType, declaredMethod, typeArgName)); } // Plumb through a type which is supposed to be a Types.Subst, then find the replacement // type that the compiler resolved. @Nullable private static Type getTypeFromTypeMapping( Type m, MethodSymbol declaredMethod, String namedTypeArg) { ImmutableListMultimap<TypeVariableSymbol, Type> substitutions = ASTHelpers.getTypeSubstitution(m, declaredMethod); for (Map.Entry<TypeVariableSymbol, Type> e : substitutions.entries()) { if (e.getKey().getSimpleName().contentEquals(namedTypeArg)) { return e.getValue(); } } return null; } // class Foo<X> { void something(@CW("X") Object x); } // new Foo<String>().something(123); @Nullable private static RequiredType resolveTypeFromClass( Type calledType, ClassSymbol clazzSymbol, String typeArgName, VisitorState state) { // Try on the class int tyargIndex = findTypeArgInList(clazzSymbol, typeArgName); if (tyargIndex != -1) { return RequiredType.create( extractTypeArgAsMemberOfSupertype(calledType, clazzSymbol, tyargIndex, state.getTypes())); } while (clazzSymbol.isInner()) { // class Foo<T> { // class Bar { // void something(@CW("T") Object o)); // } // } // new Foo<String>().new Bar().something(123); // should fail, 123 needs to match String ClassSymbol encloser = clazzSymbol.owner.enclClass(); calledType = calledType.getEnclosingType(); tyargIndex = findTypeArgInList(encloser, typeArgName); if (tyargIndex != -1) { if (calledType.getTypeArguments().isEmpty()) { // If the receiver is held in a reference without the enclosing class's type arguments, we // can't determine the required type: // new Foo<String>().new Bar().something(123); // Yep // Foo<String>.Bar bar = ...; // bar.something(123); // Yep // Foo.Bar bar = ...; // bar.something(123); // Nope (this call would be unchecked if arg was T) return null; } return RequiredType.create(calledType.getTypeArguments().get(tyargIndex)); } clazzSymbol = encloser; } return null; } private static int findTypeArgInList(Parameterizable hasTypeParams, String typeArgName) { List<? extends TypeParameterElement> typeParameters = hasTypeParams.getTypeParameters(); for (int i = 0; i < typeParameters.size(); i++) { if (typeParameters.get(i).getSimpleName().contentEquals(typeArgName)) { return i; } } return -1; } }
11,963
38.098039
151
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/collectionincompatibletype/TypeArgOfMethodArgMatcher.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.collectionincompatibletype; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.util.ASTHelpers.getType; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.google.errorprone.VisitorState; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.Signatures; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Type; import java.util.Collection; import java.util.Optional; import javax.annotation.Nullable; /** * Matches an instance method like {@link Collection#removeAll}, for which we need to extract the * type argument to the method argument. */ class TypeArgOfMethodArgMatcher extends AbstractCollectionIncompatibleTypeMatcher { private final Matcher<ExpressionTree> methodMatcher; private final String receiverTypeName; private final int receiverTypeArgIndex; private final int methodArgIndex; private final String methodArgTypeName; private final int methodArgTypeArgIndex; /** * @param receiverTypeName The fully-qualified name of the type of the method receiver whose * descendants to match on * @param signature The signature of the method to match on * @param receiverTypeArgIndex The index of the type argument that should match the method * argument * @param methodArgIndex The index of the method argument whose type argument we should extract * @param methodArgTypeName The fully-qualified name of the type of the method argument whose type * argument we should extract * @param methodArgTypeArgIndex The index of the type argument to extract from the method argument */ public TypeArgOfMethodArgMatcher( String receiverTypeName, String signature, int receiverTypeArgIndex, int methodArgIndex, String methodArgTypeName, int methodArgTypeArgIndex) { this.methodMatcher = instanceMethod().onDescendantOf(receiverTypeName).withSignature(signature); this.receiverTypeName = receiverTypeName; this.receiverTypeArgIndex = receiverTypeArgIndex; this.methodArgIndex = methodArgIndex; this.methodArgTypeName = methodArgTypeName; this.methodArgTypeArgIndex = methodArgTypeArgIndex; } @Override Matcher<ExpressionTree> methodMatcher() { return methodMatcher; } @Override ExpressionTree extractSourceTree(MethodInvocationTree tree, VisitorState state) { return Iterables.get(tree.getArguments(), methodArgIndex); } @Nullable @Override ExpressionTree extractSourceTree(MemberReferenceTree tree, VisitorState state) { return tree; } @Override Type extractSourceType(MethodInvocationTree tree, VisitorState state) { return extractTypeArgAsMemberOfSupertype( getType(Iterables.get(tree.getArguments(), methodArgIndex)), state.getSymbolFromString(methodArgTypeName), methodArgTypeArgIndex, state.getTypes()); } @Nullable @Override Type extractSourceType(MemberReferenceTree tree, VisitorState state) { return extractTypeArgAsMemberOfSupertype( getType(tree).allparams().get(methodArgIndex), state.getSymbolFromString(methodArgTypeName), methodArgTypeArgIndex, state.getTypes()); } @Override Type extractTargetType(MethodInvocationTree tree, VisitorState state) { return extractTypeArgAsMemberOfSupertype( ASTHelpers.getReceiverType(tree), state.getSymbolFromString(receiverTypeName), receiverTypeArgIndex, state.getTypes()); } @Nullable @Override Type extractTargetType(MemberReferenceTree tree, VisitorState state) { return extractTypeArgAsMemberOfSupertype( ASTHelpers.getReceiverType(tree), state.getSymbolFromString(receiverTypeName), receiverTypeArgIndex, state.getTypes()); } String getMethodArgTypeName() { return methodArgTypeName; } @Override Optional<Fix> buildFix(MatchResult result) { String fullyQualifiedType = getMethodArgTypeName(); String simpleType = Iterables.getLast(Splitter.on('.').split(fullyQualifiedType)); return Optional.of( SuggestedFix.builder() .prefixWith(result.sourceTree(), String.format("(%s<?>) ", simpleType)) .addImport(fullyQualifiedType) .build()); } @Override public String message(MatchResult result, String sourceType, String targetType) { String sourceTreeType = Signatures.prettyType(getType(result.sourceTree())); return String.format( "Argument '%s' should not be passed to this method; its type %s has a type argument " + "%s that is not compatible with its collection's type argument %s", result.sourceTree(), sourceTreeType, sourceType, targetType); } }
5,696
35.754839
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/collectionincompatibletype/CollectionUndefinedEquality.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.collectionincompatibletype; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.anyMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.TypesWithUndefinedEquality; import com.google.errorprone.bugpatterns.collectionincompatibletype.AbstractCollectionIncompatibleTypeMatcher.MatchResult; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MethodInvocationTree; import java.util.Arrays; /** * Highlights use of {@code Collection#contains} (and others) with types that do not have * well-defined equals. */ @BugPattern( summary = "This type does not have well-defined equals behavior.", tags = StandardTags.FRAGILE_CODE, severity = WARNING) public final class CollectionUndefinedEquality extends BugChecker implements MethodInvocationTreeMatcher, MemberReferenceTreeMatcher { // NOTE: this is a bit crude; methods like `containsValue` are still likely to be subject to // equality constraints on the value type. private static final Matcher<ExpressionTree> TYPES_NOT_DEPENDING_ON_OBJECT_EQUALITY = anyMethod() .onDescendantOfAny( "java.util.IdentityHashMap", "java.util.IdentityHashSet", "java.util.SortedMap", "java.util.SortedSet"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return match(tree, state); } @Override public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) { return match(tree, state); } public Description match(ExpressionTree tree, VisitorState state) { MatchResult result = ContainmentMatchers.firstNonNullMatchResult(tree, state); if (result == null) { return NO_MATCH; } if (TYPES_NOT_DEPENDING_ON_OBJECT_EQUALITY.matches(tree, state)) { return NO_MATCH; } return Arrays.stream(TypesWithUndefinedEquality.values()) .filter( b -> b.matchesType(result.sourceType(), state) || b.matchesType(result.targetType(), state)) .findFirst() .map( b -> buildDescription(tree) .setMessage(b.shortName() + " does not have well-defined equals behavior.") .build()) .orElse(NO_MATCH); } }
3,593
38.494505
122
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/collectionincompatibletype/MethodArgMatcher.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.collectionincompatibletype; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.util.ASTHelpers.getType; import com.google.common.collect.Iterables; import com.google.errorprone.VisitorState; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Type; import java.util.Collection; import java.util.Optional; import javax.annotation.Nullable; /** * Matches an instance method like {@link Collection#contains}, for which we just need to compare * the method argument's type to the receiver's type argument. This is the common case. */ final class MethodArgMatcher extends AbstractCollectionIncompatibleTypeMatcher { private final Matcher<ExpressionTree> methodMatcher; private final String typeName; private final int typeArgIndex; private final int methodArgIndex; /** * @param typeName The fully-qualified name of the type whose descendants to match on * @param signature The signature of the method to match on * @param typeArgIndex The index of the type argument that should match the method argument * @param methodArgIndex The index of the method argument that should match the type argument */ MethodArgMatcher(String typeName, String signature, int typeArgIndex, int methodArgIndex) { this.methodMatcher = instanceMethod().onDescendantOf(typeName).withSignature(signature); this.typeName = typeName; this.typeArgIndex = typeArgIndex; this.methodArgIndex = methodArgIndex; } @Override Matcher<ExpressionTree> methodMatcher() { return methodMatcher; } @Override ExpressionTree extractSourceTree(MethodInvocationTree tree, VisitorState state) { return Iterables.get(tree.getArguments(), methodArgIndex); } @Nullable @Override ExpressionTree extractSourceTree(MemberReferenceTree tree, VisitorState state) { return tree; } @Override Type extractSourceType(MethodInvocationTree tree, VisitorState state) { return getType(extractSourceTree(tree, state)); } @Nullable @Override Type extractSourceType(MemberReferenceTree tree, VisitorState state) { return state.getTypes().findDescriptorType(getType(tree)).getParameterTypes().get(0); } @Override Type extractTargetType(MethodInvocationTree tree, VisitorState state) { return extractTypeArgAsMemberOfSupertype( ASTHelpers.getReceiverType(tree), state.getSymbolFromString(typeName), typeArgIndex, state.getTypes()); } @Nullable @Override Type extractTargetType(MemberReferenceTree tree, VisitorState state) { return extractTypeArgAsMemberOfSupertype( ASTHelpers.getReceiverType(tree), state.getSymbolFromString(typeName), typeArgIndex, state.getTypes()); } @Override Optional<Fix> buildFix(MatchResult result) { return Optional.of(SuggestedFix.prefixWith(result.sourceTree(), "(Object) ")); } @Override public String message(MatchResult result, String sourceType, String targetType) { return String.format( "Argument '%s' should not be passed to this method; its type %s is not compatible " + "with its collection's type argument %s", result.sourceTree(), sourceType, targetType); } }
4,201
34.310924
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/collectionincompatibletype/TruthIncompatibleType.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.collectionincompatibletype; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.collectionincompatibletype.AbstractCollectionIncompatibleTypeMatcher.extractTypeArgAsMemberOfSupertype; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.google.errorprone.suppliers.Suppliers.typeFromString; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isCastable; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static java.util.stream.Stream.concat; 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; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.TypeCompatibilityUtils; import com.google.errorprone.bugpatterns.TypeCompatibilityUtils.TypeCompatibilityReport; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.Signatures; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeCastTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ArrayType; import java.util.stream.Stream; import javax.inject.Inject; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "Argument is not compatible with the subject's type.", severity = WARNING) public class TruthIncompatibleType extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> START_OF_ASSERTION = anyOf( staticMethod() .onClassAny("com.google.common.truth.Truth", "com.google.common.truth.Truth8") .named("assertThat"), staticMethod() .onClass("com.google.common.truth.extensions.proto.ProtoTruth") .named("assertThat"), instanceMethod() .onDescendantOf("com.google.common.truth.StandardSubjectBuilder") .named("that")); private static final Matcher<ExpressionTree> IS_EQUAL_TO = anyOf( instanceMethod() .onDescendantOf("com.google.common.truth.Subject") .namedAnyOf("isEqualTo", "isNotEqualTo"), instanceMethod() .onDescendantOf("com.google.common.truth.extensions.proto.ProtoFluentAssertion") .namedAnyOf("isEqualTo", "isNotEqualTo")); private static final Matcher<ExpressionTree> FLUENT_PROTO_CHAIN = anyOf( instanceMethod() .onDescendantOf("com.google.common.truth.extensions.proto.ProtoFluentAssertion"), instanceMethod().onDescendantOf("com.google.common.truth.extensions.proto.ProtoSubject")); private static final Matcher<ExpressionTree> SCALAR_CONTAINS = instanceMethod() .onDescendantOfAny( "com.google.common.truth.IterableSubject", "com.google.common.truth.StreamSubject") .namedAnyOf( "contains", "containsExactly", "doesNotContain", "containsAnyOf", "containsNoneOf"); private static final Matcher<ExpressionTree> VECTOR_CONTAINS = instanceMethod() .onDescendantOfAny( "com.google.common.truth.IterableSubject", "com.google.common.truth.StreamSubject") .namedAnyOf( "containsExactlyElementsIn", "containsAnyIn", "containsAtLeastElementsIn", "containsNoneIn") .withParameters("java.lang.Iterable"); private static final Matcher<ExpressionTree> MAP_SCALAR_CONTAINS = instanceMethod() .onDescendantOfAny( "com.google.common.truth.MapSubject", "com.google.common.truth.MultimapSubject") .namedAnyOf("containsEntry", "doesNotContainEntry", "containsExactly", "containsAtLeast"); private static final Matcher<ExpressionTree> MAP_SCALAR_KEYS = instanceMethod() .onDescendantOfAny( "com.google.common.truth.MapSubject", "com.google.common.truth.MultimapSubject") .namedAnyOf("containsKey", "doesNotContainKey"); private static final Matcher<ExpressionTree> MAP_VECTOR_CONTAINS = instanceMethod() .onDescendantOfAny( "com.google.common.truth.MapSubject", "com.google.common.truth.MultimapSubject") .namedAnyOf("containsExactlyEntriesIn", "containsAtLeastEntriesIn"); private static final Matcher<ExpressionTree> COMPARING_ELEMENTS_USING = instanceMethod() .onDescendantOf("com.google.common.truth.IterableSubject") .named("comparingElementsUsing"); private static final Matcher<ExpressionTree> ARRAY_CONTAINS = allOf( instanceMethod() .onDescendantOf("com.google.common.truth.IterableSubject") .namedAnyOf( "containsExactlyElementsIn", "containsAnyIn", "containsAtLeastElementsIn", "containsNoneIn"), not(VECTOR_CONTAINS)); private static final Supplier<Type> CORRESPONDENCE = typeFromString("com.google.common.truth.Correspondence"); private final TypeCompatibilityUtils typeCompatibilityUtils; @Inject TruthIncompatibleType(ErrorProneFlags flags) { this.typeCompatibilityUtils = TypeCompatibilityUtils.fromFlags(flags); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { Streams.concat( matchEquality(tree, state), matchVectorContains(tree, state), matchArrayContains(tree, state), matchScalarContains(tree, state), matchCorrespondence(tree, state), matchMapVectorContains(tree, state), matchMapScalarContains(tree, state), matchMapContainsKey(tree, state)) .forEach(state::reportMatch); return NO_MATCH; } private Stream<Description> matchEquality(MethodInvocationTree tree, VisitorState state) { if (!IS_EQUAL_TO.matches(tree, state)) { return Stream.empty(); } ExpressionTree receiver = getReceiver(tree); while (true) { if (!(receiver instanceof MethodInvocationTree)) { return Stream.empty(); } if (START_OF_ASSERTION.matches(receiver, state)) { break; } // TODO(b/190357148): Handle fluent methods which change the expected target type. if (!FLUENT_PROTO_CHAIN.matches(receiver, state)) { return Stream.empty(); } receiver = getReceiver(receiver); } Type targetType = getType(ignoringCasts(getOnlyElement(((MethodInvocationTree) receiver).getArguments()))); Type sourceType = getType(getOnlyElement(tree.getArguments())); if (isNumericType(sourceType, state) && isNumericType(targetType, state)) { return Stream.of(); } return checkCompatibility(getOnlyElement(tree.getArguments()), targetType, sourceType, state); } private Stream<Description> matchVectorContains(MethodInvocationTree tree, VisitorState state) { if (!VECTOR_CONTAINS.matches(tree, state)) { return Stream.empty(); } ExpressionTree receiver = getReceiver(tree); if (!START_OF_ASSERTION.matches(receiver, state)) { return Stream.empty(); } Type targetType = getIterableTypeArg( getOnlyElement(getSymbol((MethodInvocationTree) receiver).getParameters()).type, ignoringCasts(getOnlyElement(((MethodInvocationTree) receiver).getArguments())), state); Type sourceType = getIterableTypeArg( getOnlyElement(getSymbol((MethodInvocationTree) receiver).getParameters()).type, getOnlyElement(tree.getArguments()), state); return checkCompatibility(getOnlyElement(tree.getArguments()), targetType, sourceType, state); } private Stream<Description> matchArrayContains(MethodInvocationTree tree, VisitorState state) { if (!ARRAY_CONTAINS.matches(tree, state)) { return Stream.empty(); } ExpressionTree receiver = getReceiver(tree); if (!START_OF_ASSERTION.matches(receiver, state)) { return Stream.empty(); } Type targetType = getIterableTypeArg( getOnlyElement(getSymbol((MethodInvocationTree) receiver).getParameters()).type, ignoringCasts(getOnlyElement(((MethodInvocationTree) receiver).getArguments())), state); Type sourceType = ((ArrayType) getType(getOnlyElement(tree.getArguments()))).elemtype; return checkCompatibility(getOnlyElement(tree.getArguments()), targetType, sourceType, state); } private Stream<Description> matchScalarContains(MethodInvocationTree tree, VisitorState state) { if (!SCALAR_CONTAINS.matches(tree, state)) { return Stream.empty(); } ExpressionTree receiver = getReceiver(tree); if (!START_OF_ASSERTION.matches(receiver, state)) { return Stream.empty(); } Tree argument = ignoringCasts(getOnlyElement(((MethodInvocationTree) receiver).getArguments())); Type targetType = getIterableTypeArg( getOnlyElement(getSymbol((MethodInvocationTree) receiver).getParameters()).type, argument, state); MethodSymbol methodSymbol = getSymbol(tree); return Streams.mapWithIndex( tree.getArguments().stream(), (arg, index) -> { Type argumentType = getType(arg); return isNonVarargsCall(methodSymbol, index, argumentType) ? checkCompatibility(arg, targetType, ((ArrayType) argumentType).elemtype, state) : checkCompatibility(arg, targetType, argumentType, state); }) .flatMap(x -> x); } private Stream<Description> matchCorrespondence(MethodInvocationTree tree, VisitorState state) { if (!COMPARING_ELEMENTS_USING.matches(tree, state)) { return Stream.empty(); } ExpressionTree receiver = getReceiver(tree); if (!START_OF_ASSERTION.matches(receiver, state)) { return Stream.empty(); } Type targetType = getIterableTypeArg( getOnlyElement(getSymbol((MethodInvocationTree) receiver).getParameters()).type, ignoringCasts(getOnlyElement(((MethodInvocationTree) receiver).getArguments())), state); if (targetType == null) { // The target collection may be raw. return Stream.empty(); } ExpressionTree argument = getOnlyElement(tree.getArguments()); Type sourceType = getCorrespondenceTypeArg(argument, state); // This is different to the others: we're checking for castability, not possible equality. if (sourceType == null || isCastable(targetType, sourceType, state)) { return Stream.empty(); } String sourceTypeName = Signatures.prettyType(sourceType); String targetTypeName = Signatures.prettyType(targetType); if (sourceTypeName.equals(targetTypeName)) { sourceTypeName = sourceType.toString(); targetTypeName = targetType.toString(); } return Stream.of( buildDescription(argument) .setMessage( String.format( "Argument '%s' should not be passed to this method: its type `%s` is" + " not compatible with `%s`", state.getSourceForNode(argument), sourceTypeName, targetTypeName)) .build()); } private Stream<Description> matchMapVectorContains( MethodInvocationTree tree, VisitorState state) { if (!MAP_VECTOR_CONTAINS.matches(tree, state)) { return Stream.empty(); } ExpressionTree receiver = getReceiver(tree); if (!START_OF_ASSERTION.matches(receiver, state)) { return Stream.empty(); } ExpressionTree assertee = getOnlyElement(((MethodInvocationTree) receiver).getArguments()); TypeSymbol assertionType = getOnlyElement(getSymbol((MethodInvocationTree) receiver).getParameters()).type.tsym; Type targetKeyType = extractTypeArgAsMemberOfSupertype( getType(ignoringCasts(assertee)), assertionType, /* typeArgIndex= */ 0, state.getTypes()); Type targetValueType = extractTypeArgAsMemberOfSupertype( getType(ignoringCasts(assertee)), assertionType, /* typeArgIndex= */ 1, state.getTypes()); Type sourceKeyType = extractTypeArgAsMemberOfSupertype( getType(getOnlyElement(tree.getArguments())), assertionType, /* typeArgIndex= */ 0, state.getTypes()); Type sourceValueType = extractTypeArgAsMemberOfSupertype( getType(getOnlyElement(tree.getArguments())), assertionType, /* typeArgIndex= */ 1, state.getTypes()); return concat( checkCompatibility( getOnlyElement(tree.getArguments()), targetKeyType, sourceKeyType, state), checkCompatibility( getOnlyElement(tree.getArguments()), targetValueType, sourceValueType, state)); } private Stream<Description> matchMapContainsKey(MethodInvocationTree tree, VisitorState state) { if (!MAP_SCALAR_KEYS.matches(tree, state)) { return Stream.empty(); } ExpressionTree receiver = getReceiver(tree); if (!START_OF_ASSERTION.matches(receiver, state)) { return Stream.empty(); } ExpressionTree assertee = getOnlyElement(((MethodInvocationTree) receiver).getArguments()); TypeSymbol assertionType = getOnlyElement(getSymbol((MethodInvocationTree) receiver).getParameters()).type.tsym; Type targetKeyType = extractTypeArgAsMemberOfSupertype( getType(ignoringCasts(assertee)), assertionType, /* typeArgIndex= */ 0, state.getTypes()); return checkCompatibility( getOnlyElement(tree.getArguments()), targetKeyType, getType(getOnlyElement(tree.getArguments())), state); } private Stream<Description> matchMapScalarContains( MethodInvocationTree tree, VisitorState state) { if (!MAP_SCALAR_CONTAINS.matches(tree, state)) { return Stream.empty(); } ExpressionTree receiver = getReceiver(tree); if (!START_OF_ASSERTION.matches(receiver, state)) { return Stream.empty(); } ExpressionTree assertee = getOnlyElement(((MethodInvocationTree) receiver).getArguments()); TypeSymbol assertionType = getOnlyElement(getSymbol((MethodInvocationTree) receiver).getParameters()).type.tsym; Type targetKeyType = extractTypeArgAsMemberOfSupertype( getType(ignoringCasts(assertee)), assertionType, /* typeArgIndex= */ 0, state.getTypes()); Type targetValueType = extractTypeArgAsMemberOfSupertype( getType(ignoringCasts(assertee)), assertionType, /* typeArgIndex= */ 1, state.getTypes()); MethodSymbol methodSymbol = getSymbol(tree); return Streams.mapWithIndex( tree.getArguments().stream(), (arg, index) -> isNonVarargsCall(methodSymbol, index, getType(arg)) ? Stream.<Description>empty() : checkCompatibility( arg, index % 2 == 0 ? targetKeyType : targetValueType, getType(arg), state)) .flatMap(x -> x); } /** Whether this is a varargs method being invoked in a non-varargs way. */ private static boolean isNonVarargsCall( MethodSymbol methodSymbol, long index, Type argumentType) { return methodSymbol.getParameters().size() - 1 == index && methodSymbol.isVarArgs() && argumentType instanceof ArrayType && !((ArrayType) argumentType).elemtype.isPrimitive(); } private Stream<Description> checkCompatibility( ExpressionTree tree, Type targetType, Type sourceType, VisitorState state) { TypeCompatibilityReport compatibilityReport = typeCompatibilityUtils.compatibilityOfTypes(targetType, sourceType, state); if (compatibilityReport.isCompatible()) { return Stream.empty(); } String sourceTypeName = Signatures.prettyType(sourceType); String targetTypeName = Signatures.prettyType(targetType); if (sourceTypeName.equals(targetTypeName)) { sourceTypeName = sourceType.toString(); targetTypeName = targetType.toString(); } return Stream.of( buildDescription(tree) .setMessage( String.format( "Argument '%s' should not be passed to this method: its type `%s` is" + " not compatible with `%s`" + compatibilityReport.extraReason(), state.getSourceForNode(tree), sourceTypeName, targetTypeName)) .build()); } private Tree ignoringCasts(Tree tree) { return tree.accept( new SimpleTreeVisitor<Tree, Void>() { @Override protected Tree defaultAction(Tree node, Void unused) { return node; } @Override public Tree visitTypeCast(TypeCastTree node, Void unused) { return node.getExpression().accept(this, null); } @Override public Tree visitParenthesized(ParenthesizedTree node, Void unused) { return node.getExpression().accept(this, null); } }, null); } private static Type getIterableTypeArg(Type type, Tree onlyElement, VisitorState state) { return extractTypeArgAsMemberOfSupertype( getType(onlyElement), type.tsym, /* typeArgIndex= */ 0, state.getTypes()); } private static Type getCorrespondenceTypeArg(Tree onlyElement, VisitorState state) { return extractTypeArgAsMemberOfSupertype( getType(onlyElement), CORRESPONDENCE.get(state).tsym, /* typeArgIndex= */ 0, state.getTypes()); } private static boolean isNumericType(Type parameter, VisitorState state) { return parameter.isNumeric() || isSubtype(parameter, JAVA_LANG_NUMBER.get(state), state); } private static final Supplier<Type> JAVA_LANG_NUMBER = VisitorState.memoize(state -> state.getTypeFromString("java.lang.Number")); }
20,066
40.205339
151
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/android/RectIntersectReturnValueIgnored.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.android; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Matchers.instanceMethod; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.AbstractReturnValueIgnored; import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions; 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 javax.inject.Inject; /** * @author avenet@google.com (Arnaud J. Venet) */ @BugPattern( summary = "Return value of android.graphics.Rect.intersect() must be checked", severity = ERROR) public final class RectIntersectReturnValueIgnored extends AbstractReturnValueIgnored { @Inject RectIntersectReturnValueIgnored(ConstantExpressions constantExpressions) { super(constantExpressions); } @Override public Matcher<? super ExpressionTree> specializedMatcher() { return instanceMethod().onExactClass("android.graphics.Rect").named("intersect"); } @Override protected Description describeReturnValueIgnored( MethodInvocationTree methodInvocationTree, VisitorState state) { if (!state.isAndroidCompatible()) { return Description.NO_MATCH; } return describeMatch(methodInvocationTree); } }
2,069
34.689655
87
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/android/MislabeledAndroidString.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.android; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.util.ASTHelpers.isStatic; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MemberSelectTree; import com.sun.tools.javac.code.Symbol; import javax.lang.model.element.ElementKind; /** * Replacement of misleading <a * href="http://developer.android.com/reference/android/R.string.html">android.R.string</a> * constants with more intuitive ones. * * @author kmb@google.com (Kevin Bierhoff) */ @BugPattern( summary = "Certain resources in `android.R.string` have names that do not match their content", severity = ERROR) public class MislabeledAndroidString extends BugChecker implements MemberSelectTreeMatcher { private static final String R_STRING_CLASSNAME = "android.R.string"; /** Maps problematic resources defined in {@value #R_STRING_CLASSNAME} to their replacements. */ @VisibleForTesting static final ImmutableMap<String, String> MISLEADING = ImmutableMap.of( "yes", "ok", "no", "cancel"); /** Maps all resources appearing in {@link #MISLEADING} to an assumed meaning. */ @VisibleForTesting static final ImmutableMap<String, String> ASSUMED_MEANINGS = ImmutableMap.of( "yes", "Yes", // assumed but not actual meaning "no", "No", // assumed but not actual meaning "ok", "OK", // assumed and actual meaning "cancel", "Cancel"); // assumed and actual meaning @Override public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) { if (!state.isAndroidCompatible()) { return Description.NO_MATCH; } Symbol symbol = ASTHelpers.getSymbol(tree); // Match symbol's owner to android.R.string separately because couldn't get fully qualified // "android.R.string.yes" out of symbol, just "yes" if (symbol == null || symbol.owner == null || symbol.getKind() != ElementKind.FIELD || !isStatic(symbol) || !R_STRING_CLASSNAME.contentEquals(symbol.owner.getQualifiedName())) { return Description.NO_MATCH; } String misleading = symbol.getSimpleName().toString(); String preferred = MISLEADING.get(misleading); if (preferred == null) { return Description.NO_MATCH; } return buildDescription(tree) .setMessage( String.format( "%s.%s is not \"%s\" but \"%s\"; prefer %s.%s for clarity", R_STRING_CLASSNAME, misleading, ASSUMED_MEANINGS.get(misleading), ASSUMED_MEANINGS.get(preferred), R_STRING_CLASSNAME, preferred)) // Keep the way tree refers to android.R.string as it is but replace the identifier .addFix( SuggestedFix.replace( tree, state.getSourceForNode(tree.getExpression()) + "." + preferred)) .build(); } }
4,025
38.470588
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/android/FragmentNotInstantiable.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.android; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import static com.google.errorprone.matchers.Matchers.kindIs; import static com.google.errorprone.matchers.Matchers.nestingKind; import static com.sun.source.tree.Tree.Kind.CLASS; import static javax.lang.model.element.Modifier.ABSTRACT; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.NestingKind.MEMBER; 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; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import java.util.List; import java.util.stream.Collectors; /** * @author avenet@google.com (Arnaud J. Venet) */ @BugPattern( altNames = {"ValidFragment"}, summary = "Subclasses of Fragment must be instantiable via Class#newInstance():" + " the class must be public, static and have a public nullary constructor", severity = WARNING, tags = StandardTags.LIKELY_ERROR) public class FragmentNotInstantiable extends BugChecker implements ClassTreeMatcher { private static final String MESSAGE_BASE = "Fragment is not instantiable: "; private static final String FRAGMENT_CLASS = "android.app.Fragment"; // Static library support version of the framework's Fragment. Used to write apps that run on // platforms prior to Android 3.0. private static final String FRAGMENT_CLASS_V4 = "android.support.v4.app.Fragment"; private final ImmutableSet<String> fragmentClasses; private final Matcher<ClassTree> fragmentMatcher; public FragmentNotInstantiable() { this(ImmutableSet.of()); } protected FragmentNotInstantiable(Iterable<String> additionalFragmentClasses) { fragmentClasses = ImmutableSet.<String>builder() .add(FRAGMENT_CLASS) .add(FRAGMENT_CLASS_V4) .addAll(additionalFragmentClasses) .build(); fragmentMatcher = allOf( kindIs(CLASS), anyOf( fragmentClasses.stream() .map(fragmentClass -> isSubtypeOf(fragmentClass)) .collect(Collectors.toList()))); } private Description buildErrorMessage(Tree tree, String explanation) { Description.Builder description = buildDescription(tree); description.setMessage(MESSAGE_BASE + explanation + "."); return description.build(); } @Override public Description matchClass(ClassTree classTree, VisitorState state) { if (!state.isAndroidCompatible()) { return Description.NO_MATCH; } if (!fragmentMatcher.matches(classTree, state)) { return Description.NO_MATCH; } String className = ASTHelpers.getSymbol(classTree).toString(); if (fragmentClasses.contains(className)) { // Do not check the base class declarations (or their stubs). return Description.NO_MATCH; } // The check doesn't apply to abstract classes. if (classTree.getModifiers().getFlags().contains(ABSTRACT)) { return Description.NO_MATCH; } // A fragment must be public. if (!classTree.getModifiers().getFlags().contains(PUBLIC)) { return buildErrorMessage(classTree, "a fragment must be public"); } // A fragment that is an inner class must be static. if (nestingKind(MEMBER).matches(classTree, state) && !ASTHelpers.getSymbol(classTree).isStatic()) { return buildErrorMessage(classTree, "a fragment inner class must be static"); } List<MethodTree> constructors = ASTHelpers.getConstructors(classTree); for (MethodTree constructor : constructors) { if (constructor.getParameters().isEmpty()) { // The nullary constructor exists. We must make sure that it is public. if (!constructor.getModifiers().getFlags().contains(PUBLIC)) { return buildErrorMessage(constructor, "the nullary constructor must be public"); } return Description.NO_MATCH; } } // If we reach this point, we know for sure that the class has at least one constructor // but no nullary constructor. return buildErrorMessage(classTree, "the nullary constructor is missing"); } }
5,421
38.007194
95
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/android/WakelockReleasedDangerously.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.android; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.util.ASTHelpers.constValue; import static com.google.errorprone.util.ASTHelpers.findEnclosingNode; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Streams; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; 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.CatchTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IfTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.LambdaExpressionTree.BodyKind; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.TryTree; 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 com.sun.tools.javac.code.Type.UnionClassType; import com.sun.tools.javac.code.Types; /** * @author epmjohnston@google.com */ @BugPattern( tags = StandardTags.FRAGILE_CODE, summary = "On Android versions < P, a wakelock acquired with a timeout may be released by the system" + " before calling `release`, even after checking `isHeld()`. If so, it will throw a" + " RuntimeException. Please wrap in a try/catch block.", severity = SeverityLevel.WARNING) public class WakelockReleasedDangerously extends BugChecker implements MethodInvocationTreeMatcher { private static final String WAKELOCK_CLASS_NAME = "android.os.PowerManager.WakeLock"; private static final Matcher<ExpressionTree> RELEASE = MethodMatchers.instanceMethod().onExactClass(WAKELOCK_CLASS_NAME).named("release"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!state.isAndroidCompatible()) { return Description.NO_MATCH; } // Match on calls to any override of WakeLock.release(). if (!RELEASE.matches(tree, state)) { return NO_MATCH; } // Ok if surrounded in try/catch block that catches RuntimeException. TryTree enclosingTry = findEnclosingNode(state.getPath(), TryTree.class); if (enclosingTry != null && tryCatchesException(enclosingTry, state.getSymtab().runtimeExceptionType, state)) { return NO_MATCH; } // Ok if WakeLock not in danger of unexpected exception. // Also, can't perform analysis if WakeLock symbol not found. Symbol wakelockSymbol = getSymbol(getReceiver(tree)); if (wakelockSymbol == null || !wakelockMayThrow(wakelockSymbol, state)) { return NO_MATCH; } Tree releaseStatement = state.getPath().getParentPath().getLeaf(); return describeMatch(releaseStatement, getFix(releaseStatement, wakelockSymbol, state)); } private static SuggestedFix getFix( Tree releaseStatement, Symbol wakelockSymbol, VisitorState state) { // Wrap the release call line in a try/catch(RuntimeException) block. String before = "\ntry {\n"; String after = "\n} catch (RuntimeException unused) {\n" + "// Ignore: already released by timeout.\n" + "// TODO: Log this exception.\n" + "}\n"; // Lambda expressions are special. If the release call is in a one-expression lambda, // only wrap body (not args) and convert to block lambda. if (releaseStatement.getKind() == Kind.LAMBDA_EXPRESSION) { LambdaExpressionTree enclosingLambda = (LambdaExpressionTree) releaseStatement; if (enclosingLambda.getBodyKind() == BodyKind.EXPRESSION) { releaseStatement = enclosingLambda.getBody(); before = "{" + before; after = ";" + after + "}"; } } // Remove `if (wakelock.isHeld())` check. // TODO(epmjohnston): can avoid this if no isHeld check in class (check call map). IfTree enclosingIfHeld = findEnclosingNode(state.getPath(), IfTree.class); if (enclosingIfHeld != null) { ExpressionTree condition = ASTHelpers.stripParentheses(enclosingIfHeld.getCondition()); if (enclosingIfHeld.getElseStatement() == null && instanceMethod() .onExactClass(WAKELOCK_CLASS_NAME) .named("isHeld") .matches(condition, state) && wakelockSymbol.equals(getSymbol(getReceiver(condition)))) { String ifBody = state.getSourceForNode(enclosingIfHeld.getThenStatement()).trim(); // Remove leading and trailing `{}` ifBody = ifBody.startsWith("{") ? ifBody.substring(1) : ifBody; ifBody = ifBody.endsWith("}") ? ifBody.substring(0, ifBody.length() - 1) : ifBody; ifBody = ifBody.trim(); String releaseStatementSource = state.getSourceForNode(releaseStatement); return SuggestedFix.replace( enclosingIfHeld, ifBody.replace(releaseStatementSource, before + releaseStatementSource + after)); } } return SuggestedFix.builder() .prefixWith(releaseStatement, before) .postfixWith(releaseStatement, after) .build(); } /** Return whether the given try-tree will catch the given exception type. */ private boolean tryCatchesException(TryTree tryTree, Type exceptionToCatch, VisitorState state) { Types types = state.getTypes(); return tryTree.getCatches().stream() .anyMatch( (CatchTree catchClause) -> { Type catchesException = getType(catchClause.getParameter().getType()); // Examine all alternative types of a union type. if (catchesException != null && catchesException.isUnion()) { return Streams.stream(((UnionClassType) catchesException).getAlternativeTypes()) .anyMatch(caught -> types.isSuperType(caught, exceptionToCatch)); } // Simple type, just check superclass. return types.isSuperType(catchesException, exceptionToCatch); }); } /** * Whether the given WakeLock may throw an unexpected RuntimeException when released. * * <p>Returns true if: 1) the given WakeLock was acquired with timeout, and 2) the given WakeLock * is reference counted. */ private boolean wakelockMayThrow(Symbol wakelockSymbol, VisitorState state) { ClassTree enclosingClass = getTopLevelClass(state); ImmutableMultimap<String, MethodInvocationTree> map = methodCallsForSymbol(wakelockSymbol, enclosingClass); // Was acquired with timeout. return map.get("acquire").stream().anyMatch(m -> m.getArguments().size() == 1) // Is reference counted, i.e., referenceCounted not explicitly set to false. && map.get("setReferenceCounted").stream() .noneMatch( m -> Boolean.FALSE.equals(constValue(m.getArguments().get(0), Boolean.class))); } private static ClassTree getTopLevelClass(VisitorState state) { return (ClassTree) Streams.findLast( Streams.stream(state.getPath().iterator()) .filter((Tree t) -> t.getKind() == Kind.CLASS)) .orElseThrow(() -> new IllegalArgumentException("No enclosing class found")); } /** * Finds all method invocations on the given symbol, and constructs a map of the called method's * name, to the {@link MethodInvocationTree} in which it was called. */ private ImmutableMultimap<String, MethodInvocationTree> methodCallsForSymbol( Symbol sym, ClassTree classTree) { ImmutableMultimap.Builder<String, MethodInvocationTree> methodMap = ImmutableMultimap.builder(); // Populate map builder with names of method called : the tree in which it is called. classTree.accept( new TreeScanner<Void, Void>() { @Override public Void visitMethodInvocation(MethodInvocationTree callTree, Void unused) { if (sym.equals(getSymbol(getReceiver(callTree)))) { MethodSymbol methodSymbol = getSymbol(callTree); methodMap.put(methodSymbol.getSimpleName().toString(), callTree); } return super.visitMethodInvocation(callTree, unused); } }, null); return methodMap.build(); } }
9,707
43.944444
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/android/StaticOrDefaultInterfaceMethod.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.android; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.enclosingClass; import static com.google.errorprone.matchers.Matchers.hasModifier; import static com.google.errorprone.matchers.Matchers.kindIs; import static com.sun.source.tree.Tree.Kind.INTERFACE; import static javax.lang.model.element.Modifier.DEFAULT; import static javax.lang.model.element.Modifier.STATIC; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; /** * @author epmjohnston@google.com (Emily P.M. Johnston) */ @BugPattern( summary = "Static and default interface methods are not natively supported on older Android devices." + " ", severity = ERROR, documentSuppression = false // for slightly customized suppression documentation ) public class StaticOrDefaultInterfaceMethod extends BugChecker implements MethodTreeMatcher { private static final Matcher<Tree> IS_STATIC_OR_DEFAULT_METHOD_ON_INTERFACE = allOf(enclosingClass(kindIs(INTERFACE)), anyOf(hasModifier(STATIC), hasModifier(DEFAULT))); @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (!state.isAndroidCompatible()) { return Description.NO_MATCH; } if (IS_STATIC_OR_DEFAULT_METHOD_ON_INTERFACE.matches(tree, state)) { return describeMatch(tree); } return Description.NO_MATCH; } }
2,512
38.265625
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/android/HardCodedSdCardPath.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.android; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.sun.source.tree.Tree.Kind.STRING_LITERAL; import com.google.common.collect.ImmutableMap; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.LiteralTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.LiteralTree; import java.util.Map; /** * @author avenet@google.com (Arnaud J. Venet) */ @BugPattern( altNames = {"SdCardPath"}, summary = "Hardcoded reference to /sdcard", severity = WARNING) public class HardCodedSdCardPath extends BugChecker implements LiteralTreeMatcher { // The proper ways of retrieving the "/sdcard" and "/data/data" directories. static final String SDCARD = "Environment.getExternalStorageDirectory().getPath()"; static final String DATA = "Context.getFilesDir().getPath()"; // Maps each platform-dependent way of accessing "/sdcard" or "/data/data" to its // portable equivalent. static final ImmutableMap<String, String> PATH_TABLE = new ImmutableMap.Builder<String, String>() .put("/sdcard", SDCARD) .put("/mnt/sdcard", SDCARD) .put("/system/media/sdcard", SDCARD) .put("file://sdcard", SDCARD) .put("file:///sdcard", SDCARD) .put("/data/data", DATA) .put("/data/user", DATA) .buildOrThrow(); @Override public Description matchLiteral(LiteralTree tree, VisitorState state) { if (!state.isAndroidCompatible()) { return Description.NO_MATCH; } if (tree.getKind() != STRING_LITERAL) { return Description.NO_MATCH; } // Hard-coded paths may come handy when writing tests. Therefore, we suppress the check // for code located under 'javatests'. if (ASTHelpers.isJUnitTestCode(state)) { return Description.NO_MATCH; } String literal = (String) tree.getValue(); if (literal == null) { return Description.NO_MATCH; } for (Map.Entry<String, String> entry : PATH_TABLE.entrySet()) { String hardCodedPath = entry.getKey(); if (!literal.startsWith(hardCodedPath)) { continue; } String correctPath = entry.getValue(); String remainderPath = literal.substring(hardCodedPath.length()); // Replace the hard-coded fragment of the path with a portable expression. SuggestedFix.Builder suggestedFix = SuggestedFix.builder(); if (remainderPath.isEmpty()) { suggestedFix.replace(tree, correctPath); } else { suggestedFix.replace(tree, correctPath + " + \"" + remainderPath + "\""); } // Add the corresponding import statements. if (correctPath.equals(SDCARD)) { suggestedFix.addImport("android.os.Environment"); } else { suggestedFix.addImport("android.content.Context"); } return describeMatch(tree, suggestedFix.build()); } return Description.NO_MATCH; } }
3,821
35.75
91
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/android/ParcelableCreator.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.android; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.hasModifier; import static com.google.errorprone.matchers.Matchers.isDirectImplementationOf; import static com.google.errorprone.matchers.Matchers.not; import com.google.common.collect.Iterables; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ClassType; import com.sun.tools.javac.code.Types; import java.util.List; import javax.lang.model.element.Modifier; /** * BugPattern to detect classes which implement android.os.Parcelable but don't have public static * CREATOR. * * @author Sumit Bhagwani (bhagwani@google.com) */ @BugPattern( summary = "Detects classes which implement Parcelable but don't have CREATOR", severity = SeverityLevel.ERROR) public class ParcelableCreator extends BugChecker implements ClassTreeMatcher { /** Matches if a non-public non-abstract class/interface is subtype of android.os.Parcelable */ private static final Matcher<ClassTree> PARCELABLE_MATCHER = allOf(isDirectImplementationOf("android.os.Parcelable"), not(hasModifier(Modifier.ABSTRACT))); private static final Matcher<VariableTree> PARCELABLE_CREATOR_MATCHER = allOf( Matchers.isSubtypeOf("android.os.Parcelable$Creator"), hasModifier(Modifier.STATIC), hasModifier(Modifier.PUBLIC)); @Override public Description matchClass(ClassTree tree, VisitorState state) { if (!state.isAndroidCompatible()) { return Description.NO_MATCH; } if (!PARCELABLE_MATCHER.matches(tree, state)) { return Description.NO_MATCH; } Symbol parcelableCreatorSymbol = ANDROID_OS_PARCELABLE_CREATOR.get(state); if (parcelableCreatorSymbol == null) { return Description.NO_MATCH; } ClassType classType = ASTHelpers.getType(tree); for (Tree member : tree.getMembers()) { if (member.getKind() != Kind.VARIABLE) { continue; } VariableTree variableTree = (VariableTree) member; if (PARCELABLE_CREATOR_MATCHER.matches(variableTree, state)) { if (isVariableClassCreator(variableTree, state, classType, parcelableCreatorSymbol)) { return Description.NO_MATCH; } } } return describeMatch(tree); } private static boolean isVariableClassCreator( VariableTree variableTree, VisitorState state, ClassType classType, Symbol parcelableCreatorSymbol) { Tree typeTree = variableTree.getType(); Type type = ASTHelpers.getType(typeTree); Types types = state.getTypes(); Type superType = types.asSuper(type, parcelableCreatorSymbol); if (superType == null) { return false; } List<Type> typeArguments = superType.getTypeArguments(); if (typeArguments.isEmpty()) { // raw creator return true; } return ASTHelpers.isSubtype(classType, Iterables.getOnlyElement(typeArguments), state); } private static final Supplier<Symbol> ANDROID_OS_PARCELABLE_CREATOR = VisitorState.memoize(state -> state.getSymbolFromString("android.os.Parcelable$Creator")); }
4,483
36.057851
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/android/FragmentInjection.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.android; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.hasModifier; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.matchers.Matchers.methodHasParameters; import static com.google.errorprone.matchers.Matchers.methodIsNamed; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.util.ASTHelpers.constValue; 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.resolveExistingMethod; 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; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.Tree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.util.FatalError; import com.sun.tools.javac.util.Name; import javax.annotation.Nullable; import javax.lang.model.element.Modifier; /** * @author epmjohnston@google.com (Emily P.M. Johnston) */ @BugPattern( summary = "Classes extending PreferenceActivity must implement isValidFragment such that it does not" + " unconditionally return true to prevent vulnerability to fragment injection" + " attacks.", severity = WARNING, tags = StandardTags.LIKELY_ERROR) public class FragmentInjection extends BugChecker implements ClassTreeMatcher { private static final Matcher<MethodTree> OVERRIDES_IS_VALID_FRAGMENT = allOf(methodIsNamed("isValidFragment"), methodHasParameters(isSameType("java.lang.String"))); @Override public Description matchClass(ClassTree tree, VisitorState state) { if (!state.isAndroidCompatible()) { return Description.NO_MATCH; } // Only examine classes that extend PreferenceActivity. Type preferenceActivityType = ANDROID_PREFERENCE_PREFERENCEACTIVITY.get(state); if (!isSubtype(getType(tree), preferenceActivityType, state)) { return NO_MATCH; } // Examine each method in the class. Complain if isValidFragment not implemented. TypeSymbol preferenceActivityTypeSymbol = preferenceActivityType.tsym; boolean methodNotImplemented = true; try { MethodSymbol isValidFragmentMethodSymbol = resolveExistingMethod( state, getSymbol(tree), ISVALIDFRAGMENT.get(state), ImmutableList.of(state.getSymtab().stringType), ImmutableList.<Type>of()); methodNotImplemented = isValidFragmentMethodSymbol.owner.equals(preferenceActivityTypeSymbol); } catch (FatalError e) { // If isValidFragment method symbol is not found, then we must be compiling against an old SDK // version (< 19) in which isValidFragment is not yet implemented, and neither this class nor // any of its super classes have implemented it. } // If neither this class nor any super class besides PreferenceActivity implements // isValidFragment, and this is not an abstract class, emit warning. if (methodNotImplemented && not(hasModifier(Modifier.ABSTRACT)).matches(tree, state)) { return buildDescription(tree) .setMessage("Class extending PreferenceActivity does not implement isValidFragment.") .build(); } // Check the implementation of isValidFragment. Complain if it always returns true. MethodTree isValidFragmentMethodTree = getMethod(OVERRIDES_IS_VALID_FRAGMENT, tree, state); if (isValidFragmentMethodTree != null) { if (isValidFragmentMethodTree.accept(ALWAYS_RETURNS_TRUE, null)) { return buildDescription(isValidFragmentMethodTree) .setMessage("isValidFragment unconditionally returns true.") .build(); } } return NO_MATCH; } /* * Return the first method tree on the given class tree that matches the given method matcher, * or null if one does not exist. */ @Nullable private static MethodTree getMethod( Matcher<MethodTree> methodMatcher, ClassTree classTree, VisitorState state) { for (Tree member : classTree.getMembers()) { if (member instanceof MethodTree) { MethodTree memberTree = (MethodTree) member; if (methodMatcher.matches(memberTree, state)) { return memberTree; } } } return null; } /* * A tree scanner for isValidFragment, accepts methods that return true on all code paths. */ private static final TreeScanner<Boolean, Void> ALWAYS_RETURNS_TRUE = new TreeScanner<Boolean, Void>() { @Override public Boolean visitReturn(ReturnTree node, Void unused) { ExpressionTree returnExpression = node.getExpression(); Boolean returnValue = constValue(returnExpression, Boolean.class); return firstNonNull(returnValue, false); } @Override public Boolean reduce(Boolean r1, Boolean r2) { // And together the results of all visits. If any visit was false (return value was false // or not constant), the method implementation is okay. // null value means not a return statement, doesn't change anything, so treat as true. return (r1 == null || r1) && (r2 == null || r2); } }; private static final Supplier<Name> ISVALIDFRAGMENT = VisitorState.memoize(state -> state.getName("isValidFragment")); private static final Supplier<Type> ANDROID_PREFERENCE_PREFERENCEACTIVITY = VisitorState.memoize( state -> state.getTypeFromString("android.preference.PreferenceActivity")); }
7,196
42.095808
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/android/BundleDeserializationCast.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.android; 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.anything; import static com.google.errorprone.matchers.Matchers.isArrayType; import static com.google.errorprone.matchers.Matchers.isPrimitiveType; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import static com.google.errorprone.matchers.Matchers.typeCast; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.suppliers.Suppliers.typeFromString; import static com.google.errorprone.util.ASTHelpers.getType; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.TypeCastTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeCastTree; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ArrayType; import com.sun.tools.javac.code.Types; /** * @author epmjohnston@google.com (Emily P.M. Johnston) */ @BugPattern( summary = "Object serialized in Bundle may have been flattened to base type.", severity = ERROR) public class BundleDeserializationCast extends BugChecker implements TypeCastTreeMatcher { private static final Matcher<TypeCastTree> BUNDLE_DESERIALIZATION_CAST_EXPRESSION = typeCast( anything(), instanceMethod().onExactClass("android.os.Bundle").named("getSerializable")); @Override public Description matchTypeCast(TypeCastTree tree, VisitorState state) { if (!state.isAndroidCompatible()) { return Description.NO_MATCH; } if (!BUNDLE_DESERIALIZATION_CAST_EXPRESSION.matches(tree, state)) { return NO_MATCH; } Tree targetType = tree.getType(); // Casting to primitive types shouldn't cause issues since they extend no type and are final. if (isPrimitiveType().matches(targetType, state)) { return NO_MATCH; } /* * Ordering of these checks determines precedence of types (which type *should* be cast to). * Deduced by inspecting serialization code, see * https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/Parcel.java#1377 * Simply allow specially handled final types, and check that other specially handled types * are cast to their base types. * * There is no documentation of what types are safe to cast to, so this code is paralleling the * code cited above to emulate the same logic in order to produce the correct behavior. */ if (isSameType("java.lang.String").matches(targetType, state)) { return NO_MATCH; } if (isSubtypeOf("java.util.Map").matches(targetType, state)) { // Make an exception for HashMap. return anyOf(isSameType("java.util.Map"), isSameType("java.util.HashMap")) .matches(targetType, state) ? NO_MATCH : getDescriptionForType(tree, "Map"); } // All Parcelables handled after this point have their types preserved. if (isSubtypeOf("android.os.Parcelable").matches(targetType, state)) { return NO_MATCH; } if (isSubtypeOf("java.lang.CharSequence").matches(targetType, state)) { return isSameType("java.lang.CharSequence").matches(targetType, state) ? NO_MATCH : getDescriptionForType(tree, "CharSequence"); } if (isSubtypeOf("java.util.List").matches(targetType, state)) { // Make an exception for ArrayList. return anyOf(isSameType("java.util.List"), isSameType("java.util.ArrayList")) .matches(targetType, state) ? NO_MATCH : getDescriptionForType(tree, "List"); } if (isSubtypeOf("android.util.SparseArray").matches(targetType, state)) { return isSameType("android.util.SparseArray").matches(targetType, state) ? NO_MATCH : getDescriptionForType(tree, "SparseArray"); } // Check component types of arrays. The only type that may cause problems is CharSequence[]. if (isArrayType().matches(targetType, state)) { Type componentType = ((ArrayType) getType(targetType)).getComponentType(); Types types = state.getTypes(); Type charSequenceType = typeFromString("java.lang.CharSequence").get(state); Type stringType = typeFromString("java.lang.String").get(state); // Okay to cast to String[] because String[] is written before CharSequence[] // in the serialization code. if (types.isSubtype(componentType, charSequenceType) && !types.isSameType(componentType, charSequenceType) && !types.isSameType(componentType, stringType)) { return getDescriptionForType(tree, "CharSequence[]"); } } return NO_MATCH; } private Description getDescriptionForType(TypeCastTree tree, String baseType) { String targetType = getType(tree.getType()).toString(); return buildDescription(tree) .setMessage( String.format( "When serialized in Bundle, %s may be transformed into an arbitrary subclass of %s." + " Please cast to %s.", targetType, baseType, baseType)) .build(); } }
6,205
42.704225
111
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/android/IsLoggableTagLength.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.android; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.anything; import static com.google.errorprone.matchers.Matchers.classLiteral; import static com.google.errorprone.matchers.Matchers.hasModifier; import static com.google.errorprone.matchers.Matchers.kindIs; import static com.google.errorprone.matchers.Matchers.receiverOfInvocation; 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.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.sun.source.tree.Tree.Kind.IDENTIFIER; import static javax.lang.model.element.Modifier.FINAL; import com.google.common.base.Utf8; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import javax.annotation.Nullable; /** * @author epmjohnston@google.com (Emily P.M. Johnston) */ @BugPattern(summary = "Log tag too long, cannot exceed 23 characters.", severity = ERROR) public class IsLoggableTagLength extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> IS_LOGGABLE_CALL = staticMethod().onClass("android.util.Log").named("isLoggable"); private static final Matcher<ExpressionTree> GET_SIMPLE_NAME_CALL = instanceMethod().onExactClass("java.lang.Class").named("getSimpleName"); private static final Matcher<MethodInvocationTree> RECEIVER_IS_CLASS_LITERAL = receiverOfInvocation(classLiteral(anything())); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!state.isAndroidCompatible()) { return Description.NO_MATCH; } if (!IS_LOGGABLE_CALL.matches(tree, state)) { return NO_MATCH; } ExpressionTree tagArg = tree.getArguments().get(0); // Check for constant value. String tagConstantValue = ASTHelpers.constValue(tagArg, String.class); if (tagConstantValue != null) { return isValidTag(tagConstantValue) ? NO_MATCH : describeMatch(tagArg); } // Check for class literal simple name (e.g. MyClass.class.getSimpleName(). ExpressionTree tagExpr = tagArg; // If the tag argument is a final field, retrieve the initializer. if (kindIs(IDENTIFIER).matches(tagArg, state)) { VariableTree declaredField = findEnclosingIdentifier((IdentifierTree) tagArg, state); if (declaredField == null || !hasModifier(FINAL).matches(declaredField, state)) { return NO_MATCH; } tagExpr = declaredField.getInitializer(); } if (GET_SIMPLE_NAME_CALL.matches(tagExpr, state) && RECEIVER_IS_CLASS_LITERAL.matches((MethodInvocationTree) tagExpr, state)) { String tagName = getSymbol(getReceiver(getReceiver(tagExpr))).getSimpleName().toString(); return isValidTag(tagName) ? NO_MATCH : describeMatch(tagArg); } return NO_MATCH; } private static boolean isValidTag(String tag) { return Utf8.encodedLength(tag) <= 23; } @Nullable private static VariableTree findEnclosingIdentifier( IdentifierTree originalNode, VisitorState state) { Symbol identifierSymbol = getSymbol(originalNode); if (!(identifierSymbol instanceof VarSymbol)) { return null; } return state .findEnclosing(ClassTree.class) .accept( new TreeScanner<VariableTree, Void>() { @Nullable @Override public VariableTree visitVariable(VariableTree node, Void p) { return getSymbol(node).equals(identifierSymbol) ? node : null; } @Override public VariableTree reduce(VariableTree r1, VariableTree r2) { return r1 != null ? r1 : r2; } }, null); } }
5,282
39.953488
95
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/android/BinderIdentityRestoredDangerously.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.android; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.findEnclosingNode; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.method.MethodMatchers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.TryTree; /** * @author pvisontay@google.com */ @BugPattern( tags = StandardTags.FRAGILE_CODE, summary = "A call to Binder.clearCallingIdentity() should be followed by " + "Binder.restoreCallingIdentity() in a finally block. Otherwise the wrong Binder " + "identity may be used by subsequent code.", severity = SeverityLevel.WARNING) public class BinderIdentityRestoredDangerously extends BugChecker implements MethodInvocationTreeMatcher { private static final String BINDER_CLASS_NAME = "android.os.Binder"; private static final Matcher<ExpressionTree> RESTORE_IDENTITY_METHOD = MethodMatchers.staticMethod().onClass(BINDER_CLASS_NAME).named("restoreCallingIdentity"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!state.isAndroidCompatible()) { return Description.NO_MATCH; } if (!RESTORE_IDENTITY_METHOD.matches(tree, state)) { return NO_MATCH; } // This is a simple implementation that doesn't have 100% accuracy - e.g. it would accept it // if both Binder.clearCallingIdentity() and Binder.restoreCallingIdentity() were in the same // finally {} block. But in practice it should work well for the large majority of existing // code. // TODO: Also detect when a clearCallingIdentity() call is not followed by // restoreCallingIdentity(). TryTree enclosingTry = findEnclosingNode(state.getPath(), TryTree.class); if (enclosingTry == null) { return describeMatch(tree); } return NO_MATCH; } }
3,004
39.066667
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inlineme/InlineMeData.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.inlineme; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.MoreCollectors.onlyElement; import static com.google.errorprone.util.ASTHelpers.findEnclosingNode; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasDirectAnnotationWithSimpleName; import static com.google.errorprone.util.ASTHelpers.isStatic; import static com.google.errorprone.util.MoreAnnotations.getValue; import com.google.auto.value.AutoValue; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSet; import com.google.errorprone.VisitorState; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.MoreAnnotations; import com.google.errorprone.util.SourceCodeEscapers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.NewArrayTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeCastTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCLambda; import com.sun.tools.javac.tree.JCTree.JCLambda.ParameterKind; import com.sun.tools.javac.tree.JCTree.JCTypeCast; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.Pretty; import com.sun.tools.javac.tree.TreeCopier; import com.sun.tools.javac.tree.TreeMaker; import java.io.IOException; import java.io.StringWriter; import java.io.UncheckedIOException; import java.util.IdentityHashMap; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.stream.Stream; @AutoValue abstract class InlineMeData { private static final String INLINE_ME = "InlineMe"; /** Builds the {@code @InlineMe} annotation as it would be found in source code. */ static String buildAnnotation( String replacement, Set<String> imports, Set<String> staticImports) { String annotation = "@InlineMe(replacement = \"" + SourceCodeEscapers.javaCharEscaper().escape(replacement) + "\""; if (!imports.isEmpty()) { annotation += ", imports = " + quote(imports); } if (!staticImports.isEmpty()) { annotation += ", staticImports = " + quote(staticImports); } annotation += ")\n"; return annotation; } String buildAnnotation() { return buildAnnotation(replacement(), imports(), staticImports()); } private static String quote(Set<String> imports) { String quoted = "\"" + Joiner.on("\", \"").join(imports) + "\""; if (imports.size() == 1) { return quoted; } return "{" + quoted + "}"; } // TODO(glorioso): be tolerant of trailing semicolon abstract String replacement(); abstract ImmutableSet<String> imports(); abstract ImmutableSet<String> staticImports(); static Optional<InlineMeData> createFromSymbol(MethodSymbol symbol) { // if the API doesn't have the @InlineMe annotation, then return no match if (!hasDirectAnnotationWithSimpleName(symbol, INLINE_ME)) { return Optional.empty(); } Attribute.Compound inlineMe = symbol.getRawAttributes().stream() .filter(a -> a.type.tsym.getSimpleName().contentEquals(INLINE_ME)) .collect(onlyElement()); // TODO(kak): we should validate that the annotation doesn't contain any elements other than // `replacement` (required), `imports` and `staticImports`. ImmutableSet<String> imports = getStrings(inlineMe, "imports"); ImmutableSet<String> staticImports = getStrings(inlineMe, "staticImports"); return getValue(inlineMe, "replacement") .flatMap(MoreAnnotations::asStringValue) .map(InlineMeData::trimTrailingSemicolons) .map(replacement -> create(replacement, imports, staticImports)); } private static InlineMeData create( String replacement, Iterable<String> imports, Iterable<String> staticImports) { return new AutoValue_InlineMeData( replacement, ImmutableSet.copyOf(imports), ImmutableSet.copyOf(staticImports)); } // TODO(b/176439392): This is a big one: // Right now, we enforce only *one* style of inlining, by requiring the body to match our // implementation (see TODO in ImportAndQualificationFinder). However, it might be appropriate // for us to allow multiple "flavors" of inlining, and ensure that the annotation is *one of* // one of the multiple flavors of inlining. // TODO(b/176094331): importing the *outer* token for a nested class like Foo.Builder.something() static InlineMeData buildExpectedInlineMeAnnotation( VisitorState state, ExpressionTree expression) { ClassSymbol classSymbol = getSymbol(findEnclosingNode(state.getPath(), ClassTree.class)); // Scan the statement to collect identifiers that need to be qualified - unqualified references // to field or instance methods, as well as collecting the imports we need to use. ImportAndQualificationFinder qualifier = new ImportAndQualificationFinder(classSymbol, state); qualifier.scan(TreePath.getPath(state.getPath(), expression), null); return create( prettyPrint( new QualifyingTreeCopier(state, qualifier.qualifications) .copy((JCExpression) expression)), qualifier.imports, qualifier.staticImports); } private static String prettyPrint(JCTree tree) { StringWriter w = new StringWriter(); tree.accept(new GooglePrinter(w)); return w.toString(); } /** Copies statements, inserting appropriate qualifiers so make it inline-ready. */ private static class QualifyingTreeCopier extends TreeCopier<Void> { private final TreeMaker treeMaker; private final VisitorState state; private final IdentityHashMap<IdentifierTree, JCExpression> qualifications; public QualifyingTreeCopier( VisitorState state, IdentityHashMap<IdentifierTree, JCExpression> qualifications) { super(state.getTreeMaker()); this.state = state; this.treeMaker = state.getTreeMaker(); this.qualifications = qualifications; } // For some reason, paramKind isn't copied in the normal tree copier. // TODO(glorioso): File bug upstream? Or maybe this is intended due to desugaring??? @Override public JCTree visitLambdaExpression(LambdaExpressionTree lambdaExpressionTree, Void unused) { JCLambda expr = (JCLambda) lambdaExpressionTree; JCLambda lambda = (JCLambda) super.visitLambdaExpression(lambdaExpressionTree, unused); lambda.paramKind = expr.paramKind; return lambda; } @Override public JCTree visitIdentifier(IdentifierTree identifierTree, Void unused) { if (qualifications.containsKey(identifierTree)) { return treeMaker.Select( qualifications.get(identifierTree), state.getName(identifierTree.toString())); } return super.visitIdentifier(identifierTree, unused); } } private static class GooglePrinter extends Pretty { private final StringWriter writer; public GooglePrinter(StringWriter writer) { super(writer, false /* don't dump extra comments */); this.writer = writer; } @Override public void visitTypeCast(JCTypeCast jcTypeCast) { // TODO(glorioso): we *should* use package-private open precedence methods try { print("("); printExpr(jcTypeCast.clazz); print(") "); printExpr(jcTypeCast.expr); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public void visitLambda(JCLambda jcLambda) { // We manually print lambdas to match our own style try { boolean paramsAreExplicit = jcLambda.paramKind == ParameterKind.EXPLICIT; boolean paramsNeedParentheses = jcLambda.params.size() != 1 || paramsAreExplicit; if (paramsNeedParentheses) { print("("); } if (paramsAreExplicit) { printExprs(jcLambda.params); } else { Joiner.on(", ").appendTo(writer, jcLambda.params.map(JCVariableDecl::getName)); } if (paramsNeedParentheses) { print(")"); } print(" -> "); printExpr(jcLambda.body); } catch (IOException e) { throw new UncheckedIOException(e); } } } private static class ImportAndQualificationFinder extends TreePathScanner<Void, Void> { final IdentityHashMap<IdentifierTree, JCExpression> qualifications = new IdentityHashMap<>(); final Set<String> imports = new TreeSet<>(); final Set<String> staticImports = new TreeSet<>(); private final ClassSymbol classSymbol; private final TreeMaker treeMaker; private final VisitorState state; ImportAndQualificationFinder(ClassSymbol classSymbol, VisitorState state) { this.classSymbol = classSymbol; this.treeMaker = state.getTreeMaker(); this.state = state; } @Override public Void visitMemberSelect(MemberSelectTree node, Void unused) { // We only want to import a MemberSelect if this is the "top" of the member select // chain. if (!(node.getExpression() instanceof MemberSelectTree)) { Symbol symbol = getSymbol(node); if (isStatic(symbol)) { maybeAddImport(symbol.owner); } } return super.visitMemberSelect(node, null); } private void maybeAddImport(Symbol symbol) { if (symbol != null) { addImport(symbol.getQualifiedName().toString()); } } private void addImport(String clazzName) { if (!clazzName.isEmpty() && !clazzName.startsWith("java.lang")) { imports.add(clazzName); } } @Override public Void visitIdentifier(IdentifierTree identifierTree, Void unused) { if (identifierTree.getName().contentEquals("this")) { return super.visitIdentifier(identifierTree, unused); } Symbol symbol = getSymbol(identifierTree); if (symbol == null || ASTHelpers.isLocal(symbol)) { return super.visitIdentifier(identifierTree, unused); } Tree parentNode = getCurrentPath().getParentPath().getLeaf(); if (nameUsageDoesntRequireQualificationOrImport(parentNode)) { return super.visitIdentifier(identifierTree, unused); } // TODO(glorioso): This suggestion has the following behavior: // * instance methods: foo() -> this.foo(), no import needed // * static methods in other classes: foo() -> foo(), static import Owner.foo; // * static methods in this class: myFoo() -> Me.myFoo(), import Me; // That seems wrong. Perhaps move the import logic from the other bits here? boolean isMemberOfThisClass = isMemberOfThisClass(symbol, parentNode); boolean nameUsageRequiresNoQualification = nameUsageDoesntRequireQualification(parentNode); if (isStatic(symbol)) { if (isMemberOfThisClass) { addImport(classSymbol.getQualifiedName().toString()); if (!nameUsageRequiresNoQualification) { qualifications.put(identifierTree, treeMaker.Ident(classSymbol)); } } else { if (parentNode instanceof NewClassTree) { // This Identifier is the class being constructed addImport(symbol.getQualifiedName().toString()); } else { // Regular static methods staticImports.add(symbol.owner.getQualifiedName() + "." + symbol.getQualifiedName()); } } } else { if (isMemberOfThisClass) { if (!nameUsageRequiresNoQualification) { qualifications.put(identifierTree, treeMaker.This(classSymbol.type)); } } else { addImport(symbol.getQualifiedName().toString()); } } return super.visitIdentifier(identifierTree, unused); } private boolean isMemberOfThisClass(Symbol symbol, Tree parentNode) { return symbol.owner != null && classSymbol.isSubClass(symbol.owner, state.getTypes()) && !(parentNode instanceof NewClassTree); } private static boolean nameUsageDoesntRequireQualificationOrImport(Tree parentNode) { return parentNode instanceof MemberSelectTree; } private static boolean nameUsageDoesntRequireQualification(Tree parentNode) { return parentNode instanceof NewClassTree || parentNode instanceof MemberReferenceTree || parentNode instanceof TypeCastTree || parentNode instanceof NewArrayTree; } } private static ImmutableSet<String> getStrings(Attribute.Compound attribute, String name) { return getValue(attribute, name) .map(MoreAnnotations::asStrings) .orElse(Stream.empty()) .collect(toImmutableSet()); } private static final CharMatcher SEMICOLON = CharMatcher.is(';'); private static String trimTrailingSemicolons(String s) { return SEMICOLON.trimTrailingFrom(s); } }
14,212
37.413514
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inlineme/Suggester.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.inlineme; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.InjectMatchers.hasProvidesAnnotation; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.hasDirectAnnotationWithSimpleName; import static com.google.errorprone.util.ASTHelpers.shouldKeep; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.DoNotCall; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.inlineme.InlinabilityResult.InlineValidationErrorReason; 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 javax.inject.Inject; import javax.lang.model.element.Modifier; /** Checker that recommends using {@code @InlineMe} on single-statement deprecated APIs. */ @BugPattern( name = "InlineMeSuggester", summary = "This deprecated API looks inlineable. If you'd like the body of the API to be" + " automatically inlined to its callers, please annotate it with @InlineMe." + " NOTE: the suggested fix makes the method final if it was not already.", severity = WARNING) public final class Suggester extends BugChecker implements MethodTreeMatcher { private static final String INLINE_ME = "com.google.errorprone.annotations.InlineMe"; @Inject Suggester() {} @Override public Description matchMethod(MethodTree tree, VisitorState state) { // only suggest @InlineMe on @Deprecated APIs if (!hasAnnotation(tree, Deprecated.class, state)) { return Description.NO_MATCH; } // if the API is already annotated with @InlineMe, then return no match if (hasDirectAnnotationWithSimpleName(tree, "InlineMe")) { return Description.NO_MATCH; } // if the API is already annotated with @DoNotCall, then return no match if (hasAnnotation(tree, DoNotCall.class, state)) { return Description.NO_MATCH; } // don't suggest on APIs that get called reflectively if (shouldKeep(tree) || hasProvidesAnnotation().matches(tree, state)) { return Description.NO_MATCH; } // if the body is not inlineable, then return no match InlinabilityResult inlinabilityResult = InlinabilityResult.forMethod(tree, state); if (!inlinabilityResult.isValidForSuggester()) { return Description.NO_MATCH; } // We attempt to actually build the annotation as a SuggestedFix. SuggestedFix.Builder fixBuilder = SuggestedFix.builder() .addImport(INLINE_ME) .prefixWith( tree, InlineMeData.buildExpectedInlineMeAnnotation(state, inlinabilityResult.body()) .buildAnnotation()); if (inlinabilityResult.error() == InlineValidationErrorReason.METHOD_CAN_BE_OVERIDDEN_BUT_CAN_BE_FIXED) { SuggestedFixes.addModifiers(tree, state, Modifier.FINAL).ifPresent(fixBuilder::merge); } return describeMatch(tree, fixBuilder.build()); } }
3,926
40.336842
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inlineme/InlinabilityResult.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.inlineme; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import com.google.errorprone.VisitorState; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionStatementTree; 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.ReturnTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree; 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.PackageSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.lang.model.element.Modifier; import org.checkerframework.checker.nullness.qual.Nullable; /** Whether an API can have {@code @InlineMe} applied to it or not. */ @AutoValue abstract class InlinabilityResult { abstract @Nullable InlineValidationErrorReason error(); abstract @Nullable ExpressionTree body(); abstract @Nullable String additionalErrorInfo(); final String errorMessage() { checkState(error() != null); String message = error().getErrorMessage(); if (additionalErrorInfo() != null) { message += " " + additionalErrorInfo(); } return message; } static InlinabilityResult fromError(InlineValidationErrorReason errorReason) { return fromError(errorReason, null); } static InlinabilityResult fromError( InlineValidationErrorReason errorReason, ExpressionTree body) { return fromError(errorReason, body, null); } static InlinabilityResult fromError( InlineValidationErrorReason errorReason, ExpressionTree body, String additionalErrorInfo) { return new AutoValue_InlinabilityResult(errorReason, body, additionalErrorInfo); } static InlinabilityResult inlinable(ExpressionTree body) { return new AutoValue_InlinabilityResult(null, body, null); } boolean isValidForSuggester() { return isValidForValidator() || error() == InlineValidationErrorReason.METHOD_CAN_BE_OVERIDDEN_BUT_CAN_BE_FIXED; } boolean isValidForValidator() { return error() == null; } enum InlineValidationErrorReason { NO_BODY("InlineMe cannot be applied to abstract methods."), NOT_EXACTLY_ONE_STATEMENT("InlineMe cannot inline methods with more than 1 statement."), COMPLEX_STATEMENT( "InlineMe cannot inline complex statements. Consider using a different refactoring tool"), CALLS_DEPRECATED_OR_PRIVATE_APIS( "InlineMe cannot be applied when the implementation references deprecated or less visible" + " API elements:"), API_IS_PRIVATE("InlineMe cannot be applied to private APIs."), LAMBDA_CAPTURES_PARAMETER( "Inlining this method will result in a change in evaluation timing for one or more" + " arguments to this method."), METHOD_CAN_BE_OVERIDDEN_AND_CANT_BE_FIXED( "Methods that are inlined should not be overridable, as the implementation of an overriding" + " method may be different than the inlining"), // Technically an error in the case where an existing @InlineMe annotation is applied, but could // be fixed while suggesting METHOD_CAN_BE_OVERIDDEN_BUT_CAN_BE_FIXED( "Methods that are inlined should not be overridable, as the implementation of an overriding" + " method may be different than the inlining"), VARARGS_USED_UNSAFELY( "When using a varargs parameter, it must only be passed in the last position of a method" + " call to another varargs method"), EMPTY_VOID("InlineMe cannot yet be applied to no-op void methods"), REUSE_OF_ARGUMENTS("Implementations cannot use an argument more than once:"); private final @Nullable String errorMessage; InlineValidationErrorReason(@Nullable String errorMessage) { this.errorMessage = errorMessage; } String getErrorMessage() { return errorMessage; } } static InlinabilityResult forMethod(MethodTree tree, VisitorState state) { if (tree.getBody() == null) { return fromError(InlineValidationErrorReason.NO_BODY); } if (tree.getBody().getStatements().size() != 1) { return fromError(InlineValidationErrorReason.NOT_EXACTLY_ONE_STATEMENT); } MethodSymbol methSymbol = getSymbol(tree); if (methSymbol.getModifiers().contains(Modifier.PRIVATE)) { return fromError(InlineValidationErrorReason.API_IS_PRIVATE); } StatementTree statement = tree.getBody().getStatements().get(0); if (state.getSourceForNode(statement) == null) { return fromError(InlineValidationErrorReason.NO_BODY); } // we can only inline either a ExpressionStatementTree or a ReturnTree ExpressionTree body; // The statement is either an ExpressionStatement or a ReturnStatement, given // InlinabilityResult.forMethod switch (statement.getKind()) { case EXPRESSION_STATEMENT: body = ((ExpressionStatementTree) statement).getExpression(); break; case RETURN: body = ((ReturnTree) statement).getExpression(); if (body == null) { return fromError(InlineValidationErrorReason.EMPTY_VOID); } break; default: return fromError(InlineValidationErrorReason.COMPLEX_STATEMENT); } if (methSymbol.isVarArgs() && usesVarargsParamPoorly(body, methSymbol.params().last(), state)) { return fromError(InlineValidationErrorReason.VARARGS_USED_UNSAFELY, body); } // TODO(kak): declare a list of all the types we don't want to allow (e.g., ClassTree) and use // contains if (body.toString().contains("{")) { return fromError(InlineValidationErrorReason.COMPLEX_STATEMENT, body); } Symbol usedMultipliedTimes = usesVariablesMultipleTimes(body, methSymbol.params(), state); if (usedMultipliedTimes != null) { return fromError( InlineValidationErrorReason.REUSE_OF_ARGUMENTS, body, usedMultipliedTimes.toString()); } Tree privateOrDeprecatedApi = usesPrivateOrDeprecatedApis(body, state, getVisibility(methSymbol)); if (privateOrDeprecatedApi != null) { return fromError( InlineValidationErrorReason.CALLS_DEPRECATED_OR_PRIVATE_APIS, body, state.getSourceForNode(privateOrDeprecatedApi)); } if (hasLambdaCapturingParameters(tree, body)) { return fromError(InlineValidationErrorReason.LAMBDA_CAPTURES_PARAMETER, body); } if (ASTHelpers.methodCanBeOverridden(methSymbol)) { // TODO(glorioso): One additional edge case we can check is if the owning class can't be // overridden due to having no publicly-accessible constructors. return fromError( methSymbol.isDefault() ? InlineValidationErrorReason.METHOD_CAN_BE_OVERIDDEN_AND_CANT_BE_FIXED : InlineValidationErrorReason.METHOD_CAN_BE_OVERIDDEN_BUT_CAN_BE_FIXED, body); } return inlinable(body); } private static Symbol usesVariablesMultipleTimes( ExpressionTree body, List<VarSymbol> parameterVariables, VisitorState state) { AtomicReference<Symbol> usesVarsTwice = new AtomicReference<>(); new TreePathScanner<Void, Void>() { final Set<Symbol> usedVariables = new HashSet<>(); @Override public Void visitIdentifier(IdentifierTree identifierTree, Void aVoid) { Symbol usedSymbol = getSymbol(identifierTree); if (parameterVariables.contains(usedSymbol) && !usedVariables.add(usedSymbol)) { usesVarsTwice.set(usedSymbol); } return super.visitIdentifier(identifierTree, aVoid); } }.scan(new TreePath(state.getPath(), body), null); return usesVarsTwice.get(); } // If the body refers to the varargs value at all, it should only be as the last argument // in a method call that is *also* varargs. private static boolean usesVarargsParamPoorly( ExpressionTree expressionTree, VarSymbol varargsParam, VisitorState state) { AtomicBoolean usesVarargsPoorly = new AtomicBoolean(false); new TreePathScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree identifierTree, Void aVoid) { if (!getSymbol(identifierTree).equals(varargsParam)) { return super.visitIdentifier(identifierTree, aVoid); } Tree parentNode = getCurrentPath().getParentPath().getLeaf(); if (!(parentNode instanceof MethodInvocationTree)) { usesVarargsPoorly.set(true); return null; } MethodInvocationTree mit = (MethodInvocationTree) parentNode; if (!getSymbol(mit).isVarArgs()) { // Passing varargs to another method that maybe takes an explicit array? usesVarargsPoorly.set(true); return null; } List<? extends ExpressionTree> args = mit.getArguments(); if (args.isEmpty()) { // buh! confusing. return super.visitIdentifier(identifierTree, aVoid); } int indexOfThisTreeUse = args.indexOf(identifierTree); if (indexOfThisTreeUse != args.size() - 1) { // Varargs not in position. usesVarargsPoorly.set(true); return null; } return super.visitIdentifier(identifierTree, aVoid); } }.scan(new TreePath(state.getPath(), expressionTree), null); return usesVarargsPoorly.get(); } private static Tree usesPrivateOrDeprecatedApis( ExpressionTree statement, VisitorState state, Visibility minVisibility) { AtomicReference<Tree> usesDeprecatedOrLessVisibleApis = new AtomicReference<>(); new TreeScanner<Void, Void>() { @Override public Void visitLambdaExpression(LambdaExpressionTree node, Void unused) { // we override so we can ignore the node.getParameters() return super.scan(node.getBody(), null); } @Override public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void aVoid) { // This check is necessary as the TreeScanner doesn't visit the "name" part of the // left-hand of an assignment. if (isDeprecatedOrLessVisible(memberSelectTree, minVisibility)) { // short circuit return null; } return super.visitMemberSelect(memberSelectTree, aVoid); } @Override public Void visitIdentifier(IdentifierTree node, Void unused) { if (!ASTHelpers.isLocal(getSymbol(node))) { if (!node.getName().contentEquals("this")) { if (isDeprecatedOrLessVisible(node, minVisibility)) { return null; // short-circuit } } } return super.visitIdentifier(node, null); } @Override public Void visitNewClass(NewClassTree newClassTree, Void aVoid) { if (isDeprecatedOrLessVisible(newClassTree, minVisibility)) { return null; } return super.visitNewClass(newClassTree, aVoid); } @Override public Void visitMethodInvocation(MethodInvocationTree node, Void unused) { if (isDeprecatedOrLessVisible(node, minVisibility)) { return null; // short-circuit } return super.visitMethodInvocation(node, null); } private boolean isDeprecatedOrLessVisible(Tree tree, Visibility minVisibility) { Symbol sym = getSymbol(tree); Visibility visibility = getVisibility(sym); if (!(sym instanceof PackageSymbol) && visibility.compareTo(minVisibility) < 0) { usesDeprecatedOrLessVisibleApis.set(tree); return true; } if (hasAnnotation(sym, "java.lang.Deprecated", state)) { usesDeprecatedOrLessVisibleApis.set(tree); return true; } return false; } }.scan(statement, null); return usesDeprecatedOrLessVisibleApis.get(); } private enum Visibility { PRIVATE, PACKAGE, PROTECTED, PUBLIC; } private static Visibility getVisibility(Symbol symbol) { if (symbol.getModifiers().contains(Modifier.PRIVATE)) { return Visibility.PRIVATE; } else if (symbol.getModifiers().contains(Modifier.PROTECTED)) { return Visibility.PROTECTED; } else if (symbol.getModifiers().contains(Modifier.PUBLIC)) { return Visibility.PUBLIC; } else { return Visibility.PACKAGE; } } private static boolean hasLambdaCapturingParameters(MethodTree meth, ExpressionTree statement) { AtomicBoolean paramReferred = new AtomicBoolean(false); ImmutableSet<VarSymbol> params = meth.getParameters().stream().map(ASTHelpers::getSymbol).collect(toImmutableSet()); new TreeScanner<Void, Void>() { LambdaExpressionTree currentLambdaTree = null; @Override public Void visitLambdaExpression(LambdaExpressionTree lambdaExpressionTree, Void o) { LambdaExpressionTree lastContext = currentLambdaTree; currentLambdaTree = lambdaExpressionTree; scan(lambdaExpressionTree.getBody(), null); currentLambdaTree = lastContext; return null; } @Override public Void visitIdentifier(IdentifierTree identifierTree, Void aVoid) { // If the lambda captures method parameters, inlining the method body can change the // timing of the evaluation of the arguments. if (currentLambdaTree != null && params.contains(getSymbol(identifierTree))) { paramReferred.set(true); } return super.visitIdentifier(identifierTree, null); } }.scan(statement, null); return paramReferred.get(); } }
15,043
37.086076
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inlineme/Inliner.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.inlineme; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.MoreCollectors.onlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.util.ASTHelpers.enclosingPackage; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.hasDirectAnnotationWithSimpleName; import static com.google.errorprone.util.ASTHelpers.stringContainsComments; import static com.google.errorprone.util.MoreAnnotations.getValue; import static com.google.errorprone.util.SideEffectAnalysis.hasSideEffect; import com.google.auto.value.AutoValue; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; 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.util.MoreAnnotations; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.inject.Inject; /** * Checker that performs the inlining at call-sites (where the invoked APIs are annotated as * {@code @InlineMe}). */ @BugPattern( name = "InlineMeInliner", summary = "Callers of this API should be inlined.", severity = WARNING, tags = Inliner.FINDING_TAG) public final class Inliner extends BugChecker implements MethodInvocationTreeMatcher, NewClassTreeMatcher { public static final String FINDING_TAG = "JavaInlineMe"; static final String PREFIX_FLAG = "InlineMe:Prefix"; static final String SKIP_COMMENTS_FLAG = "InlineMe:SkipInliningsWithComments"; private static final Splitter PACKAGE_SPLITTER = Splitter.on('.'); private static final String CHECK_FIX_COMPILES = "InlineMe:CheckFixCompiles"; private static final String INLINE_ME = "InlineMe"; private static final String VALIDATION_DISABLED = "InlineMeValidationDisabled"; private final ImmutableSet<String> apiPrefixes; private final boolean skipCallsitesWithComments; private final boolean checkFixCompiles; @Inject Inliner(ErrorProneFlags flags) { this.apiPrefixes = ImmutableSet.copyOf(flags.getSet(PREFIX_FLAG).orElse(ImmutableSet.<String>of())); this.skipCallsitesWithComments = flags.getBoolean(SKIP_COMMENTS_FLAG).orElse(true); this.checkFixCompiles = flags.getBoolean(CHECK_FIX_COMPILES).orElse(false); } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { MethodSymbol symbol = getSymbol(tree); if (!hasDirectAnnotationWithSimpleName(symbol, INLINE_ME)) { return Description.NO_MATCH; } ImmutableList<String> callingVars = tree.getArguments().stream().map(state::getSourceForNode).collect(toImmutableList()); String receiverString = "new " + state.getSourceForNode(tree.getIdentifier()); return match(tree, symbol, callingVars, receiverString, null, state); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { MethodSymbol symbol = getSymbol(tree); if (!hasDirectAnnotationWithSimpleName(symbol, INLINE_ME)) { return Description.NO_MATCH; } ImmutableList<String> callingVars = tree.getArguments().stream().map(state::getSourceForNode).collect(toImmutableList()); String receiverString = ""; ExpressionTree receiver = getReceiver(tree); if (receiver != null) { receiverString = state.getSourceForNode(receiver); } ExpressionTree methodSelectTree = tree.getMethodSelect(); if (methodSelectTree != null) { String methodSelect = state.getSourceForNode(methodSelectTree); if (methodSelect.equals("super")) { receiverString = methodSelect; } // TODO(kak): Can we omit the `this` case? The getReceiver() call above handles `this` if (methodSelect.equals("this")) { receiverString = methodSelect; } } return match(tree, symbol, callingVars, receiverString, receiver, state); } private Description match( ExpressionTree tree, MethodSymbol symbol, ImmutableList<String> callingVars, String receiverString, ExpressionTree receiver, VisitorState state) { Optional<InlineMeData> inlineMe = InlineMeData.createFromSymbol(symbol); if (inlineMe.isEmpty()) { return Description.NO_MATCH; } Api api = Api.create(symbol, state); if (!matchesApiPrefixes(api)) { return Description.NO_MATCH; } if (skipCallsitesWithComments && stringContainsComments(state.getSourceForNode(tree), state.context)) { return Description.NO_MATCH; } SuggestedFix.Builder builder = SuggestedFix.builder(); Map<String, String> typeNames = new HashMap<>(); for (String newImport : inlineMe.get().imports()) { String typeName = Iterables.getLast(PACKAGE_SPLITTER.split(newImport)); String qualifiedTypeName = SuggestedFixes.qualifyType(state, builder, newImport); typeNames.put(typeName, qualifiedTypeName); } for (String newStaticImport : inlineMe.get().staticImports()) { builder.addStaticImport(newStaticImport); } ImmutableList<String> varNames = symbol.getParameters().stream() .map(varSymbol -> varSymbol.getSimpleName().toString()) .collect(toImmutableList()); boolean varargsWithEmptyArguments = false; if (symbol.isVarArgs()) { // If we're calling a varargs method, its inlining *should* have the varargs parameter in a // reasonable position. If there are are 0 arguments, we'll need to do more surgery if (callingVars.size() == varNames.size() - 1) { varargsWithEmptyArguments = true; } else { ImmutableList<String> nonvarargs = callingVars.subList(0, varNames.size() - 1); String varargsJoined = Joiner.on(", ").join(callingVars.subList(varNames.size() - 1, callingVars.size())); callingVars = ImmutableList.<String>builderWithExpectedSize(varNames.size()) .addAll(nonvarargs) .add(varargsJoined) .build(); } } String replacement = inlineMe.get().replacement(); int replacementStart = ((DiagnosticPosition) tree).getStartPosition(); int replacementEnd = state.getEndPosition(tree); // Special case replacements starting with "this." so the receiver portion is not included in // the replacement. This avoids overlapping replacement regions for fluent chains. if (replacement.startsWith("this.") && receiver != null) { replacementStart = state.getEndPosition(receiver); replacement = replacement.substring("this".length()); } if (Strings.isNullOrEmpty(receiverString)) { replacement = replacement.replaceAll("\\bthis\\.\\b", ""); } else { if (replacement.equals("this")) { // e.g.: foo.b() -> foo Tree parent = state.getPath().getParentPath().getLeaf(); // If the receiver is a side-effect-free expression and the whole expression is standalone, // the receiver likely can't stand on its own (e.g.: "foo;" is not a valid statement while // "foo.noOpMethod();" is). if (parent instanceof ExpressionStatementTree && !hasSideEffect(receiver)) { return describe(parent, SuggestedFix.delete(parent), api); } } replacement = replacement.replaceAll("\\bthis\\b", receiverString); } // Qualify imports first, then replace parameter values to avoid clobbering source from the // inlined method. for (Map.Entry<String, String> typeName : typeNames.entrySet()) { // TODO(b/189535612): we'll need to be smarter about our replacements (to avoid clobbering // inline parameter comments like /* paramName= */ replacement = replacement.replaceAll( "\\b" + Pattern.quote(typeName.getKey()) + "\\b", Matcher.quoteReplacement(typeName.getValue())); } for (int i = 0; i < varNames.size(); i++) { // Ex: foo(int a, int... others) -> this.bar(a, others) // If caller passes 0 args in the varargs position, we want to remove the preceding comma to // make this.bar(a) (as opposed to "this.bar(a, )" boolean terminalVarargsReplacement = varargsWithEmptyArguments && i == varNames.size() - 1; String capturePrefixForVarargs = terminalVarargsReplacement ? "(?:,\\s*)?" : "\\b"; // We want to avoid replacing a method invocation with the same name as the method. var extractArgAndNextToken = Pattern.compile(capturePrefixForVarargs + Pattern.quote(varNames.get(i)) + "\\b([^(])"); String replacementResult = Matcher.quoteReplacement(terminalVarargsReplacement ? "" : callingVars.get(i)) + "$1"; Matcher matcher = extractArgAndNextToken.matcher(replacement); replacement = matcher.replaceAll(replacementResult); } builder.replace(replacementStart, replacementEnd, replacement); SuggestedFix fix = builder.build(); if (checkFixCompiles && fix.getImportsToAdd().isEmpty()) { // If there are no new imports being added (then there are no new dependencies). Therefore, we // can verify that the fix compiles (if CHECK_FIX_COMPILES is enabled). return SuggestedFixes.compilesWithFix(fix, state) ? describe(tree, fix, api) : Description.NO_MATCH; } return describe(tree, fix, api); } private static ImmutableList<String> getStrings(Attribute.Compound attribute, String name) { return getValue(attribute, name) .map(MoreAnnotations::asStrings) .orElse(Stream.empty()) .collect(toImmutableList()); } private Description describe(Tree tree, SuggestedFix fix, Api api) { return buildDescription(tree).setMessage(api.message()).addFix(fix).build(); } @AutoValue abstract static class Api { private static final Splitter CLASS_NAME_SPLITTER = Splitter.on('.'); static Api create(MethodSymbol method, VisitorState state) { String extraMessage = ""; if (hasDirectAnnotationWithSimpleName(method, VALIDATION_DISABLED)) { Attribute.Compound inlineMeValidationDisabled = method.getRawAttributes().stream() .filter(a -> a.type.tsym.getSimpleName().contentEquals(VALIDATION_DISABLED)) .collect(onlyElement()); String reason = Iterables.getOnlyElement(getStrings(inlineMeValidationDisabled, "value")); extraMessage = " NOTE: this is an unvalidated inlining! Reasoning: " + reason; } return new AutoValue_Inliner_Api( method.owner.getQualifiedName().toString(), method.getSimpleName().toString(), enclosingPackage(method).toString(), method.isConstructor(), hasAnnotation(method, "java.lang.Deprecated", state), extraMessage); } abstract String className(); abstract String methodName(); abstract String packageName(); abstract boolean isConstructor(); abstract boolean isDeprecated(); abstract String extraMessage(); final String message() { return "Migrate (via inlining) away from " + (isDeprecated() ? "deprecated " : "") + shortName() + "." + extraMessage(); } /** Returns {@code FullyQualifiedClassName#methodName}. */ final String methodId() { return String.format("%s#%s", className(), methodName()); } /** * Returns a short, human readable description of this API in markdown format (e.g., {@code * `ClassName.methodName()`}). */ final String shortName() { String humanReadableClassName = className().replaceFirst(packageName() + ".", ""); return String.format("`%s.%s()`", humanReadableClassName, methodName()); } /** Returns the simple class name (e.g., {@code ClassName}). */ final String simpleClassName() { return Iterables.getLast(CLASS_NAME_SPLITTER.split(className())); } } private boolean matchesApiPrefixes(Api api) { if (apiPrefixes.isEmpty()) { return true; } for (String apiPrefix : apiPrefixes) { if (api.methodId().startsWith(apiPrefix)) { return true; } } return false; } }
14,101
38.836158
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inlineme/Validator.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.inlineme; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.util.ASTHelpers.findSuperMethods; import static com.google.errorprone.util.ASTHelpers.getAnnotationWithSimpleName; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.hasDirectAnnotationWithSimpleName; import static com.google.errorprone.util.ASTHelpers.shouldKeep; import com.google.common.base.CharMatcher; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.InlineMeValidationDisabled; import com.google.errorprone.bugpatterns.BugChecker; 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.ErrorProneToken; import com.google.errorprone.util.ErrorProneTokens; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.MethodTree; import com.sun.tools.javac.util.Context; import java.util.EnumSet; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import javax.inject.Inject; /** Checker that ensures the {@code @InlineMe} annotation is used correctly. */ @BugPattern( name = "InlineMeValidator", summary = "Ensures that the @InlineMe annotation is used correctly.", suppressionAnnotations = InlineMeValidationDisabled.class, documentSuppression = false, severity = ERROR) public final class Validator extends BugChecker implements MethodTreeMatcher { static final String CLEANUP_INLINE_ME_FLAG = "InlineMe:CleanupInlineMes"; private final boolean cleanupInlineMes; @Inject Validator(ErrorProneFlags flags) { this.cleanupInlineMes = flags.getBoolean(CLEANUP_INLINE_ME_FLAG).orElse(false); } @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (cleanupInlineMes) { return shouldDelete(tree, state) // TODO(b/216312289): maybe use SuggestedFixes.delete(tree)? ? describeMatch(tree, SuggestedFixes.replaceIncludingComments(state.getPath(), "", state)) : Description.NO_MATCH; } else { return InlineMeData.createFromSymbol(getSymbol(tree)) .map(data -> match(data, tree, state)) .orElse(Description.NO_MATCH); } } /** Whether or not the API should be deleted when run in cleanup mode. */ private static boolean shouldDelete(MethodTree tree, VisitorState state) { // We don't delete @InlineMe APIs that are: // * annotated with @InlineMeValidationDisabled (this stops us from deleting default methods) // * annotated with @Override (since the code would likely no longer compile, or it would // start inheriting behavior from the supertype). // * annotated with @Keep or an annotation that is @Keep (e.g., an @Inject API) // TODO(kak): it would be nice if we could query to see if there are still any existing // usages of the API before unilaterally deleting it. return hasDirectAnnotationWithSimpleName(tree, "InlineMe") && !shouldKeep(tree) && !hasAnnotation(tree, "java.lang.Override", state) && findSuperMethods(getSymbol(tree), state.getTypes()).isEmpty(); } private Description match(InlineMeData existingAnnotation, MethodTree tree, VisitorState state) { InlinabilityResult result = InlinabilityResult.forMethod(tree, state); if (!result.isValidForValidator()) { return buildDescription(tree) .setMessage(result.errorMessage()) // This method is un-inlineable, so let's remove the annotation (since we can't fix it) .addFix(SuggestedFix.delete(getInlineMeAnnotationTree(tree))) .build(); } InlineMeData inferredFromMethodBody = InlineMeData.buildExpectedInlineMeAnnotation(state, result.body()); Set<MismatchedInlineMeComponents> mismatches = compatibleWithAnnotation(inferredFromMethodBody, existingAnnotation, state.context); if (mismatches.isEmpty()) { return Description.NO_MATCH; } // There's some mismatch, render an error. return buildDescription(tree) .setMessage(renderInlineMeMismatch(inferredFromMethodBody, existingAnnotation, mismatches)) .addFix( SuggestedFix.replace( getInlineMeAnnotationTree(tree), inferredFromMethodBody.buildAnnotation())) .build(); } private static AnnotationTree getInlineMeAnnotationTree(MethodTree tree) { return getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "InlineMe"); } private static String renderInlineMeMismatch( InlineMeData inferredFromMethodBody, InlineMeData existingAnnotation, Set<MismatchedInlineMeComponents> mismatches) { StringBuilder message = new StringBuilder( "There is a mismatch between the implementation of the method and the replacement" + " suggested in the annotation."); if (mismatches.contains(MismatchedInlineMeComponents.REPLACEMENT_STRING)) { message.append( String.format( "\nReplacement text: \n InferredFromBody: %s\n FromAnnotation: %s", inferredFromMethodBody.replacement(), existingAnnotation.replacement())); } if (mismatches.contains(MismatchedInlineMeComponents.IMPORTS)) { message.append( String.format( "\nImports: \n InferredFromBody: %s\n FromAnnotation: %s", inferredFromMethodBody.imports(), existingAnnotation.imports())); } if (mismatches.contains(MismatchedInlineMeComponents.STATIC_IMPORTS)) { message.append( String.format( "\nStatic imports: \n InferredFromBody: %s\n FromAnnotation: %s", inferredFromMethodBody.staticImports(), existingAnnotation.staticImports())); } return message.toString(); } private enum MismatchedInlineMeComponents { REPLACEMENT_STRING, IMPORTS, STATIC_IMPORTS } private static Set<MismatchedInlineMeComponents> compatibleWithAnnotation( InlineMeData inferredFromMethodBody, InlineMeData anno, Context context) { EnumSet<MismatchedInlineMeComponents> mismatches = EnumSet.noneOf(MismatchedInlineMeComponents.class); // Developers can customize the @InlineMe implementation a bit, so we have some leniency in // determining if an annotation properly represents the implementation of a method. if (!parseAndCheckForTokenEquivalence( anno.replacement(), inferredFromMethodBody.replacement(), context)) { mismatches.add(MismatchedInlineMeComponents.REPLACEMENT_STRING); } if (!inferredFromMethodBody.imports().equals(anno.imports())) { mismatches.add(MismatchedInlineMeComponents.IMPORTS); } if (!inferredFromMethodBody.staticImports().equals(anno.staticImports())) { mismatches.add(MismatchedInlineMeComponents.STATIC_IMPORTS); } return mismatches; } private static final CharMatcher SEMICOLON = CharMatcher.is(';'); /** Determines if the first and second token strings are equivalent. */ private static boolean parseAndCheckForTokenEquivalence( String first, String second, Context context) { ImmutableList<ErrorProneToken> tokens1 = ErrorProneTokens.getTokens(SEMICOLON.trimTrailingFrom(first), context); ImmutableList<ErrorProneToken> tokens2 = ErrorProneTokens.getTokens(SEMICOLON.trimTrailingFrom(second), context); if (tokens1.size() != tokens2.size()) { return false; } for (int i = 0; i < tokens1.size(); i++) { ErrorProneToken token1 = tokens1.get(i); ErrorProneToken token2 = tokens2.get(i); if (!token1.kind().equals(token2.kind())) { return false; } // note we specifically avoid checking ErrorProneToken::comments if (mismatch(token1, token2, ErrorProneToken::hasName, ErrorProneToken::name) || mismatch(token1, token2, ErrorProneToken::hasStringVal, ErrorProneToken::stringVal) || mismatch(token1, token2, ErrorProneToken::hasRadix, ErrorProneToken::radix)) { return false; } } return true; } private static <T> boolean mismatch( ErrorProneToken first, ErrorProneToken second, Predicate<ErrorProneToken> guard, Function<ErrorProneToken, T> extractor) { return guard.test(first) && !extractor.apply(first).equals(extractor.apply(second)); } }
9,432
41.111607
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/nullness/DereferenceWithNullBranch.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.nullness; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.VisitorState.memoize; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.hasDefinitelyNullBranch; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.varsProvenNullByParentTernary; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static javax.lang.model.element.ElementKind.PACKAGE; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.MemberSelectTree; import com.sun.tools.javac.code.Symbol; import javax.lang.model.element.Name; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "Dereference of an expression with a null branch", severity = ERROR) public final class DereferenceWithNullBranch extends BugChecker implements MemberSelectTreeMatcher { private static final Supplier<Name> CLASS_KEYWORD = memoize(state -> state.getName("class")); @Override public Description matchMemberSelect(MemberSelectTree select, VisitorState state) { if (!memberSelectExpressionIsATrueExpression(select, state)) { return NO_MATCH; } if (!hasDefinitelyNullBranch( select.getExpression(), /* * TODO(cpovirk): Precompute sets of definitelyNullVars instead passing an empty set, and * include and varsProvenNullByParentIf alongside varsProvenNullByParentTernary. */ ImmutableSet.of(), varsProvenNullByParentTernary(state.getPath()), state)) { return NO_MATCH; } return describeMatch(select); } private static boolean memberSelectExpressionIsATrueExpression( MemberSelectTree select, VisitorState state) { // We use the same logic here as we do in // https://github.com/jspecify/jspecify-reference-checker/blob/06e85b1eb79ecbb9aa6f5713bc759fb5cf402975/src/main/java/com/google/jspecify/nullness/NullSpecVisitor.java#L195-L206 // (Here, we might not need the isInterface() check, but we keep it for consistency.) // I could also imagine checking for `getKind() != MODULE`, but it's been working without. if (select.getIdentifier().equals(CLASS_KEYWORD.get(state))) { return false; } Symbol symbol = getSymbol(select.getExpression()); if (symbol == null) { return true; } return !symbol.getKind().isClass() && !symbol.getKind().isInterface() && symbol.getKind() != PACKAGE; } }
3,544
41.202381
181
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/nullness/FieldMissingNullable.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.nullness; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.findDeclaration; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.fixByAddingNullableAnnotationToType; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.getNullCheck; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.hasDefinitelyNullBranch; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.isAlreadyAnnotatedNullable; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.nullnessChecksShouldBeConservative; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.varsProvenNullByParentIf; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static javax.lang.model.element.ElementKind.FIELD; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.AssignmentTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.bugpatterns.nullness.NullnessUtils.NullCheck; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.code.Symbol; import javax.inject.Inject; import javax.lang.model.element.Name; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Field is assigned (or compared against) a definitely null value but is not annotated" + " @Nullable", severity = SUGGESTION) public class FieldMissingNullable extends BugChecker implements BinaryTreeMatcher, AssignmentTreeMatcher, VariableTreeMatcher { private final boolean beingConservative; @Inject FieldMissingNullable(ErrorProneFlags flags) { this.beingConservative = nullnessChecksShouldBeConservative(flags); } @Override public Description matchBinary(BinaryTree tree, VisitorState state) { if (beingConservative) { /* * We occasionally see unnecessary null checks for fields. Probably sometime the checks were * necessary years ago. Other times, they were never necessary but were inserted, e.g., by * IDEs as part of an autogenerated equals() implementation. */ return NO_MATCH; } NullCheck nullCheck = getNullCheck(tree); if (nullCheck == null) { return NO_MATCH; } // TODO(cpovirk): Consider not adding @Nullable in cases like `checkState(foo != null)`. return matchIfLocallyDeclaredReferenceFieldWithoutNullable( /* * We do want the Symbol here: We conclude that a field may be null if there is code that * compares *any* access of the field (foo, this.foo, other.foo) to null. */ nullCheck.varSymbolButUsuallyPreferBareIdentifier(), tree, state); } @Override public Description matchAssignment(AssignmentTree tree, VisitorState state) { return match(getSymbol(tree.getVariable()), tree.getExpression(), state); } @Override public Description matchVariable(VariableTree tree, VisitorState state) { return match(getSymbol(tree), tree.getInitializer(), state); } private Description match(Symbol assigned, ExpressionTree expression, VisitorState state) { if (expression == null) { return NO_MATCH; } ImmutableSet<Name> varsProvenNullByParentIf = varsProvenNullByParentIf( /* * Start at the AssignmentTree/VariableTree, not its expression. This matches what we do * for ReturnMissingNullable, where we start at the ReturnTree and not its expression. */ state.getPath().getParentPath()); if (!hasDefinitelyNullBranch( expression, // TODO(cpovirk): Precompute a set of definitelyNullVars instead of passing an empty set. ImmutableSet.of(), varsProvenNullByParentIf, state)) { return NO_MATCH; } return matchIfLocallyDeclaredReferenceFieldWithoutNullable(assigned, expression, state); } private Description matchIfLocallyDeclaredReferenceFieldWithoutNullable( Symbol assigned, ExpressionTree treeToReportOn, VisitorState state) { if (assigned == null || assigned.getKind() != FIELD || assigned.type.isPrimitive()) { return NO_MATCH; } /* * TODO(cpovirk): In conservative mode, consider skipping fields whose type is a type-variable * usage, just as we do in ReturnMissingNullable. (Alternatively, we may decide that that's * *too* conservative, even for ReturnMissingNullable.) */ if (isAlreadyAnnotatedNullable(assigned)) { return NO_MATCH; } VariableTree fieldDecl = findDeclaration(state, assigned); if (fieldDecl == null) { return NO_MATCH; } SuggestedFix fix = fixByAddingNullableAnnotationToType(state, fieldDecl); if (fix.isEmpty()) { return NO_MATCH; } return describeMatch(treeToReportOn, fix); } }
6,183
39.953642
107
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/nullness/ExtendsObject.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.nullness; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getType; import static java.lang.String.format; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.TypeParameterTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeParameterTree; /** A bugpattern: see the summary. */ @BugPattern( summary = "`T extends Object` is redundant" + " (unless you are using the Checker Framework).", severity = SeverityLevel.WARNING) public final class ExtendsObject extends BugChecker implements TypeParameterTreeMatcher { private static final String NON_NULL = "org.checkerframework.checker.nullness.qual.NonNull"; @Override public Description matchTypeParameter(TypeParameterTree tree, VisitorState state) { for (Tree bound : tree.getBounds()) { if (!state.getTypes().isSameType(getType(bound), state.getSymtab().objectType)) { continue; } if (!(bound instanceof AnnotatedTypeTree)) { SuggestedFix.Builder fix = SuggestedFix.builder(); String nonNull = SuggestedFixes.qualifyType(state, fix, NON_NULL); return describeMatch(bound, fix.prefixWith(bound, format(" @%s ", nonNull)).build()); } } return NO_MATCH; } }
2,326
39.824561
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/nullness/NullnessUtils.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.nullness; import static com.google.common.collect.Lists.reverse; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.NullCheck.Polarity.IS_NOT_NULL; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.NullCheck.Polarity.IS_NULL; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.NullableAnnotationToUse.annotationToBeImported; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.NullableAnnotationToUse.annotationWithoutImporting; import static com.google.errorprone.fixes.SuggestedFix.emptyFix; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.staticMethod; import static com.google.errorprone.suppliers.Suppliers.JAVA_LANG_VOID_TYPE; import static com.google.errorprone.util.ASTHelpers.enclosingClass; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.stripParentheses; import static com.sun.source.tree.Tree.Kind.ANNOTATED_TYPE; import static com.sun.source.tree.Tree.Kind.ARRAY_TYPE; import static com.sun.source.tree.Tree.Kind.CONDITIONAL_EXPRESSION; import static com.sun.source.tree.Tree.Kind.IDENTIFIER; import static com.sun.source.tree.Tree.Kind.NULL_LITERAL; import static com.sun.source.tree.Tree.Kind.PARAMETERIZED_TYPE; import static com.sun.tools.javac.parser.Tokens.TokenKind.DOT; import static java.lang.Boolean.TRUE; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.nullness.NullnessUtils.NullCheck.Polarity; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import com.google.errorprone.dataflow.nullnesspropagation.NullnessAnnotations; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.FindIdentifiers; import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.ArrayTypeTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.CaseTree; import com.sun.source.tree.ConditionalExpressionTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.IfTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ParameterizedTypeTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeCastTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.source.util.TreePath; import com.sun.source.util.Trees; import com.sun.tools.javac.code.Kinds.KindSelector; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import java.lang.reflect.Method; import java.util.List; import java.util.Objects; import java.util.Set; import javax.annotation.Nullable; import javax.lang.model.element.Name; /** * Static utility methods for common functionality in the nullable checkers. * * @author awturner@google.com (Andy Turner) */ class NullnessUtils { private NullnessUtils() {} private static final Matcher<ExpressionTree> OPTIONAL_OR_NULL = instanceMethod().onDescendantOf("com.google.common.base.Optional").named("orNull"); private static final Matcher<ExpressionTree> OPTIONAL_OR_ELSE = instanceMethod().onDescendantOf("java.util.Optional").named("orElse"); private static final Matcher<ExpressionTree> EMPTY_TO_NULL = staticMethod().onClass("com.google.common.base.Strings").named("emptyToNull"); /** * Returns {@code true} if the flags request that we look to add @Nullable annotations only where * they are nearly certain to be correct and to be about as uncontroversial as nullness * annotations can ever be. In Google terms, that means annotations that we'd be willing to roll * out across the depot with global approval. * * <p>If this method returns {@code false}, that gives checkers permission to be more aggressive. * Their suggestions should still be very likely to be correct, but the goal is more to assist a * human who is aiming to annotate a codebase. The expectation, then, is that at least one human * will check whether each new annotation is justified. */ static boolean nullnessChecksShouldBeConservative(ErrorProneFlags flags) { return flags.getBoolean("Nullness:Conservative").orElse(true); } /* * TODO(cpovirk): Walking up the tree of enclosing elements may be more expensive than we'd like. * (But I haven't checked.) To improve upon that, would we go so far as to build special tracking * of @NullMarked-ness of the current TreePath into Error Prone itself? (Of course, even that * would help only with the case in which we're interested in the @NullMarked-ness of the tree * we're currently visiting.) * * Another advantage of that approach is that callers wouldn't need to start from a Symbol. For * example, VoidMissingNullable.matchParameterizedType wouldn't have to walk up the path to find * such a Symbol. */ static boolean isInNullMarkedScope(Symbol sym, VisitorState state) { for (; sym != null; sym = sym.getEnclosingElement()) { if (hasAnnotation(sym, "org.jspecify.nullness.NullMarked", state)) { return true; } } return false; } /** * Returns a {@link SuggestedFix} to add a {@code Nullable} annotation to the given method's * return type. */ static SuggestedFix fixByAddingNullableAnnotationToReturnType( VisitorState state, MethodTree method) { return fixByAddingNullableAnnotationToElementOrType( state, method, method.getReturnType(), "nullness:return"); } /** * Returns a {@link SuggestedFix} to add a {@code Nullable} annotation to the given variable's * type. */ static SuggestedFix fixByAddingNullableAnnotationToType( VisitorState state, VariableTree variable) { return fixByAddingNullableAnnotationToElementOrType( state, variable, variable.getType(), /* suppressionToRemove= */ null); } private static SuggestedFix fixByAddingNullableAnnotationToElementOrType( VisitorState state, Tree elementTree, Tree typeTree, @Nullable String suppressionToRemove) { NullableAnnotationToUse nullableAnnotationToUse = pickNullableAnnotation(state); switch (applyOnlyIfAlreadyInScope(state)) { case TRUE: if (!nullableAnnotationToUse.isAlreadyInScope()) { return emptyFix(); } break; case IF_NOT: if (nullableAnnotationToUse.isAlreadyInScope()) { return emptyFix(); } break; default: break; } if (!nullableAnnotationToUse.isTypeUse()) { return nullableAnnotationToUse.fixPrefixingOnto(elementTree, state, suppressionToRemove); } return fixByAddingKnownTypeUseNullableAnnotation( state, typeTree, nullableAnnotationToUse, suppressionToRemove); } /** * Returns a {@link SuggestedFix} to add a <b>type-use</b> {@code Nullable} annotation to the * given tree. The tree should be a "type-use-only" location, like a type argument or a bounds of * a type parameter or wildcard. Prefer to use {@link #fixByAddingNullableAnnotationToReturnType} * and {@link #fixByAddingNullableAnnotationToType} instead of this method when applicable. */ static SuggestedFix fixByAnnotatingTypeUseOnlyLocationWithNullableAnnotation( VisitorState state, Tree typeTree) { NullableAnnotationToUse nullableAnnotationToUse = pickNullableAnnotation(state); if (!nullableAnnotationToUse.isTypeUse()) { return emptyFix(); } return fixByAddingKnownTypeUseNullableAnnotation( state, typeTree, nullableAnnotationToUse, /* suppressionToRemove= */ null); } private static SuggestedFix fixByAddingKnownTypeUseNullableAnnotation( VisitorState state, Tree typeTree, NullableAnnotationToUse nullableAnnotationToUse, @Nullable String suppressionToRemove) { if (typeTree.getKind() == PARAMETERIZED_TYPE) { typeTree = ((ParameterizedTypeTree) typeTree).getType(); } switch (typeTree.getKind()) { case ARRAY_TYPE: Tree beforeBrackets = typeTree; while (true) { Tree pastAnnotations = beforeBrackets.getKind() == ANNOTATED_TYPE ? ((AnnotatedTypeTree) beforeBrackets).getUnderlyingType() : beforeBrackets; if (pastAnnotations.getKind() == ARRAY_TYPE) { beforeBrackets = ((ArrayTypeTree) pastAnnotations).getType(); } else { break; } } // For an explanation of "int @Foo [][] f," etc., see JLS 4.11. return nullableAnnotationToUse.fixPostfixingOnto( beforeBrackets, state, suppressionToRemove); case MEMBER_SELECT: int lastDot = reverse(state.getOffsetTokensForNode(typeTree)).stream() .filter(t -> t.kind() == DOT) .findFirst() .get() .pos(); return nullableAnnotationToUse.fixPostfixingOnto(lastDot, state, suppressionToRemove); case ANNOTATED_TYPE: return nullableAnnotationToUse.fixPrefixingOnto( ((AnnotatedTypeTree) typeTree).getAnnotations().get(0), state, suppressionToRemove); case IDENTIFIER: return nullableAnnotationToUse.fixPrefixingOnto(typeTree, state, suppressionToRemove); default: throw new AssertionError( "unexpected kind for type tree: " + typeTree.getKind() + " for " + typeTree); } // TODO(cpovirk): Remove any @NonNull, etc. annotation that is present? } static boolean isAlreadyAnnotatedNullable(Symbol symbol) { return NullnessAnnotations.fromAnnotationsOn(symbol).orElse(null) == Nullness.NULLABLE; } static boolean hasExtraParameterForEnclosingInstance(MethodSymbol symbol) { // TODO(b/232103314): Figure out which cases the implicit outer `this` parameter exists in. if (!symbol.isConstructor()) { return false; } ClassSymbol constructedClass = enclosingClass(symbol); return enclosingClass(constructedClass) != null && !constructedClass.isStatic(); } @AutoValue abstract static class NullableAnnotationToUse { static NullableAnnotationToUse annotationToBeImported(String qualifiedName, boolean isTypeUse) { return new AutoValue_NullnessUtils_NullableAnnotationToUse( qualifiedName, qualifiedName.replaceFirst(".*[.]", ""), isTypeUse, /* isAlreadyInScope= */ false); } static NullableAnnotationToUse annotationWithoutImporting( String name, boolean isTypeUse, boolean isAlreadyInScope) { return new AutoValue_NullnessUtils_NullableAnnotationToUse( null, name, isTypeUse, isAlreadyInScope); } /** * Returns a {@link SuggestedFix} to add a {@code Nullable} annotation after the given position. */ final SuggestedFix fixPostfixingOnto( int position, VisitorState state, @Nullable String suppressionToRemove) { return prepareBuilder(state, suppressionToRemove) .replace(position + 1, position + 1, " @" + use() + " ") .build(); } /** Returns a {@link SuggestedFix} to add a {@code Nullable} annotation after the given tree. */ final SuggestedFix fixPostfixingOnto( Tree tree, VisitorState state, @Nullable String suppressionToRemove) { return prepareBuilder(state, suppressionToRemove) .postfixWith(tree, " @" + use() + " ") .build(); } /** * Returns a {@link SuggestedFix} to add a {@code Nullable} annotation before the given tree. */ final SuggestedFix fixPrefixingOnto( Tree tree, VisitorState state, @Nullable String suppressionToRemove) { return prepareBuilder(state, suppressionToRemove).prefixWith(tree, "@" + use() + " ").build(); } @Nullable abstract String importToAdd(); abstract String use(); abstract boolean isTypeUse(); abstract boolean isAlreadyInScope(); private SuggestedFix.Builder prepareBuilder( VisitorState state, @Nullable String suppressionToRemove) { SuggestedFix.Builder builder = SuggestedFix.builder(); if (importToAdd() != null) { builder.addImport(importToAdd()); } if (applyRemoveSuppressWarnings(state)) { SuggestedFixes.removeSuppressWarnings(builder, state, suppressionToRemove); } return builder; } } private static NullableAnnotationToUse pickNullableAnnotation(VisitorState state) { /* * TODO(cpovirk): Instead of hardcoding these two annotations, pick the one that seems most * appropriate for each user: * * - Look for usages in other files in the compilation? * * - Look for imports of other annotations that are part of an artifact that also contains * @Nullable (e.g., javax.annotation.Nonnull). * * - Call getSymbolFromString. (But that may return transitive dependencies that will cause * compilation to fail strict-deps checking.) * * - Among available candidates, prefer type-usage annotations. * * - When we suggest a jsr305 annotation, might we want to suggest @CheckForNull over @Nullable? * It's more verbose, but it's more obviously a declaration annotation, and it's the * annotation that is *technically* defined to produce the behaviors that users want. (But do * tools like Dagger recognize it?) */ Symbol sym = FindIdentifiers.findIdent("Nullable", state, KindSelector.VAL_TYP); ErrorProneFlags flags = state.errorProneOptions().getFlags(); String defaultType = flags .get("Nullness:DefaultNullnessAnnotation") .orElse( state.isAndroidCompatible() ? "androidx.annotation.Nullable" : "org.jspecify.nullness.Nullable"); if (sym != null) { ClassSymbol classSym = (ClassSymbol) sym; if (classSym.isAnnotationType()) { // We've got an existing annotation called Nullable. We can use this. return annotationWithoutImporting( "Nullable", isTypeUse(classSym.className()), /* isAlreadyInScope= */ true); } else { // The imported `Nullable` is not an annotation type. Fully qualify the annotation. return annotationWithoutImporting( defaultType, isTypeUse(defaultType), /* isAlreadyInScope= */ false); } } // There is no symbol already. Import and use. return annotationToBeImported(defaultType, isTypeUse(defaultType)); } private static boolean isTypeUse(String className) { /* * TODO(b/205115472): Make this tri-state ({type-use, declaration, both}) and avoid using "both" * annotations in any cases in which they would be ambiguous (e.g., arrays/elements). */ switch (className) { case "libcore.util.Nullable": case "org.checkerframework.checker.nullness.compatqual.NullableType": case "org.checkerframework.checker.nullness.qual.Nullable": case "org.jspecify.annotations.NonNull": case "org.jspecify.annotations.Nullable": case "org.jspecify.nullness.NonNull": case "org.jspecify.nullness.Nullable": return true; default: // TODO(cpovirk): Detect type-use-ness from the class symbol if it's available? return false; } } @Nullable static NullCheck getNullCheck(ExpressionTree tree) { tree = stripParentheses(tree); Polarity polarity; switch (tree.getKind()) { case EQUAL_TO: polarity = IS_NULL; break; case NOT_EQUAL_TO: polarity = IS_NOT_NULL; break; default: return null; } BinaryTree equalityTree = (BinaryTree) tree; ExpressionTree nullChecked; if (equalityTree.getRightOperand().getKind() == NULL_LITERAL) { nullChecked = equalityTree.getLeftOperand(); } else if (equalityTree.getLeftOperand().getKind() == NULL_LITERAL) { nullChecked = equalityTree.getRightOperand(); } else { return null; } Name name = nullChecked.getKind() == IDENTIFIER ? ((IdentifierTree) nullChecked).getName() : null; Symbol symbol = getSymbol(nullChecked); VarSymbol varSymbol = symbol instanceof VarSymbol ? (VarSymbol) symbol : null; return new AutoValue_NullnessUtils_NullCheck(name, varSymbol, polarity); } /** * A check of a variable against {@code null}, like {@code foo == null}. * * <p>This class exposes the variable in two forms: the {@link VarSymbol} (if available) and the * {@link Name} (if the null check was performed on a bare identifier, like {@code foo}). Many * callers restrict themselves to bare identifiers because it's easy and safe: Using {@code * Symbol} might lead code to assume that a null check of {@code foo.bar} guarantees something * about {@code otherFoo.bar}, which is represented by the same symbol. * * <p>Even when restricting themselves to bare identifiers, callers should be wary when examining * code that might: * * <ul> * <li>assign a new value to the identifier after the null check but before some usage * <li>declare a new identifier that hides the old * </ul> * * TODO(cpovirk): What our callers really care about is not "bare identifiers" but "this * particular 'instance' of a variable," so we could generalize to cover more cases of that. For * example, we could probably assume that a null check of {@code foo.bar} ensures that {@code * foo.bar} is non-null in the future. One case that might be particularly useful is {@code * this.bar}. We might even go further, assuming that {@code foo.bar()} will continue to have the * same value in some cases. */ @com.google.auto.value.AutoValue // fully qualified to work around JDK-7177813(?) in JDK8 build abstract static class NullCheck { /** * Returns the bare identifier that was checked against {@code null}, if the null check took * that form. Prefer this over {@link #varSymbolButUsuallyPreferBareIdentifier} in most cases, * as discussed in the class documentation. */ @Nullable abstract Name bareIdentifier(); /** Returns the symbol that was checked against {@code null}. */ @Nullable abstract VarSymbol varSymbolButUsuallyPreferBareIdentifier(); abstract Polarity polarity(); boolean bareIdentifierMatches(ExpressionTree other) { return other.getKind() == IDENTIFIER && bareIdentifier() != null && bareIdentifier().equals(((IdentifierTree) other).getName()); } ExpressionTree nullCase(ConditionalExpressionTree tree) { return polarity() == IS_NULL ? tree.getTrueExpression() : tree.getFalseExpression(); } StatementTree nullCase(IfTree tree) { return polarity() == IS_NULL ? tree.getThenStatement() : tree.getElseStatement(); } enum Polarity { IS_NULL, IS_NOT_NULL, } } static boolean hasDefinitelyNullBranch( ExpressionTree tree, Set<VarSymbol> definitelyNullVars, /* * TODO(cpovirk): Compute varsProvenNullByParentIf inside this method, using the TreePath from * an instance of VisitorState, which must be an instance with the current path instead of * stateForCompilationUnit? (This would also let us eliminate the `tree` parameter, since that * would be accessible through getLeaf().) But we'll need to be consistent about whether we * pass the path of the expression or its enclosing statement. */ ImmutableSet<Name> varsProvenNullByParentIf, VisitorState stateForCompilationUnit) { return new SimpleTreeVisitor<Boolean, Void>() { @Override public Boolean visitAssignment(AssignmentTree tree, Void unused) { return visit(tree.getExpression(), unused); } @Override public Boolean visitConditionalExpression(ConditionalExpressionTree tree, Void unused) { return visit(tree.getTrueExpression(), unused) || visit(tree.getFalseExpression(), unused) || isTernaryXIfXIsNull(tree); } @Override public Boolean visitIdentifier(IdentifierTree tree, Void unused) { return super.visitIdentifier(tree, unused) || varsProvenNullByParentIf.contains(tree.getName()); } @Override public Boolean visitMethodInvocation(MethodInvocationTree tree, Void unused) { return super.visitMethodInvocation(tree, unused) || isOptionalOrNull(tree) || isStringsEmptyToNull(tree); } @Override public Boolean visitParenthesized(ParenthesizedTree tree, Void unused) { return visit(tree.getExpression(), unused); } // For visitSwitchExpression logic, see defaultAction. @Override public Boolean visitTypeCast(TypeCastTree tree, Void unused) { return visit(tree.getExpression(), unused); } @Override protected Boolean defaultAction(Tree tree, Void unused) { /* * This covers not only "Void" and "CAP#1 extends Void" but also the null literal. (It * covers the null literal even through parenthesized expressions. Still, we end up * needing special handling for parenthesized expressions for cases like `(foo ? bar : * null)`.) */ return isVoid(getType(tree), stateForCompilationUnit) || definitelyNullVars.contains(getSymbol(tree)) /* * TODO(cpovirk): It would be nicer to report the finding on the null-returning `case` * rather than on the `switch` as a whole. To do so, maybe we could change our visitor * to accept `Boolean isCaseOfReturnedExpressionSwitch` instead of `Void unused`? */ || isSwitchExpressionWithDefinitelyNullBranch(tree); } boolean isOptionalOrNull(MethodInvocationTree tree) { return OPTIONAL_OR_NULL.matches(tree, stateForCompilationUnit) || (OPTIONAL_OR_ELSE.matches(tree, stateForCompilationUnit) && tree.getArguments().get(0).getKind() == NULL_LITERAL); /* * TODO(cpovirk): Instead of checking only for NULL_LITERAL, call hasDefinitelyNullBranch? * But consider whether that would interfere with the TODO at the top of that method. */ } boolean isStringsEmptyToNull(MethodInvocationTree tree) { return EMPTY_TO_NULL.matches(tree, stateForCompilationUnit); } boolean isSwitchExpressionWithDefinitelyNullBranch(Tree tree) { return tree.getKind().name().equals("SWITCH_EXPRESSION") && getCases(tree).stream() .map(NullnessUtils::getBody) .anyMatch(t -> Objects.equals(visit(t, null), TRUE)); } }.visit(tree, null); } private static List<?> getCases(Tree switchExpressionTree) { try { if (getCasesMethod == null) { getCasesMethod = Class.forName("com.sun.source.tree.SwitchExpressionTree").getMethod("getCases"); } return (List<?>) getCasesMethod.invoke(switchExpressionTree); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } private static Tree getBody(Object caseTree) { try { if (getBodyMethod == null) { getBodyMethod = CaseTree.class.getMethod("getBody"); } return (Tree) getBodyMethod.invoke(caseTree); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } private static Method getCasesMethod; private static Method getBodyMethod; /** Returns true if this is {@code x == null ? x : ...} or similar. */ private static boolean isTernaryXIfXIsNull(ConditionalExpressionTree tree) { NullCheck nullCheck = getNullCheck(tree.getCondition()); if (nullCheck == null) { return false; } ExpressionTree needsToBeKnownNull = nullCheck.nullCase(tree); return nullCheck.bareIdentifierMatches(needsToBeKnownNull); } static boolean isVoid(Type type, VisitorState state) { return type != null && state.getTypes().isSubtype(type, JAVA_LANG_VOID_TYPE.get(state)); } /** Returns x if the path's leaf is the only statement inside {@code if (x == null) { ... }}. */ static ImmutableSet<Name> varsProvenNullByParentIf(TreePath path) { Tree parent = path.getParentPath().getLeaf(); if (!(parent instanceof BlockTree)) { return ImmutableSet.of(); } if (((BlockTree) parent).getStatements().size() > 1) { return ImmutableSet.of(); } Tree grandparent = path.getParentPath().getParentPath().getLeaf(); if (!(grandparent instanceof IfTree)) { return ImmutableSet.of(); } IfTree ifTree = (IfTree) grandparent; NullCheck nullCheck = getNullCheck(ifTree.getCondition()); if (nullCheck == null) { return ImmutableSet.of(); } if (parent != nullCheck.nullCase(ifTree)) { return ImmutableSet.of(); } if (nullCheck.bareIdentifier() == null) { return ImmutableSet.of(); } return ImmutableSet.of(nullCheck.bareIdentifier()); } /** Returns x if the path's leaf is inside {@code (x == null) ? ... : ...}. */ public static ImmutableSet<Name> varsProvenNullByParentTernary(TreePath path) { Tree child = path.getLeaf(); for (Tree tree : path.getParentPath()) { if (!(tree instanceof ExpressionTree)) { break; } if (tree.getKind() == CONDITIONAL_EXPRESSION) { ConditionalExpressionTree ternary = (ConditionalExpressionTree) tree; NullCheck nullCheck = getNullCheck(ternary.getCondition()); if (nullCheck == null) { return ImmutableSet.of(); } if (child != nullCheck.nullCase(ternary)) { return ImmutableSet.of(); } if (nullCheck.bareIdentifier() == null) { return ImmutableSet.of(); } return ImmutableSet.of(nullCheck.bareIdentifier()); } child = tree; } return ImmutableSet.of(); } @Nullable static VariableTree findDeclaration(VisitorState state, Symbol sym) { JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(state.context); TreePath declPath = Trees.instance(javacEnv).getPath(sym); // Skip fields declared in other compilation units since we can't make a fix for them here. if (declPath != null && declPath.getCompilationUnit() == state.getPath().getCompilationUnit() && (declPath.getLeaf() instanceof VariableTree)) { return (VariableTree) declPath.getLeaf(); } return null; } private enum OnlyIfInScope { IF_NOT, FALSE, TRUE } private static OnlyIfInScope applyOnlyIfAlreadyInScope(VisitorState state) { return state .errorProneOptions() .getFlags() .getEnum("Nullness:OnlyIfAnnotationAlreadyInScope", OnlyIfInScope.class) .orElse(OnlyIfInScope.FALSE); } private static boolean applyRemoveSuppressWarnings(VisitorState state) { return state .errorProneOptions() .getFlags() .getBoolean("Nullness:RemoveSuppressWarnings") .orElse(false); } }
28,685
39.574257
122
java