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/nullness/UnnecessaryCheckNotNull.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.nullness; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Matchers.argument; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.sun.source.tree.Tree.Kind.STRING_LITERAL; 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.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.tree.JCTree.JCIdent; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Checks for unnecessarily performing null checks on expressions which can't be null. * * @author awturner@google.com (Andy Turner) * @author bhagwani@google.com (Sumit Bhagwani) */ @BugPattern( summary = "This null check is unnecessary; the expression can never be null", severity = ERROR, altNames = {"PreconditionsCheckNotNull", "PreconditionsCheckNotNullPrimitive"}) public class UnnecessaryCheckNotNull extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<MethodInvocationTree> CHECK_NOT_NULL_MATCHER = Matchers.<MethodInvocationTree>anyOf( staticMethod().onClass("com.google.common.base.Preconditions").named("checkNotNull"), staticMethod().onClass("com.google.common.base.Verify").named("verifyNotNull"), staticMethod().onClass("java.util.Objects").named("requireNonNull")); private static final Matcher<MethodInvocationTree> NEW_INSTANCE_MATCHER = argument( 0, Matchers.<ExpressionTree>kindAnyOf(ImmutableSet.of(Kind.NEW_CLASS, Kind.NEW_ARRAY))); private static final Matcher<MethodInvocationTree> STRING_LITERAL_ARG_MATCHER = argument(0, Matchers.<ExpressionTree>kindIs(STRING_LITERAL)); private static final Matcher<MethodInvocationTree> PRIMITIVE_ARG_MATCHER = argument(0, Matchers.<ExpressionTree>isPrimitiveType()); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!CHECK_NOT_NULL_MATCHER.matches(tree, state) || tree.getArguments().isEmpty()) { return Description.NO_MATCH; } if (NEW_INSTANCE_MATCHER.matches(tree, state)) { return matchNewInstance(tree, state); } if (STRING_LITERAL_ARG_MATCHER.matches(tree, state)) { return matchStringLiteral(tree, state); } if (PRIMITIVE_ARG_MATCHER.matches(tree, state)) { return describePrimitiveMatch(tree, state); } return Description.NO_MATCH; } private Description matchNewInstance(MethodInvocationTree tree, VisitorState state) { Fix fix = SuggestedFix.replace(tree, state.getSourceForNode(tree.getArguments().get(0))); return describeMatch(tree, fix); } private Description matchStringLiteral( MethodInvocationTree methodInvocationTree, VisitorState state) { List<? extends ExpressionTree> arguments = methodInvocationTree.getArguments(); ExpressionTree stringLiteralValue = arguments.get(0); Fix fix; if (arguments.size() == 2) { fix = SuggestedFix.swap(arguments.get(0), arguments.get(1)); } else { fix = SuggestedFix.delete(state.getPath().getParentPath().getLeaf()); } return describeMatch(stringLiteralValue, fix); } /** * If the call to Preconditions.checkNotNull is part of an expression (assignment, return, etc.), * we substitute the argument for the method call. E.g.: {@code bar = * Preconditions.checkNotNull(foo); ==> bar = foo;} * * <p>If the argument to Preconditions.checkNotNull is a comparison using == or != and one of the * operands is null, we call checkNotNull on the non-null operand. E.g.: {@code checkNotNull(a == * null); ==> checkNotNull(a);} * * <p>If the argument is a method call or binary tree and its return type is boolean, change it to * a checkArgument/checkState. E.g.: {@code Preconditions.checkNotNull(foo.hasFoo()) ==> * Preconditions.checkArgument(foo.hasFoo())} * * <p>Otherwise, delete the checkNotNull call. E.g.: {@code Preconditions.checkNotNull(foo); ==> * [delete the line]} */ private Description describePrimitiveMatch( MethodInvocationTree methodInvocationTree, VisitorState state) { ExpressionTree arg1 = methodInvocationTree.getArguments().get(0); Tree parent = state.getPath().getParentPath().getLeaf(); // Assignment, return, etc. if (parent.getKind() != Kind.EXPRESSION_STATEMENT) { return describeMatch( arg1, SuggestedFix.replace(methodInvocationTree, state.getSourceForNode(arg1))); } // Comparison to null if (arg1.getKind() == Kind.EQUAL_TO || arg1.getKind() == Kind.NOT_EQUAL_TO) { BinaryTree binaryExpr = (BinaryTree) arg1; if (binaryExpr.getLeftOperand().getKind() == Kind.NULL_LITERAL) { return describeMatch( arg1, SuggestedFix.replace(arg1, state.getSourceForNode(binaryExpr.getRightOperand()))); } if (binaryExpr.getRightOperand().getKind() == Kind.NULL_LITERAL) { return describeMatch( arg1, SuggestedFix.replace(arg1, state.getSourceForNode(binaryExpr.getLeftOperand()))); } } if ((arg1 instanceof BinaryTree || arg1.getKind() == Kind.METHOD_INVOCATION || arg1.getKind() == Kind.LOGICAL_COMPLEMENT) && state.getTypes().isSameType(ASTHelpers.getType(arg1), state.getSymtab().booleanType)) { return describeMatch(arg1, createCheckArgumentOrStateCall(methodInvocationTree, state, arg1)); } return describeMatch(arg1, SuggestedFix.delete(parent)); } /** * Creates a SuggestedFix that replaces the checkNotNull call with a checkArgument or checkState * call. */ private static Fix createCheckArgumentOrStateCall( MethodInvocationTree methodInvocationTree, VisitorState state, ExpressionTree arg1) { String replacementMethod = "checkState"; if (hasMethodParameter(state.getPath(), arg1)) { replacementMethod = "checkArgument"; } SuggestedFix.Builder fix = SuggestedFix.builder(); String name = SuggestedFixes.qualifyStaticImport( "com.google.common.base.Preconditions." + replacementMethod, fix, state); fix.replace(methodInvocationTree.getMethodSelect(), name); return fix.build(); } /** * Determines whether the expression contains a reference to one of the enclosing method's * parameters. * * <p>TODO(eaftan): Extract this to ASTHelpers. * * @param path the path to the current tree node * @param tree the node to compare against the parameters * @return whether the argument is a parameter to the enclosing method */ private static boolean hasMethodParameter(TreePath path, ExpressionTree tree) { Set<Symbol> symbols = new HashSet<>(); for (IdentifierTree ident : getVariableUses(tree)) { Symbol sym = ASTHelpers.getSymbol(ident); if (ASTHelpers.isLocal(sym)) { symbols.add(sym); } } // Find enclosing method declaration. while (path != null && !(path.getLeaf() instanceof MethodTree)) { path = path.getParentPath(); } if (path == null) { throw new IllegalStateException("Should have an enclosing method declaration"); } MethodTree methodDecl = (MethodTree) path.getLeaf(); for (VariableTree param : methodDecl.getParameters()) { if (symbols.contains(ASTHelpers.getSymbol(param))) { return true; } } return false; } /** * Find the root variable identifiers from an arbitrary expression. * * <p>Examples: a.trim().intern() ==> {a} a.b.trim().intern() ==> {a} this.intValue.foo() ==> * {this} this.foo() ==> {this} intern() ==> {} String.format() ==> {} java.lang.String.format() * ==> {} x.y.z(s.t) ==> {x,s} */ static List<IdentifierTree> getVariableUses(ExpressionTree tree) { List<IdentifierTree> freeVars = new ArrayList<>(); new TreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree node, Void v) { if (((JCIdent) node).sym instanceof VarSymbol) { freeVars.add(node); } return super.visitIdentifier(node, v); } }.scan(tree, null); return freeVars; } }
9,848
39.036585
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/nullness/EqualsBrokenForNull.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.nullness; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isConsideredFinal; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import com.google.errorprone.dataflow.nullnesspropagation.NullnessAnalysis; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.IfTree; import com.sun.source.tree.InstanceOfTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeCastTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import java.util.HashSet; import java.util.Set; import javax.annotation.Nullable; /** * {@link BugChecker} adds a null check to {@code equals()} method implementations which don't * satisfy the null contract of {@link Object#equals} i.e. {@code equals(null)} should return false. * * @author bhagwani@google.com (Sumit Bhagwani) */ @BugPattern( summary = "equals() implementation may throw NullPointerException when given null", severity = SeverityLevel.WARNING) public class EqualsBrokenForNull extends BugChecker implements MethodTreeMatcher { @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (!Matchers.equalsMethodDeclaration().matches(tree, state)) { return NO_MATCH; } // Keep track of variables which, if true, imply that the incoming variable is non-null. Set<VarSymbol> impliesNonNull = new HashSet<>(); Set<VarSymbol> incomingVariableSymbols = new HashSet<>(); VarSymbol varSymbol = getSymbol(getOnlyElement(tree.getParameters())); incomingVariableSymbols.add(varSymbol); NullnessAnalysis analysis = NullnessAnalysis.instance(state.context); // we run nullness analysis on all the subtrees and match if there is a method invocation on // the argument to the equals method. boolean[] crashesWithNull = {false}; new TreePathScanner<Void, Void>() { @Override public Void visitMemberSelect(MemberSelectTree node, Void unused) { if (!crashesWithNull[0]) { Symbol symbol = getSymbol(node.getExpression()); if (symbol instanceof VarSymbol && incomingVariableSymbols.contains(symbol)) { Nullness nullness = analysis.getNullness( new TreePath(getCurrentPath(), node.getExpression()), state.context); if (nullness == Nullness.NULLABLE) { crashesWithNull[0] = true; } } } return super.visitMemberSelect(node, null); } @Override public Void visitVariable(VariableTree variableTree, Void unused) { // Track variables assigned from our parameter. Tree initializer = variableTree.getInitializer(); VarSymbol symbol = getSymbol(variableTree); if (isConsideredFinal(symbol) && initializer instanceof InstanceOfTree) { InstanceOfTree instanceOf = (InstanceOfTree) initializer; if (instanceOf.getExpression() instanceof IdentifierTree && incomingVariableSymbols.contains(getSymbol(instanceOf.getExpression()))) { impliesNonNull.add(getSymbol(variableTree)); } } if (incomingVariableSymbols.contains(findVariable(variableTree.getInitializer()))) { incomingVariableSymbols.add(getSymbol(variableTree)); } return super.visitVariable(variableTree, null); } @Override public Void visitIf(IfTree ifTree, Void unused) { ExpressionTree condition = ASTHelpers.stripParentheses(ifTree.getCondition()); if (condition instanceof IdentifierTree && impliesNonNull.contains(getSymbol(condition))) { return scan(ifTree.getElseStatement(), null); } return super.visitIf(ifTree, unused); } @Override public Void visitLambdaExpression(LambdaExpressionTree node, Void unused) { // Our nullness analyzer isn't good at straddling lambda boundaries. return null; } /** * Unwraps expressions like `(Foo) foo` or `((Foo) foo)` to return the VarSymbol of `foo`, or * null if the expression wasn't of this form. */ @Nullable private VarSymbol findVariable(Tree tree) { while (tree != null) { switch (tree.getKind()) { case TYPE_CAST: tree = ((TypeCastTree) tree).getExpression(); break; case PARENTHESIZED: tree = ((ParenthesizedTree) tree).getExpression(); break; case IDENTIFIER: Symbol symbol = getSymbol(tree); return symbol instanceof VarSymbol ? (VarSymbol) symbol : null; default: return null; } } return null; } }.scan(state.getPath(), null); if (!crashesWithNull[0]) { return NO_MATCH; } String stringAddition = String.format("if (%s == null) { return false; }\n", varSymbol.name); Fix fix = SuggestedFix.prefixWith(tree.getBody().getStatements().get(0), stringAddition); return describeMatch(tree, fix); } }
6,760
40.734568
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/nullness/ParameterMissingNullable.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.nullness; import static com.google.common.collect.Streams.forEachPair; 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.hasExtraParameterForEnclosingInstance; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.isAlreadyAnnotatedNullable; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.nullnessChecksShouldBeConservative; 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.hasNoExplicitType; import static javax.lang.model.element.ElementKind.PARAMETER; import static javax.lang.model.type.TypeKind.TYPEVAR; 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.BinaryTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; 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.AssertTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IfTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.ThrowTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import java.util.List; import javax.inject.Inject; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Parameter has handling for null but is not annotated @Nullable", severity = SUGGESTION) public final class ParameterMissingNullable extends BugChecker implements BinaryTreeMatcher, MethodInvocationTreeMatcher, NewClassTreeMatcher { private final boolean beingConservative; @Inject ParameterMissingNullable(ErrorProneFlags flags) { this.beingConservative = nullnessChecksShouldBeConservative(flags); } @Override public Description matchBinary(BinaryTree tree, VisitorState state) { if (beingConservative) { // The rules in matchBinary are mostly heuristics, as discussed in the large comment below. return NO_MATCH; } /* * This check's basic principle is: If an implementation checks `param == null` or * `param != null`, then it's going to take one of two actions: * * 1. fail: `checkArgument(param != null)`, `if (param == null) throw new IAE()` * * 2. take some action to treat null as a valid input: `this.p = p == null ? DEFAULT_P : p;` * * So: If we see a comparison of a parameter against null, we look for code that appears to be * implementing "fail." If we don't find such code, then we assume that the method treats a null * parameter as a valid input, and we suggest adding @Nullable. * * TODO(cpovirk): For implementation convenience, we currently make no distinction between * `param != null` and `param == null`. This means that we treat `checkArgument(param == null)` * as if it implements "fail if null." Fortunately, this doesn't appear to come up much in * practice. And anyway, it's OK for us to fail to add @Nullable when it would make sense. * Still, it's sloppy, and we might want to clean it up someday. We just may need to be careful * about more complex expressions like `checkArgument(!(a == null || b == null))` and about * "inverted" methods like `Assert.not(param == null)`. */ NullCheck nullCheck = getNullCheck(tree); if (nullCheck == null) { return NO_MATCH; } /* * We really do want to use the Symbol here. NullCheck exposes a symbol only in the case of a * local variable or parameter, but that's OK here because we care only about parameters. And * ultimately we need the Symbol so that we can look at its annotations and find its * declaration. */ Symbol symbol = nullCheck.varSymbolButUsuallyPreferBareIdentifier(); if (!isParameterWithoutNullable(symbol)) { return NO_MATCH; } /* * OK, it's `param == null` or `param != null` for some `param` that is not `@Nullable`. * * We'll move on to determine whether the code implements "fail" or not. */ /* * But first, a special case: A null check does *not* guarantee safety if the parameter is * dereferenced and reassigned before the check occurs. If that happens, it's probably because * of a loop: * * do { param = param.next(); } while (param ! null); * * So we don't add @Nullable based on a null check in a loop condition. */ if (isLoopCondition(state.getPath())) { return NO_MATCH; } // Now the big check: if (nullCheckLikelyToProduceException(state)) { return NO_MATCH; } // OK, looks like the code handles null as a valid input. Let's add @Nullable if we can+should. VariableTree param = findDeclaration(state, symbol); if (param == null) { return NO_MATCH; // hopefully impossible: A parameter must come from the same compilation unit } if (hasNoExplicitType(param, state)) { return NO_MATCH; } SuggestedFix fix = fixByAddingNullableAnnotationToType(state, param); if (fix.isEmpty()) { return NO_MATCH; } return describeMatch(tree, fix); } private static boolean isLoopCondition(TreePath path) { /* * Looking at the grandparent is mostly sufficient: * * Even if we have `while (something) checkArgument(param != null)`, the null check has parent * MethodInvocationTree and grandparent StatementExpressionTree -- i.e., *not* a grandparent * WhileLoopTree -- so we don't falsely conclude that the null check is in the loop condition. * * TODO(cpovirk): Consider looking further up the tree to detect loop conditions like * `param != null && param.somethingElse()`. */ switch (path.getParentPath().getParentPath().getLeaf().getKind()) { case WHILE_LOOP: case DO_WHILE_LOOP: return true; default: } switch (path.getParentPath().getLeaf().getKind()) { case FOR_LOOP: return true; default: } return false; } private static boolean isParameterWithoutNullable(Symbol sym) { return sym != null && sym.getKind() == PARAMETER && !isAlreadyAnnotatedNullable(sym); } private static boolean nullCheckLikelyToProduceException(VisitorState state) { boolean[] likelyToProduceException = {false}; Tree childInPath = null; for (Tree tree : state.getPath()) { if (tree instanceof AssertTree || tree instanceof MethodInvocationTree) { /* * An assert or method call is likely to be something like checkArgument(param != null), so * we assume that it will throw an exception for a null argument. * * That said, we don't check the form of the assert or method call at all. So we might be * looking at checkArgument(foo == null) -- which would mean that we *should* add @Nullable. * For more discussion, see the TODO at the top of matchBinary. */ return true; } else if (tree instanceof IfTree && childInPath.equals(((IfTree) tree).getCondition())) { /* * We have something like `if (foo == null)`, etc., so we scan the then+else for code that * throws exceptions. * * As in the AssertTree+MethodInvocationTree case above, it would make sense for us to look * *only* at the `then` or *only* at the `else`, depending on the form of the null check. */ new TreeScanner<Void, Void>() { // Checking for both `new SomeException` and `throw` is probably redundant, but it's easy. @Override public Void visitNewClass(NewClassTree tree, Void unused) { likelyToProduceException[0] |= state.getTypes().isSubtype(getType(tree), state.getSymtab().throwableType); return super.visitNewClass(tree, unused); } @Override public Void visitThrow(ThrowTree tree, Void unused) { likelyToProduceException[0] = true; return null; } }.scan(tree, null); } childInPath = tree; } /* * TODO(cpovirk): Consider also looking for calls to methods that "look like failures," such as * calls to logging APIs or methods with "fail" in the name. However, my initial attempt at this * didn't add any value for the code I tested on. */ return likelyToProduceException[0]; } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return matchCall(getSymbol(tree), tree.getArguments(), state); } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { return matchCall(getSymbol(tree), tree.getArguments(), state); } private Description matchCall( MethodSymbol methodSymbol, List<? extends ExpressionTree> arguments, VisitorState state) { if (hasExtraParameterForEnclosingInstance(methodSymbol)) { // TODO(b/232103314): Figure out the right way to handle the implicit outer `this` parameter. return NO_MATCH; } if (methodSymbol.isVarArgs()) { /* * TODO(b/232103314): Figure out the right way to handle this, or at least handle all * parameters but the last. */ return NO_MATCH; } forEachPair( arguments.stream(), methodSymbol.getParameters().stream(), (argTree, paramSymbol) -> { if (!hasDefinitelyNullBranch( argTree, /* * TODO(cpovirk): Precompute sets of definitelyNullVars and varsProvenNullByParentIf * instead of passing empty sets. */ ImmutableSet.of(), ImmutableSet.of(), state)) { return; } if (isAlreadyAnnotatedNullable(paramSymbol)) { return; } if (paramSymbol.asType().getKind() == TYPEVAR) { // TODO(cpovirk): Don't always give up for type variables, at least in aggressive mode. return; } VariableTree paramTree = findDeclaration(state, paramSymbol); if (paramTree == null) { /* * First, we can't reliably make changes to declarations in other compilation units. * * But even if we could, we'd "trust" calls in other compilation units less: Plenty of * code passes null when it "shouldn't": * * - Some code gets away with it because that call never runs. * * - Some tests get away with it because they know that no one will read the value. * * - Some tests are deliberately checking that passing null produces NPE. * * Still, maybe we'd consider trusting such calls when running in aggressive mode if we * had the ability someday. */ return; } SuggestedFix fix = fixByAddingNullableAnnotationToType(state, paramTree); if (fix.isEmpty()) { return; } /* * TODO(cpovirk): Would it be better to report this on the parameter, rather than the * argument? If so, we may want to rework this checker to be a CompilationUnitMatcher. * That way, it can scan the whole file to find parameters and *then* evaluate * suppressions. (Under the current MethodInvocationTreeMatcher approach, a suppression at * the *arg* site would suppress errors that would be reported on the param. Even if we * were to manually make suppressions at the param *also* have an effect, the remaining * effect for *arg*-site suppressions would be unfortunate.) */ state.reportMatch(describeMatch(argTree, fix)); }); return NO_MATCH; } /* * TODO(cpovirk): Check for assignment to a @Nullable field. We'll need special cases, though: * * - fields that should initially be set to a non-null value, only to be nulled out later * * - fields that are allowed to be set to null from some constructors/methods but not from others * (e.g., Foo() sets a field to null; Foo(Object) sets it to the given non-null object) * * - others? */ }
14,157
41.136905
109
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/nullness/VoidMissingNullable.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.nullness; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.fixByAddingNullableAnnotationToReturnType; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.fixByAddingNullableAnnotationToType; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.fixByAnnotatingTypeUseOnlyLocationWithNullableAnnotation; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.isVoid; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.nullnessChecksShouldBeConservative; 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.hasNoExplicitType; import static com.sun.source.tree.Tree.Kind.METHOD; import static javax.lang.model.element.ElementKind.LOCAL_VARIABLE; import com.google.common.collect.ImmutableList; 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.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ParameterizedTypeTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import com.google.errorprone.dataflow.nullnesspropagation.NullnessAnnotations; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ParameterizedTypeTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.tree.WildcardTree; 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 javax.inject.Inject; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "The type Void is not annotated @Nullable", severity = SUGGESTION) public class VoidMissingNullable extends BugChecker implements ParameterizedTypeTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { private final boolean beingConservative; @Inject VoidMissingNullable(ErrorProneFlags flags) { this.beingConservative = nullnessChecksShouldBeConservative(flags); } /* * TODO(cpovirk): Handle `Void[]`, probably mostly in casts, while avoiding `Void[].class`. * * (We're missing other cases, too, like a hypothetical `? extends Void & Foo`.) * * If we end up wanting to cover more cases, then we may want to rework this checker to be a * matcher of IdentifierTree and MemberSelectTree that looks at the parent in the TreePath for an * AnnotatedTypeTree with the appropriate annotations. However, that approach would still require * special cases for methods and variables: Annotations are attached to the method/variable rather * than the type (sensibly so for nullness declaration annotations; less sensibly so for nullness * type-use annotations). Thus, we'd need to look not just for AnnotatedTypeTree but for * MethodTree and VariableTree, as well. That might still pay off if we start caring about cases * like Void[], but those cases may be rare enough that we don't need to care. */ @Override public Description matchParameterizedType( ParameterizedTypeTree parameterizedTypeTree, VisitorState state) { if (beingConservative && state.errorProneOptions().isTestOnlyTarget()) { return NO_MATCH; } if (beingConservative && !isInNullMarkedScope(state)) { return NO_MATCH; } for (Tree tree : parameterizedTypeTree.getTypeArguments()) { if (tree instanceof WildcardTree) { tree = ((WildcardTree) tree).getBound(); } checkTree(tree, state); } return NO_MATCH; // Any reports were made through state.reportMatch. } /* * TODO(cpovirk): Consider promoting this variant of isInNullMarkedScope to live in NullnessUtils * alongside the main variant. But note that it may be even more expensive than the main variant, * and see the more ambitious alternative TODO(cpovirk): in that file. */ private static boolean isInNullMarkedScope(VisitorState state) { for (Tree tree : state.getPath()) { if (tree.getKind().asInterface().equals(ClassTree.class) || tree.getKind() == METHOD) { Symbol enclosingElement = getSymbol(tree); return NullnessUtils.isInNullMarkedScope(enclosingElement, state); } } throw new AssertionError( "parameterized type without enclosing element: " + Iterables.toString(state.getPath())); } @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (beingConservative && state.errorProneOptions().isTestOnlyTarget()) { return NO_MATCH; } MethodSymbol sym = getSymbol(tree); if (!typeMatches(sym.getReturnType(), sym, state)) { return NO_MATCH; } if (beingConservative && !NullnessUtils.isInNullMarkedScope(sym, state)) { return NO_MATCH; } return describeMatch(tree, fixByAddingNullableAnnotationToReturnType(state, tree)); } @Override public Description matchVariable(VariableTree tree, VisitorState state) { if (beingConservative && state.errorProneOptions().isTestOnlyTarget()) { return NO_MATCH; } if (hasNoExplicitType(tree, state)) { /* * In the case of `var`, a declaration-annotation @Nullable would be valid. But a type-use * @Nullable would not be. But more importantly, we expect that tools will infer the * "top-level" nullness of all local variables, `var` and otherwise, without ever requiring a * @Nullable annotation on them. */ return NO_MATCH; } VarSymbol sym = getSymbol(tree); if (sym.getKind() == LOCAL_VARIABLE) { return NO_MATCH; // Local variables are discussed in the comment about `var`, etc. above. } if (!typeMatches(sym.type, sym, state)) { return NO_MATCH; } if (beingConservative && !NullnessUtils.isInNullMarkedScope(sym, state)) { return NO_MATCH; } SuggestedFix fix = fixByAddingNullableAnnotationToType(state, tree); if (fix.isEmpty()) { return NO_MATCH; } return describeMatch(tree, fix); } private void checkTree(Tree tree, VisitorState state) { if (!typeMatches(getType(tree), state)) { return; } /* * Redundant-looking check required for anonymous classes because JCTree.type doesn't show the * annotations in that case -- presumably a bug? * * TODO(cpovirk): Provide this pair of checks as NullnessAnnotations.fromAnnotationsOn(Tree), * which might also be useful for a hypothetical future TypeArgumentMissingNullable? */ if (NullnessAnnotations.fromAnnotations(annotationsIfAnnotatedTypeTree(tree)).orElse(null) == Nullness.NULLABLE) { return; } SuggestedFix fix = fixByAnnotatingTypeUseOnlyLocationWithNullableAnnotation(state, tree); if (fix.isEmpty()) { return; } state.reportMatch(describeMatch(tree, fix)); } private boolean typeMatches(Type type, Symbol sym, VisitorState state) { return isVoid(type, state) && NullnessAnnotations.fromAnnotationsOn(sym).orElse(null) != Nullness.NULLABLE; } /** * Like the other overload but without looking for annotations on the Symbol (like declaration * annotations on a method or variable). */ private boolean typeMatches(Type type, VisitorState state) { return isVoid(type, state) && NullnessAnnotations.fromAnnotationsOn(type).orElse(null) != Nullness.NULLABLE; } private static ImmutableList<String> annotationsIfAnnotatedTypeTree(Tree tree) { if (tree instanceof AnnotatedTypeTree) { AnnotatedTypeTree annotated = ((AnnotatedTypeTree) tree); return annotated.getAnnotations().stream() .map(ASTHelpers::getAnnotationName) .collect(toImmutableList()); } return ImmutableList.of(); } }
9,240
41.782407
128
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/nullness/ReturnMissingNullable.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.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.collect.Streams.concat; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import static com.google.errorprone.VisitorState.memoize; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.fixByAddingNullableAnnotationToReturnType; 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.isVoid; 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.matchers.Matchers.anyMethod; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.expressionStatement; import static com.google.errorprone.matchers.Matchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.constValue; import static com.google.errorprone.util.ASTHelpers.findEnclosingMethod; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.isConsideredFinal; import static com.google.errorprone.util.ASTHelpers.methodCanBeOverridden; import static com.sun.source.tree.Tree.Kind.NULL_LITERAL; import static com.sun.source.tree.Tree.Kind.THROW; import static java.lang.Boolean.FALSE; import static java.util.regex.Pattern.compile; import static javax.lang.model.type.TypeKind.TYPEVAR; 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.CompilationUnitTreeMatcher; 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.BlockTree; 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.MethodTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import java.util.List; import java.util.stream.Stream; import javax.inject.Inject; import javax.lang.model.element.Name; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Method returns a definitely null value but is not annotated @Nullable", severity = SUGGESTION) public class ReturnMissingNullable extends BugChecker implements CompilationUnitTreeMatcher { private static final Matcher<StatementTree> METHODS_THAT_NEVER_RETURN = expressionStatement( anyOf( anyMethod().anyClass().withNameMatching(compile("throw.*Exception")), staticMethod() .onClassAny( "org.junit.Assert", "junit.framework.Assert", /* * I'm not sure if TestCase is necessary, as it doesn't define its own fail() * method, but it commonly appears in lists like this one, so I've included * it. (Maybe the method was defined on TestCase many versions ago?) * * TODO(cpovirk): Confirm need, or remove from everywhere. */ "junit.framework.TestCase") .named("fail"), staticMethod().onClass("java.lang.System").named("exit"))); private static final Matcher<StatementTree> FAILS_IF_PASSED_FALSE = expressionStatement( staticMethod() .onClassAny("com.google.common.base.Preconditions", "com.google.common.base.Verify") .namedAnyOf("checkArgument", "checkState", "verify")); /** * A supplier that returns a set of methods <i>that users can <b>override</b></i> and whose * implementations must in practice always return a nullable type. * * <p>We use this so that we can say things like "An implementation of {@code Map.get} should be * annotated with {@code @Nullable}," <i>not</i> to say that things like "A method with {@code * return map.get(foo)} should be annotated with {@code @Nullable}." */ // TODO(cpovirk): For performance, generate a Multimap indexed by Name? private static final Supplier<ImmutableSet<MethodSymbol>> METHODS_KNOWN_TO_RETURN_NULL = memoize( state -> concat( /* * We assume that no one is implementing a Map<MyEnum, V> that contains every * enum constant and throws an exception for non-MyEnum values. Also, we * assume that no one minds annotating methods like ImmutableMap.put() with * @Nullable even though they always throw an exception instead of returning. */ streamElements(state, "java.util.Map") .filter( m -> hasName(m, "get") || hasName(m, "put") || hasName(m, "putIfAbsent") || (hasName(m, "remove") && hasParams(m, 1)) || (hasName(m, "replace") && hasParams(m, 2))), streamElements(state, "com.google.common.collect.BiMap") .filter(m -> hasName(m, "forcePut")), streamElements(state, "com.google.common.collect.Table") .filter( m -> hasName(m, "get") || hasName(m, "put") || hasName(m, "remove")), streamElements(state, "com.google.common.cache.Cache") .filter(m -> hasName(m, "getIfPresent")), /* * We assume that no one is implementing a never-empty Queue, etc. -- or at * least that no one minds annotating its return types with @Nullable anyway. */ streamElements(state, "java.util.Queue") .filter(m -> hasName(m, "poll") || hasName(m, "peek")), streamElements(state, "java.util.Deque") .filter( m -> hasName(m, "pollFirst") || hasName(m, "peekFirst") || hasName(m, "pollLast") || hasName(m, "peekLast")), streamElements(state, "java.util.NavigableSet") .filter( m -> hasName(m, "lower") || hasName(m, "floor") || hasName(m, "ceiling") || hasName(m, "higher") || hasName(m, "pollFirst") || hasName(m, "pollLast")), streamElements(state, "java.util.NavigableMap") .filter( m -> hasName(m, "lowerEntry") || hasName(m, "floorEntry") || hasName(m, "ceilingEntry") || hasName(m, "higherEntry") || hasName(m, "lowerKey") || hasName(m, "floorKey") || hasName(m, "ceilingKey") || hasName(m, "higherKey") || hasName(m, "firstEntry") || hasName(m, "lastEntry") || hasName(m, "pollFirstEntry") || hasName(m, "pollLastEntry")), // We assume no one is implementing an infinite Spliterator. streamElements(state, "java.util.Spliterator") .filter(m -> hasName(m, "trySplit"))) /* * TODO(cpovirk): Consider AbstractIterator.computeNext(). * */ .map(MethodSymbol.class::cast) .collect(toImmutableSet())); private final boolean beingConservative; @Inject ReturnMissingNullable(ErrorProneFlags flags) { this.beingConservative = nullnessChecksShouldBeConservative(flags); } @Override public Description matchCompilationUnit( CompilationUnitTree tree, VisitorState stateForCompilationUnit) { if (beingConservative && stateForCompilationUnit.errorProneOptions().isTestOnlyTarget()) { // Annotating test code for nullness can be useful, but it's not our primary focus. return NO_MATCH; } /* * In each scanner below, we define helper methods so that we can return early without the * verbosity of `return super.visitFoo(...)`. */ ImmutableSet.Builder<VarSymbol> definitelyNullVarsBuilder = ImmutableSet.builder(); new TreePathScanner<Void, Void>() { @Override public Void visitVariable(VariableTree tree, Void unused) { doVisitVariable(tree); return super.visitVariable(tree, unused); } void doVisitVariable(VariableTree tree) { VarSymbol symbol = getSymbol(tree); if (!isConsideredFinal(symbol)) { return; } ExpressionTree initializer = tree.getInitializer(); if (initializer == null) { return; } if (initializer.getKind() != NULL_LITERAL) { return; } definitelyNullVarsBuilder.add(symbol); } }.scan(tree, null); ImmutableSet<VarSymbol> definitelyNullVars = definitelyNullVarsBuilder.build(); new TreePathScanner<Void, Void>() { @Override public Void visitBlock(BlockTree block, Void unused) { for (StatementTree statement : block.getStatements()) { if (METHODS_THAT_NEVER_RETURN.matches(statement, stateForCompilationUnit)) { break; } if (FAILS_IF_PASSED_FALSE.matches(statement, stateForCompilationUnit) && constValue( ((MethodInvocationTree) ((ExpressionStatementTree) statement).getExpression()) .getArguments() .get(0)) == FALSE) { break; } scan(statement, null); } return null; } @Override public Void visitMethod(MethodTree tree, Void unused) { doVisitMethod(tree); return super.visitMethod(tree, unused); } void doVisitMethod(MethodTree tree) { MethodSymbol possibleOverride = getSymbol(tree); /* * TODO(cpovirk): Provide an option to shortcut if !hasAnnotation(possibleOverride, * Override.class). NullAway makes this assumption for performance reasons, so we could * follow suit, at least for compile-time checking. (Maybe this will confuse someone * someday, but hopefully Error Prone users are saved by the MissingOverride check.) We * should still retain the *option* to check for overriding even in the absence of an * annotation (in order to serve the case of running this in refactoring/patch mode over a * codebase). */ if (isAlreadyAnnotatedNullable(possibleOverride)) { return; } if (tree.getBody() != null && tree.getBody().getStatements().size() == 1 && getOnlyElement(tree.getBody().getStatements()).getKind() == THROW) { return; } if (hasAnnotation( tree, "com.google.errorprone.annotations.DoNotCall", stateForCompilationUnit)) { return; } for (MethodSymbol methodKnownToReturnNull : METHODS_KNOWN_TO_RETURN_NULL.get(stateForCompilationUnit)) { if (stateForCompilationUnit .getElements() .overrides(possibleOverride, methodKnownToReturnNull, possibleOverride.enclClass())) { SuggestedFix fix = fixByAddingNullableAnnotationToReturnType( stateForCompilationUnit.withPath(getCurrentPath()), tree); if (!fix.isEmpty()) { stateForCompilationUnit.reportMatch( buildDescription(tree) .setMessage( "Nearly all implementations of this method must return null, but it is" + " not annotated @Nullable") .addFix(fix) .build()); } } } } @Override public Void visitReturn(ReturnTree tree, Void unused) { doVisitReturn(tree); return super.visitReturn(tree, unused); } void doVisitReturn(ReturnTree returnTree) { /* * We need the VisitorState to have the correct TreePath for (a) the call to * findEnclosingMethod and (b) the call to NullnessFixes (which looks up identifiers). */ VisitorState state = stateForCompilationUnit.withPath(getCurrentPath()); ExpressionTree returnExpression = returnTree.getExpression(); if (returnExpression == null) { return; } MethodTree methodTree = findEnclosingMethod(state); if (methodTree == null) { return; } MethodSymbol method = getSymbol(methodTree); List<? extends StatementTree> statements = methodTree.getBody().getStatements(); if (beingConservative && statements.size() == 1 && getOnlyElement(statements) == returnTree && returnExpression.getKind() == NULL_LITERAL && methodCanBeOverridden(method)) { /* * When the entire body of an overrideable method is `return null`, we are sometimes * looking at a "stub" implementation that all "real" implementations are meant to * override. Ideally such stubs would use implementation like `throw new * UnsupportedOperationException()`, but we see `return null` often enough in practice * that it warrants a special case when running in conservative mode. */ return; } Type returnType = method.getReturnType(); if (beingConservative && isVoid(returnType, state)) { // `@Nullable Void` is accurate but noisy, so some users won't want it. return; } if (returnType.isPrimitive()) { // Buggy code, but adding @Nullable just makes it worse. return; } if (beingConservative && returnType.getKind() == TYPEVAR) { /* * Consider AbstractFuture.getDoneValue: It returns a literal `null`, but it shouldn't be * annotated @Nullable because it returns null *only* if the AbstractFuture's type * argument permits that. */ return; } if (isAlreadyAnnotatedNullable(method)) { return; } ImmutableSet<Name> varsProvenNullByParentIf = varsProvenNullByParentIf(getCurrentPath()); /* * TODO(cpovirk): Consider reporting only one finding per method? Our patching * infrastructure is smart enough not to mind duplicate suggested fixes, but users might be * annoyed by multiple robocomments with the same fix. */ if (hasDefinitelyNullBranch( returnExpression, definitelyNullVars, varsProvenNullByParentIf, stateForCompilationUnit)) { SuggestedFix fix = fixByAddingNullableAnnotationToReturnType( state.withPath(getCurrentPath()), methodTree); if (!fix.isEmpty()) { state.reportMatch(describeMatch(returnTree, fix)); } } } @Override public Void scan(Tree tree, Void unused) { if (isSuppressed(tree, stateForCompilationUnit)) { return null; } return super.scan(tree, unused); } }.scan(tree, null); return NO_MATCH; // Any reports were made through state.reportMatch. } private static boolean hasName(Symbol symbol, String name) { return symbol.name.contentEquals(name); } private static boolean hasParams(Symbol method, int paramCount) { return ((MethodSymbol) method).getParameters().size() == paramCount; } private static Stream<Symbol> streamElements(VisitorState state, String clazz) { Symbol symbol = state.getSymbolFromString(clazz); return symbol == null ? Stream.empty() : symbol.getEnclosedElements().stream(); } }
18,681
43.69378
113
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/nullness/UnsafeWildcard.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.nullness; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static java.lang.Math.min; import com.google.common.collect.ImmutableListMultimap; 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.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ConditionalExpressionTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.LambdaExpressionTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ParenthesizedTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.TypeCastTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ConditionalExpressionTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeCastTree; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.code.Flags; 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.Type.ArrayType; import com.sun.tools.javac.code.Type.IntersectionClassType; import com.sun.tools.javac.code.Type.MethodType; import com.sun.tools.javac.code.Type.UnionClassType; import com.sun.tools.javac.code.Type.WildcardType; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCLambda; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCNewClass; import com.sun.tools.javac.tree.JCTree.JCParens; import com.sun.tools.javac.tree.JCTree.JCTypeCast; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import java.util.HashSet; import java.util.Map; import javax.lang.model.element.ElementKind; import javax.lang.model.type.TypeKind; /** Check to detect unsafe upcasts of {@code null} values to wildcard types. */ @BugPattern(summary = "Certain wildcard types can confuse the compiler.", severity = ERROR) public class UnsafeWildcard extends BugChecker implements AssignmentTreeMatcher, ClassTreeMatcher, ConditionalExpressionTreeMatcher, LambdaExpressionTreeMatcher, MethodInvocationTreeMatcher, NewClassTreeMatcher, ParenthesizedTreeMatcher, ReturnTreeMatcher, TypeCastTreeMatcher, VariableTreeMatcher { @Override public Description matchAssignment(AssignmentTree tree, VisitorState state) { return checkForUnsafeNullAssignment( ((JCExpression) tree.getVariable()).type, tree.getExpression(), state); } @Override public Description matchClass(ClassTree tree, VisitorState state) { JCClassDecl classDecl = (JCClassDecl) tree; // Check "extends" and "implements" for unsafe wildcards for (JCExpression implemented : classDecl.getImplementsClause()) { state.reportMatch( checkForUnsafeWildcards(implemented, "Unsafe wildcard type: ", implemented.type, state)); } if (classDecl.getExtendsClause() != null) { return checkForUnsafeWildcards( classDecl.getExtendsClause(), "Unsafe wildcard type: ", classDecl.getExtendsClause().type, state); } return Description.NO_MATCH; } @Override public Description matchConditionalExpression( ConditionalExpressionTree tree, VisitorState state) { // Ternary branches are implicitly upcast, so check in case they're null Type ternaryType = ((JCExpression) tree).type; state.reportMatch(checkForUnsafeNullAssignment(ternaryType, tree.getTrueExpression(), state)); return checkForUnsafeNullAssignment(ternaryType, tree.getFalseExpression(), state); } @Override public Description matchLambdaExpression(LambdaExpressionTree tree, VisitorState state) { if (tree.getBody() instanceof ExpressionTree) { Type targetType = ((JCLambda) tree).getDescriptorType(state.getTypes()).getReturnType(); return checkForUnsafeNullAssignment(targetType, (ExpressionTree) tree.getBody(), state); } // else covered by matchReturn return Description.NO_MATCH; } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { // MethodType of this invocation gives us the args' target types with any type parameters // substituted (unlike the method's symbol, which doesn't give us effective target types). MethodType mtype = (MethodType) ((JCMethodInvocation) tree).meth.type; MethodSymbol callee = ASTHelpers.getSymbol(tree); if (!((JCMethodInvocation) tree).getTypeArguments().isEmpty()) { // Check type arguments for problematic wildcards given in source. for (JCExpression typearg : ((JCMethodInvocation) tree).getTypeArguments()) { state.reportMatch( checkForUnsafeWildcards(typearg, "Unsafe wildcard type: ", typearg.type, state)); } } else if (!callee.type.getTypeArguments().isEmpty()) { // Otherwise, check any inferred type arguments ImmutableListMultimap<TypeVariableSymbol, Type> mapping = ASTHelpers.getTypeSubstitution(mtype, callee); HashSet<Type> seen = new HashSet<>(); for (Map.Entry<TypeVariableSymbol, Type> inferredTypearg : mapping.entries()) { if (!seen.add(inferredTypearg.getValue())) { continue; // avoid duplicate reports for the same type } state.reportMatch( checkForUnsafeWildcards( tree, "Unsafe wildcard in inferred type argument for callee's type parameter " + inferredTypearg.getKey() + ": ", inferredTypearg.getValue(), state)); } } int paramIndex = 0; for (ExpressionTree arg : tree.getArguments()) { // Check null arguments against parameter type // NB: this will be an array type for vararg parameters, but checkForUnsafeNullAssignment // sees through array types, so there's no need to unwrap the type here Type paramType = mtype.argtypes.get(paramIndex); state.reportMatch(checkForUnsafeNullAssignment(paramType, arg, state)); paramIndex = min(paramIndex + 1, mtype.argtypes.size() - 1); } return Description.NO_MATCH; } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { // MethodType of this invocation gives us the args' target types with any type parameters // substituted (unlike the method's symbol, which doesn't give us effective target types). MethodType mtype = (MethodType) ((JCNewClass) tree).constructorType; // mtype contains type of outer object in some cases, which we can skip since null enclosing // expression would cause exception. int paramIndex = tree.getClassBody() != null && tree.getEnclosingExpression() != null ? 1 : 0; for (ExpressionTree arg : tree.getArguments()) { // Check null arguments against parameter type // NB: this will be an array type for vararg parameters, but checkForUnsafeNullAssignment // sees through array types, so there's no need to unwrap the type here Type paramType = mtype.argtypes.get(paramIndex); state.reportMatch(checkForUnsafeNullAssignment(paramType, arg, state)); paramIndex = min(paramIndex + 1, mtype.argtypes.size() - 1); } // Check type arguments for problematic wildcards (visiting class type will recursively visit // its arguments return checkForUnsafeWildcards( tree, "Unsafe wildcard type argument: ", ((JCNewClass) tree).type, state); } @Override public Description matchParenthesized(ParenthesizedTree tree, VisitorState state) { // Treat (null) like null return checkForUnsafeNullAssignment(((JCParens) tree).type, tree.getExpression(), state); } @Override public Description matchReturn(ReturnTree tree, VisitorState state) { // Check "return null" against return type if (tree.getExpression() == null || ((JCExpression) tree.getExpression()).type.getKind() != TypeKind.NULL) { return Description.NO_MATCH; } // Figure out return type of surrounding method or lambda and check it Tree method = state.findEnclosing(MethodTree.class, LambdaExpressionTree.class); if (method instanceof MethodTree) { return checkForUnsafeNullAssignment( ((JCMethodDecl) method).getReturnType().type, tree.getExpression(), state); } else if (method instanceof LambdaExpressionTree) { Type targetType = ((JCLambda) method).getDescriptorType(state.getTypes()).getReturnType(); return checkForUnsafeNullAssignment(targetType, tree.getExpression(), state); } return Description.NO_MATCH; } @Override public Description matchTypeCast(TypeCastTree tree, VisitorState state) { // Check explicit casts of null return checkForUnsafeNullAssignment( ((JCTypeCast) tree).getType().type, tree.getExpression(), state); } @Override public Description matchVariable(VariableTree tree, VisitorState state) { // Check initializer like assignment if (tree.getInitializer() != null) { return checkForUnsafeNullAssignment( ((JCVariableDecl) tree).type, tree.getInitializer(), state); } VarSymbol symbol = ASTHelpers.getSymbol(tree); if (symbol.getKind() == ElementKind.FIELD && (symbol.flags() & Flags.FINAL) == 0) { // Fields start out as null, so check their type as if this was a null assignment. While all // fields start out null, we ignore them here if they're final or we checked their // initializer above. In either case we know we'll see at least one assignment to the field, // and if those check out they guarantees us that the field's type is ok: non-null // assignments guarantee that there is a concrete type compatible with any // wildcards in this field's type, and null assignments will be checked separately (possibly // right above). return checkForUnsafeWildcards( tree, "Uninitialized field with unsafe wildcard type: ", ((JCVariableDecl) tree).type, state); } return Description.NO_MATCH; } /** * Checks for unsafe wildcards in {@code targetType} if the given expression is `null`. * * @return diagnostic for {@code tree} if unsafe wildcard is found, {@link Description#NO_MATCH} * otherwise. * @see #checkForUnsafeWildcards */ private Description checkForUnsafeNullAssignment( Type targetType, ExpressionTree tree, VisitorState state) { if (!targetType.isReference() || ((JCExpression) tree).type.getKind() != TypeKind.NULL) { return Description.NO_MATCH; } return checkForUnsafeWildcards(tree, "Cast to wildcard type unsafe: ", targetType, state); } /** * Recursively looks through {@code targetType} for any wildcard whose lower bounds isn't known to * be a subtype of the corresponding type parameter's upper bound. * * @return diagnostic for {@code tree} with given {@code messageHeader} if unsafe wildcard found, * {@link Description#NO_MATCH} otherwise. */ private Description checkForUnsafeWildcards( Tree tree, String messageHeader, Type targetType, VisitorState state) { while (targetType instanceof ArrayType) { // Check array component type targetType = ((ArrayType) targetType).getComponentType(); } int i = 0; for (Type arg : targetType.getTypeArguments()) { // Check components of generic types (getTypeArguments() is empty for other kinds of types) if (arg instanceof WildcardType && ((WildcardType) arg).getSuperBound() != null) { Type lowerBound = ((WildcardType) arg).getSuperBound(); // We only check lower bounds that are themselves type variables with trivial upper bounds. // Javac already checks other lower bounds, namely lower bounds that are concrete types or // type variables with non-trivial upper bounds, to be in bounds of the corresponding type // parameter (boundVar below). // We skip these cases because the subtype check below can spuriously fail for them because // it doesn't correctly substitute type variables when comparing lowerBound and boundVar's // upper bound. // Note javax.lang.model.type.TypeVariable#getUpperBound() guarantees the result to be non- // null for type variables, so we use null check as a proxy for whether lowerBound is a type // variable. // TODO(kmb): avoid counting on compiler's handling of non-trivial upper bounds here Type boundVar = targetType.tsym.type.getTypeArguments().get(i); if (lowerBound.getUpperBound() != null && lowerBound.getUpperBound().toString().endsWith("java.lang.Object")) { if (!state.getTypes().isSubtypeNoCapture(lowerBound, boundVar.getUpperBound())) { return buildDescription(tree) .setMessage( messageHeader + targetType + " because of type argument " + i + " with implicit upper bound " + boundVar.getUpperBound()) .build(); } } else { // Compiler sometimes infers ? super Object even though boundVar has an upper bound, so // check for wildcards that are impossible, ie., lower bound is strict supertype of upper. // TODO(kmb): consider implementing this as a more general check for inferred type // arguments whose wildcards wouldn't typecheck if they were written explicitly. if (state.getTypes().isSubtypeNoCapture(boundVar.getUpperBound(), lowerBound) && !state.getTypes().isSameType(boundVar.getUpperBound(), lowerBound)) { return buildDescription(tree) .setMessage( messageHeader + targetType + " because of impossible type argument " + i + " with implicit upper bound " + boundVar.getUpperBound()) .build(); } } // Also check the super bound itself Description contained = checkForUnsafeWildcards(tree, messageHeader + i + " nested: ", lowerBound, state); if (contained != Description.NO_MATCH) { return contained; } } else if (arg instanceof WildcardType && ((WildcardType) arg).getExtendsBound() != null) { // Check the wildcard's bound Description contained = checkForUnsafeWildcards( tree, messageHeader + i + " nested: ", ((WildcardType) arg).getExtendsBound(), state); if (contained != Description.NO_MATCH) { return contained; } } else { // Check for wildcards in the type argument Description contained = checkForUnsafeWildcards(tree, messageHeader + i + " nested: ", arg, state); if (contained != Description.NO_MATCH) { return contained; } } ++i; } // For union and intersection types, check their components. if (targetType instanceof IntersectionClassType) { for (Type bound : ((IntersectionClassType) targetType).getExplicitComponents()) { Description contained = checkForUnsafeWildcards(tree, messageHeader + "bound ", bound, state); if (contained != Description.NO_MATCH) { return contained; } } } if (targetType instanceof UnionClassType) { for (Type alternative : ((UnionClassType) targetType).getAlternativeTypes()) { Description contained = checkForUnsafeWildcards(tree, messageHeader + "alternative ", alternative, state); if (contained != Description.NO_MATCH) { return contained; } } } return Description.NO_MATCH; } }
17,719
45.387435
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/nullness/EqualsMissingNullable.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.nullness; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.fixByAddingNullableAnnotationToType; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.isAlreadyAnnotatedNullable; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.isInNullMarkedScope; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.nullnessChecksShouldBeConservative; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.equalsMethodDeclaration; import static com.google.errorprone.util.ASTHelpers.getSymbol; 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.MethodTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.code.Symbol.VarSymbol; import javax.inject.Inject; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Method overrides Object.equals but does not have @Nullable on its parameter", severity = SUGGESTION) public class EqualsMissingNullable extends BugChecker implements MethodTreeMatcher { private final boolean beingConservative; @Inject EqualsMissingNullable(ErrorProneFlags flags) { this.beingConservative = nullnessChecksShouldBeConservative(flags); } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { if (beingConservative && state.errorProneOptions().isTestOnlyTarget()) { return NO_MATCH; } if (!equalsMethodDeclaration().matches(methodTree, state)) { return NO_MATCH; } VariableTree parameterTree = getOnlyElement(methodTree.getParameters()); VarSymbol parameter = getSymbol(parameterTree); if (isAlreadyAnnotatedNullable(parameter)) { return NO_MATCH; } if (beingConservative && !isInNullMarkedScope(parameter, state)) { return NO_MATCH; } SuggestedFix fix = fixByAddingNullableAnnotationToType(state, parameterTree); if (fix.isEmpty()) { return NO_MATCH; } return describeMatch(parameterTree, fix); } }
3,208
39.1125
107
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/nullness/NullArgumentForNonNullParameter.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.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Streams.forEachPair; 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.hasExtraParameterForEnclosingInstance; import static com.google.errorprone.bugpatterns.nullness.NullnessUtils.nullnessChecksShouldBeConservative; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.suppliers.Suppliers.typeFromString; import static com.google.errorprone.util.ASTHelpers.enclosingClass; import static com.google.errorprone.util.ASTHelpers.enclosingPackage; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static java.util.Arrays.stream; import static javax.lang.model.type.TypeKind.TYPEVAR; 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.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import com.google.errorprone.dataflow.nullnesspropagation.NullnessAnnotations; import com.google.errorprone.matchers.Description; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.util.Name; import java.util.List; import javax.inject.Inject; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "Null is not permitted for this parameter.", severity = ERROR) public final class NullArgumentForNonNullParameter extends BugChecker implements MethodInvocationTreeMatcher, NewClassTreeMatcher { private static final Supplier<Type> JAVA_OPTIONAL_TYPE = typeFromString("java.util.Optional"); private static final Supplier<Type> GUAVA_OPTIONAL_TYPE = typeFromString("com.google.common.base.Optional"); private static final Supplier<Type> ARGUMENT_CAPTOR_CLASS = typeFromString("org.mockito.ArgumentCaptor"); private static final Supplier<Name> OF_NAME = memoize(state -> state.getName("of")); private static final Supplier<Name> FOR_CLASS_NAME = memoize(state -> state.getName("forClass")); private static final Supplier<Name> BUILDER_NAME = memoize(state -> state.getName("Builder")); private static final Supplier<Name> GUAVA_COLLECT_IMMUTABLE_PREFIX = memoize(state -> state.getName("com.google.common.collect.Immutable")); private static final Supplier<Name> GUAVA_GRAPH_IMMUTABLE_PREFIX = memoize(state -> state.getName("com.google.common.graph.Immutable")); private static final Supplier<ImmutableSet<Name>> NULL_MARKED_PACKAGES_WE_TRUST = memoize( state -> stream( new String[] { "com.google.common", }) .map(state::getName) .collect(toImmutableSet())); private final boolean beingConservative; @Inject NullArgumentForNonNullParameter(ErrorProneFlags flags) { this.beingConservative = nullnessChecksShouldBeConservative(flags); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return match(getSymbol(tree), tree.getArguments(), state); } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { return match(getSymbol(tree), tree.getArguments(), state); } private Description match( MethodSymbol methodSymbol, List<? extends ExpressionTree> args, VisitorState state) { if (hasExtraParameterForEnclosingInstance(methodSymbol)) { // TODO(b/232103314): Figure out the right way to handle the implicit outer `this` parameter. return NO_MATCH; } if (methodSymbol.isVarArgs()) { /* * TODO(b/232103314): Figure out the right way to handle this, or at least handle all * parameters but the last. */ return NO_MATCH; } forEachPair( args.stream(), methodSymbol.getParameters().stream(), (argTree, paramSymbol) -> { if (!hasDefinitelyNullBranch( argTree, /* * TODO(cpovirk): Precompute sets of definitelyNullVars and varsProvenNullByParentIf * instead of passing empty sets. */ ImmutableSet.of(), ImmutableSet.of(), state)) { return; } if (!argumentMustBeNonNull(paramSymbol, state)) { return; } state.reportMatch(describeMatch(argTree)); }); return NO_MATCH; // Any matches were reported through state.reportMatch. } private boolean argumentMustBeNonNull(VarSymbol sym, VisitorState state) { // We hardcode checking of one test method, ArgumentCaptor.forClass, which throws as of // https://github.com/mockito/mockito/commit/fe1cb2de0923e78bf7d7ae46cbab792dd4e94136#diff-8d274a9bda2d871524d15bbfcd6272bd893a47e6b1a0b460d82a8845615f26daR31 // For discussion of hardcoding in general, see below. if (sym.owner.name.equals(FOR_CLASS_NAME.get(state)) && isParameterOfMethodOnType(sym, ARGUMENT_CAPTOR_CLASS, state)) { return true; } if (state.errorProneOptions().isTestOnlyTarget()) { return false; // The tests of `foo` often invoke `foo(null)` to verify that it NPEs. /* * TODO(cpovirk): But consider still matching *some* cases. For example, we might check * primitives, since it would be strange to test that `foo(int i)` throws NPE if you call * `foo((Integer) null)`. And tests that *use* a class like `Optional` (as opposed to * *testing* Optional) could benefit from checking that they use `Optional.of` correctly. */ } if (sym.asType().isPrimitive()) { return true; } /* * Though we get most of our nullness information from annotations, there are technical * obstacles to relying purely on them, including around type variables (see comments below)—not * to mention that there are no annotations on JDK classes. * * As a workaround, we can hardcode specific APIs that feel worth the effort. Most of the * hardcoding is below, but one bit is at the top of this method. */ // Hardcoding #1: Optional.of if (sym.owner.name.equals(OF_NAME.get(state)) && (isParameterOfMethodOnType(sym, JAVA_OPTIONAL_TYPE, state) || isParameterOfMethodOnType(sym, GUAVA_OPTIONAL_TYPE, state))) { return true; } // Hardcoding #2: Immutable*.of if (sym.owner.name.equals(OF_NAME.get(state)) && (isParameterOfMethodOnTypeStartingWith(sym, GUAVA_COLLECT_IMMUTABLE_PREFIX, state) || isParameterOfMethodOnTypeStartingWith(sym, GUAVA_GRAPH_IMMUTABLE_PREFIX, state))) { return true; } // Hardcoding #3: Immutable*.Builder.* if (enclosingClass(sym).name.equals(BUILDER_NAME.get(state)) && (isParameterOfMethodOnTypeStartingWith(sym, GUAVA_COLLECT_IMMUTABLE_PREFIX, state) || isParameterOfMethodOnTypeStartingWith(sym, GUAVA_GRAPH_IMMUTABLE_PREFIX, state))) { return true; } /* * TODO(b/203207989): In theory, we should program this check to exclude inner classes until we * fix the bug in MoreAnnotations.getDeclarationAndTypeAttributes, which is used by * fromAnnotationsOn. In practice, annotations on both inner classes and outer classes are rare * (especially when NullableOnContainingClass is enabled!), so this code currently still looks * at parameters that are inner types, even though we might misinterpret them. */ Nullness nullness = NullnessAnnotations.fromAnnotationsOn(sym).orElse(null); if (nullness == Nullness.NONNULL && !beingConservative) { /* * Much code in the wild has @NonNull annotations on parameters that are apparently * legitimately passed null arguments. Thus, we don't trust such annotations when running in * conservative mode. * * TODO(cpovirk): Instead of ignoring @NonNull annotations entirely, add special cases for * specific badly annotated APIs. Or better yet, get the annotations fixed. */ return true; } if (nullness == Nullness.NULLABLE) { return false; } if (sym.asType().getKind() == TYPEVAR) { /* * TODO(cpovirk): We could sometimes return true if we looked for @NullMarked and for any * annotations on the type-parameter bounds. But looking at type-parameter bounds is hard * because of JDK-8225377. */ return false; } if (enclosingAnnotationDefaultsNonTypeVariablesToNonNull(sym, state)) { return true; } return false; } private static boolean isParameterOfMethodOnType( VarSymbol sym, Supplier<Type> typeSupplier, VisitorState state) { Type target = typeSupplier.get(state); return target != null && state.getTypes().isSameType(enclosingClass(sym).type, target); } private static boolean isParameterOfMethodOnTypeStartingWith( VarSymbol sym, Supplier<Name> nameSupplier, VisitorState state) { return enclosingClass(sym).fullname.startsWith(nameSupplier.get(state)); } private boolean enclosingAnnotationDefaultsNonTypeVariablesToNonNull( Symbol sym, VisitorState state) { for (; sym != null; sym = sym.getEnclosingElement()) { if (hasAnnotation(sym, "com.google.protobuf.Internal$ProtoNonnullApi", state)) { return true; } if (hasAnnotation(sym, "org.jspecify.nullness.NullMarked", state) && weTrustNullMarkedOn(sym, state)) { return true; } } return false; } private boolean weTrustNullMarkedOn(Symbol sym, VisitorState state) { /* * Similar to @NonNull (discussed above), the "default to non-null" annotation @NullMarked is * sometimes used on code that hasn't had @Nullable annotations added to it where necessary. To * avoid false positives, our conservative mode trusts @NullMarked only when it appears in a * package from a list that we maintain in this checker. * * TODO(cpovirk): Expand the list of packages that our conservative mode trusts @NullMarked on. * We might be able to identify some packages that would be safe to trust today. For others, we * could use ParameterMissingNullable, which adds missing annotations in situations similar to * the ones identified by this check. (But note that ParameterMissingNullable doesn't help with * calls that cross file boundaries.) */ if (!beingConservative) { return true; } ImmutableSet<Name> packagesWeTrust = NULL_MARKED_PACKAGES_WE_TRUST.get(state); for (sym = enclosingPackage(sym); sym != null; sym = sym.owner) { if (packagesWeTrust.contains(sym.getQualifiedName())) { return true; } } return false; } }
12,348
42.178322
162
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/formatstring/StrictFormatStringValidation.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.formatstring; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.isConsideredFinal; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.FormatMethod; import com.google.errorprone.annotations.FormatString; import com.google.errorprone.bugpatterns.formatstring.FormatStringValidation.ValidationResult; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; import java.util.List; import javax.annotation.Nullable; import javax.lang.model.element.ElementKind; /** * Format string validation utility that fails on more cases than {@link FormatStringValidation} to * enforce strict format string checking. */ public class StrictFormatStringValidation { private static final Matcher<ExpressionTree> MOCKITO_MATCHERS = staticMethod().onClassAny("org.mockito.Matchers", "org.mockito.ArgumentMatchers"); @Nullable public static ValidationResult validate( ExpressionTree formatStringTree, List<? extends ExpressionTree> args, VisitorState state) { if (MOCKITO_MATCHERS.matches(formatStringTree, state)) { // Mockito matchers do not pass standard @FormatString requirements, but we allow them so // that people can verify @FormatMethod methods. return null; } boolean hasConstantValue = FormatStringValidation.constValues(formatStringTree).findAny().isPresent(); // If formatString has a constant value, then it couldn't have been an @FormatString parameter, // so don't bother with annotations and just check if the parameters match the format string. if (hasConstantValue) { return FormatStringValidation.validate( /* formatMethodSymbol= */ null, ImmutableList.<ExpressionTree>builder().add(formatStringTree).addAll(args).build(), state); } // The format string is not a compile time constant. Check if it is an @FormatString method // parameter or is in an @FormatMethod method. Symbol formatStringSymbol = ASTHelpers.getSymbol(formatStringTree); if (!(formatStringSymbol instanceof VarSymbol)) { return ValidationResult.create( String.format( "Format strings must be either literals or variables. Other expressions" + " are not valid.\n" + "Invalid format string: %s", formatStringTree)); } if (!isConsideredFinal(formatStringSymbol)) { return ValidationResult.create( "All variables passed as @FormatString must be final or effectively final"); } if (formatStringSymbol.getKind() == ElementKind.PARAMETER) { return validateFormatStringParameter(formatStringTree, formatStringSymbol, args, state); } else { // The format string is final but not a method parameter or compile time constant. Ensure that // it is only assigned to compile time constant values and ensure that any possible assignment // works with the format arguments. return validateFormatStringVariable(formatStringTree, formatStringSymbol, args, state); } } /** Helps {@code validate()} validate a format string that is declared as a method parameter. */ @Nullable private static ValidationResult validateFormatStringParameter( ExpressionTree formatStringTree, Symbol formatStringSymbol, List<? extends ExpressionTree> args, VisitorState state) { if (!isFormatStringParameter(formatStringSymbol, state)) { return ValidationResult.create( String.format( "Format strings must be compile time constants or parameters annotated " + "@FormatString: %s", formatStringTree)); } List<VarSymbol> ownerParams = ((MethodSymbol) formatStringSymbol.owner).getParameters(); int ownerFormatStringIndex = ownerParams.indexOf(formatStringSymbol); ImmutableList.Builder<Type> ownerFormatArgTypesBuilder = ImmutableList.builder(); for (VarSymbol paramSymbol : ownerParams.subList(ownerFormatStringIndex + 1, ownerParams.size())) { ownerFormatArgTypesBuilder.add(paramSymbol.type); } ImmutableList<Type> ownerFormatArgTypes = ownerFormatArgTypesBuilder.build(); Types types = state.getTypes(); ImmutableList.Builder<Type> calleeFormatArgTypesBuilder = ImmutableList.builder(); for (ExpressionTree formatArgExpression : args) { calleeFormatArgTypesBuilder.add(types.erasure(ASTHelpers.getType(formatArgExpression))); } ImmutableList<Type> calleeFormatArgTypes = calleeFormatArgTypesBuilder.build(); if (ownerFormatArgTypes.size() != calleeFormatArgTypes.size()) { return ValidationResult.create( String.format( "The number of format arguments passed " + "with an @FormatString must match the number of format arguments in the " + "@FormatMethod header where the format string was declared.\n\t" + "Format args passed: %d\n\tFormat args expected: %d", calleeFormatArgTypes.size(), ownerFormatArgTypes.size())); } else { for (int i = 0; i < calleeFormatArgTypes.size(); i++) { if (!ASTHelpers.isSameType( ownerFormatArgTypes.get(i), calleeFormatArgTypes.get(i), state)) { return ValidationResult.create( String.format( "The format argument types passed " + "with an @FormatString must match the types of the format arguments in " + "the @FormatMethod header where the format string was declared.\n\t" + "Format arg types passed: %s\n\tFormat arg types expected: %s", calleeFormatArgTypes, ownerFormatArgTypes)); } } } // Format string usage was valid. return null; } /** * Helps {@code validate()} validate a format string that is a variable, but not a parameter. This * method assumes that the format string variable has already been asserted to be final or * effectively final. */ private static ValidationResult validateFormatStringVariable( ExpressionTree formatStringTree, Symbol formatStringSymbol, List<? extends ExpressionTree> args, VisitorState state) { if (formatStringSymbol.getKind() != ElementKind.LOCAL_VARIABLE) { return ValidationResult.create( String.format( "Variables used as format strings that are not local variables must be compile time" + " constants.\n%s is neither a local variable nor a compile time constant.", formatStringTree)); } // Find the Tree for the block in which the variable is defined. If it is not defined in this // class (though it may have been in a super class). We require compile time constant values in // that case. Symbol owner = formatStringSymbol.owner; TreePath path = TreePath.getPath(state.getPath(), formatStringTree); while (path != null && ASTHelpers.getSymbol(path.getLeaf()) != owner) { path = path.getParentPath(); } // A local variable must be declared in a parent tree to be accessed. This case should be // impossible. if (path == null) { throw new IllegalStateException( String.format( "Could not find the Tree where local variable %s is declared. " + "This should be impossible.", formatStringTree)); } // Scan down from the scope where the variable was declared ValidationResult result = path.getLeaf() .accept( new TreeScanner<ValidationResult, Void>() { @Override public ValidationResult visitVariable(VariableTree node, Void unused) { if (ASTHelpers.getSymbol(node) == formatStringSymbol) { if (node.getInitializer() == null) { return ValidationResult.create( String.format( "Variables used as format strings must be initialized when they are" + " declared.\nInvalid declaration: %s", node)); } return validateStringFromAssignment(node, node.getInitializer(), args, state); } return super.visitVariable(node, unused); } @Nullable @Override public ValidationResult reduce(ValidationResult r1, ValidationResult r2) { if (r1 == null && r2 == null) { return null; } return MoreObjects.firstNonNull(r1, r2); } }, null); return result; } private static ValidationResult validateStringFromAssignment( Tree formatStringAssignment, ExpressionTree formatStringRhs, List<? extends ExpressionTree> args, VisitorState state) { String value = ASTHelpers.constValue(formatStringRhs, String.class); if (value == null) { return ValidationResult.create( String.format( "Local format string variables must only be assigned to compile time constant values." + " Invalid format string assignment: %s", formatStringAssignment)); } else { return FormatStringValidation.validate( /* formatMethodSymbol= */ null, ImmutableList.<ExpressionTree>builder().add(formatStringRhs).addAll(args).build(), state); } } /** * Returns whether an input {@link Symbol} is a format string in a {@link FormatMethod}. This is * true if the {@link Symbol} is a {@link String} parameter in a {@link FormatMethod} and is * either: * * <ol> * <li>Annotated with {@link FormatString} * <li>The first {@link String} parameter in the method with no other parameters annotated * {@link FormatString}. * </ol> */ private static boolean isFormatStringParameter(Symbol formatString, VisitorState state) { Type stringType = state.getSymtab().stringType; // The input symbol must be a String and a parameter of a @FormatMethod to be a @FormatString. if (!ASTHelpers.isSameType(formatString.type, stringType, state) || !(formatString.owner instanceof MethodSymbol) || !ASTHelpers.hasAnnotation(formatString.owner, FormatMethod.class, state)) { return false; } // If the format string is annotated @FormatString in a @FormatMethod, it is a format string. if (ASTHelpers.hasAnnotation(formatString, FormatString.class, state)) { return true; } // Check if format string is the first string with no @FormatString params in the @FormatMethod. MethodSymbol owner = (MethodSymbol) formatString.owner; boolean formatStringFound = false; for (Symbol param : owner.getParameters()) { if (param == formatString) { formatStringFound = true; } if (ASTHelpers.isSameType(param.type, stringType, state)) { // If this is a String parameter before the input Symbol, then the input symbol can't be the // format string since it wasn't annotated @FormatString. if (!formatStringFound) { return false; } else if (ASTHelpers.hasAnnotation(param, FormatString.class, state)) { return false; } } } return true; } private StrictFormatStringValidation() {} }
12,805
41.54485
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/formatstring/FormatStringAnnotationChecker.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.formatstring; 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.annotations.FormatMethod; import com.google.errorprone.annotations.FormatString; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.VariableTree; 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; /** {@link BugChecker} to assert validity of methods calls with {@link FormatString} annotations. */ @BugPattern( name = "FormatStringAnnotation", summary = "Invalid format string passed to formatting method.", severity = ERROR) public final class FormatStringAnnotationChecker extends BugChecker implements MethodInvocationTreeMatcher, MethodTreeMatcher, NewClassTreeMatcher { /** * Matches a method or constructor invocation. The input symbol should match the invoked method or * constructor and the args should be the parameters in the invocation. */ private Description matchInvocation( ExpressionTree tree, MethodSymbol symbol, List<? extends ExpressionTree> args, VisitorState state) { if (!ASTHelpers.hasAnnotation(symbol, FormatMethod.class, state)) { return Description.NO_MATCH; } int formatString = formatStringIndex(symbol, state); if (formatString == -1) { // will be an error at call site return NO_MATCH; } FormatStringValidation.ValidationResult result = StrictFormatStringValidation.validate( args.get(formatString), args.subList(formatString + 1, args.size()), state); if (result != null) { return buildDescription(tree).setMessage(result.message()).build(); } else { return Description.NO_MATCH; } } private static int formatStringIndex(MethodSymbol symbol, VisitorState state) { Type stringType = state.getSymtab().stringType; List<VarSymbol> params = symbol.getParameters(); int firstStringIndex = -1; for (int i = 0; i < params.size(); i++) { VarSymbol param = params.get(i); if (ASTHelpers.hasAnnotation(param, FormatString.class, state)) { return i; } if (firstStringIndex < 0 && ASTHelpers.isSameType(param.type, stringType, state)) { firstStringIndex = i; } } return firstStringIndex; } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return matchInvocation(tree, ASTHelpers.getSymbol(tree), tree.getArguments(), state); } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { return matchInvocation(tree, ASTHelpers.getSymbol(tree), tree.getArguments(), state); } @Override public Description matchMethod(MethodTree tree, VisitorState state) { Type stringType = state.getSymtab().stringType; boolean isFormatMethod = ASTHelpers.hasAnnotation(ASTHelpers.getSymbol(tree), FormatMethod.class, state); boolean foundFormatString = false; boolean foundString = false; for (VariableTree param : tree.getParameters()) { VarSymbol paramSymbol = ASTHelpers.getSymbol(param); boolean isStringParam = ASTHelpers.isSameType(paramSymbol.type, stringType, state); if (isStringParam) { foundString = true; } if (ASTHelpers.hasAnnotation(paramSymbol, FormatString.class, state)) { if (!isFormatMethod) { return buildDescription(tree) .setMessage( "A parameter can only be annotated @FormatString in a method annotated " + "@FormatMethod: " + state.getSourceForNode(param)) .build(); } if (!isStringParam) { return buildDescription(param) .setMessage("Only strings can be annotated @FormatString.") .build(); } if (foundFormatString) { return buildDescription(tree) .setMessage("A method cannot have more than one @FormatString parameter.") .build(); } foundFormatString = true; } } if (isFormatMethod && !foundString) { return buildDescription(tree) .setMessage("An @FormatMethod must contain at least one String parameter.") .build(); } return Description.NO_MATCH; } }
5,712
36.097403
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/formatstring/FormatString.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.formatstring; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Symbol.MethodSymbol; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "Invalid printf-style format string", severity = ERROR) public class FormatString extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> FORMATTED_METHOD = instanceMethod().onExactClass("java.lang.String").named("formatted"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { ImmutableList<ExpressionTree> args; MethodSymbol sym = ASTHelpers.getSymbol(tree); if (FORMATTED_METHOD.matches(tree, state)) { /* Java 15 and greater supports the formatted method on an instance of string. If found then use the string value as the pattern and all-of-the arguments and send directly to the validate method. */ ExpressionTree receiver = ASTHelpers.getReceiver(tree); if (receiver == null) { // an unqualified call to 'formatted', possibly inside the definition // of java.lang.String return Description.NO_MATCH; } args = ImmutableList.<ExpressionTree>builder().add(receiver).addAll(tree.getArguments()).build(); } else { args = FormatStringUtils.formatMethodArguments(tree, state); } if (args.isEmpty()) { return Description.NO_MATCH; } FormatStringValidation.ValidationResult result = FormatStringValidation.validate(sym, args, state); if (result == null) { return Description.NO_MATCH; } return buildDescription(tree).setMessage(result.message()).build(); } }
3,024
39.333333
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/formatstring/FormatStringUtils.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.formatstring; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import com.google.common.collect.ImmutableList; import com.google.errorprone.VisitorState; 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.Locale; /** Format string utilities. */ public final class FormatStringUtils { // TODO(cushon): add support for additional printf methods, maybe with an annotation private static final Matcher<ExpressionTree> FORMAT_METHOD = anyOf( instanceMethod() .onDescendantOfAny( "java.io.PrintStream", "java.io.PrintWriter", "java.util.Formatter", "java.io.Console") .namedAnyOf("format", "printf"), staticMethod().onClass("java.lang.String").named("format"), // Exclude zero-arg java.io.Console.readPassword from format methods. instanceMethod() .onExactClass("java.io.Console") .withSignature("readPassword(java.lang.String,java.lang.Object...)"), // Exclude zero-arg method java.io.Console.readLine from format methods. instanceMethod() .onExactClass("java.io.Console") .withSignature("readLine(java.lang.String,java.lang.Object...)")); public static ImmutableList<ExpressionTree> formatMethodArguments( MethodInvocationTree tree, VisitorState state) { if (!FORMAT_METHOD.matches(tree, state)) { return ImmutableList.of(); } ImmutableList<ExpressionTree> args = ImmutableList.copyOf(tree.getArguments()); // skip the first argument of printf(Locale,String,Object...) if (ASTHelpers.isSameType( ASTHelpers.getType(args.get(0)), state.getTypeFromString(Locale.class.getName()), state)) { args = args.subList(1, args.size()); } return args; } private FormatStringUtils() {} }
2,841
39.6
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/formatstring/FormatStringValidation.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.formatstring; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.util.ASTHelpers.isSameType; import static java.util.Arrays.asList; import com.google.auto.value.AutoValue; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.errorprone.VisitorState; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ConditionalExpressionTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.Tree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; import java.math.BigDecimal; import java.math.BigInteger; import java.time.Instant; import java.time.ZoneId; import java.time.temporal.TemporalAccessor; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Deque; import java.util.DuplicateFormatFlagsException; import java.util.FormatFlagsConversionMismatchException; import java.util.GregorianCalendar; import java.util.IllegalFormatCodePointException; import java.util.IllegalFormatConversionException; import java.util.IllegalFormatException; import java.util.IllegalFormatFlagsException; import java.util.IllegalFormatPrecisionException; import java.util.IllegalFormatWidthException; import java.util.List; import java.util.MissingFormatArgumentException; import java.util.MissingFormatWidthException; import java.util.UnknownFormatConversionException; import java.util.UnknownFormatFlagsException; import java.util.stream.IntStream; import java.util.stream.Stream; import javax.annotation.Nullable; import javax.lang.model.type.TypeKind; /** Utilities for validating format strings. */ public final class FormatStringValidation { /** Description of an incorrect format method call. */ @AutoValue public abstract static class ValidationResult { /** A human-readable diagnostic message. */ public abstract String message(); public static ValidationResult create(String message) { return new AutoValue_FormatStringValidation_ValidationResult(message); } } static Stream<String> constValues(Tree tree) { List<Tree> flat = new ArrayList<>(); new SimpleTreeVisitor<Void, Void>() { @Override public Void visitConditionalExpression(ConditionalExpressionTree tree, Void unused) { visit(tree.getTrueExpression(), null); visit(tree.getFalseExpression(), null); return null; } @Override protected Void defaultAction(Tree tree, Void unused) { flat.add(tree); return null; } }.visit(tree, null); return flat.stream().map(t -> ASTHelpers.constValue(t, String.class)).filter(x -> x != null); } @Nullable public static ValidationResult validate( @Nullable MethodSymbol formatMethodSymbol, Collection<? extends ExpressionTree> arguments, VisitorState state) { Preconditions.checkArgument( !arguments.isEmpty(), "A format method should have one or more arguments, but method (%s) has zero arguments.", formatMethodSymbol); Deque<ExpressionTree> args = new ArrayDeque<>(arguments); Stream<String> formatStrings = constValues(args.removeFirst()); if (formatStrings == null) { return null; } // If the only argument is an Object[], it's an explicit varargs call. // Bail out, since we don't know what the actual argument types are. if (args.size() == 1 && (formatMethodSymbol == null || formatMethodSymbol.isVarArgs())) { Type type = ASTHelpers.getType(Iterables.getOnlyElement(args)); if (type instanceof Type.ArrayType && ASTHelpers.isSameType( ((Type.ArrayType) type).elemtype, state.getSymtab().objectType, state)) { return null; } } Object[] instances = args.stream() .map( (ExpressionTree input) -> { try { return getInstance(input, state); } catch (RuntimeException t) { // ignore symbol completion failures return null; } }) .toArray(); return formatStrings .map(formatString -> validate(formatString, instances)) .filter(x -> x != null) .findFirst() .orElse(null); } /** * Return an instance of the given type if it receives special handling by {@code String.format}. * For example, an intance of {@link Integer} will be returned for an input of type {@code int} or * {@link Integer}. */ @Nullable private static Object getInstance(Tree tree, VisitorState state) { Object value = ASTHelpers.constValue(tree); if (value != null) { return value; } Type type = ASTHelpers.getType(tree); return getInstance(type, state); } @Nullable private static Object getInstance(Type type, VisitorState state) { Types types = state.getTypes(); if (type.getKind() == TypeKind.NULL) { return null; } // normalize boxed primitives Type unboxedType = types.unboxedTypeOrType(types.erasure(type)); if (unboxedType.isPrimitive()) { type = unboxedType; switch (type.getKind()) { case BOOLEAN: return false; case BYTE: return (byte) 1; case SHORT: return (short) 2; case INT: return 3; case LONG: return 4L; case CHAR: return 'c'; case FLOAT: return 5.0f; case DOUBLE: return 6.0d; case VOID: case NONE: case NULL: case ERROR: return null; case ARRAY: return new Object[0]; default: throw new AssertionError(type.getKind()); } } if (isSubtype(types, type, state.getSymtab().stringType)) { return "string"; } if (isSubtype(types, type, state.getTypeFromString(BigDecimal.class.getName()))) { return BigDecimal.valueOf(42.0d); } if (isSubtype(types, type, state.getTypeFromString(BigInteger.class.getName()))) { return BigInteger.valueOf(43L); } if (isSameType(type, state.getTypeFromString(Number.class.getName()), state)) { // String.format only supports well-known subtypes of Number, but custom subtypes of Number // are rarer than using it as a union of Byte/Short/Integer/Long/BigInteger, so we allow // Number to avoid false positives. return 0; } if (isSubtype(types, type, state.getTypeFromString(Date.class.getName()))) { return new Date(); } if (isSubtype(types, type, state.getTypeFromString(Calendar.class.getName()))) { return new GregorianCalendar(); } if (isSubtype(types, type, state.getTypeFromString(Instant.class.getName()))) { return Instant.now(); } if (isSubtype(types, type, state.getTypeFromString(TemporalAccessor.class.getName()))) { return Instant.now().atZone(ZoneId.systemDefault()); } Type lazyArg = COM_GOOGLE_COMMON_FLOGGER_LAZYARG.get(state); if (lazyArg != null) { Type asLazyArg = types.asSuper(type, lazyArg.tsym); if (asLazyArg != null && !asLazyArg.getTypeArguments().isEmpty()) { return getInstance(getOnlyElement(asLazyArg.getTypeArguments()), state); } } return new Object(); } private static boolean isSubtype(Types types, Type t, Type s) { return s != null && types.isSubtype(t, s); } private static ValidationResult validate(String formatString, Object[] arguments) { try { String unused = String.format(formatString, arguments); } catch (DuplicateFormatFlagsException e) { return ValidationResult.create(String.format("duplicate format flags: %s", e.getFlags())); } catch (FormatFlagsConversionMismatchException e) { return ValidationResult.create( String.format( "format specifier '%%%s' is not compatible with the given flag(s): %s", e.getConversion(), e.getFlags())); } catch (IllegalFormatCodePointException e) { return ValidationResult.create( String.format("invalid Unicode code point: %x", e.getCodePoint())); } catch (IllegalFormatConversionException e) { return ValidationResult.create( String.format( "illegal format conversion: '%s' cannot be formatted using '%%%s'", e.getArgumentClass().getName(), e.getConversion())); } catch (IllegalFormatFlagsException e) { return ValidationResult.create(String.format("illegal format flags: %s", e.getFlags())); } catch (IllegalFormatPrecisionException e) { return ValidationResult.create( String.format("illegal format precision: %d", e.getPrecision())); } catch (IllegalFormatWidthException e) { return ValidationResult.create(String.format("illegal format width: %s", e.getWidth())); } catch (MissingFormatArgumentException e) { return ValidationResult.create( String.format("missing argument for format specifier '%s'", e.getFormatSpecifier())); } catch (MissingFormatWidthException e) { return ValidationResult.create( String.format("missing format width: %s", e.getFormatSpecifier())); } catch (UnknownFormatConversionException e) { return ValidationResult.create(unknownFormatConversion(e.getConversion())); } catch (UnknownFormatFlagsException e) { // TODO(cushon): I don't think the implementation ever throws this. return ValidationResult.create(String.format("unknown format flag(s): %s", e.getFlags())); } catch (IllegalFormatException e) { // Fall back for other invalid format strings, e.g. IllegalFormatArgumentIndexException that // was added in JDK 16 return ValidationResult.create(e.getMessage()); } return extraFormatArguments(formatString, asList(arguments)); } @Nullable private static ValidationResult extraFormatArguments( String formatString, List<Object> arguments) { int used = IntStream.rangeClosed(0, arguments.size()) .filter(i -> doesItFormat(formatString, arguments.subList(0, i))) .findFirst() .orElse(0); if (used == arguments.size()) { return null; } return ValidationResult.create( String.format("extra format arguments: used %d, provided %d", used, arguments.size())); } private static boolean doesItFormat(String formatString, List<Object> arguments) { try { String unused = String.format(formatString, arguments.toArray()); return true; } catch (IllegalFormatException e) { return false; } } private static String unknownFormatConversion(String conversion) { if (conversion.equals("l")) { return "%l is not a valid format specifier; use %d to format integral types as a decimal " + "integer, and %f, %g or %e to format floating point types (depending on your " + "formatting needs)"; } return String.format("unknown format conversion: '%s'", conversion); } private FormatStringValidation() {} private static final Supplier<Type> COM_GOOGLE_COMMON_FLOGGER_LAZYARG = VisitorState.memoize(state -> state.getTypeFromString("com.google.common.flogger.LazyArg")); }
12,179
36.708978
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/formatstring/InlineFormatString.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.formatstring; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isSubtype; import com.google.common.collect.ImmutableList; import com.google.common.collect.MultimapBuilder; import com.google.common.collect.SetMultimap; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.FormatMethod; import com.google.errorprone.annotations.FormatString; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.lang.model.element.ElementKind; import org.checkerframework.checker.nullness.qual.Nullable; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Prefer to create format strings inline, instead of extracting them to a single-use" + " constant", severity = WARNING) public class InlineFormatString extends BugChecker implements CompilationUnitTreeMatcher { private static final Matcher<ExpressionTree> PRECONDITIONS_CHECK = allOf( anyOf( staticMethod().onClass("com.google.common.base.Preconditions"), staticMethod().onClass("com.google.common.base.Verify")), InlineFormatString::secondParameterIsString); private static boolean secondParameterIsString(ExpressionTree tree, VisitorState state) { Symbol symbol = getSymbol(tree); if (!(symbol instanceof MethodSymbol)) { return false; } MethodSymbol methodSymbol = (MethodSymbol) symbol; return methodSymbol.getParameters().size() >= 2 && isSubtype(methodSymbol.getParameters().get(1).type, state.getSymtab().stringType, state); } private static @Nullable ExpressionTree formatString( MethodInvocationTree tree, VisitorState state) { ImmutableList<ExpressionTree> args = FormatStringUtils.formatMethodArguments(tree, state); if (!args.isEmpty()) { return args.get(0); } if (PRECONDITIONS_CHECK.matches(tree, state)) { return tree.getArguments().get(1); } return formatMethodAnnotationArguments(tree, state); } private static @Nullable ExpressionTree formatMethodAnnotationArguments( MethodInvocationTree tree, VisitorState state) { MethodSymbol sym = getSymbol(tree); if (!ASTHelpers.hasAnnotation(sym, FormatMethod.class, state)) { return null; } return tree.getArguments().get(formatStringIndex(state, sym)); } private static int formatStringIndex(VisitorState state, MethodSymbol sym) { int idx = 0; List<VarSymbol> parameters = sym.getParameters(); for (VarSymbol p : parameters) { if (ASTHelpers.hasAnnotation(p, FormatString.class, state)) { return idx; } idx++; } return 0; } @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { SetMultimap<Symbol, Tree> uses = MultimapBuilder.linkedHashKeys().linkedHashSetValues().build(); Map<Symbol, VariableTree> declarations = new LinkedHashMap<>(); // find calls to String.format and similar where the format string is a private compile-time // constant field tree.accept( new TreeScanner<Void, Void>() { @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { handle(tree); return super.visitMethodInvocation(tree, null); } private void handle(MethodInvocationTree tree) { ExpressionTree arg = formatString(tree, state); if (arg == null) { return; } Symbol variable = getSymbol(arg); if (variable == null || variable.getKind() != ElementKind.FIELD || !variable.isPrivate() || ASTHelpers.constValue(arg, String.class) == null) { return; } uses.put(variable, arg); } }, null); // find all uses of the candidate fields, and reject them if they are used outside for calls to // format methods tree.accept( new TreeScanner<Void, Void>() { @Override public Void visitMemberSelect(MemberSelectTree tree, Void unused) { handle(tree); return super.visitMemberSelect(tree, null); } @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { handle(tree); return super.visitIdentifier(tree, null); } private void handle(Tree tree) { Symbol sym = getSymbol(tree); if (sym == null) { return; } if (uses.containsKey(sym) && !uses.containsValue(tree)) { uses.removeAll(sym); } } }, null); // find the field declarations new SuppressibleTreePathScanner<Void, Void>(state) { @Override public Void visitVariable(VariableTree tree, Void unused) { VarSymbol sym = getSymbol(tree); if (uses.containsKey(sym)) { declarations.put(sym, tree); } return super.visitVariable(tree, null); } }.scan(state.getPath(), null); for (Map.Entry<Symbol, Collection<Tree>> e : uses.asMap().entrySet()) { Symbol sym = e.getKey(); Collection<Tree> use = e.getValue(); VariableTree def = declarations.get(sym); if (def == null || !(def.getInitializer() instanceof LiteralTree)) { // only inline the constant if its initializer is a literal String continue; } String constValue = state.getSourceForNode(def.getInitializer()); SuggestedFix.Builder fix = SuggestedFix.builder(); if (use.size() > 1) { // if the format string is used multiple times don't inline at each use-site // TODO(cushon): consider suggesting a helper method to do the formatting continue; } fix.delete(def); for (Tree u : use) { fix.replace(u, constValue); } state.reportMatch(describeMatch(def, fix.build())); } return NO_MATCH; } }
8,045
37.497608
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/InvalidThrowsLink.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.javadoc; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.getDiagnosticPosition; 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.MethodTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.doctree.ErroneousTree; import com.sun.source.tree.MethodTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.tree.DCTree.DCDocComment; import com.sun.tools.javac.tree.DCTree.DCErroneous; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Matches misuse of link tags within throws tags. */ @BugPattern( summary = "Javadoc links to exceptions in @throws without a @link tag (@throws Exception, not" + " @throws {@link Exception}).", severity = WARNING, tags = StandardTags.STYLE, documentSuppression = false) public final class InvalidThrowsLink extends BugChecker implements MethodTreeMatcher { @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { DocTreePath path = Utils.getDocTreePath(state); if (path != null) { new ThrowsChecker(state).scan(path, null); } return Description.NO_MATCH; } private final class ThrowsChecker extends DocTreePathScanner<Void, Void> { private final VisitorState state; private ThrowsChecker(VisitorState state) { this.state = state; } @Override public Void visitErroneous(ErroneousTree node, Void unused) { Matcher matcher = THROWS_LINK.matcher(node.getBody()); Comment comment = ((DCDocComment) getCurrentPath().getDocComment()).comment; if (matcher.find()) { int beforeAt = comment.getSourcePos(((DCErroneous) node).pos + matcher.start()); int startOfCurly = comment.getSourcePos(((DCErroneous) node).pos + matcher.end()); SuggestedFix fix = SuggestedFix.replace(beforeAt, startOfCurly, "@throws " + matcher.group(1)); state.reportMatch( describeMatch( getDiagnosticPosition(beforeAt, getCurrentPath().getTreePath().getLeaf()), fix)); } return super.visitErroneous(node, null); } } private static final Pattern THROWS_LINK = Pattern.compile("^@throws \\{@link ([^}]+)}"); }
3,283
38.095238
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/EmptyBlockTag.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.javadoc; import static com.google.errorprone.BugPattern.LinkType.CUSTOM; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.diagnosticPosition; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.doctree.BlockTagTree; import com.sun.source.doctree.DeprecatedTree; import com.sun.source.doctree.DocTree; import com.sun.source.doctree.ParamTree; import com.sun.source.doctree.ReturnTree; import com.sun.source.doctree.ThrowsTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; import java.util.List; /** * Matches block tags ({@literal @}param, {@literal @}return, {@literal @}throws, * {@literal @}deprecated) with an empty description. * * @author andrewash@google.com (Andrew Ash) */ @BugPattern( summary = "A block tag (@param, @return, @throws, @deprecated) has an empty description. Block tags" + " without descriptions don't add much value for future readers of the code; consider" + " removing the tag entirely or adding a description.", severity = WARNING, linkType = CUSTOM, link = "https://google.github.io/styleguide/javaguide.html#s7.1.3-javadoc-block-tags", documentSuppression = false) public final class EmptyBlockTag extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { @Override public Description matchClass(ClassTree classTree, VisitorState state) { checkForEmptyBlockTags(state); return Description.NO_MATCH; } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { checkForEmptyBlockTags(state); return Description.NO_MATCH; } @Override public Description matchVariable(VariableTree variableTree, VisitorState state) { checkForEmptyBlockTags(state); return Description.NO_MATCH; } private void checkForEmptyBlockTags(VisitorState state) { DocTreePath path = Utils.getDocTreePath(state); if (path != null) { new EmptyBlockTagChecker(state).scan(path, null); } } private final class EmptyBlockTagChecker extends DocTreePathScanner<Void, Void> { private final VisitorState state; private EmptyBlockTagChecker(VisitorState state) { this.state = state; } @Override public Void visitParam(ParamTree paramTree, Void unused) { reportMatchIfEmpty(paramTree, paramTree.getDescription()); return super.visitParam(paramTree, null); } @Override public Void visitReturn(ReturnTree returnTree, Void unused) { reportMatchIfEmpty(returnTree, returnTree.getDescription()); return super.visitReturn(returnTree, null); } @Override public Void visitThrows(ThrowsTree throwsTree, Void unused) { reportMatchIfEmpty(throwsTree, throwsTree.getDescription()); return super.visitThrows(throwsTree, null); } @Override public Void visitDeprecated(DeprecatedTree deprecatedTree, Void unused) { reportMatchIfEmpty(deprecatedTree, deprecatedTree.getBody()); return super.visitDeprecated(deprecatedTree, null); } private void reportMatchIfEmpty( BlockTagTree blockTagTree, List<? extends DocTree> description) { if (description.isEmpty()) { state.reportMatch( describeMatch( diagnosticPosition(getCurrentPath(), state), // Don't generate a fix for deprecated; this will be annoying in conjunction with // the check which requires a @deprecated tag for @Deprecated elements. blockTagTree.getTagName().equals("deprecated") ? SuggestedFix.emptyFix() : Utils.replace(blockTagTree, "", state))); } } } }
4,973
36.398496
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/InvalidLink.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.javadoc; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.diagnosticPosition; import static com.google.errorprone.bugpatterns.javadoc.Utils.getDocComment; import static com.google.errorprone.bugpatterns.javadoc.Utils.getDocTreePath; import static com.google.errorprone.bugpatterns.javadoc.Utils.getStartPosition; import static com.google.errorprone.bugpatterns.javadoc.Utils.replace; import static com.google.errorprone.matchers.Description.NO_MATCH; 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.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.doctree.DocTree; import com.sun.source.doctree.ErroneousTree; import com.sun.source.doctree.LinkTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; import com.sun.tools.javac.api.JavacTrees; import com.sun.tools.javac.tree.DCTree.DCDocComment; import com.sun.tools.javac.tree.DCTree.DCText; import com.sun.tools.javac.util.Log; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.lang.model.element.Element; /** Finds some common errors in {@literal @}link tags. */ @BugPattern(summary = "This @link tag looks wrong.", severity = WARNING) public final class InvalidLink extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { private static final Pattern EXTRACT_TARGET = Pattern.compile("([^}]*)}"); @Override public Description matchClass(ClassTree classTree, VisitorState state) { DocTreePath path = getDocTreePath(state); if (path != null) { new InvalidLinkChecker(state, classTree, /* parameters= */ ImmutableSet.of()) .scan(path, null); } return NO_MATCH; } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { DocTreePath path = getDocTreePath(state); if (path != null) { ImmutableSet<String> parameters = methodTree.getParameters().stream() .map(v -> v.getName().toString()) .collect(toImmutableSet()); new InvalidLinkChecker(state, methodTree, parameters).scan(path, null); } return NO_MATCH; } @Override public Description matchVariable(VariableTree variableTree, VisitorState state) { DocTreePath path = getDocTreePath(state); if (path != null) { new InvalidLinkChecker(state, variableTree, /* parameters= */ ImmutableSet.of()) .scan(path, null); } return NO_MATCH; } private final class InvalidLinkChecker extends DocTreePathScanner<Void, Void> { private final VisitorState state; private final Tree tree; private final ImmutableSet<String> parameters; private InvalidLinkChecker(VisitorState state, Tree tree, ImmutableSet<String> parameters) { this.state = state; this.tree = tree; this.parameters = parameters; } @Override public Void visitErroneous(ErroneousTree erroneousTree, Void unused) { String body = erroneousTree.getBody(); if (body.startsWith("{@link ")) { DocTree parent = getCurrentPath().getParentPath().getLeaf(); if (!(parent instanceof DCDocComment)) { return null; } DCDocComment comment = (DCDocComment) parent; int nextIndex = comment.getFullBody().indexOf(erroneousTree) + 1; if (nextIndex >= comment.getFullBody().size()) { return null; } DocTree next = comment.getFullBody().get(nextIndex); Matcher match = EXTRACT_TARGET.matcher(next.toString()); if (!match.matches()) { return null; } String target = match.group(1); String reference = erroneousTree.getBody().replaceFirst("\\{@link ", ""); String fixedLink = fixLink(reference, target); DCDocComment docComment = getDocComment(state, tree); if (!(next instanceof DCText)) { return null; } DCText nextText = (DCText) next; int endPos = docComment.comment.getSourcePos(nextText.pos + nextText.text.indexOf("}") + 1); SuggestedFix fix = SuggestedFix.replace(getStartPosition(erroneousTree, state), endPos, fixedLink); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage("{@link} cannot be used for HTTP links. Use an <a> tag instead.") .addFix(fix) .build()); } return super.visitErroneous(erroneousTree, null); } @Override public Void visitLink(LinkTree linkTree, Void unused) { if (linkTree.getReference() == null) { return super.visitLink(linkTree, null); } String reference = linkTree.getReference().getSignature(); Element element = null; Log log = Log.instance(state.context); // Install a deferred diagnostic handler before calling DocTrees.getElement(DocTreePath) // TODO(cushon): revert if https://bugs.openjdk.java.net/browse/JDK-8248117 is fixed Log.DeferredDiagnosticHandler deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log); try { element = JavacTrees.instance(state.context) .getElement(new DocTreePath(getCurrentPath(), linkTree.getReference())); } catch (NullPointerException | AssertionError e) { // TODO(b/176098078): remove once JDK 12 is the minimum supported version // https://bugs.openjdk.java.net/browse/JDK-8200432 } finally { log.popDiagnosticHandler(deferredDiagnosticHandler); } // Don't warn about fully qualified types; they won't always be known at compile-time. if (element != null || reference.contains(".")) { return super.visitLink(linkTree, null); } if (parameters.contains(reference)) { String message = String.format( "`%s` is a parameter; use {@code paramName} to refer to parameters inline.", reference); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .addFix(replace(linkTree, String.format("{@code %s}", reference), state)) .build()); return super.visitLink(linkTree, null); } if (Character.isLowerCase(reference.charAt(0)) && !reference.contains("#")) { String message = String.format( "`%s` is not known here. Should it be a reference to a method?", reference); // TODO(ghm): Find a way (JavacTrees#searchMethod?) to check whether the suggestion is // valid. int pos = getStartPosition(linkTree.getReference(), state); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .addFix(SuggestedFix.replace(pos, pos, "#")) .build()); return super.visitLink(linkTree, null); } if (reference.charAt(0) == '#') { state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage( String.format( "The reference `%s` to a method doesn't resolve to anything. Is it" + " misspelt, or is the parameter list not correct? See" + " https://docs.oracle.com/javase/8/docs/technotes/tools/unix/javadoc.html#JSSOR654" + " for documentation on how to form method links.%s", reference, reference.contains("<") ? " Note, in particular, that the _erasure_ of generic types should be" + " used (for example, List rather than List<Foo>)." : "")) .build()); } // TODO(ghm): If this is a method reference, we could check whether class is available but the // method isn't. return super.visitLink(linkTree, null); } private String fixLink(String reference, String label) { if (label.isEmpty()) { label = "link"; } return String.format("<a href=\"%s\">%s</a>", reference, label); } } }
9,612
41.915179
113
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/EscapedEntity.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.javadoc; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.diagnosticPosition; import static com.google.errorprone.bugpatterns.javadoc.Utils.getDocTreePath; 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; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.matchers.Description; import com.sun.source.doctree.LiteralTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; /** * Finds unescaped entities in Javadocs. * * @author ghm@google.com (Graeme Morgan) */ @BugPattern( summary = "HTML entities in @code/@literal tags will appear literally in the rendered javadoc.", severity = WARNING, documentSuppression = false) public final class EscapedEntity extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { private static final Pattern HTML_ENTITY = Pattern.compile("&[a-z0-9]+;|&#[0-9]+;|&#x[0-9a-f]+;", Pattern.CASE_INSENSITIVE); @Override public Description matchClass(ClassTree classTree, VisitorState state) { return handle(getDocTreePath(state), state); } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { return handle(getDocTreePath(state), state); } @Override public Description matchVariable(VariableTree variableTree, VisitorState state) { return handle(getDocTreePath(state), state); } private Description handle(@Nullable DocTreePath path, VisitorState state) { if (path == null) { return NO_MATCH; } new Scanner(state).scan(path, null); return NO_MATCH; } private final class Scanner extends DocTreePathScanner<Void, Void> { private final VisitorState state; private Scanner(VisitorState state) { this.state = state; } @Override public Void visitLiteral(LiteralTree node, Void unused) { Matcher matcher = HTML_ENTITY.matcher(node.getBody().getBody()); if (matcher.find()) { state.reportMatch(buildDescription(diagnosticPosition(getCurrentPath(), state)).build()); } return super.visitLiteral(node, null); } } }
3,391
34.333333
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/InvalidParam.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.javadoc; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.MoreCollectors.onlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.diagnosticPosition; import static com.google.errorprone.bugpatterns.javadoc.Utils.getBestMatch; import static com.google.errorprone.bugpatterns.javadoc.Utils.getDocComment; import static com.google.errorprone.bugpatterns.javadoc.Utils.getDocTreePath; import static com.google.errorprone.bugpatterns.javadoc.Utils.replace; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.names.LevenshteinEditDistance.getEditDistance; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isRecord; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.matchers.Description; import com.sun.source.doctree.DocTree; import com.sun.source.doctree.DocTree.Kind; import com.sun.source.doctree.LiteralTree; import com.sun.source.doctree.ParamTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; import com.sun.tools.javac.tree.DCTree.DCDocComment; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; /** * Matches incorrect Javadoc {@literal @}param tags. * * @author ghm@google.com (Graeme Morgan) */ // TODO(ghm): Split this into the @param part and the @code part; the former is always right that // there's a mistake, but the latter is based on a heuristic. @BugPattern( summary = "This @param tag doesn't refer to a parameter of the method.", severity = WARNING, documentSuppression = false) public final class InvalidParam extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher { private static final Pattern POSSIBLE_PARAMETER = Pattern.compile("[a-z][A-Za-z0-9]*"); /** Names which are often used in {@literal @}code blocks, and shouldn't be checked. */ private static final ImmutableSet<String> EXCLUSIONS = ImmutableSet.of("true", "false"); /** * Heuristic for the relative edit distance below which we report maybe-param {@literal @code}s. */ private static final double LIKELY_PARAMETER_THRESHOLD = 0.25; @Override public Description matchClass(ClassTree classTree, VisitorState state) { DocTreePath path = getDocTreePath(state); if (path != null) { ImmutableSet<String> parameters = isRecord(getSymbol((Tree) classTree)) ? getCanonicalRecordConstructor(classTree).getParameters().stream() .map(p -> p.getName().toString()) .collect(toImmutableSet()) : ImmutableSet.of(); ImmutableSet<String> typeParameters = classTree.getTypeParameters().stream() .map(t -> t.getName().toString()) .collect(toImmutableSet()); new ParamsChecker(state, classTree, parameters, typeParameters).scan(path, null); } return NO_MATCH; } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { DocTreePath path = getDocTreePath(state); if (path != null) { ImmutableSet<String> parameters = methodTree.getParameters().stream() .map(v -> v.getName().toString()) .collect(toImmutableSet()); ImmutableSet<String> typeParameters = methodTree.getTypeParameters().stream() .map(t -> t.getName().toString()) .collect(toImmutableSet()); new ParamsChecker(state, methodTree, parameters, typeParameters).scan(path, null); } return NO_MATCH; } private static MethodTree getCanonicalRecordConstructor(ClassTree classTree) { return classTree.getMembers().stream() .filter(MethodTree.class::isInstance) .map(MethodTree.class::cast) .filter(tree -> isRecord(getSymbol((Tree) tree))) .collect(onlyElement()); } /** Checks that documented parameters match the method's parameter list. */ private final class ParamsChecker extends DocTreePathScanner<Void, Void> { private final VisitorState state; private final ImmutableSet<String> documentedParameters; private final ImmutableSet<String> documentedTypeParameters; private final ImmutableSet<String> parameters; private final ImmutableSet<String> typeParameters; private ParamsChecker( VisitorState state, Tree tree, ImmutableSet<String> parameters, ImmutableSet<String> typeParameters) { this.state = state; DCDocComment dcDocComment = getDocComment(state, tree); this.documentedParameters = extractDocumentedParams(dcDocComment, /* isTypeParameter= */ false); this.documentedTypeParameters = extractDocumentedParams(dcDocComment, /* isTypeParameter= */ true); this.parameters = parameters; this.typeParameters = typeParameters; } @Override public Void visitParam(ParamTree paramTree, Void unused) { ImmutableSet<String> paramNames = paramTree.isTypeParameter() ? typeParameters : parameters; if (!paramNames.contains(paramTree.getName().toString())) { ImmutableSet<String> documentedParamNames = paramTree.isTypeParameter() ? documentedTypeParameters : documentedParameters; Set<String> undocumentedParameters = Sets.difference(paramNames, documentedParamNames); Optional<String> bestMatch = getBestMatch( paramTree.getName().toString(), /* maxEditDistance= */ 5, undocumentedParameters); String message = String.format("Parameter name `%s` is unknown.", paramTree.getName()); state.reportMatch( bestMatch .map( bm -> buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message + String.format(" Did you mean %s?", bm)) .addFix(replace(paramTree.getName(), bm, state)) .build()) .orElse( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .addFix(replace(paramTree, "", state)) .build())); } return super.visitParam(paramTree, null); } @Override public Void visitLiteral(LiteralTree node, Void unused) { if (node.getKind() != Kind.CODE) { return super.visitLiteral(node, null); } String body = node.getBody().getBody(); if (!POSSIBLE_PARAMETER.matcher(body).matches() || EXCLUSIONS.contains(body)) { return super.visitLiteral(node, null); } String bestMatch = null; int minDistance = Integer.MAX_VALUE; for (String parameter : parameters) { int distance = getEditDistance(body, parameter); if (distance < minDistance) { bestMatch = parameter; minDistance = distance; } } if (bestMatch != null && !bestMatch.equals(body) && (double) minDistance / body.length() <= LIKELY_PARAMETER_THRESHOLD) { String message = String.format( "`%s` is very close to the parameter `%s`. " + "Did you mean to reference the parameter?", body, bestMatch); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .addFix(replace(node.getBody(), bestMatch, state)) .build()); } return super.visitLiteral(node, null); } } private static ImmutableSet<String> extractDocumentedParams( DCDocComment docCommentTree, boolean isTypeParameter) { ImmutableSet.Builder<String> parameters = ImmutableSet.builder(); for (DocTree docTree : docCommentTree.getBlockTags()) { if (!(docTree instanceof ParamTree)) { continue; } ParamTree paramTree = (ParamTree) docTree; if (paramTree.isTypeParameter() == isTypeParameter) { parameters.add(paramTree.getName().getName().toString()); } } return parameters.build(); } }
9,415
40.480176
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/Utils.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.javadoc; import static com.google.errorprone.names.LevenshteinEditDistance.getEditDistance; import com.google.errorprone.VisitorState; import com.google.errorprone.fixes.FixedPosition; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.util.ASTHelpers; import com.sun.source.doctree.DocCommentTree; import com.sun.source.doctree.DocTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.Tree; import com.sun.source.util.DocSourcePositions; import com.sun.source.util.DocTreePath; import com.sun.tools.javac.api.JavacTrees; import com.sun.tools.javac.tree.DCTree.DCDocComment; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.Position; import java.util.Optional; import javax.annotation.Nullable; /** Common utility methods for fixing Javadocs. */ final class Utils { static Optional<String> getBestMatch(String to, int maxEditDistance, Iterable<String> choices) { String bestMatch = null; int minDistance = Integer.MAX_VALUE; for (String choice : choices) { int distance = getEditDistance(to, choice); if (distance < minDistance && distance < maxEditDistance) { bestMatch = choice; minDistance = distance; } } return Optional.ofNullable(bestMatch); } static DCDocComment getDocComment(VisitorState state, Tree tree) { return ((JCCompilationUnit) state.getPath().getCompilationUnit()) .docComments.getCommentTree((JCTree) tree); } static SuggestedFix replace(DocTree docTree, String replacement, VisitorState state) { DocSourcePositions positions = JavacTrees.instance(state.context).getSourcePositions(); CompilationUnitTree compilationUnitTree = state.getPath().getCompilationUnit(); int startPos = getStartPosition(docTree, state); int endPos = (int) positions.getEndPosition(compilationUnitTree, getDocCommentTree(state), docTree); if (endPos == Position.NOPOS) { return SuggestedFix.emptyFix(); } return SuggestedFix.replace(startPos, endPos, replacement); } static int getStartPosition(DocTree docTree, VisitorState state) { DocSourcePositions positions = JavacTrees.instance(state.context).getSourcePositions(); CompilationUnitTree compilationUnitTree = state.getPath().getCompilationUnit(); return (int) positions.getStartPosition(compilationUnitTree, getDocCommentTree(state), docTree); } static int getEndPosition(DocTree docTree, VisitorState state) { DocSourcePositions positions = JavacTrees.instance(state.context).getSourcePositions(); CompilationUnitTree compilationUnitTree = state.getPath().getCompilationUnit(); return (int) positions.getEndPosition(compilationUnitTree, getDocCommentTree(state), docTree); } /** * Gets a {@link DiagnosticPosition} for the {@link DocTree} pointed to by {@code path}, attached * to the {@link Tree} which it documents. */ static DiagnosticPosition diagnosticPosition(DocTreePath path, VisitorState state) { int startPosition = getStartPosition(path.getLeaf(), state); Tree tree = path.getTreePath().getLeaf(); if (startPosition == Position.NOPOS) { // javac doesn't seem to store positions for e.g. trivial empty javadoc like `/** */` // see: https://github.com/google/error-prone/issues/1981 startPosition = ASTHelpers.getStartPosition(tree); } return getDiagnosticPosition(startPosition, tree); } static DiagnosticPosition getDiagnosticPosition(int startPosition, Tree tree) { return new FixedPosition(tree, startPosition); } @Nullable static DocTreePath getDocTreePath(VisitorState state) { DocCommentTree docCommentTree = getDocCommentTree(state); if (docCommentTree == null) { return null; } return new DocTreePath(state.getPath(), docCommentTree); } @Nullable private static DocCommentTree getDocCommentTree(VisitorState state) { return JavacTrees.instance(state.context).getDocCommentTree(state.getPath()); } private Utils() {} }
4,803
39.369748
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/ReturnFromVoid.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.javadoc; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.diagnosticPosition; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSameType; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; 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.sun.source.doctree.ReturnTree; import com.sun.source.tree.MethodTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; /** * Finds common Javadoc errors, and tries to suggest useful fixes. * * @author ghm@google.com (Graeme Morgan) */ @BugPattern( summary = "Void methods should not have a @return tag.", severity = WARNING, tags = StandardTags.STYLE, documentSuppression = false) public final class ReturnFromVoid extends BugChecker implements MethodTreeMatcher { @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { DocTreePath path = Utils.getDocTreePath(state); if (path != null) { new VoidReturnTypeChecker(state, methodTree).scan(path, null); } return Description.NO_MATCH; } private final class VoidReturnTypeChecker extends DocTreePathScanner<Void, Void> { private final VisitorState state; private final MethodTree methodTree; private VoidReturnTypeChecker(VisitorState state, MethodTree methodTree) { this.state = state; this.methodTree = methodTree; } @Override public Void visitReturn(ReturnTree returnTree, Void unused) { if (isSameType(getType(methodTree.getReturnType()), state.getSymtab().voidType, state)) { state.reportMatch( describeMatch( diagnosticPosition(getCurrentPath(), state), Utils.replace(returnTree, "", state))); } return super.visitReturn(returnTree, null); } } }
2,781
35.605263
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/AlmostJavadoc.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.javadoc; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.BugPattern.StandardTags.STYLE; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static java.util.stream.Collectors.joining; import com.google.common.collect.ImmutableMap; 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.CompilationUnitTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.ErrorProneToken; import com.google.errorprone.util.ErrorProneTokens; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.parser.Tokens.Comment; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.regex.Pattern; import javax.lang.model.element.ElementKind; /** * Flags comments which appear to be intended to be Javadoc, but are not started with an extra * {@code *}. */ @BugPattern( summary = "This comment contains Javadoc or HTML tags, but isn't started with a double asterisk" + " (/**); is it meant to be Javadoc?", severity = WARNING, tags = STYLE, documentSuppression = false) public final class AlmostJavadoc extends BugChecker implements CompilationUnitTreeMatcher { private static final Pattern HAS_TAG = Pattern.compile( String.format( "<\\w+>|@(%s)", Streams.concat( JavadocTag.VALID_CLASS_TAGS.stream(), JavadocTag.VALID_METHOD_TAGS.stream(), JavadocTag.VALID_VARIABLE_TAGS.stream()) .map(JavadocTag::name) .map(Pattern::quote) .distinct() .collect(joining("|")))); @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { ImmutableMap<Integer, Tree> javadocableTrees = getJavadocableTrees(tree, state); for (ErrorProneToken token : ErrorProneTokens.getTokens(state.getSourceCode().toString(), state.context)) { for (Comment comment : token.comments()) { if (!javadocableTrees.containsKey(token.pos())) { continue; } generateFix(comment) .ifPresent( fix -> state.reportMatch(describeMatch(javadocableTrees.get(token.pos()), fix))); } } return NO_MATCH; } private static Optional<SuggestedFix> generateFix(Comment comment) { String text = comment.getText(); if (text.startsWith("/*") && !text.startsWith("/**") && HAS_TAG.matcher(text).find()) { int pos = comment.getSourcePos(1); return Optional.of(SuggestedFix.replace(pos, pos, "*")); } if (text.startsWith("//") && text.endsWith("*/") && HAS_TAG.matcher(text).find()) { if (text.startsWith("// /**")) { return Optional.of( SuggestedFix.replace(comment.getSourcePos(0), comment.getSourcePos(2), "")); } int endReplacement = 2; while (endReplacement < text.length()) { char c = text.charAt(endReplacement); if (c == '/') { return Optional.empty(); } if (c != '*' && c != ' ') { break; } ++endReplacement; } return Optional.of( SuggestedFix.replace( comment.getSourcePos(1), comment.getSourcePos(endReplacement), "**")); } return Optional.empty(); } private ImmutableMap<Integer, Tree> getJavadocableTrees( CompilationUnitTree tree, VisitorState state) { Map<Integer, Tree> javadoccablePositions = new HashMap<>(); new SuppressibleTreePathScanner<Void, Void>(state) { @Override public Void visitClass(ClassTree classTree, Void unused) { if (!shouldMatch()) { return null; } javadoccablePositions.put(startPos(classTree), classTree); return super.visitClass(classTree, null); } @Override public Void visitMethod(MethodTree methodTree, Void unused) { if (!shouldMatch()) { return null; } if (!ASTHelpers.isGeneratedConstructor(methodTree)) { javadoccablePositions.put(startPos(methodTree), methodTree); } return super.visitMethod(methodTree, null); } @Override public Void visitVariable(VariableTree variableTree, Void unused) { if (!shouldMatch()) { return null; } ElementKind kind = getSymbol(variableTree).getKind(); if (kind == ElementKind.FIELD) { javadoccablePositions.put(startPos(variableTree), variableTree); } // For enum constants, skip past the desugared class declaration. if (kind == ElementKind.ENUM_CONSTANT) { javadoccablePositions.put(startPos(variableTree), variableTree); if (variableTree.getInitializer() instanceof NewClassTree) { ClassTree classBody = ((NewClassTree) variableTree.getInitializer()).getClassBody(); if (classBody != null) { scan(classBody.getMembers(), null); } return null; } } return super.visitVariable(variableTree, null); } private boolean shouldMatch() { // Check there isn't already a Javadoc for the element under question, otherwise we might // suggest double Javadoc. return Utils.getDocTreePath(state.withPath(getCurrentPath())) == null; } private int startPos(Tree tree) { return getStartPosition(tree); } }.scan(tree, null); return ImmutableMap.copyOf(javadoccablePositions); } }
6,869
36.955801
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/MissingSummary.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.javadoc; import static com.google.errorprone.BugPattern.LinkType.CUSTOM; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.diagnosticPosition; import static com.google.errorprone.bugpatterns.javadoc.Utils.getDocTreePath; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.findSuperMethods; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.isEffectivelyPrivate; 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.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.doctree.DocTree; import com.sun.source.doctree.ReturnTree; import com.sun.source.doctree.SeeTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.tree.DCTree.DCDocComment; import java.util.List; import java.util.Set; import javax.annotation.Nullable; import javax.lang.model.element.Modifier; /** * Matches Javadocs which are missing a required summary line. * * @author ghm@google.com (Graeme Morgan) */ @BugPattern( summary = "A summary line is required on public/protected Javadocs.", severity = WARNING, linkType = CUSTOM, link = "https://google.github.io/styleguide/javaguide.html#s7.2-summary-fragment", documentSuppression = false) public final class MissingSummary extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { private static final String CONSIDER_USING_MESSAGE = "A summary fragment is required; consider using the value of the @%s block as a " + "summary fragment instead."; @Override public Description matchClass(ClassTree classTree, VisitorState state) { return handle(getDocTreePath(state), state); } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { return handle(getDocTreePath(state), state); } @Override public Description matchVariable(VariableTree variableTree, VisitorState state) { return handle(getDocTreePath(state), state); } private Description handle(@Nullable DocTreePath docTreePath, VisitorState state) { if (docTreePath == null) { return NO_MATCH; } if (!requiresJavadoc(docTreePath.getTreePath().getLeaf(), state)) { return Description.NO_MATCH; } List<? extends DocTree> firstSentence = docTreePath.getDocComment().getFirstSentence(); if (!firstSentence.isEmpty()) { return NO_MATCH; } Symbol symbol = getSymbol(docTreePath.getTreePath().getLeaf()); if (symbol == null) { return NO_MATCH; } // Skip constructors: a summary line on a constructor doesn't necessarily add a lot of value. if (symbol.isConstructor()) { return NO_MATCH; } ReturnTree returnTree = findFirst(docTreePath, ReturnTree.class); if (returnTree != null) { Description description = generateReturnFix(docTreePath, returnTree, state); if (!description.equals(NO_MATCH)) { return description; } } SeeTree seeTree = findFirst(docTreePath, SeeTree.class); if (seeTree != null) { return generateSeeFix(docTreePath, seeTree, state); } Set<Modifier> modifiers = symbol.getModifiers(); if (!modifiers.contains(Modifier.PUBLIC) && !modifiers.contains(Modifier.PROTECTED)) { return NO_MATCH; } if (hasAnnotation(symbol, "java.lang.Override", state) || hasAnnotation(symbol, "java.lang.Deprecated", state)) { return NO_MATCH; } return buildDescription(diagnosticPosition(docTreePath, state)).build(); } private Description generateReturnFix( DocTreePath docTreePath, ReturnTree returnTree, VisitorState state) { int pos = ((DCDocComment) docTreePath.getDocComment()).comment.getSourcePos(0); String description = returnTree.toString().replaceAll("^@return ", ""); if (description.isEmpty()) { return NO_MATCH; } SuggestedFix fix = SuggestedFix.builder() .merge(Utils.replace(returnTree, "", state)) .replace( pos, pos, String.format( "Returns %s%s\n", lowerFirstLetter(description), description.endsWith(".") ? "" : ".")) .build(); return buildDescription(diagnosticPosition(docTreePath, state)) .setMessage(String.format(CONSIDER_USING_MESSAGE, "return")) .addFix(fix) .build(); } private Description generateSeeFix(DocTreePath docTreePath, SeeTree seeTree, VisitorState state) { int pos = ((DCDocComment) docTreePath.getDocComment()).comment.getSourcePos(0); // javac fails to provide an endpos for @see sometimes; don't emit a fix in that case. SuggestedFix replacement = Utils.replace(seeTree, "", state); SuggestedFix fix = replacement.isEmpty() ? replacement : SuggestedFix.builder() .merge(replacement) .replace( pos, pos, String.format( "See {@link %s}.\n", seeTree.getReference().stream() .map(Object::toString) .collect(joining(" ")))) .build(); return buildDescription(diagnosticPosition(docTreePath, state)) .setMessage(String.format(CONSIDER_USING_MESSAGE, "see")) .addFix(fix) .build(); } @Nullable private static <T> T findFirst(DocTreePath docTreePath, Class<T> clazz) { return new DocTreeScanner<T, Void>() { @Override public T scan(DocTree docTree, Void unused) { if (clazz.isInstance(docTree)) { return clazz.cast(docTree); } return super.scan(docTree, null); } }.scan(docTreePath.getLeaf(), null); } private static String lowerFirstLetter(String description) { return Character.toLowerCase(description.charAt(0)) + description.substring(1); } private static boolean requiresJavadoc(Tree tree, VisitorState state) { if (state.errorProneOptions().isTestOnlyTarget()) { return false; } Symbol symbol = getSymbol(tree); if (symbol instanceof MethodSymbol && !findSuperMethods((MethodSymbol) symbol, state.getTypes()).isEmpty()) { return false; } return symbol != null && !isEffectivelyPrivate(symbol); } }
7,902
37.55122
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/NotJavadoc.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.javadoc; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.getDiagnosticPosition; import static com.google.errorprone.fixes.SuggestedFix.replace; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ErrorProneTokens.getTokens; import static com.sun.tools.javac.parser.Tokens.Comment.CommentStyle.JAVADOC; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableRangeSet; import com.google.common.collect.Range; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.ErrorProneToken; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ModuleTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.PackageTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.parser.Tokens.Comment; import java.util.HashMap; import java.util.Map; import javax.lang.model.element.ElementKind; /** A BugPattern; see the summary. */ @BugPattern( summary = "Avoid using `/**` for comments which aren't actually Javadoc.", severity = WARNING, documentSuppression = false) public final class NotJavadoc extends BugChecker implements CompilationUnitTreeMatcher { @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { ImmutableMap<Integer, Tree> javadocableTrees = getJavadoccableTrees(tree); ImmutableRangeSet<Integer> suppressedRegions = suppressedRegions(state); for (ErrorProneToken token : getTokens(state.getSourceCode().toString(), state.context)) { for (Comment comment : token.comments()) { if (!comment.getStyle().equals(JAVADOC) || comment.getText().equals("/**/")) { continue; } if (javadocableTrees.containsKey(token.pos())) { continue; } if (suppressedRegions.intersects( Range.closed( comment.getSourcePos(0), comment.getSourcePos(comment.getText().length() - 1)))) { continue; } int endPos = 2; while (comment.getText().charAt(endPos) == '*') { endPos++; } state.reportMatch( describeMatch( getDiagnosticPosition(comment.getSourcePos(0), tree), replace(comment.getSourcePos(1), comment.getSourcePos(endPos - 1), ""))); } } return NO_MATCH; } private ImmutableMap<Integer, Tree> getJavadoccableTrees(CompilationUnitTree tree) { Map<Integer, Tree> javadoccablePositions = new HashMap<>(); new TreePathScanner<Void, Void>() { @Override public Void visitPackage(PackageTree packageTree, Void unused) { javadoccablePositions.put(getStartPosition(packageTree), packageTree); return super.visitPackage(packageTree, null); } @Override public Void visitClass(ClassTree classTree, Void unused) { if (!(getSymbol(classTree).owner instanceof MethodSymbol)) { javadoccablePositions.put(getStartPosition(classTree), classTree); } return super.visitClass(classTree, null); } @Override public Void visitMethod(MethodTree methodTree, Void unused) { if (!ASTHelpers.isGeneratedConstructor(methodTree)) { javadoccablePositions.put(getStartPosition(methodTree), methodTree); } return super.visitMethod(methodTree, null); } @Override public Void visitVariable(VariableTree variableTree, Void unused) { ElementKind kind = getSymbol(variableTree).getKind(); if (kind == ElementKind.FIELD) { javadoccablePositions.put(getStartPosition(variableTree), variableTree); } // For enum constants, skip past the desugared class declaration. if (kind == ElementKind.ENUM_CONSTANT) { javadoccablePositions.put(getStartPosition(variableTree), variableTree); if (variableTree.getInitializer() instanceof NewClassTree) { ClassTree classBody = ((NewClassTree) variableTree.getInitializer()).getClassBody(); if (classBody != null) { scan(classBody.getMembers(), null); } return null; } } return super.visitVariable(variableTree, null); } @Override public Void visitModule(ModuleTree moduleTree, Void unused) { javadoccablePositions.put(getStartPosition(moduleTree), moduleTree); return super.visitModule(moduleTree, null); } }.scan(tree, null); return ImmutableMap.copyOf(javadoccablePositions); } }
5,930
39.903448
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/UnrecognisedJavadocTag.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.javadoc; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.getDiagnosticPosition; import static com.google.errorprone.bugpatterns.javadoc.Utils.getStartPosition; import static com.google.errorprone.matchers.Description.NO_MATCH; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.matchers.Description; import com.sun.source.doctree.DocTree.Kind; import com.sun.source.doctree.LinkTree; import com.sun.source.doctree.LiteralTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.tree.DCTree.DCDocComment; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; /** Flags tags which haven't been recognised by the Javadoc parser. */ @BugPattern( summary = "This Javadoc tag wasn't recognised by the parser. Is it malformed somehow, perhaps with" + " mismatched braces?", severity = WARNING, documentSuppression = false) public final class UnrecognisedJavadocTag extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { private static final Pattern TAG = Pattern.compile("\\{@(code|link)"); @Override public Description matchClass(ClassTree classTree, VisitorState state) { return handle(Utils.getDocTreePath(state), state); } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { return handle(Utils.getDocTreePath(state), state); } @Override public Description matchVariable(VariableTree variableTree, VisitorState state) { return handle(Utils.getDocTreePath(state), state); } private Description handle(@Nullable DocTreePath path, VisitorState state) { if (path == null) { return NO_MATCH; } ImmutableSet<Integer> recognisedTags = findRecognisedTags(path, state); ImmutableSet<Integer> tagStrings = findTags(((DCDocComment) path.getDocComment()).comment); for (int pos : Sets.difference(tagStrings, recognisedTags)) { state.reportMatch( buildDescription(getDiagnosticPosition(pos, path.getTreePath().getLeaf())).build()); } return NO_MATCH; } private ImmutableSet<Integer> findRecognisedTags(DocTreePath path, VisitorState state) { ImmutableSet.Builder<Integer> tags = ImmutableSet.builder(); new DocTreePathScanner<Void, Void>() { @Override public Void visitLink(LinkTree linkTree, Void unused) { tags.add(getStartPosition(linkTree, state)); return super.visitLink(linkTree, null); } @Override public Void visitLiteral(LiteralTree literalTree, Void unused) { if (literalTree.getKind().equals(Kind.CODE)) { tags.add(getStartPosition(literalTree, state)); } return super.visitLiteral(literalTree, null); } }.scan(path, null); return tags.build(); } private static ImmutableSet<Integer> findTags(Comment comment) { Matcher matcher = TAG.matcher(comment.getText()); ImmutableSet.Builder<Integer> tags = ImmutableSet.builder(); while (matcher.find()) { tags.add(comment.getSourcePos(matcher.start())); } return tags.build(); } }
4,482
37.316239
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/InvalidInlineTag.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.javadoc; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getFirst; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.JavadocTag.inlineTag; import static com.google.errorprone.bugpatterns.javadoc.Utils.diagnosticPosition; import static com.google.errorprone.bugpatterns.javadoc.Utils.getDiagnosticPosition; import static java.util.stream.Collectors.joining; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.bugpatterns.javadoc.JavadocTag.TagType; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.FindIdentifiers; import com.sun.source.doctree.DocTree; import com.sun.source.doctree.ErroneousTree; import com.sun.source.doctree.TextTree; import com.sun.source.doctree.UnknownInlineTagTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; import com.sun.tools.javac.code.Kinds.KindSelector; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.tree.DCTree.DCDocComment; import com.sun.tools.javac.tree.DCTree.DCInlineTag; import com.sun.tools.javac.tree.DCTree.DCText; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Matches invalid Javadoc tags, and tries to suggest fixes. * * @author ghm@google.com (Graeme Morgan) */ @BugPattern(summary = "This tag is invalid.", severity = WARNING, documentSuppression = false) public final class InvalidInlineTag extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { private static final Pattern PARAM_MATCHER = Pattern.compile("\\{?@param ([a-zA-Z0-9]+)}?"); private static final Pattern ANCHORED_PARAM_MATCHER = Pattern.compile("^\\{?@param ([a-zA-Z0-9]+)}?"); private static final Splitter DOT_SPLITTER = Splitter.on('.'); private void scanTags( VisitorState state, Context context, ImmutableSet<String> parameters, DocTreePath path) { new InvalidTagChecker(state, context, parameters).scan(path, null); } private enum Context { CLASS(JavadocTag.VALID_CLASS_TAGS), METHOD(JavadocTag.VALID_METHOD_TAGS), VARIABLE(JavadocTag.VALID_VARIABLE_TAGS); final ImmutableSet<JavadocTag> validTags; final Pattern misplacedCurly; final Pattern parensRatherThanCurly; Context(ImmutableSet<JavadocTag> validTags) { this.validTags = validTags; String validInlineTags = validTags.stream() .filter(tag -> tag.type() == TagType.INLINE) .map(JavadocTag::name) .collect(joining("|")); this.misplacedCurly = Pattern.compile(String.format("@(%s)\\{", validInlineTags)); this.parensRatherThanCurly = Pattern.compile(String.format("\\(@(%s)", validInlineTags)); } } @Override public Description matchClass(ClassTree classTree, VisitorState state) { DocTreePath path = Utils.getDocTreePath(state); if (path != null) { ImmutableSet<String> parameters = ImmutableSet.of(); scanTags(state, Context.CLASS, parameters, path); } return Description.NO_MATCH; } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { DocTreePath path = Utils.getDocTreePath(state); if (path != null) { ImmutableSet<String> parameters = methodTree.getParameters().stream() .map(v -> v.getName().toString()) .collect(toImmutableSet()); scanTags(state, Context.METHOD, parameters, path); } return Description.NO_MATCH; } @Override public Description matchVariable(VariableTree variableTree, VisitorState state) { DocTreePath path = Utils.getDocTreePath(state); if (path != null) { scanTags(state, Context.VARIABLE, /* parameters= */ ImmutableSet.of(), path); } return Description.NO_MATCH; } static String getMessageForInvalidTag(String paramName) { return String.format( "@%1$s is not a valid tag, but is a parameter name. " + "Use {@code %1$s} to refer to parameter names inline.", paramName); } final class InvalidTagChecker extends DocTreePathScanner<Void, Void> { private final VisitorState state; private final ImmutableSet<String> parameters; private final Context context; private final Set<DocTree> fixedTags = new HashSet<>(); private InvalidTagChecker( VisitorState state, Context context, ImmutableSet<String> parameters) { this.state = state; this.context = context; this.parameters = parameters; } @Override public Void visitErroneous(ErroneousTree erroneousTree, Void unused) { Matcher matcher = ANCHORED_PARAM_MATCHER.matcher(erroneousTree.getBody()); if (matcher.find()) { String parameterName = matcher.group(1); if (parameters.contains(parameterName)) { String message = String.format( "@param cannot be used inline to refer to parameters; {@code %s} is recommended", parameterName); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .addFix( Utils.replace( erroneousTree, String.format("{@code %s}", parameterName), state)) .build()); } } return null; } @Override public Void visitText(TextTree node, Void unused) { handleMalformedTags(node); handleIncorrectParens(node); handleDanglingParams(node); return super.visitText(node, null); } private void handleMalformedTags(TextTree node) { String body = node.getBody(); Matcher matcher = context.misplacedCurly.matcher(body); Comment comment = ((DCDocComment) getCurrentPath().getDocComment()).comment; while (matcher.find()) { int beforeAt = comment.getSourcePos(((DCText) node).pos + matcher.start()); int startOfCurly = comment.getSourcePos(((DCText) node).pos + matcher.end(1)); SuggestedFix fix = SuggestedFix.builder() .replace(beforeAt, beforeAt, "{") .replace(startOfCurly, startOfCurly + 1, " ") .build(); state.reportMatch( describeMatch( getDiagnosticPosition(beforeAt, getCurrentPath().getTreePath().getLeaf()), fix)); } } private void handleIncorrectParens(TextTree node) { String body = node.getBody(); Matcher matcher = context.parensRatherThanCurly.matcher(body); Comment comment = ((DCDocComment) getCurrentPath().getDocComment()).comment; while (matcher.find()) { int beforeAt = comment.getSourcePos(((DCText) node).pos + matcher.start()); SuggestedFix.Builder fix = SuggestedFix.builder().replace(beforeAt, beforeAt + 1, "{"); Optional<Integer> found = findClosingBrace(body, matcher.start(1)); found.ifPresent( pos -> { int closing = comment.getSourcePos(((DCText) node).pos + pos); fix.replace(closing, closing + 1, "}"); }); state.reportMatch( buildDescription( getDiagnosticPosition(beforeAt, getCurrentPath().getTreePath().getLeaf())) .setMessage( String.format( "Curly braces should be used for inline Javadoc tags: {@%s ...}", matcher.group(1))) .addFix(fix.build()) .build()); } } /** Looks for a matching closing brace, if one is found. */ private Optional<Integer> findClosingBrace(String body, int startPos) { int parenDepth = 0; for (int pos = startPos; pos < body.length(); ++pos) { char c = body.charAt(pos); switch (c) { case '(': parenDepth++; continue; case ')': if (parenDepth == 0) { return Optional.of(pos); } parenDepth--; break; case '}': return Optional.empty(); default: // fall out } } return Optional.empty(); } private void handleDanglingParams(TextTree node) { Matcher matcher = PARAM_MATCHER.matcher(node.getBody()); Comment comment = ((DCDocComment) getCurrentPath().getDocComment()).comment; while (matcher.find()) { int startPos = comment.getSourcePos(((DCText) node).pos + matcher.start()); int endPos = comment.getSourcePos(((DCText) node).pos + matcher.end()); String paramName = matcher.group(1); SuggestedFix fix = SuggestedFix.replace(startPos, endPos, String.format("{@code %s}", paramName)); state.reportMatch( describeMatch( getDiagnosticPosition(startPos, getCurrentPath().getTreePath().getLeaf()), fix)); } } @Override public Void visitUnknownInlineTag(UnknownInlineTagTree unknownInlineTagTree, Void unused) { String name = unknownInlineTagTree.getTagName(); if (name.equals("param")) { int startPos = Utils.getStartPosition(unknownInlineTagTree, state); int endPos = Utils.getEndPosition(unknownInlineTagTree, state); CharSequence text = state.getSourceCode().subSequence(startPos, endPos); Matcher matcher = PARAM_MATCHER.matcher(text); if (matcher.find()) { String parameterName = matcher.group(1); if (parameters.contains(parameterName)) { String message = String.format( "@param cannot be used inline to refer to parameters; {@code %s} is" + " recommended", parameterName); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .addFix( Utils.replace( unknownInlineTagTree, String.format("{@code %s}", parameterName), state)) .build()); } fixedTags.add(unknownInlineTagTree); return super.visitUnknownInlineTag(unknownInlineTagTree, null); } } if (parameters.contains(name)) { String message = getMessageForInvalidTag(name); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .addFix( Utils.replace(unknownInlineTagTree, String.format("{@code %s}", name), state)) .build()); fixedTags.add(unknownInlineTagTree); return super.visitUnknownInlineTag(unknownInlineTagTree, null); } if (isProbablyType(name)) { int startPos = Utils.getStartPosition(unknownInlineTagTree, state); String message = String.format( "The tag {@%1$s} is not valid, and will not display or cross-link " + "to the type %1$s correctly. Prefer {@link %1$s}.", name); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .addFix(SuggestedFix.replace(startPos, startPos + 2, "{@link ")) .build()); fixedTags.add(unknownInlineTagTree); return super.visitUnknownInlineTag(unknownInlineTagTree, null); } reportUnknownTag(unknownInlineTagTree, inlineTag(name)); return super.visitUnknownInlineTag(unknownInlineTagTree, null); } private boolean isProbablyType(String name) { Symbol typeSymbol = FindIdentifiers.findIdent( getFirst(DOT_SPLITTER.split(name), null), state, KindSelector.TYP); return typeSymbol instanceof TypeSymbol || name.chars().filter(c -> c == '.').count() >= 3 || name.contains("#"); } private void reportUnknownTag(DocTree docTree, JavadocTag tag) { Optional<String> bestMatch = Utils.getBestMatch( tag.name(), /* maxEditDistance= */ 2, context.validTags.stream() .filter(t -> t.type().equals(tag.type())) .map(JavadocTag::name) .collect(toImmutableSet())); int pos = Utils.getStartPosition(docTree, state) + docTree.toString().indexOf(tag.name()); String message = String.format("Tag name `%s` is unknown.", tag.name()); state.reportMatch( bestMatch .map( bm -> buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message + String.format(" Did you mean tag `%s`?", bm)) .addFix(SuggestedFix.replace(pos, pos + tag.name().length(), bm)) .build()) .orElse( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage( message + " If this is a commonly-used custom tag, please " + "click 'not useful' and file a bug.") .build())); fixedTags.add(docTree); } @Override public Void scan(DocTree docTree, Void unused) { super.scan(docTree, null); // Don't complain about this unknown tag if we already generated a better fix for it. if (fixedTags.contains(docTree)) { return null; } if (!(docTree instanceof DCInlineTag)) { return null; } JavadocTag tag = inlineTag(((DCInlineTag) docTree).getTagName()); if (context.validTags.contains(tag) || JavadocTag.KNOWN_OTHER_TAGS.contains(tag)) { return null; } String message = String.format("The tag @%s is not allowed on this type of element.", tag.name()); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .addFix(Utils.replace(docTree, "", state)) .build()); return null; } } }
15,797
39.096447
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/InvalidThrows.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.javadoc; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.diagnosticPosition; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSubtype; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.matchers.Description; import com.sun.source.doctree.ReferenceTree; import com.sun.source.doctree.ThrowsTree; import com.sun.source.tree.MethodTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; import com.sun.tools.javac.api.JavacTrees; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.TypeTag; import javax.lang.model.element.Element; /** * Matches errors in Javadoc {@literal @}throws tags. * * @author ghm@google.com (Graeme Morgan) */ @BugPattern( summary = "The documented method doesn't actually throw this checked exception.", severity = WARNING, documentSuppression = false) public final class InvalidThrows extends BugChecker implements MethodTreeMatcher { @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { DocTreePath path = Utils.getDocTreePath(state); if (path != null) { new ThrowsChecker(state, methodTree).scan(path, null); } return Description.NO_MATCH; } private final class ThrowsChecker extends DocTreePathScanner<Void, Void> { private final VisitorState state; private final MethodTree methodTree; private ThrowsChecker(VisitorState state, MethodTree methodTree) { this.state = state; this.methodTree = methodTree; } @Override public Void visitThrows(ThrowsTree throwsTree, Void unused) { ReferenceTree exName = throwsTree.getExceptionName(); Element element = JavacTrees.instance(state.context).getElement(new DocTreePath(getCurrentPath(), exName)); if (element != null) { Type type = (Type) element.asType(); if (isCheckedException(type)) { if (methodTree.getThrows().stream().noneMatch(t -> isSubtype(type, getType(t), state))) { state.reportMatch( describeMatch( diagnosticPosition(getCurrentPath(), state), Utils.replace(throwsTree, "", state))); } } } return super.visitThrows(throwsTree, null); } private boolean isCheckedException(Type type) { return type.hasTag(TypeTag.CLASS) && !state.getTypes().isAssignable(type, state.getSymtab().errorType) && !state.getTypes().isAssignable(type, state.getSymtab().runtimeExceptionType); } } }
3,515
36.404255
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/UrlInSee.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.javadoc; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.diagnosticPosition; import static com.google.errorprone.bugpatterns.javadoc.Utils.getDocTreePath; import static com.google.errorprone.bugpatterns.javadoc.Utils.replace; 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; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.matchers.Description; import com.sun.source.doctree.ErroneousTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; /** Discourages using URLs in {@literal @}see tags. */ @BugPattern( summary = "URLs should not be used in @see tags; they are designed for Java elements which could be" + " used with @link.", severity = WARNING) public final class UrlInSee extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { @Override public Description matchClass(ClassTree classTree, VisitorState state) { DocTreePath path = getDocTreePath(state); if (path != null) { new UrlInSeeChecker(state).scan(path, null); } return NO_MATCH; } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { DocTreePath path = getDocTreePath(state); if (path != null) { new UrlInSeeChecker(state).scan(path, null); } return NO_MATCH; } @Override public Description matchVariable(VariableTree variableTree, VisitorState state) { DocTreePath path = getDocTreePath(state); if (path != null) { new UrlInSeeChecker(state).scan(path, null); } return NO_MATCH; } private final class UrlInSeeChecker extends DocTreePathScanner<Void, Void> { private final VisitorState state; private UrlInSeeChecker(VisitorState state) { this.state = state; } @Override public Void visitErroneous(ErroneousTree erroneousTree, Void unused) { if (erroneousTree.getBody().startsWith("@see http")) { state.reportMatch( describeMatch( diagnosticPosition(getCurrentPath(), state), replace( erroneousTree, erroneousTree.getBody().replaceFirst("@see", "See"), state))); } return super.visitErroneous(erroneousTree, unused); } } }
3,443
35.638298
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/InheritDoc.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.javadoc; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.diagnosticPosition; import static com.google.errorprone.util.ASTHelpers.findSuperMethods; import static com.google.errorprone.util.ASTHelpers.getSymbol; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.matchers.Description; import com.sun.source.doctree.InheritDocTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; import com.sun.source.util.SimpleTreeVisitor; import com.sun.tools.javac.code.Symbol.MethodSymbol; /** * Matches invalid usage of {@literal @inheritDoc}. * * @author ghm@google.com (Graeme Morgan) */ @BugPattern( summary = "Invalid use of @inheritDoc.", severity = WARNING, tags = StandardTags.STYLE, documentSuppression = false) public final class InheritDoc extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { @Override public Description matchClass(ClassTree classTree, VisitorState state) { return handle(state); } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { return handle(state); } @Override public Description matchVariable(VariableTree variableTree, VisitorState state) { return handle(state); } private Description handle(VisitorState state) { DocTreePath path = Utils.getDocTreePath(state); if (path != null) { new InheritDocChecker(state).scan(path, null); } return Description.NO_MATCH; } private final class InheritDocChecker extends DocTreePathScanner<Void, Void> { private final VisitorState state; private InheritDocChecker(VisitorState state) { this.state = state; } @Override public Void visitInheritDoc(InheritDocTree inheritDocTree, Void unused) { new SimpleTreeVisitor<Void, Void>() { @Override public Void visitVariable(VariableTree variableTree, Void unused) { state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage( "@inheritDoc doesn't make sense on variables as " + "they cannot override a super element.") .build()); return null; } @Override public Void visitMethod(MethodTree methodTree, Void unused) { MethodSymbol methodSymbol = getSymbol(methodTree); if (findSuperMethods(methodSymbol, state.getTypes()).isEmpty()) { state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage( "This method does not override anything to inherit documentation from.") .build()); } return null; } @Override public Void visitClass(ClassTree classTree, Void unused) { if (classTree.getExtendsClause() == null && classTree.getImplementsClause().isEmpty()) { state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage( "This class does not extend or implement anything to inherit " + "documentation from.") .build()); } return null; } }.visit(getCurrentPath().getTreePath().getLeaf(), null); return super.visitInheritDoc(inheritDocTree, null); } } }
4,710
35.804688
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/JavadocTag.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.javadoc; import static com.google.common.collect.ImmutableSet.toImmutableSet; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.Immutable; import java.util.stream.Stream; /** Describes Javadoc tags, and contains lists of valid tags. */ @Immutable @AutoValue abstract class JavadocTag { /** Non-standard commonly-used tags which we should allow. */ static final ImmutableSet<JavadocTag> KNOWN_OTHER_TAGS = ImmutableSet.of( blockTag("apiNote"), blockTag("attr"), // commonly used by Android blockTag("contact"), blockTag("fails"), // commonly used tag for denoting async failure modes blockTag("hide"), blockTag("implNote"), blockTag("implSpec"), blockTag("removed"), // Used in the android framework (metalava) blockTag("required"), blockTag("team")); private static final ImmutableSet<JavadocTag> COMMON_TAGS = ImmutableSet.of( inlineTag("code"), blockTag("deprecated"), inlineTag("docRoot"), inlineTag("link"), inlineTag("linkplain"), inlineTag("literal"), blockTag("see"), blockTag("since")); static final ImmutableSet<JavadocTag> VALID_CLASS_TAGS = ImmutableSet.<JavadocTag>builder() .addAll(COMMON_TAGS) .add( blockTag("author"), inlineTag("inheritDoc"), blockTag("param"), inlineTag("value"), blockTag("version")) .build(); static final ImmutableSet<JavadocTag> VALID_VARIABLE_TAGS = ImmutableSet.<JavadocTag>builder() .addAll(COMMON_TAGS) .add( blockTag("serial"), blockTag("serialData"), blockTag("serialField"), inlineTag("value")) .build(); static final ImmutableSet<JavadocTag> VALID_METHOD_TAGS = ImmutableSet.<JavadocTag>builder() .addAll(COMMON_TAGS) .add( blockTag("author"), blockTag("exception"), inlineTag("inheritDoc"), blockTag("param"), blockTag("return"), blockTag("serial"), blockTag("throws"), blockTag("serialData"), blockTag("serialField"), inlineTag("value"), blockTag("version")) .build(); static final ImmutableSet<JavadocTag> ALL_INLINE_TAGS = Stream.of(VALID_CLASS_TAGS, VALID_VARIABLE_TAGS, VALID_METHOD_TAGS) .flatMap(ImmutableSet::stream) .filter(tag -> tag.type() == TagType.INLINE) .collect(toImmutableSet()); abstract String name(); abstract TagType type(); enum TagType { BLOCK, INLINE } static JavadocTag blockTag(String name) { return of(name, TagType.BLOCK); } static JavadocTag inlineTag(String name) { return of(name, TagType.INLINE); } private static JavadocTag of(String name, TagType type) { return new AutoValue_JavadocTag(name, type); } }
3,800
30.413223
82
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/InvalidBlockTag.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.javadoc; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.JavadocTag.blockTag; import static com.google.errorprone.bugpatterns.javadoc.JavadocTag.inlineTag; import static com.google.errorprone.bugpatterns.javadoc.Utils.diagnosticPosition; import static com.google.errorprone.bugpatterns.javadoc.Utils.replace; 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.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.doctree.DocTree; import com.sun.source.doctree.EndElementTree; import com.sun.source.doctree.ErroneousTree; import com.sun.source.doctree.StartElementTree; import com.sun.source.doctree.UnknownBlockTagTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; import com.sun.tools.javac.tree.DCTree.DCBlockTag; import com.sun.tools.javac.tree.DCTree.DCDocComment; import com.sun.tools.javac.tree.DCTree.DCErroneous; import com.sun.tools.javac.util.JCDiagnostic; import java.util.HashSet; import java.util.Optional; import java.util.Set; /** * Matches invalid Javadoc tags, and tries to suggest fixes. * * @author ghm@google.com (Graeme Morgan) */ @BugPattern(summary = "This tag is invalid.", severity = WARNING, documentSuppression = false) public final class InvalidBlockTag extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { /** * HTML tags which imply we're showing code, and should therefore probably escape unknown block * tags. */ private static final ImmutableSet<String> CODE_TAGS = ImmutableSet.of("code", "pre"); @Override public Description matchClass(ClassTree classTree, VisitorState state) { DocTreePath path = Utils.getDocTreePath(state); if (path != null) { ImmutableSet<String> parameters = ImmutableSet.of(); new InvalidTagChecker(state, JavadocTag.VALID_CLASS_TAGS, parameters).scan(path, null); } return Description.NO_MATCH; } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { DocTreePath path = Utils.getDocTreePath(state); if (path != null) { ImmutableSet<String> parameters = methodTree.getParameters().stream() .map(v -> v.getName().toString()) .collect(toImmutableSet()); new InvalidTagChecker(state, JavadocTag.VALID_METHOD_TAGS, parameters).scan(path, null); } return Description.NO_MATCH; } @Override public Description matchVariable(VariableTree variableTree, VisitorState state) { DocTreePath path = Utils.getDocTreePath(state); if (path != null) { new InvalidTagChecker( state, JavadocTag.VALID_VARIABLE_TAGS, /* parameters= */ ImmutableSet.of()) .scan(path, null); } return Description.NO_MATCH; } private final class InvalidTagChecker extends DocTreePathScanner<Void, Void> { private final VisitorState state; private final ImmutableSet<JavadocTag> validTags; private final ImmutableSet<String> parameters; private final Set<DocTree> fixedTags = new HashSet<>(); private int codeTagNestedDepth = 0; private InvalidTagChecker( VisitorState state, ImmutableSet<JavadocTag> validTags, ImmutableSet<String> parameters) { this.state = state; this.validTags = validTags; this.parameters = parameters; } @Override public Void visitStartElement(StartElementTree startElementTree, Void unused) { if (CODE_TAGS.contains(startElementTree.getName().toString())) { codeTagNestedDepth++; } return super.visitStartElement(startElementTree, null); } @Override public Void visitEndElement(EndElementTree endElementTree, Void unused) { if (CODE_TAGS.contains(endElementTree.getName().toString())) { codeTagNestedDepth--; } return super.visitEndElement(endElementTree, null); } @Override public Void visitErroneous(ErroneousTree erroneousTree, Void unused) { JCDiagnostic diagnostic = ((DCErroneous) erroneousTree).diag; if (!diagnostic.getCode().equals("compiler.err.dc.bad.inline.tag")) { return null; } JavadocTag tag = inlineTag(erroneousTree.toString().replace("@", "")); SuggestedFix fix = validTags.contains(tag) ? replace(erroneousTree, String.format("{%s}", erroneousTree), state) : SuggestedFix.emptyFix(); String message = String.format( "%s is not a valid block tag. Should it be an inline tag instead?", erroneousTree); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .addFix(fix) .build()); return null; } @Override public Void visitUnknownBlockTag(UnknownBlockTagTree unknownBlockTagTree, Void unused) { String tagName = unknownBlockTagTree.getTagName(); JavadocTag tag = blockTag(tagName); if (JavadocTag.KNOWN_OTHER_TAGS.contains(tag)) { return super.visitUnknownBlockTag(unknownBlockTagTree, null); } if (codeTagNestedDepth > 0) { // If we're in a <code> tag, this is probably meant to be an annotation. if (parentIsErroneousCodeTag()) { String message = String.format("@%s is interpreted as a block tag here, not as a literal.", tagName); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .build()); fixedTags.add(unknownBlockTagTree); return super.visitUnknownBlockTag(unknownBlockTagTree, null); } int startPos = Utils.getStartPosition(unknownBlockTagTree, state); String message = String.format( "@%s is not a valid block tag. Did you mean to escape it? Annotations must be" + " escaped even within <pre> and <code>, but will be rendered correctly inside" + " {@code blocks.", tagName); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .addFix(SuggestedFix.replace(startPos, startPos + 1, "{@literal @}")) .build()); fixedTags.add(unknownBlockTagTree); return super.visitUnknownBlockTag(unknownBlockTagTree, null); } if (parameters.contains(tagName)) { int startPos = Utils.getStartPosition(unknownBlockTagTree, state); String message = String.format( "@%1$s is not a valid tag, but is a parameter name. " + "Use {@code %1$s} to refer to parameter names inline.", tagName); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .addFix(SuggestedFix.replace(startPos, startPos + 1, "@param ")) .build()); fixedTags.add(unknownBlockTagTree); return super.visitUnknownBlockTag(unknownBlockTagTree, null); } reportUnknownTag(unknownBlockTagTree, tag); return super.visitUnknownBlockTag(unknownBlockTagTree, null); } /** * When we have an erroneous block tag inside a {@literal @}code tag, the enclosing * {@literal @}code tag will fail to parse. So, we're looking for an enclosing erroneous tag. */ private boolean parentIsErroneousCodeTag() { if (getCurrentPath().getParentPath() == null) { return false; } DocTree parentDoc = getCurrentPath().getParentPath().getLeaf(); if (!(parentDoc instanceof DCDocComment)) { return false; } DCDocComment dcDocComment = (DCDocComment) parentDoc; return dcDocComment.getFullBody().stream() .anyMatch( dc -> dc instanceof DCErroneous && ((DCErroneous) dc).body.startsWith("{@code")); } private void reportUnknownTag(DocTree docTree, JavadocTag tag) { Optional<String> bestMatch = Utils.getBestMatch( tag.name(), /* maxEditDistance= */ 2, validTags.stream() .filter(t -> t.type().equals(tag.type())) .map(JavadocTag::name) .collect(toImmutableSet())); int pos = Utils.getStartPosition(docTree, state) + docTree.toString().indexOf(tag.name()); String message = String.format("Tag name `%s` is unknown.", tag.name()); state.reportMatch( bestMatch .map( bm -> buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message + String.format(" Did you mean tag `%s`?", bm)) .addFix(SuggestedFix.replace(pos, pos + tag.name().length(), bm)) .build()) .orElse( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage( message + " If this is a commonly-used custom tag, please " + "click 'not useful' and file a bug.") .build())); fixedTags.add(docTree); } @Override public Void scan(DocTree docTree, Void unused) { super.scan(docTree, null); // Don't complain about this unknown tag if we already generated a better fix for it. if (fixedTags.contains(docTree)) { return null; } if (!(docTree instanceof DCBlockTag)) { return null; } JavadocTag tag = blockTag(((DCBlockTag) docTree).getTagName()); if (validTags.contains(tag) || JavadocTag.KNOWN_OTHER_TAGS.contains(tag)) { return null; } String message = String.format("The tag @%s is not allowed on this type of element.", tag.name()); state.reportMatch( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage(message) .addFix(Utils.replace(docTree, "", state)) .build()); return null; } } }
11,518
39.992883
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/MalformedInlineTag.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.javadoc; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.getDiagnosticPosition; 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.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.DocTreePath; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.tree.DCTree.DCDocComment; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Finds malformed inline tags where {@literal @}{tag is used instead of {{@literal @}tag. * * @author aaronhurst@google.com (Aaron Hurst) */ @BugPattern( summary = "This Javadoc tag is malformed. The correct syntax is {@tag and not @{tag.", severity = WARNING, documentSuppression = false) public final class MalformedInlineTag extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { private static final Pattern MALFORMED_PATTERN = Pattern.compile( "@\\{(" + JavadocTag.ALL_INLINE_TAGS.stream().map(JavadocTag::name).collect(joining("|")) + ")"); @Override public Description matchClass(ClassTree classTree, VisitorState state) { return handle(state); } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { return handle(state); } @Override public Description matchVariable(VariableTree variableTree, VisitorState state) { return handle(state); } /** * Main action on each class/method/variable Javadoc comment. * * <p>Match all instances of the malformed regex pattern in the full comment text. There isn't any * benefit to iterating over the parsed tree, as the syntax errors can appear anywhere and won't * be parsed. */ private Description handle(VisitorState state) { DocTreePath path = Utils.getDocTreePath(state); if (path == null) { return Description.NO_MATCH; } Comment comment = ((DCDocComment) path.getDocComment()).comment; Matcher matcher = MALFORMED_PATTERN.matcher(comment.getText()); while (matcher.find()) { String tag = matcher.group(1); int startPos = comment.getSourcePos(matcher.start()); int endPos = comment.getSourcePos(matcher.end()); state.reportMatch( buildDescription(getDiagnosticPosition(startPos, path.getTreePath().getLeaf())) .setMessage(String.format("The correct syntax to open this inline tag is {@%s.", tag)) .addFix(SuggestedFix.replace(startPos, endPos, "{@" + tag)) .build()); } // Intentionally returning NO_MATCH here, because multiple findings are reported above return Description.NO_MATCH; } }
3,902
36.528846
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/UnescapedEntity.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.javadoc; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.javadoc.Utils.diagnosticPosition; import static com.google.errorprone.bugpatterns.javadoc.Utils.getDiagnosticPosition; import static com.google.errorprone.bugpatterns.javadoc.Utils.getEndPosition; import static com.google.errorprone.bugpatterns.javadoc.Utils.getStartPosition; import static com.google.errorprone.bugpatterns.javadoc.Utils.replace; import static com.google.errorprone.matchers.Description.NO_MATCH; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Range; import com.google.common.collect.RangeSet; import com.google.common.collect.TreeRangeSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.doctree.DocTree; import com.sun.source.doctree.EndElementTree; import com.sun.source.doctree.ErroneousTree; import com.sun.source.doctree.LinkTree; import com.sun.source.doctree.LiteralTree; import com.sun.source.doctree.SeeTree; import com.sun.source.doctree.StartElementTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.tree.DCTree.DCDocComment; import com.sun.tools.javac.util.Position; import java.util.ArrayDeque; import java.util.Deque; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; /** * Finds unescaped entities in Javadocs. * * @author ghm@google.com (Graeme Morgan) */ @BugPattern( summary = "Javadoc is interpreted as HTML, so HTML entities such as &, <, > must be escaped. If this" + " finding seems wrong (e.g. is within a @code or @literal tag), check whether the tag" + " could be malformed and not recognised by the compiler.", severity = WARNING, documentSuppression = false) public final class UnescapedEntity extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { private static final ImmutableSet<String> PRE_TAGS = ImmutableSet.of("pre", "code"); private static final String TYPE = "[A-Z][a-zA-Z0-9_]*"; private static final String TYPE_PARAMETERS = "[A-Z][A-Za-z0-9,.& ]+"; private static final Pattern GENERIC_PATTERN = Pattern.compile( String.format("(%s<%s>|%s<%s<%s>>)", TYPE, TYPE_PARAMETERS, TYPE, TYPE, TYPE_PARAMETERS)); /** * Pattern for code/literal tags which should not be wrapped in a code tag, as they contain HTML * entities, annotations, or other tags. */ private static final Pattern SHOULD_NOT_WRAP = Pattern.compile("&[a-zA-Z0-9]+;|&#[0-9]+;|&#x[0-9a-fA-F]+;|\n *\\*\\s*@|\\{@(literal|code)"); @Override public Description matchClass(ClassTree classTree, VisitorState state) { return handle(Utils.getDocTreePath(state), state); } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { return handle(Utils.getDocTreePath(state), state); } @Override public Description matchVariable(VariableTree variableTree, VisitorState state) { return handle(Utils.getDocTreePath(state), state); } private Description handle(@Nullable DocTreePath path, VisitorState state) { if (path == null) { return NO_MATCH; } RangesFinder rangesFinder = new RangesFinder(state); rangesFinder.scan(path, null); Comment comment = ((DCDocComment) path.getDocComment()).comment; Matcher matcher = GENERIC_PATTERN.matcher(comment.getText()); RangeSet<Integer> generics = TreeRangeSet.create(); while (matcher.find()) { generics.add( Range.closedOpen( comment.getSourcePos(matcher.start()), comment.getSourcePos(matcher.end()))); } RangeSet<Integer> emittedFixes = fixGenerics(generics, rangesFinder.preTags, rangesFinder.dontEmitCodeFix, state); new EntityChecker(state, generics, rangesFinder.preTags, emittedFixes).scan(path, null); return NO_MATCH; } private RangeSet<Integer> fixGenerics( RangeSet<Integer> generics, RangeSet<Integer> preTags, RangeSet<Integer> dontEmitCodeFix, VisitorState state) { RangeSet<Integer> emittedFixes = TreeRangeSet.create(); for (Range<Integer> range : generics.asRanges()) { if (emittedFixes.intersects(range) || dontEmitCodeFix.intersects(range)) { continue; } Range<Integer> regionToWrap = preTags.rangeContaining(range.lowerEndpoint()); if (regionToWrap == null) { regionToWrap = range; } emittedFixes.add(regionToWrap); state.reportMatch( buildDescription(getDiagnosticPosition(range.lowerEndpoint(), state.getPath().getLeaf())) .setMessage( "This looks like a type with type parameters. The < and > characters here will " + "be interpreted as HTML, which can be avoided by wrapping it in a " + "{@code } tag.") .addFix(wrapInCodeTag(regionToWrap)) .build()); } return emittedFixes; } private static final class RangesFinder extends DocTreePathScanner<Void, Void> { private final VisitorState state; /** * Ranges of {@code <pre>} and {@code <code>} tags that could reasonably have an inner * {@literal @}code tag put inside them to escape HTML. */ private final RangeSet<Integer> preTags = TreeRangeSet.create(); /** * Ranges of source code which should not have an inner {@literal @}code tag. This could be * because they're already escaping literals, or because it's a {@code <pre>} block with * already-escaped HTML. */ private final RangeSet<Integer> dontEmitCodeFix = TreeRangeSet.create(); private final Deque<Integer> startPosStack = new ArrayDeque<>(); private boolean containsAnotherTag = false; private RangesFinder(VisitorState state) { this.state = state; } @Override public Void visitStartElement(StartElementTree startTree, Void unused) { if (PRE_TAGS.contains(startTree.getName().toString())) { startPosStack.offerLast(getEndPosition(startTree, state)); containsAnotherTag = false; } return super.visitStartElement(startTree, null); } @Override public Void visitEndElement(EndElementTree endTree, Void unused) { if (PRE_TAGS.contains(endTree.getName().toString())) { if (!containsAnotherTag) { Integer startPos = startPosStack.pollLast(); if (startPos != null) { int endPos = getStartPosition(endTree, state); String source = state.getSourceCode().subSequence(startPos, endPos).toString(); if (SHOULD_NOT_WRAP.matcher(source).find()) { dontEmitCodeFix.add(Range.closed(startPos, endPos)); } else { preTags.add(Range.closed(startPos, endPos)); } } } containsAnotherTag = true; return super.visitEndElement(endTree, null); } return super.visitEndElement(endTree, null); } @Override public Void visitLink(LinkTree linkTree, Void unused) { excludeFromCodeFixes(linkTree); return super.visitLink(linkTree, null); } @Override public Void visitLiteral(LiteralTree literalTree, Void unused) { excludeFromCodeFixes(literalTree); return super.visitLiteral(literalTree, null); } @Override public Void visitSee(SeeTree seeTree, Void unused) { excludeFromCodeFixes(seeTree); return super.visitSee(seeTree, null); } private void excludeFromCodeFixes(DocTree tree) { int endPos = getEndPosition(tree, state); if (endPos != Position.NOPOS) { dontEmitCodeFix.add(Range.closed(getStartPosition(tree, state), endPos)); } } } private final class EntityChecker extends DocTreePathScanner<Void, Void> { private final VisitorState state; private final RangeSet<Integer> generics; private final RangeSet<Integer> preTags; private final RangeSet<Integer> emittedFixes; private EntityChecker( VisitorState state, RangeSet<Integer> generics, RangeSet<Integer> preTags, RangeSet<Integer> emittedFixes) { this.state = state; this.generics = generics; this.preTags = preTags; this.emittedFixes = emittedFixes; } @Override public Void visitErroneous(ErroneousTree erroneousTree, Void unused) { if (erroneousTree.getBody().equals("&")) { generateFix("&amp;").ifPresent(state::reportMatch); return super.visitErroneous(erroneousTree, null); } if (erroneousTree.getBody().equals("<")) { generateFix("&lt;").ifPresent(state::reportMatch); return super.visitErroneous(erroneousTree, null); } if (erroneousTree.getBody().equals(">")) { generateFix("&gt;").ifPresent(state::reportMatch); return super.visitErroneous(erroneousTree, null); } return super.visitErroneous(erroneousTree, null); } private Optional<Description> generateFix(String replacement) { int startPosition = getStartPosition(getCurrentPath().getLeaf(), state); if (emittedFixes.contains(startPosition)) { // We already emitted a fix surrounding this location. return Optional.empty(); } Range<Integer> containingPre = preTags.rangeContaining(startPosition); if (containingPre == null) { return generics.contains(startPosition) ? Optional.of(replacementFix(replacement)) : Optional.empty(); } if (emittedFixes.intersects(containingPre)) { return Optional.empty(); } emittedFixes.add(containingPre); SuggestedFix fix = wrapInCodeTag(containingPre); return Optional.of( buildDescription(diagnosticPosition(getCurrentPath(), state)) .setMessage( "This HTML entity is invalid. Enclosing the code in this <pre>/<code> tag with" + " a {@code } block will force Javadoc to interpret HTML literally.") .addFix(fix) .build()); } private Description replacementFix(String replacement) { return describeMatch( diagnosticPosition(getCurrentPath(), state), replace(getCurrentPath().getLeaf(), replacement, state)); } } private static SuggestedFix wrapInCodeTag(Range<Integer> containingPre) { return SuggestedFix.builder() .replace(containingPre.lowerEndpoint(), containingPre.lowerEndpoint(), "{@code ") .replace(containingPre.upperEndpoint(), containingPre.upperEndpoint(), "}") .build(); } }
11,957
37.574194
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/Matchers.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.argumentselectiondefects; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.enclosingMethod; import static com.google.errorprone.matchers.Matchers.hasAnnotation; import static com.google.errorprone.matchers.Matchers.hasArguments; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.matchers.Matchers.staticMethod; import com.google.errorprone.VisitorState; import com.google.errorprone.matchers.ChildMultiMatcher.MatchType; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; 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.List; import java.util.regex.Pattern; /** * Matchers for the various checkers in this package. They are factored out into this class so that * {@code ArgumentSelectionDefectChecker} can avoid reporting duplicate findings that the other * checkers would have found * * @author andrewrice@google.com (Andrew Rice) */ final class Matchers { /** Matches if the tree is a constructor for an AutoValue class. */ static final Matcher<NewClassTree> AUTOVALUE_CONSTRUCTOR = new Matcher<NewClassTree>() { @Override public boolean matches(NewClassTree tree, VisitorState state) { MethodSymbol sym = ASTHelpers.getSymbol(tree); ClassSymbol owner = (ClassSymbol) sym.owner; if (owner == null) { return false; } Type superType = owner.getSuperclass(); if (superType == null) { return false; } Symbol superSymbol = superType.tsym; if (superSymbol == null) { return false; } if (!ASTHelpers.hasDirectAnnotationWithSimpleName(superSymbol, "AutoValue")) { return false; } return true; } }; // if any of the arguments are instances of throwable then abort - people like to use // 'expected' as the name of the exception they are expecting private static final Matcher<MethodInvocationTree> ARGUMENT_EXTENDS_TRHOWABLE = hasArguments(MatchType.AT_LEAST_ONE, isSubtypeOf(Throwable.class)); // if the method is a refaster-before template then it might be explicitly matching bad behaviour private static final Matcher<MethodInvocationTree> METHOD_ANNOTATED_WITH_BEFORETEMPLATE = enclosingMethod(hasAnnotation("com.google.errorprone.refaster.annotation.BeforeTemplate")); private static final Matcher<MethodInvocationTree> TWO_PARAMETER_ASSERT = new Matcher<MethodInvocationTree>() { @Override public boolean matches(MethodInvocationTree tree, VisitorState state) { List<VarSymbol> parameters = ASTHelpers.getSymbol(tree).getParameters(); if (parameters.size() != 2) { return false; } return ASTHelpers.isSameType( parameters.get(0).asType(), parameters.get(1).asType(), state); } }; private static final Matcher<MethodInvocationTree> THREE_PARAMETER_ASSERT = new Matcher<MethodInvocationTree>() { @Override public boolean matches(MethodInvocationTree tree, VisitorState state) { List<VarSymbol> parameters = ASTHelpers.getSymbol(tree).getParameters(); if (parameters.size() != 3) { return false; } return ASTHelpers.isSameType( parameters.get(0).asType(), state.getSymtab().stringType, state) && ASTHelpers.isSameType( parameters.get(1).asType(), parameters.get(2).asType(), state); } }; /** Matches if the tree corresponds to an assertEquals-style method */ static final Matcher<MethodInvocationTree> ASSERT_METHOD = allOf( staticMethod() .onClassAny( "org.junit.Assert", "junit.framework.TestCase", "junit.framework.Assert", /* this final case is to allow testing without using the junit classes. we need to do this because the junit dependency might not have been compiled with parameters information which would cause the tests to fail.*/ "ErrorProneTest") .withNameMatching(Pattern.compile("assert.*")), anyOf(TWO_PARAMETER_ASSERT, THREE_PARAMETER_ASSERT), not(ARGUMENT_EXTENDS_TRHOWABLE), not(METHOD_ANNOTATED_WITH_BEFORETEMPLATE)); private Matchers() {} }
5,595
39.846715
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/PenaltyThresholdHeuristic.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.argumentselectiondefects; import com.google.errorprone.VisitorState; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol.MethodSymbol; /** * Heuristic to keep suggestions which score sufficiently different to the original. The idea is * that we should leave the arguments alone if we are not sure we can swap them so if the overall * score of the alternative is not significantly better than the original we want to leave the * original in place. * * @author andrewrice@google.com (Andrew Rice) */ class PenaltyThresholdHeuristic implements Heuristic { private final double threshold; private static final double DEFAULT_THRESHOLD = 0.6; PenaltyThresholdHeuristic(double threshold) { this.threshold = threshold; } /** Constructs an instance using the default threshold value. */ PenaltyThresholdHeuristic() { this(DEFAULT_THRESHOLD); } /** Return true if the change is sufficiently different. */ @Override public boolean isAcceptableChange( Changes changes, Tree node, MethodSymbol symbol, VisitorState state) { int numberOfChanges = changes.changedPairs().size(); return changes.totalOriginalCost() - changes.totalAssignmentCost() >= threshold * numberOfChanges; } }
1,907
32.473684
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/NameInCommentHeuristic.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.argumentselectiondefects; import com.google.common.collect.ImmutableList; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.argumentselectiondefects.NamedParameterComment.MatchType; import com.google.errorprone.util.Commented; import com.google.errorprone.util.Comments; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol.MethodSymbol; /** * Heuristic to detect if the name for the formal parameter has been used in the comment for an * actual parameter - if it has then we shouldn't swap that parameter. * * @author andrewrice@google.com (Andrew Rice) */ class NameInCommentHeuristic implements Heuristic { /** * Return true if there are no comments on the original actual parameter of a change which match * the name of the formal parameter. */ @Override public boolean isAcceptableChange( Changes changes, Tree node, MethodSymbol symbol, VisitorState state) { // Now check to see if there is a comment in the position of any actual parameter we want to // change which matches the formal parameter ImmutableList<Commented<ExpressionTree>> comments = findCommentsForArguments(node, state); return changes.changedPairs().stream() .noneMatch( p -> { MatchType match = NamedParameterComment.match(comments.get(p.formal().index()), p.formal().name()) .matchType(); return match == MatchType.EXACT_MATCH || match == MatchType.APPROXIMATE_MATCH; }); } private static ImmutableList<Commented<ExpressionTree>> findCommentsForArguments( Tree tree, VisitorState state) { switch (tree.getKind()) { case METHOD_INVOCATION: return Comments.findCommentsForArguments((MethodInvocationTree) tree, state); case NEW_CLASS: return Comments.findCommentsForArguments((NewClassTree) tree, state); default: throw new IllegalArgumentException( "Only MethodInvocationTree or NewClassTree is supported"); } } }
2,847
38.555556
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/Costs.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.argumentselectiondefects; import static com.google.common.collect.ImmutableList.toImmutableList; import blogspot.software_and_algorithms.stern_library.optimization.HungarianAlgorithm; import com.google.common.collect.ImmutableList; import java.util.stream.Stream; /** * Accumulates the various costs of using existing arguments or alternatives. These are modelled as * edge weights in a bipartite graph mapping parameters on to potential arguments. The {@link * #computeAssignments()} function can then be used to find the optimal assignment of parameters to * arguments. * * @author andrewrice@google.com (Andrew Rice) */ class Costs { /** Formal parameters for the method being called. */ private final ImmutableList<Parameter> formals; /** Actual parameters (argments) for the method call. */ private final ImmutableList<Parameter> actuals; /** * The cost matrix of distances: Element (i,j) is the distance between the ith formal parameter * and the name of the jth actual parameter. The next stages assign costs to the elements of this * matrix using Infinity to indicate that this alternative should not be considered. We will refer * to combinations of formal parameter and (potential) actual parameter as pairs. */ private final double[][] costMatrix; Costs(ImmutableList<Parameter> formals, ImmutableList<Parameter> actuals) { this.formals = formals; this.actuals = actuals; this.costMatrix = new double[formals.size()][actuals.size()]; } Changes computeAssignments() { int[] assignments = new HungarianAlgorithm(costMatrix).execute(); ImmutableList<Parameter> formalsWithChange = formals.stream() .filter(f -> assignments[f.index()] != f.index()) .collect(toImmutableList()); if (formalsWithChange.isEmpty()) { return Changes.empty(); } ImmutableList<Double> originalCost = formalsWithChange.stream() .map(f2 -> costMatrix[f2.index()][f2.index()]) .collect(toImmutableList()); ImmutableList<Double> assignmentCost = formalsWithChange.stream() .map(f1 -> costMatrix[f1.index()][assignments[f1.index()]]) .collect(toImmutableList()); ImmutableList<ParameterPair> changes = formalsWithChange.stream() .map(f -> ParameterPair.create(f, actuals.get(assignments[f.index()]))) .collect(toImmutableList()); return Changes.create(originalCost, assignmentCost, changes); } /** * Constructs a stream for every element of formals paired with every element of actuals (cross * product). Each item contains the formal and the actual, which in turn contain their index into * the cost matrix. Elements whose cost is Inf in the cost matrix are filtered out so only viable * pairings remain. */ Stream<ParameterPair> viablePairs() { return formals.stream() .flatMap(f -> actuals.stream().map(a -> ParameterPair.create(f, a))) .filter( p -> costMatrix[p.formal().index()][p.actual().index()] != Double.POSITIVE_INFINITY); } /** Update the cost of the given pairing. */ void updatePair(ParameterPair p, double cost) { costMatrix[p.formal().index()][p.actual().index()] = cost; } /** Set the cost of this pairing to be Inf. */ void invalidatePair(ParameterPair p) { updatePair(p, Double.POSITIVE_INFINITY); } @Override public String toString() { StringBuilder builder = new StringBuilder("Costs:\n"); builder.append("formals=").append(formals).append("\n"); builder.append("actuals=").append(actuals).append("\n"); builder.append("costMatrix=\n"); builder.append(String.format("%20s", "")); for (int j = 0; j < costMatrix[0].length; j++) { builder.append(String.format("%20s", actuals.get(j).name())); } builder.append("\n"); for (int i = 0; i < costMatrix.length; i++) { builder.append(String.format("%20s", formals.get(i).name())); for (int j = 0; j < costMatrix[i].length; j++) { builder.append(String.format("%20.1f", costMatrix[i][j])); } builder.append("\n"); } return builder.toString(); } }
4,837
36.796875
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/Parameter.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.argumentselectiondefects; import static com.google.common.collect.ImmutableList.toImmutableList; import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Streams; import com.google.errorprone.VisitorState; import com.google.errorprone.names.NamingConventions; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.CompletionFailure; 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.comp.Check; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import java.util.List; import java.util.Optional; /** * Represents either a formal or actual parameter and its position in the argument list. * * @author andrewrice@google.com (Andrew Rice) */ @AutoValue abstract class Parameter { private static final ImmutableSet<String> METHODNAME_PREFIXES_TO_REMOVE = ImmutableSet.of("get", "set", "is"); /** We use this placeholder to indicate a name which is a null literal. */ @VisibleForTesting static final String NAME_NULL = "*NULL*"; /** We use this placeholder to indicate a name which we couldn't get a canonical string for. */ @VisibleForTesting static final String NAME_NOT_PRESENT = "*NOT_PRESENT*"; abstract String name(); abstract Type type(); abstract int index(); abstract String text(); abstract Kind kind(); abstract boolean constant(); static ImmutableList<Parameter> createListFromVarSymbols(List<VarSymbol> varSymbols) { return Streams.mapWithIndex( varSymbols.stream(), (s, i) -> new AutoValue_Parameter( s.getSimpleName().toString(), s.asType(), (int) i, s.getSimpleName().toString(), Kind.IDENTIFIER, false)) .collect(toImmutableList()); } static ImmutableList<Parameter> createListFromExpressionTrees( List<? extends ExpressionTree> trees) { return Streams.mapWithIndex( trees.stream(), (t, i) -> new AutoValue_Parameter( getArgumentName(t), Optional.ofNullable(ASTHelpers.getResultType(t)).orElse(Type.noType), (int) i, t.toString(), t.getKind(), ASTHelpers.constValue(t) != null)) .collect(toImmutableList()); } static ImmutableList<Parameter> createListFromVariableTrees(List<? extends VariableTree> trees) { return createListFromVarSymbols( trees.stream().map(ASTHelpers::getSymbol).collect(toImmutableList())); } /** * Return true if this parameter is assignable to the target parameter. This will consider * subclassing, autoboxing and null. */ boolean isAssignableTo(Parameter target, VisitorState state) { if (state.getTypes().isSameType(type(), Type.noType) || state.getTypes().isSameType(target.type(), Type.noType)) { return false; } try { return state.getTypes().isAssignable(type(), target.type()); } catch (CompletionFailure e) { // Report completion errors to avoid e.g. https://github.com/bazelbuild/bazel/issues/4105 Check.instance(state.context) .completionError((DiagnosticPosition) state.getPath().getLeaf(), e); return false; } } boolean isNullLiteral() { return name().equals(NAME_NULL); } boolean isUnknownName() { return name().equals(NAME_NOT_PRESENT); } private static String getClassName(ClassSymbol s) { if (s.isAnonymous()) { return s.getSuperclass().tsym.getSimpleName().toString(); } else { return s.getSimpleName().toString(); } } /** * Extract the name from an argument. * * <p> * * <ul> * <li>IdentifierTree - if the identifier is 'this' then use the name of the enclosing class, * otherwise use the name of the identifier * <li>MemberSelectTree - the name of its identifier * <li>NewClassTree - the name of the class being constructed * <li>Null literal - a wildcard name * <li>MethodInvocationTree - use the method name stripping off 'get', 'set', 'is' prefix. If * this results in an empty name then recursively search the receiver * </ul> * * All other trees (including literals other than Null literal) do not have a name and this method * will return the marker for an unknown name. */ @VisibleForTesting static String getArgumentName(ExpressionTree expressionTree) { switch (expressionTree.getKind()) { case MEMBER_SELECT: return ((MemberSelectTree) expressionTree).getIdentifier().toString(); case NULL_LITERAL: // null could match anything pretty well return NAME_NULL; case IDENTIFIER: IdentifierTree idTree = (IdentifierTree) expressionTree; if (idTree.getName().contentEquals("this")) { // for the 'this' keyword the argument name is the name of the object's class Symbol sym = ASTHelpers.getSymbol(idTree); return sym != null ? getClassName(ASTHelpers.enclosingClass(sym)) : NAME_NOT_PRESENT; } else { // if we have a variable, just extract its name return idTree.getName().toString(); } case METHOD_INVOCATION: MethodInvocationTree methodInvocationTree = (MethodInvocationTree) expressionTree; MethodSymbol methodSym = ASTHelpers.getSymbol(methodInvocationTree); String name = methodSym.getSimpleName().toString(); ImmutableList<String> terms = NamingConventions.splitToLowercaseTerms(name); String firstTerm = Iterables.getFirst(terms, null); if (METHODNAME_PREFIXES_TO_REMOVE.contains(firstTerm)) { if (terms.size() == 1) { ExpressionTree receiver = ASTHelpers.getReceiver(methodInvocationTree); if (receiver == null) { return getClassName(ASTHelpers.enclosingClass(methodSym)); } // recursively try to get a name from the receiver return getArgumentName(receiver); } else { return name.substring(firstTerm.length()); } } else { return name; } case NEW_CLASS: MethodSymbol constructorSym = ASTHelpers.getSymbol((NewClassTree) expressionTree); return constructorSym.owner != null ? getClassName((ClassSymbol) constructorSym.owner) : NAME_NOT_PRESENT; default: return NAME_NOT_PRESENT; } } }
7,887
36.207547
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/ArgumentChangeFinder.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.argumentselectiondefects; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.function.Function; /** * Instances of this class are used to find whether there should be argument swaps on a method * invocation. It's general operation is through using the provided distance function to compute the * similarity of a parameter name and an argument name. A change is a permutation of the original * arguments which has the lowest total distance. This is computed as the minimum cost distance * match on the bi-partite graph mapping parameters to assignable arguments. * * @author andrewrice@google.com (Andrew Rice) */ @AutoValue abstract class ArgumentChangeFinder { /** * The distance function to use when comparing formal and actual parameters. The function should * return 0 for highly similar names and larger positive values as names are more different. */ abstract Function<ParameterPair, Double> distanceFunction(); /** List of heuristics to apply to eliminate spurious suggestions. */ abstract ImmutableList<Heuristic> heuristics(); static Builder builder() { return new AutoValue_ArgumentChangeFinder.Builder(); } @AutoValue.Builder abstract static class Builder { /** Set the distance function that {@link ArgumentChangeFinder} should use. */ abstract Builder setDistanceFunction(Function<ParameterPair, Double> distanceFunction); abstract ImmutableList.Builder<Heuristic> heuristicsBuilder(); /** * Add the given heuristic to the list to be considered by {@link ArgumentChangeFinder} for * eliminating spurious findings. Heuristics are applied in order so add more expensive checks * last. */ @CanIgnoreReturnValue Builder addHeuristic(Heuristic heuristic) { heuristicsBuilder().add(heuristic); return this; } abstract ArgumentChangeFinder build(); } /** * Find the optimal permutation of arguments for this method invocation or return {@code * Changes.empty()} if no good permutations were found. */ Changes findChanges(InvocationInfo invocationInfo) { /* Methods with one or fewer parameters cannot possibly have a swap */ if (invocationInfo.formalParameters().size() <= 1) { return Changes.empty(); } /* Sometimes we don't have enough actual parameters. This seems to happen sometimes with calls * to super and javac finds two parameters arg0 and arg1 and no arguments */ if (invocationInfo.actualParameters().size() < invocationInfo.formalParameters().size()) { return Changes.empty(); } ImmutableList<Parameter> formals = Parameter.createListFromVarSymbols(invocationInfo.formalParameters()); ImmutableList<Parameter> actuals = Parameter.createListFromExpressionTrees( invocationInfo.actualParameters().subList(0, invocationInfo.formalParameters().size())); Costs costs = new Costs(formals, actuals); /* Set the distance between a pair to Inf if not assignable */ costs .viablePairs() .filter(ParameterPair::isAlternativePairing) .filter(p -> !p.actual().isAssignableTo(p.formal(), invocationInfo.state())) .forEach(p -> costs.invalidatePair(p)); /* If there are no formal parameters which are assignable to any alternative actual parameters then we can stop without trying to look for permutations */ if (costs.viablePairs().noneMatch(ParameterPair::isAlternativePairing)) { return Changes.empty(); } /* Set the lexical distance between pairs */ costs.viablePairs().forEach(p -> costs.updatePair(p, distanceFunction().apply(p))); Changes changes = costs.computeAssignments(); if (changes.isEmpty()) { return changes; } /* Only keep this change if all of the heuristics match */ for (Heuristic heuristic : heuristics()) { if (!heuristic.isAcceptableChange( changes, invocationInfo.tree(), invocationInfo.symbol(), invocationInfo.state())) { return Changes.empty(); } } return changes; } }
4,821
36.968504
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/AssertEqualsArgumentOrderChecker.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.argumentselectiondefects; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; 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.MethodInvocationTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.TypeSymbol; import java.util.function.Function; import javax.lang.model.element.ElementKind; /** * Checker to make sure that assertEquals-like methods are called with the arguments expected and * actual the right way round. * * <p>Warning: this check relies on recovering parameter names from library class files. These names * are only included if you compile with debugging symbols (-g) or with -parameters. You also need * to tell the compiler to read these names from the classfiles and so must compile your project * with -parameters too. * * @author andrewrice@google.com (Andrew Rice) */ @BugPattern(summary = "Arguments are swapped in assertEquals-like call", severity = WARNING) public class AssertEqualsArgumentOrderChecker extends BugChecker implements MethodInvocationTreeMatcher { private final ArgumentChangeFinder argumentchangeFinder = ArgumentChangeFinder.builder() .setDistanceFunction(buildDistanceFunction()) .addHeuristic(AssertEqualsArgumentOrderChecker::changeMustBeBetterThanOriginal) .addHeuristic(new CreatesDuplicateCallHeuristic()) .addHeuristic(new NameInCommentHeuristic()) .build(); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!Matchers.ASSERT_METHOD.matches(tree, state)) { return Description.NO_MATCH; } MethodSymbol symbol = ASTHelpers.getSymbol(tree); InvocationInfo invocationInfo = InvocationInfo.createFromMethodInvocation(tree, symbol, state); Changes changes = argumentchangeFinder.findChanges(invocationInfo); if (changes.isEmpty()) { return Description.NO_MATCH; } return buildDescription(invocationInfo.tree()) .addFix(changes.buildPermuteArgumentsFix(invocationInfo)) .addFix(changes.buildCommentArgumentsFix(invocationInfo)) .build(); } /** * This function looks explicitly for parameters named expected and actual. All other pairs with * parameters other than these are given a distance of 0 if they are in their original position * and Inf otherwise (i.e. they will not be considered for moving). For expected and actual, if * the actual parameter name starts with expected or actual respectively then we consider it a * perfect match otherwise we return a distance of 1. */ private static Function<ParameterPair, Double> buildDistanceFunction() { return new Function<ParameterPair, Double>() { @Override public Double apply(ParameterPair parameterPair) { Parameter formal = parameterPair.formal(); Parameter actual = parameterPair.actual(); String formalName = formal.name(); String actualName = actual.name(); if (formalName.equals("expected")) { if (actual.constant() || isEnumIdentifier(actual)) { return 0.0; } if (actualName.startsWith("expected")) { return 0.0; } return 1.0; } if (formalName.equals("actual")) { if (actual.constant() || isEnumIdentifier(actual)) { return 1.0; } if (actualName.startsWith("actual")) { return 0.0; } return 1.0; } return formal.index() == actual.index() ? 0.0 : Double.POSITIVE_INFINITY; } }; } /** Returns true if this parameter is an enum identifier */ private static boolean isEnumIdentifier(Parameter parameter) { switch (parameter.kind()) { case IDENTIFIER: case MEMBER_SELECT: break; default: return false; } TypeSymbol typeSymbol = parameter.type().tsym; if (typeSymbol != null) { return typeSymbol.getKind() == ElementKind.ENUM; } return false; } private static boolean changeMustBeBetterThanOriginal( Changes changes, Tree node, MethodSymbol sym, VisitorState state) { return changes.totalAssignmentCost() < changes.totalOriginalCost(); } }
5,250
35.978873
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/Heuristic.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.argumentselectiondefects; import com.google.errorprone.VisitorState; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol.MethodSymbol; /** * A heuristic to apply to a suggested change. If the test method returns false then the change will * be abandoned. * * @author andrewrice@google.com (Andrew Rice) */ interface Heuristic { boolean isAcceptableChange(Changes changes, Tree node, MethodSymbol symbol, VisitorState state); }
1,108
32.606061
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/NamedParameterComment.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.argumentselectiondefects; import com.google.auto.value.AutoValue; import com.google.common.base.CharMatcher; import com.google.common.collect.Streams; import com.google.errorprone.util.Commented; import com.google.errorprone.util.Comments; import com.sun.source.tree.ExpressionTree; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle; import java.util.Arrays; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; /** * Helper methods for checking if a commented argument matches a formal parameter and for generating * comments in the right format. * * <p>We look for a <i>NamedParameterComment</i>: this is the last block comment before the argument * which ends with an equals sign. */ public final class NamedParameterComment { public static final Pattern PARAMETER_COMMENT_PATTERN = Pattern.compile( "\\s*(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*)(\\Q...\\E)?\\s*=\\s*"); private static final String PARAMETER_COMMENT_MARKER = "="; /** Encodes the kind of match we found between a comment and the name of the parameter. */ enum MatchType { /** The NamedParameterComment exactly matches the parameter name. */ EXACT_MATCH, /** The NamedParameterComment doesn't match the parameter name. */ BAD_MATCH, /** * There is no NamedParameterComment but a word in one of the other comments equals the * parameter name. */ APPROXIMATE_MATCH, /** There is no NamedParameterComment and no approximate matches */ NOT_ANNOTATED, } @AutoValue abstract static class MatchedComment { abstract Comment comment(); abstract MatchType matchType(); static MatchedComment create(Comment comment, MatchType matchType) { return new AutoValue_NamedParameterComment_MatchedComment(comment, matchType); } static MatchedComment notAnnotated() { return new AutoValue_NamedParameterComment_MatchedComment( new Comment() { @Override public String getText() { throw new IllegalArgumentException( "Attempt to call getText on comment when in NOT_ANNOTATED state"); } @Override public int getSourcePos(int i) { throw new IllegalArgumentException( "Attempt to call getText on comment when in NOT_ANNOTATED state"); } @Override public CommentStyle getStyle() { throw new IllegalArgumentException( "Attempt to call getText on comment when in NOT_ANNOTATED state"); } @Override public boolean isDeprecated() { throw new IllegalArgumentException( "Attempt to call getText on comment when in NOT_ANNOTATED state"); } }, MatchType.NOT_ANNOTATED); } } private static boolean isApproximateMatchingComment(Comment comment, String formal) { switch (comment.getStyle()) { case BLOCK: case LINE: // sometimes people use comments around arguments for higher level structuring - such as // dividing two separate blocks of arguments. In these cases we want to avoid concluding // that it's a match. Therefore we also check to make sure that the comment is not really // long and that it doesn't contain acsii-art style markup. String commentText = Comments.getTextFromComment(comment); boolean textMatches = Arrays.asList(commentText.split("[^a-zA-Z0-9_]+", -1)).contains(formal); boolean tooLong = commentText.length() > formal.length() + 5 && commentText.length() > 50; boolean tooMuchMarkup = CharMatcher.anyOf("-*!@<>").countIn(commentText) > 5; return textMatches && !tooLong && !tooMuchMarkup; default: return false; } } /** * Determine the kind of match we have between the comments on this argument and the formal * parameter name. */ static MatchedComment match(Commented<ExpressionTree> actual, String formal) { Optional<Comment> lastBlockComment = Streams.findLast( actual.beforeComments().stream().filter(c -> c.getStyle() == CommentStyle.BLOCK)); if (lastBlockComment.isPresent()) { Matcher m = PARAMETER_COMMENT_PATTERN.matcher(Comments.getTextFromComment(lastBlockComment.get())); if (m.matches()) { return MatchedComment.create( lastBlockComment.get(), m.group(1).equals(formal) ? MatchType.EXACT_MATCH : MatchType.BAD_MATCH); } } Optional<Comment> approximateMatchComment = Stream.concat(actual.beforeComments().stream(), actual.afterComments().stream()) .filter(comment -> isApproximateMatchingComment(comment, formal)) .findFirst(); if (approximateMatchComment.isPresent()) { // Report EXACT_MATCH for comments that don't use the recommended style (e.g. `/*foo*/` // instead of `/* foo= */`), but which match the formal parameter name exactly, since it's // a style nit rather than a possible correctness issue. // TODO(cushon): revisit this if we standardize on the recommended comment style. String text = CharMatcher.anyOf("=:") .trimTrailingFrom(Comments.getTextFromComment(approximateMatchComment.get()).trim()); return MatchedComment.create( approximateMatchComment.get(), text.equals(formal) ? MatchType.EXACT_MATCH : MatchType.APPROXIMATE_MATCH); } return MatchedComment.notAnnotated(); } /** * Generate comment text which {@code exactMatch} would consider to match the formal parameter * name. */ static String toCommentText(String formal) { return String.format("/* %s%s */", formal, PARAMETER_COMMENT_MARKER); } // Include: // * enclosing instance parameters, as javac doesn't account for parameters when associating // names (see b/64954766). // * synthetic constructor parameters, e.g. in anonymous classes (see b/65065109) private static final Pattern SYNTHETIC_PARAMETER_NAME = Pattern.compile("(arg|this\\$|x)[0-9]+"); /** * Returns true if the method has synthetic parameter names, indicating the real names are not * available. */ public static boolean containsSyntheticParameterName(MethodSymbol sym) { return sym.getParameters().stream() .anyMatch(p -> SYNTHETIC_PARAMETER_NAME.matcher(p.getSimpleName()).matches()); } private NamedParameterComment() {} }
7,363
37.15544
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/AutoValueConstructorOrderChecker.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.argumentselectiondefects; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; 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.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol; import java.util.function.Function; /** * Checker to make sure that constructors for AutoValue types are invoked with arguments in the * correct order. * * <p>Warning: this check relies on recovering parameter names from library class files. These names * are only included if you compile with debugging symbols (-g) or with -parameters. You also need * to tell the compiler to read these names from the classfiles and so must compile your project * with -parameters too. * * @author andrewrice@google.com (Andrew Rice) */ @BugPattern(summary = "Arguments to AutoValue constructor are in the wrong order", severity = ERROR) public class AutoValueConstructorOrderChecker extends BugChecker implements NewClassTreeMatcher { private final ArgumentChangeFinder argumentChangeFinder = ArgumentChangeFinder.builder() .setDistanceFunction(buildDistanceFunction()) .addHeuristic(AutoValueConstructorOrderChecker::allArgumentsMustMatch) .addHeuristic(new CreatesDuplicateCallHeuristic()) .build(); @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { if (!Matchers.AUTOVALUE_CONSTRUCTOR.matches(tree, state)) { return Description.NO_MATCH; } InvocationInfo invocationInfo = InvocationInfo.createFromNewClass(tree, ASTHelpers.getSymbol(tree), state); Changes changes = argumentChangeFinder.findChanges(invocationInfo); if (changes.isEmpty()) { return Description.NO_MATCH; } return describeMatch(invocationInfo.tree(), changes.buildPermuteArgumentsFix(invocationInfo)); } private static Function<ParameterPair, Double> buildDistanceFunction() { return new Function<ParameterPair, Double>() { @Override public Double apply(ParameterPair parameterPair) { Parameter formal = parameterPair.formal(); Parameter actual = parameterPair.actual(); if (formal.isUnknownName() || actual.isUnknownName()) { return formal.index() == actual.index() ? 0.0 : 1.0; } else { return formal.name().equals(actual.name()) ? 0.0 : 1.0; } } }; } private static boolean allArgumentsMustMatch( Changes changes, Tree node, Symbol.MethodSymbol sym, VisitorState state) { return changes.assignmentCost().stream().allMatch(c -> c < 1.0); } }
3,526
37.758242
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/EnclosedByReverseHeuristic.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.argumentselectiondefects; import com.google.common.collect.ImmutableSet; import com.google.errorprone.VisitorState; import com.google.errorprone.names.NamingConventions; 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 java.util.Optional; import org.checkerframework.checker.nullness.qual.Nullable; /** * Detect whether the method invocation we are examining is enclosed by either a method or a class * which is involved in reversing things. * * @author andrewrice@google.com (Andrew Rice) */ class EnclosedByReverseHeuristic implements Heuristic { private static final ImmutableSet<String> DEFAULT_REVERSE_WORDS_TERMS = ImmutableSet.of( "backward", "backwards", "complement", "endian", "flip", "inverse", "invert", "landscape", "opposite", "portrait", "reciprocal", "reverse", "reversed", "rotate", "rotated", "rotation", "swap", "swapped", "transpose", "transposed", "undo"); private final ImmutableSet<String> reverseWordsTerms; EnclosedByReverseHeuristic() { this(DEFAULT_REVERSE_WORDS_TERMS); } EnclosedByReverseHeuristic(ImmutableSet<String> reverseWordsTerms) { this.reverseWordsTerms = reverseWordsTerms; } /** Return true if this call is not enclosed in a method call about reversing things */ @Override public boolean isAcceptableChange( Changes changes, Tree node, MethodSymbol symbol, VisitorState state) { return findReverseWordsMatchInParentNodes(state) == null; } protected @Nullable String findReverseWordsMatchInParentNodes(VisitorState state) { for (Tree tree : state.getPath()) { Optional<String> name = getName(tree); if (name.isPresent()) { for (String term : NamingConventions.splitToLowercaseTerms(name.get())) { if (reverseWordsTerms.contains(term)) { return term; } } } } return null; } private static Optional<String> getName(Tree tree) { if (tree instanceof MethodTree) { return Optional.of(((MethodTree) tree).getName().toString()); } if (tree instanceof ClassTree) { return Optional.of(((ClassTree) tree).getSimpleName().toString()); } return Optional.empty(); } }
3,154
29.336538
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/InvocationInfo.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.argumentselectiondefects; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.errorprone.VisitorState; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import java.util.List; /** * Holds information about the method invocation (or new class construction) that we are processing. * * @author andrewrice@google.com (Andrew Rice) */ @AutoValue abstract class InvocationInfo { abstract Tree tree(); abstract MethodSymbol symbol(); abstract ImmutableList<? extends ExpressionTree> actualParameters(); abstract ImmutableList<VarSymbol> formalParameters(); abstract VisitorState state(); static InvocationInfo createFromMethodInvocation( MethodInvocationTree tree, MethodSymbol symbol, VisitorState state) { return new AutoValue_InvocationInfo( tree, symbol, ImmutableList.copyOf(tree.getArguments()), getFormalParametersWithoutVarArgs(symbol), state); } static InvocationInfo createFromNewClass( NewClassTree tree, MethodSymbol symbol, VisitorState state) { return new AutoValue_InvocationInfo( tree, symbol, ImmutableList.copyOf(tree.getArguments()), getFormalParametersWithoutVarArgs(symbol), state); } private static ImmutableList<VarSymbol> getFormalParametersWithoutVarArgs( MethodSymbol invokedMethodSymbol) { List<VarSymbol> formalParameters = invokedMethodSymbol.getParameters(); /* javac can get argument names from debugging symbols if they are not available from other sources. When it does this for an inner class sometimes it returns the implicit this pointer for the outer class as the first name (but not the first type). If we see this, then just abort */ if (!formalParameters.isEmpty() && formalParameters.get(0).getSimpleName().toString().matches("this\\$[0-9]+")) { return ImmutableList.of(); } /* If we have a varargs method then just ignore the final parameter and trailing actual parameters */ int size = invokedMethodSymbol.isVarArgs() ? formalParameters.size() - 1 : formalParameters.size(); return ImmutableList.copyOf(formalParameters.subList(0, size)); } }
3,115
34.011236
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/Changes.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.argumentselectiondefects; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.errorprone.fixes.SuggestedFix; import com.sun.source.tree.ExpressionTree; import java.util.stream.Collectors; /** * Value class for holding suggested changes to method call arguments. * * @author andrewrice@google.com (Andrew Rice) */ @AutoValue abstract class Changes { abstract ImmutableList<Double> originalCost(); abstract ImmutableList<Double> assignmentCost(); abstract ImmutableList<ParameterPair> changedPairs(); boolean isEmpty() { return changedPairs().isEmpty(); } double totalAssignmentCost() { return assignmentCost().stream().mapToDouble(d -> d).sum(); } double totalOriginalCost() { return originalCost().stream().mapToDouble(d -> d).sum(); } static Changes create( ImmutableList<Double> originalCost, ImmutableList<Double> assignmentCost, ImmutableList<ParameterPair> changedPairs) { return new AutoValue_Changes(originalCost, assignmentCost, changedPairs); } static Changes empty() { return new AutoValue_Changes(ImmutableList.of(), ImmutableList.of(), ImmutableList.of()); } SuggestedFix buildCommentArgumentsFix(InvocationInfo info) { SuggestedFix.Builder commentArgumentsFixBuilder = SuggestedFix.builder(); for (ParameterPair change : changedPairs()) { int index = change.formal().index(); ExpressionTree actual = info.actualParameters().get(index); int startPosition = getStartPosition(actual); String formal = info.formalParameters().get(index).getSimpleName().toString(); commentArgumentsFixBuilder.replace( startPosition, startPosition, NamedParameterComment.toCommentText(formal)); } return commentArgumentsFixBuilder.build(); } SuggestedFix buildPermuteArgumentsFix(InvocationInfo info) { SuggestedFix.Builder permuteArgumentsFixBuilder = SuggestedFix.builder(); for (ParameterPair pair : changedPairs()) { permuteArgumentsFixBuilder.replace( info.actualParameters().get(pair.formal().index()), // use getSourceForNode to avoid javac pretty printing the replacement (pretty printing // converts unicode characters to unicode escapes) info.state().getSourceForNode(info.actualParameters().get(pair.actual().index()))); } return permuteArgumentsFixBuilder.build(); } public String describe(InvocationInfo info) { return "The following arguments may have been swapped: " + changedPairs().stream() .map( p -> String.format( "'%s' for formal parameter '%s'", info.state() .getSourceForNode(info.actualParameters().get(p.formal().index())), p.formal().name())) .collect(Collectors.joining(", ")) + ". Either add clarifying `/* paramName= */` comments, or swap the arguments if that is" + " what was intended"; } }
3,788
35.432692
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/LowInformationNameHeuristic.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.argumentselectiondefects; import com.google.common.collect.ImmutableSet; import com.google.errorprone.VisitorState; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol.MethodSymbol; import org.checkerframework.checker.nullness.qual.Nullable; /** * A heuristic for checking if a formal parameter matches a predefined set of words which have been * identified as ones which don't have a reliable similarity score. Typically these are words which * are used in many different contexts e.g. {@code key}, {@code value}, {@code str0}. * * @author andrewrice@google.com (Andrew Rice) */ class LowInformationNameHeuristic implements Heuristic { private static final ImmutableSet<String> DEFAULT_FORMAL_PARAMETER_EXCLUSION_REGEXS = ImmutableSet.of( "[a-z][a-z]?[0-9]*", "arg[0-9]", "value", "key", "label", "param[0-9]", "str[0-9]"); private final ImmutableSet<String> overloadedNamesRegexs; LowInformationNameHeuristic(ImmutableSet<String> overloadedNamesRegexs) { this.overloadedNamesRegexs = overloadedNamesRegexs; } LowInformationNameHeuristic() { this(DEFAULT_FORMAL_PARAMETER_EXCLUSION_REGEXS); } /** * Return true if this parameter does not match any of the regular expressions in the list of * overloaded words. */ @Override public boolean isAcceptableChange( Changes changes, Tree node, MethodSymbol symbol, VisitorState state) { return changes.changedPairs().stream().allMatch(p -> findMatch(p.formal()) == null); } /** * Return the first regular expression from the list of overloaded words which matches the * parameter name. */ protected @Nullable String findMatch(Parameter parameter) { for (String regex : overloadedNamesRegexs) { if (parameter.name().matches(regex)) { return regex; } } return null; } }
2,506
34.309859
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/CreatesDuplicateCallHeuristic.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.argumentselectiondefects; import com.google.common.collect.ImmutableList; import com.google.errorprone.VisitorState; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol.MethodSymbol; import java.util.List; import java.util.Objects; /** * Detect whether our suggestion would create a method call which duplicates another one in this * block. * * @author andrewrice@google.com (Andrew Rice) */ class CreatesDuplicateCallHeuristic implements Heuristic { /** * Returns true if there are no other calls to this method which already have an actual parameter * in the position we are moving this one too. */ @Override public boolean isAcceptableChange( Changes changes, Tree node, MethodSymbol symbol, VisitorState state) { return findArgumentsForOtherInstances(symbol, node, state).stream() .allMatch(arguments -> !anyArgumentsMatch(changes.changedPairs(), arguments)); } /** * Return true if the replacement name is equal to the argument name for any replacement position. */ private static boolean anyArgumentsMatch( List<ParameterPair> changedPairs, List<Parameter> arguments) { return changedPairs.stream() .anyMatch( change -> Objects.equals( change.actual().text(), arguments.get(change.formal().index()).text())); } /** * Find all the other calls to {@code calledMethod} within the method (or class) which enclosed * the original call. * * <p>We are interested in two different cases: 1) where there are other calls to the method we * are calling; 2) declarations of the method we are calling (this catches the case when there is * a recursive call with the arguments correctly swapped). * * @param calledMethod is the method call we are analysing for swaps * @param currentNode is the tree node the method call occurred at * @param state is the current visitor state * @return a list containing argument lists for each call found */ private static ImmutableList<List<Parameter>> findArgumentsForOtherInstances( MethodSymbol calledMethod, Tree currentNode, VisitorState state) { Tree enclosingNode = ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class); if (enclosingNode == null) { enclosingNode = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class); } if (enclosingNode == null) { return ImmutableList.of(); } ImmutableList.Builder<List<Parameter>> resultBuilder = ImmutableList.builder(); new TreeScanner<Void, Void>() { @Override public Void visitMethodInvocation(MethodInvocationTree methodInvocationTree, Void unused) { addToResult(ASTHelpers.getSymbol(methodInvocationTree), methodInvocationTree); return super.visitMethodInvocation(methodInvocationTree, unused); } @Override public Void visitNewClass(NewClassTree newClassTree, Void unused) { addToResult(ASTHelpers.getSymbol(newClassTree), newClassTree); return super.visitNewClass(newClassTree, unused); } @Override public Void visitMethod(MethodTree methodTree, Void unused) { MethodSymbol methodSymbol = ASTHelpers.getSymbol(methodTree); // if the method declared here is the one we are calling then add it addToResult(methodSymbol, methodTree); // if any supermethod of the one declared here is the one we are calling then add it for (MethodSymbol superSymbol : ASTHelpers.findSuperMethods(methodSymbol, state.getTypes())) { addToResult(superSymbol, methodTree); } return super.visitMethod(methodTree, unused); } private void addToResult(MethodSymbol foundSymbol, Tree tree) { if (foundSymbol != null && Objects.equals(calledMethod, foundSymbol) && !currentNode.equals(tree)) { resultBuilder.add(createParameterList(tree)); } } private ImmutableList<Parameter> createParameterList(Tree tree) { if (tree instanceof MethodInvocationTree) { return Parameter.createListFromExpressionTrees( ((MethodInvocationTree) tree).getArguments()); } if (tree instanceof NewClassTree) { return Parameter.createListFromExpressionTrees(((NewClassTree) tree).getArguments()); } if (tree instanceof MethodTree) { return Parameter.createListFromVariableTrees(((MethodTree) tree).getParameters()); } return ImmutableList.of(); } }.scan(enclosingNode, null); return resultBuilder.build(); } }
5,545
38.333333
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/ArgumentSelectionDefectChecker.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.argumentselectiondefects; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import com.google.common.annotations.VisibleForTesting; 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.names.NamingConventions; import com.google.errorprone.names.NeedlemanWunschEditDistance; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.tools.javac.code.Symbol.MethodSymbol; import java.util.function.Function; /** * Checks the lexical distance between method parameter names and the argument names at call sites. * If another permutation of the arguments produces a lower distance then it is possible that the * programmer has accidentally reordered them. * * <p>Rice, Andrew, et al. <a href="https://ai.google/research/pubs/pub46317">"Detecting argument * selection defects"</a>. Proceedings of the ACM on Programming Languages OOPSLA (2017). * * <p>Terminology: * * <ul> * <li>Formal parameter - as given in the definition of the method * <li>Actual parameter - as used in the invocation of the method * <li>Parameter - either a formal or actual parameter * </ul> * * @author andrewrice@google.com (Andrew Rice) */ @BugPattern( summary = "Arguments are in the wrong order or could be commented for clarity.", severity = WARNING) public class ArgumentSelectionDefectChecker extends BugChecker implements MethodInvocationTreeMatcher, NewClassTreeMatcher { private final ArgumentChangeFinder argumentChangeFinder; public ArgumentSelectionDefectChecker() { this( ArgumentChangeFinder.builder() .setDistanceFunction(buildDefaultDistanceFunction()) .addHeuristic(new LowInformationNameHeuristic()) .addHeuristic(new PenaltyThresholdHeuristic()) .addHeuristic(new EnclosedByReverseHeuristic()) .addHeuristic(new CreatesDuplicateCallHeuristic()) .addHeuristic(new NameInCommentHeuristic()) .build()); } @VisibleForTesting ArgumentSelectionDefectChecker(ArgumentChangeFinder argumentChangeFinder) { this.argumentChangeFinder = argumentChangeFinder; } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { MethodSymbol symbol = ASTHelpers.getSymbol(tree); // Don't return a match if the AssertEqualsArgumentOrderChecker would match it too if (Matchers.ASSERT_METHOD.matches(tree, state)) { return Description.NO_MATCH; } return visitNewClassOrMethodInvocation( InvocationInfo.createFromMethodInvocation(tree, symbol, state)); } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { MethodSymbol symbol = ASTHelpers.getSymbol(tree); // Don't return a match if the AutoValueConstructorOrderChecker would match it too if (Matchers.AUTOVALUE_CONSTRUCTOR.matches(tree, state)) { return Description.NO_MATCH; } return visitNewClassOrMethodInvocation(InvocationInfo.createFromNewClass(tree, symbol, state)); } private Description visitNewClassOrMethodInvocation(InvocationInfo invocationInfo) { Changes changes = argumentChangeFinder.findChanges(invocationInfo); if (changes.isEmpty()) { return Description.NO_MATCH; } Description.Builder description = buildDescription(invocationInfo.tree()).setMessage(changes.describe(invocationInfo)); // Fix 1 (semantics-preserving): apply comments with parameter names to potentially-swapped // arguments of the method description.addFix(changes.buildCommentArgumentsFix(invocationInfo)); // Fix 2: permute the arguments as required description.addFix(changes.buildPermuteArgumentsFix(invocationInfo)); return description.build(); } /** * Computes the distance between a formal and actual parameter. If either is a null literal then * the distance is zero (null matches everything). If both have a name then we compute the * normalised NeedlemanWunschEditDistance. Otherwise, one of the names is unknown and so we return * 0 distance between it and its original parameter and infinite distance between all others. */ private static Function<ParameterPair, Double> buildDefaultDistanceFunction() { return new Function<ParameterPair, Double>() { @Override public Double apply(ParameterPair pair) { if (pair.formal().isNullLiteral() || pair.actual().isNullLiteral()) { return 0.0; } if (!pair.formal().isUnknownName() && !pair.actual().isUnknownName()) { String normalizedSource = NamingConventions.convertToLowerUnderscore(pair.formal().name()); String normalizedTarget = NamingConventions.convertToLowerUnderscore(pair.actual().name()); return NeedlemanWunschEditDistance.getNormalizedEditDistance( /* source= */ normalizedSource, /* target= */ normalizedTarget, /* caseSensitive= */ false, /* changeCost= */ 8, /* openGapCost= */ 8, /* continueGapCost= */ 1); } return pair.formal().index() == pair.actual().index() ? 0.0 : Double.POSITIVE_INFINITY; } }; } }
6,275
38.721519
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/ParameterPair.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.argumentselectiondefects; import com.google.auto.value.AutoValue; /** * Represents a pair of a formal parameter and an actual parameter. Pairs can correspond to those in * the original method invocation but can also represent potential alternatives and suggested * changes. * * @author andrewrice@google.com (Andrew Rice) */ @AutoValue abstract class ParameterPair { abstract Parameter formal(); abstract Parameter actual(); static ParameterPair create(Parameter formal, Parameter actual) { return new AutoValue_ParameterPair(formal, actual); } boolean isAlternativePairing() { return formal().index() != actual().index(); } }
1,310
29.488372
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/IllegalGuardedBy.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.threadsafety; import com.google.errorprone.annotations.FormatMethod; import com.google.errorprone.annotations.FormatString; /** * An error that occurred during the parsing or binding of a GuardedBy expression. * * @author cushon@google.com (Liam Miller-Cushon) */ public class IllegalGuardedBy extends RuntimeException { public IllegalGuardedBy(String message) { super(message); } /** Throws an {@link IllegalGuardedBy} exception if the given condition is false. */ public static void checkGuardedBy(boolean condition, String message) { if (!condition) { throw new IllegalGuardedBy(message); } } /** Throws an {@link IllegalGuardedBy} exception if the given condition is false. */ @FormatMethod public static void checkGuardedBy( boolean condition, @FormatString String formatString, Object... formatArgs) { if (!condition) { throw new IllegalGuardedBy(String.format(formatString, formatArgs)); } } @Override public String toString() { return getMessage(); } }
1,687
30.849057
86
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableAnnotationChecker.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.threadsafety; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getGeneratedBy; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import 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.annotations.Immutable; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.Violation; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol.ClassSymbol; import java.util.Collections; import java.util.Optional; import javax.inject.Inject; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( name = "ImmutableAnnotationChecker", altNames = "Immutable", summary = "Annotations should always be immutable", severity = WARNING, tags = StandardTags.LIKELY_ERROR) public class ImmutableAnnotationChecker extends BugChecker implements ClassTreeMatcher { public static final String ANNOTATED_ANNOTATION_MESSAGE = "annotations are immutable by default; annotating them with" + " @com.google.errorprone.annotations.Immutable is unnecessary"; private static final ImmutableSet<String> IGNORED_PROCESSORS = ImmutableSet.of("com.google.auto.value.processor.AutoAnnotationProcessor"); private final WellKnownMutability wellKnownMutability; @Inject ImmutableAnnotationChecker(WellKnownMutability wellKnownMutability) { this.wellKnownMutability = wellKnownMutability; } @Override public Description matchClass(ClassTree tree, VisitorState state) { ClassSymbol symbol = getSymbol(tree); if (symbol.isAnnotationType() || !WellKnownMutability.isAnnotation(state, symbol.type)) { return NO_MATCH; } if (!Collections.disjoint(getGeneratedBy(symbol, state), IGNORED_PROCESSORS)) { return NO_MATCH; } if (ASTHelpers.hasAnnotation(symbol, Immutable.class, state)) { AnnotationTree annotation = ASTHelpers.getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "Immutable"); if (annotation != null) { state.reportMatch( buildDescription(annotation) .setMessage(ANNOTATED_ANNOTATION_MESSAGE) .addFix(SuggestedFix.delete(annotation)) .build()); } else { state.reportMatch(buildDescription(tree).setMessage(ANNOTATED_ANNOTATION_MESSAGE).build()); } } Violation info = new ImmutableAnalysis( this::isSuppressed, state, wellKnownMutability, ImmutableSet.of(Immutable.class.getName())) .checkForImmutability( Optional.of(tree), ImmutableSet.of(), getType(tree), this::describeClass); if (!info.isPresent()) { return NO_MATCH; } return describeClass(tree, info).build(); } Description.Builder describeClass(Tree tree, Violation info) { String message = "annotations should be immutable: " + info.message(); return buildDescription(tree).setMessage(message); } }
4,343
38.135135
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableEnumChecker.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.threadsafety; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Streams; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.Violation; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import java.util.Optional; import java.util.stream.Stream; import javax.inject.Inject; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( name = "ImmutableEnumChecker", altNames = "Immutable", summary = "Enums should always be immutable", severity = WARNING) public class ImmutableEnumChecker extends BugChecker implements ClassTreeMatcher { public static final String ANNOTATED_ENUM_MESSAGE = "enums are immutable by default; annotating them with" + " @com.google.errorprone.annotations.Immutable is unnecessary"; private final WellKnownMutability wellKnownMutability; @Inject ImmutableEnumChecker(WellKnownMutability wellKnownMutability) { this.wellKnownMutability = wellKnownMutability; } @Override public Description matchClass(ClassTree tree, VisitorState state) { ClassSymbol symbol = getSymbol(tree); if (!symbol.isEnum()) { return NO_MATCH; } if (ASTHelpers.hasAnnotation(symbol, Immutable.class, state) && !implementsExemptInterface(symbol, state)) { AnnotationTree annotation = ASTHelpers.getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "Immutable"); if (annotation != null) { state.reportMatch( buildDescription(annotation) .setMessage(ANNOTATED_ENUM_MESSAGE) .addFix(SuggestedFix.delete(annotation)) .build()); } else { state.reportMatch(buildDescription(tree).setMessage(ANNOTATED_ENUM_MESSAGE).build()); } } Violation info = new ImmutableAnalysis( this::isSuppressed, state, wellKnownMutability, ImmutableSet.of(Immutable.class.getName())) .checkForImmutability( Optional.of(tree), ImmutableSet.of(), getType(tree), this::describe); if (!info.isPresent()) { return NO_MATCH; } return describe(tree, info).build(); } private Description.Builder describe(Tree tree, Violation info) { String message = "enums should be immutable: " + info.message(); return buildDescription(tree).setMessage(message); } private static boolean implementsExemptInterface(ClassSymbol symbol, VisitorState state) { return Streams.concat(symbol.getInterfaces().stream(), Stream.of(symbol.getSuperclass())) .anyMatch(supertype -> hasExemptAnnotation(supertype.tsym, state)); } private static final ImmutableSet<String> EXEMPT_ANNOTATIONS = ImmutableSet.of("com.google.errorprone.annotations.Immutable"); private static boolean hasExemptAnnotation(Symbol symbol, VisitorState state) { return EXEMPT_ANNOTATIONS.stream() .anyMatch(annotation -> ASTHelpers.hasAnnotation(symbol, annotation, state)); } }
4,549
37.235294
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/SynchronizeOnNonFinalField.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.threadsafety; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.stripParentheses; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.SynchronizedTree; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import java.util.stream.Stream; import javax.lang.model.element.Name; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( name = "SynchronizeOnNonFinalField", summary = "Synchronizing on non-final fields is not safe: if the field is ever updated," + " different threads may end up locking on different objects.", severity = WARNING, tags = StandardTags.FRAGILE_CODE) public class SynchronizeOnNonFinalField extends BugChecker implements BugChecker.SynchronizedTreeMatcher { @Override public Description matchSynchronized(SynchronizedTree tree, VisitorState state) { Symbol symbol = ASTHelpers.getSymbol(stripParentheses(tree.getExpression())); if (!(symbol instanceof VarSymbol)) { return NO_MATCH; } // TODO(cushon): check that the receiver doesn't contain mutable state. // Currently 'this.locks[i].mu' is accepted if 'mu' is final but 'locks' is non-final. VarSymbol varSymbol = (VarSymbol) symbol; if (ASTHelpers.isLocal(varSymbol) || varSymbol.isStatic() || (varSymbol.flags() & Flags.FINAL) != 0) { return NO_MATCH; } if (ASTHelpers.hasAnnotation(varSymbol, LazyInit.class, state)) { return NO_MATCH; } Name ownerName = varSymbol.owner.enclClass().getQualifiedName(); if (Stream.of("java.io.Writer", "java.io.Reader").anyMatch(ownerName::contentEquals)) { // These classes contain a non-final 'lock' variable available to subclasses, and we can't // make these locks final. return NO_MATCH; } return describeMatch(tree.getExpression()); } }
3,056
38.701299
96
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ConstantExpressions.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.threadsafety; import static com.google.errorprone.VisitorState.memoize; 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.instanceEqualsInvocation; import static com.google.errorprone.matchers.Matchers.staticEqualsInvocation; import static com.google.errorprone.matchers.method.MethodMatchers.constructor; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.constValue; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.isConsideredFinal; import static com.google.errorprone.util.ASTHelpers.isStatic; import static java.lang.String.format; import static java.util.stream.Collectors.joining; import static javax.lang.model.element.Modifier.ABSTRACT; import com.google.auto.value.AutoOneOf; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions.ConstantExpression.ConstantExpressionKind; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.UnaryTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.PackageSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import javax.inject.Inject; import org.checkerframework.checker.nullness.qual.Nullable; /** Helper for establishing whether expressions correspond to a constant expression. */ public final class ConstantExpressions { private final Matcher<ExpressionTree> pureMethods; private final Supplier<ThreadSafety> threadSafety; @Inject ConstantExpressions(WellKnownMutability wellKnownMutability) { this.pureMethods = anyOf( basePureMethods, instanceMethod() .onDescendantOfAny(wellKnownMutability.getKnownImmutableClasses().keySet())); this.threadSafety = memoize( s -> ThreadSafety.builder() .setPurpose(ThreadSafety.Purpose.FOR_IMMUTABLE_CHECKER) .knownTypes(wellKnownMutability) .acceptedAnnotations(ImmutableSet.of(Immutable.class.getName())) .markerAnnotations(ImmutableSet.of()) .build(s)); } public static ConstantExpressions fromFlags(ErrorProneFlags flags) { return new ConstantExpressions(WellKnownMutability.fromFlags(flags)); } /** Represents sets of things known to be true and false if a boolean statement evaluated true. */ @AutoValue public abstract static class Truthiness { public abstract ImmutableSet<ConstantExpression> requiredTrue(); public abstract ImmutableSet<ConstantExpression> requiredFalse(); private static Truthiness create( Iterable<ConstantExpression> requiredTrue, Iterable<ConstantExpression> requiredFalse) { return new AutoValue_ConstantExpressions_Truthiness( ImmutableSet.copyOf(requiredTrue), ImmutableSet.copyOf(requiredFalse)); } } /** * Scans an {@link ExpressionTree} to find anything guaranteed to be false or true if this * expression is true. */ public Truthiness truthiness(ExpressionTree tree, boolean not, VisitorState state) { ImmutableSet.Builder<ConstantExpression> requiredTrue = ImmutableSet.builder(); ImmutableSet.Builder<ConstantExpression> requiredFalse = ImmutableSet.builder(); // Keep track of whether we saw an expression too complex for us to handle, and failed. AtomicBoolean failed = new AtomicBoolean(); new SimpleTreeVisitor<Void, Void>() { boolean negated = not; @Override public Void visitParenthesized(ParenthesizedTree tree, Void unused) { return visit(tree.getExpression(), null); } @Override public Void visitUnary(UnaryTree tree, Void unused) { if (tree.getKind().equals(Kind.LOGICAL_COMPLEMENT)) { withNegation(() -> visit(tree.getExpression(), null)); } return null; } @Override public Void visitBinary(BinaryTree tree, Void unused) { if (tree.getKind().equals(Kind.EQUAL_TO) || tree.getKind().equals(Kind.NOT_EQUAL_TO)) { constantExpression(tree, state) .ifPresent( e -> { if (tree.getKind().equals(Kind.NOT_EQUAL_TO)) { withNegation(() -> add(e)); } else { add(e); } }); } else if (negated ? tree.getKind().equals(Kind.CONDITIONAL_OR) : tree.getKind().equals(Kind.CONDITIONAL_AND)) { visit(tree.getLeftOperand(), null); visit(tree.getRightOperand(), null); } else { failed.set(true); } return null; } @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { constantExpression(tree, state).ifPresent(this::add); return null; } @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { constantExpression(tree, state).ifPresent(this::add); return null; } private void withNegation(Runnable runnable) { negated = !negated; runnable.run(); negated = !negated; } private void add(ConstantExpression e) { if (negated) { requiredFalse.add(e); } else { requiredTrue.add(e); } } }.visit(tree, null); if (failed.get()) { return Truthiness.create(ImmutableSet.of(), ImmutableSet.of()); } return Truthiness.create(requiredTrue.build(), requiredFalse.build()); } /** Represents a constant expression. */ @AutoOneOf(ConstantExpressionKind.class) public abstract static class ConstantExpression { /** The kind of a constant expression. */ public enum ConstantExpressionKind { LITERAL, CONSTANT_EQUALS, PURE_METHOD, } public abstract ConstantExpressionKind kind(); abstract Object literal(); private static ConstantExpression literal(Object object) { return AutoOneOf_ConstantExpressions_ConstantExpression.literal(object); } abstract ConstantEquals constantEquals(); private static ConstantExpression constantEquals(ConstantEquals constantEquals) { return AutoOneOf_ConstantExpressions_ConstantExpression.constantEquals(constantEquals); } public abstract PureMethodInvocation pureMethod(); private static ConstantExpression pureMethod(PureMethodInvocation pureMethodInvocation) { return AutoOneOf_ConstantExpressions_ConstantExpression.pureMethod(pureMethodInvocation); } @Override public final String toString() { switch (kind()) { case LITERAL: return literal().toString(); case CONSTANT_EQUALS: return constantEquals().toString(); case PURE_METHOD: return pureMethod().toString(); } throw new AssertionError(); } public void accept(ConstantExpressionVisitor visitor) { switch (kind()) { case LITERAL: visitor.visitConstant(literal()); break; case CONSTANT_EQUALS: constantEquals().lhs().accept(visitor); constantEquals().rhs().accept(visitor); break; case PURE_METHOD: pureMethod().accept(visitor); break; } } } public Optional<ConstantExpression> constantExpression(ExpressionTree tree, VisitorState state) { if (tree.getKind().equals(Kind.EQUAL_TO) || tree.getKind().equals(Kind.NOT_EQUAL_TO)) { BinaryTree binaryTree = (BinaryTree) tree; Optional<ConstantExpression> lhs = constantExpression(binaryTree.getLeftOperand(), state); Optional<ConstantExpression> rhs = constantExpression(binaryTree.getRightOperand(), state); if (lhs.isPresent() && rhs.isPresent()) { return Optional.of( ConstantExpression.constantEquals(ConstantEquals.of(lhs.get(), rhs.get()))); } } Object value = constValue(tree); if (value != null && tree instanceof LiteralTree) { return Optional.of(ConstantExpression.literal(value)); } return symbolizeImmutableExpression(tree, state).map(ConstantExpression::pureMethod); } /** Represents a binary equals call on two constant expressions. */ @AutoValue public abstract static class ConstantEquals { abstract ConstantExpression lhs(); abstract ConstantExpression rhs(); @Override public final boolean equals(@Nullable Object other) { if (!(other instanceof ConstantEquals)) { return false; } ConstantEquals that = (ConstantEquals) other; return (lhs().equals(that.lhs()) && rhs().equals(that.rhs())) || (lhs().equals(that.rhs()) && rhs().equals(that.lhs())); } @Override public final String toString() { return format("%s equals %s", lhs(), rhs()); } @Override public final int hashCode() { return lhs().hashCode() + rhs().hashCode(); } static ConstantEquals of(ConstantExpression lhs, ConstantExpression rhs) { return new AutoValue_ConstantExpressions_ConstantEquals(lhs, rhs); } } /** * Represents both a constant method call or a constant field/local access, depending on the * actual type of {@code symbol}. */ @AutoValue public abstract static class PureMethodInvocation { public abstract Symbol symbol(); abstract ImmutableList<ConstantExpression> arguments(); public abstract Optional<ConstantExpression> receiver(); @Override public final String toString() { String receiver = receiver().map(r -> r + ".").orElse(""); if (symbol() instanceof VarSymbol || symbol() instanceof ClassSymbol) { return receiver + symbol().getSimpleName(); } return receiver + (isStatic(symbol()) ? symbol().owner.getSimpleName() + "." : "") + symbol().getSimpleName() + arguments().stream().map(Object::toString).collect(joining(", ", "(", ")")); } private static PureMethodInvocation of( Symbol symbol, Iterable<ConstantExpression> arguments, Optional<ConstantExpression> receiver) { return new AutoValue_ConstantExpressions_PureMethodInvocation( symbol, ImmutableList.copyOf(arguments), receiver); } public void accept(ConstantExpressionVisitor visitor) { visitor.visitIdentifier(symbol()); arguments().forEach(a -> a.accept(visitor)); receiver().ifPresent(r -> r.accept(visitor)); } } /** * Returns a list of the methods called to get to this expression, as well as a terminating * variable if needed. */ public Optional<PureMethodInvocation> symbolizeImmutableExpression( ExpressionTree tree, VisitorState state) { var receiver = tree instanceof MethodInvocationTree || tree instanceof MemberSelectTree ? getReceiver(tree) : null; Symbol symbol = getSymbol(tree); Optional<ConstantExpression> receiverConstant; if (receiver == null || (symbol != null && isStatic(symbol))) { receiverConstant = Optional.empty(); } else { receiverConstant = constantExpression(receiver, state); if (receiverConstant.isEmpty()) { return Optional.empty(); } } if (isPureIdentifier(tree)) { return Optional.of( PureMethodInvocation.of(getSymbol(tree), ImmutableList.of(), receiverConstant)); } else if (tree instanceof MethodInvocationTree && pureMethods.matches(tree, state)) { ImmutableList.Builder<ConstantExpression> arguments = ImmutableList.builder(); for (ExpressionTree argument : ((MethodInvocationTree) tree).getArguments()) { Optional<ConstantExpression> argumentConstant = constantExpression(argument, state); if (argumentConstant.isEmpty()) { return Optional.empty(); } arguments.add(argumentConstant.get()); } return Optional.of( PureMethodInvocation.of(getSymbol(tree), arguments.build(), receiverConstant)); } else { return Optional.empty(); } } private static boolean isPureIdentifier(ExpressionTree receiver) { if (!(receiver instanceof IdentifierTree || receiver instanceof MemberSelectTree)) { return false; } Symbol symbol = getSymbol(receiver); return symbol.owner.isEnum() || (symbol instanceof VarSymbol && isConsideredFinal(symbol)) || symbol instanceof ClassSymbol || symbol instanceof PackageSymbol; } /** Visitor for scanning over the components of a constant expression. */ public interface ConstantExpressionVisitor { default void visitConstant(Object constant) {} default void visitIdentifier(Symbol identifier) {} } private static final Pattern NOT_NOW = Pattern.compile("^?!(now)"); private final Matcher<ExpressionTree> basePureMethods = anyOf( staticMethod() .onClassAny( "com.google.common.base.Optional", "com.google.common.base.Pair", "com.google.common.base.Splitter", "com.google.common.collect.ImmutableBiMap", "com.google.common.collect.ImmutableCollection", "com.google.common.collect.ImmutableList", "com.google.common.collect.ImmutableListMultimap", "com.google.common.collect.ImmutableMap", "com.google.common.collect.ImmutableMultimap", "com.google.common.collect.ImmutableMultiset", "com.google.common.collect.ImmutableRangeMap", "com.google.common.collect.ImmutableRangeSet", "com.google.common.collect.ImmutableSet", "com.google.common.collect.ImmutableSetMultimap", "com.google.common.collect.ImmutableSortedMap", "com.google.common.collect.ImmutableSortedMultiset", "com.google.common.collect.ImmutableSortedSet", "com.google.common.collect.ImmutableTable", "com.google.common.collect.Range"), staticMethod().onClass("com.google.protobuf.GeneratedMessage"), staticMethod() .onClass("java.time.Duration") .namedAnyOf("ofNanos", "ofMillis", "ofSeconds", "ofMinutes", "ofHours", "ofDays") .withParameters("long"), staticMethod() .onClass("java.time.Instant") .namedAnyOf("ofEpochMilli", "ofEpochSecond") .withParameters("long"), 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"), staticMethod() .onClass("org.joda.time.Duration") .namedAnyOf( "millis", "standardSeconds", "standardMinutes", "standardHours", "standardDays") .withParameters("long"), constructor().forClass("org.joda.time.Instant").withParameters("long"), constructor().forClass("org.joda.time.DateTime").withParameters("long"), staticMethod().onClass("java.time.LocalDate").withNameMatching(NOT_NOW), staticMethod().onClass("java.time.LocalDateTime").withNameMatching(NOT_NOW), staticMethod().onClass("java.time.LocalTime").withNameMatching(NOT_NOW), staticMethod().onClass("java.time.MonthDay"), staticMethod().onClass("java.time.OffsetDateTime").withNameMatching(NOT_NOW), staticMethod().onClass("java.time.OffsetTime").withNameMatching(NOT_NOW), staticMethod() .onClassAny( "java.time.Period", "java.time.Year", "java.time.YearMonth", "java.time.ZoneId", "java.time.ZoneOffset"), instanceMethod().onDescendantOf("java.lang.String"), staticMethod().onClass("java.time.ZonedDateTime").withNameMatching(NOT_NOW), staticMethod() .onClassAny( "java.util.Optional", "java.util.OptionalDouble", "java.util.OptionalInt", "java.util.OptionalLong"), staticMethod().onClass("java.util.regex.Pattern"), staticMethod() .onClassAny( "org.joda.time.DateTime", "org.joda.time.DateTimeZone", "org.joda.time.Days", "org.joda.time.Duration", "org.joda.time.Instant", "org.joda.time.Interval", "org.joda.time.LocalDate", "org.joda.time.LocalDateTime", "org.joda.time.Period", "org.joda.time.format.DateTimeFormatter"), anyMethod().onClass("java.lang.String"), Matchers.hasAnnotation("org.checkerframework.dataflow.qual.Pure"), (tree, state) -> { Symbol symbol = getSymbol(tree); return hasAnnotation(symbol.owner, "com.google.auto.value.AutoValue", state) && symbol.getModifiers().contains(ABSTRACT); }, staticMethod() .onDescendantOf("com.google.protobuf.MessageLite") .named("getDefaultInstance"), allOf( instanceEqualsInvocation(), (t, s) -> { if (!(t instanceof MethodInvocationTree)) { return false; } ExpressionTree receiver = getReceiver(t); if (receiver == null) { return false; } return typeIsImmutable(getType(receiver), s) && typeIsImmutable( getType(((MethodInvocationTree) t).getArguments().get(0)), s); }), allOf( staticEqualsInvocation(), (t, s) -> { if (!(t instanceof MethodInvocationTree)) { return false; } List<? extends ExpressionTree> args = ((MethodInvocationTree) t).getArguments(); return typeIsImmutable(getType(args.get(0)), s) && typeIsImmutable(getType(args.get(1)), s); })); private boolean typeIsImmutable(Type type, VisitorState state) { ThreadSafety threadSafety = this.threadSafety.get(state); return !threadSafety .isThreadSafeType( /* allowContainerTypeParameters= */ true, threadSafety.threadSafeTypeParametersInScope(type.tsym), type) .isPresent(); } }
21,122
38.335196
116
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedBySymbolResolver.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns.threadsafety; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.errorprone.bugpatterns.threadsafety.IllegalGuardedBy.checkGuardedBy; import static com.google.errorprone.util.ASTHelpers.isStatic; import static java.util.Objects.requireNonNull; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.errorprone.VisitorState; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Scope; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.comp.Attr; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.util.Context; import javax.annotation.Nullable; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Name; /** * A symbol resolver used while binding guardedby expressions from string literals. * * @author cushon@google.com (Liam Miller-Cushon) */ public class GuardedBySymbolResolver implements GuardedByBinder.Resolver { private final ClassSymbol enclosingClass; private final MethodInfo method; private final Tree decl; private final JCTree.JCCompilationUnit compilationUnit; private final Context context; private final VisitorState visitorState; private final Types types; public static GuardedBySymbolResolver from(Tree tree, VisitorState visitorState) { return GuardedBySymbolResolver.from( ASTHelpers.getSymbol(tree).owner.enclClass(), MethodInfo.create(tree, visitorState), visitorState.getPath().getCompilationUnit(), visitorState.context, tree, visitorState); } public static GuardedBySymbolResolver from( ClassSymbol owner, MethodInfo method, CompilationUnitTree compilationUnit, Context context, Tree leaf, VisitorState visitorState) { return new GuardedBySymbolResolver(owner, method, compilationUnit, context, leaf, visitorState); } private GuardedBySymbolResolver( ClassSymbol enclosingClass, MethodInfo method, CompilationUnitTree compilationUnit, Context context, Tree leaf, VisitorState visitorState) { this.compilationUnit = (JCCompilationUnit) compilationUnit; this.enclosingClass = requireNonNull(enclosingClass); this.method = method; this.context = context; this.types = visitorState.getTypes(); this.decl = leaf; this.visitorState = visitorState; } public Context context() { return context; } public VisitorState visitorState() { return visitorState; } public ClassSymbol enclosingClass() { return enclosingClass; } @Override public Symbol resolveIdentifier(IdentifierTree node) { String name = node.getName().toString(); if (name.equals("this")) { return enclosingClass; } // TODO(cushon): consider disallowing this? It's the only case where the lock description // isn't legal java. if (name.equals("itself")) { Symbol sym = ASTHelpers.getSymbol(decl); if (sym == null) { throw new IllegalGuardedBy(decl.getClass().toString()); } return sym; } VarSymbol field = getField(enclosingClass, name); if (field != null) { return field; } VarSymbol param = getParam(method, name); if (param != null) { return param; } Symbol type = resolveType(name, SearchSuperTypes.YES); if (type != null) { return type; } throw new IllegalGuardedBy(name); } @Override public MethodSymbol resolveMethod(MethodInvocationTree node, Name name) { return getMethod(enclosingClass, name.toString()); } @Override public MethodSymbol resolveMethod( MethodInvocationTree node, GuardedByExpression base, Name identifier) { Symbol baseSym = base.kind() == GuardedByExpression.Kind.THIS ? enclosingClass : base.type().asElement(); return getMethod(baseSym, identifier.toString()); } private MethodSymbol getMethod(Symbol classSymbol, String name) { return getMember(MethodSymbol.class, ElementKind.METHOD, classSymbol, name); } @Override public Symbol resolveSelect(GuardedByExpression base, MemberSelectTree node) { Symbol baseSym = base.kind() == GuardedByExpression.Kind.THIS ? enclosingClass : base.type().asElement(); return getField(baseSym, node.getIdentifier().toString()); } @Override public Symbol resolveMemberReference(GuardedByExpression base, MemberReferenceTree node) { Symbol baseSym = base.kind() == GuardedByExpression.Kind.THIS ? enclosingClass : base.type().asElement(); return getMember(MethodSymbol.class, ElementKind.METHOD, baseSym, node.getName().toString()); } private VarSymbol getField(Symbol classSymbol, String name) { return getMember(VarSymbol.class, ElementKind.FIELD, classSymbol, name); } private <T extends Symbol> T getMember( Class<T> type, ElementKind kind, Symbol classSymbol, String name) { if (classSymbol.type == null) { return null; } for (Type t : types.closure(classSymbol.type)) { Scope scope = t.tsym.members(); for (Symbol sym : scope.getSymbolsByName(visitorState.getName(name))) { if (sym.getKind().equals(kind)) { return type.cast(sym); } } } if (classSymbol.hasOuterInstance()) { T sym = getMember(type, kind, classSymbol.type.getEnclosingType().asElement(), name); if (sym != null) { return sym; } } if (classSymbol.owner != null && classSymbol != classSymbol.owner && classSymbol.owner instanceof Symbol.ClassSymbol) { T sym = getMember(type, kind, classSymbol.owner, name); if (sym != null && isStatic(sym)) { return sym; } } return null; } @Nullable private VarSymbol getParam(@Nullable MethodInfo method, String name) { if (method == null) { return null; } int idx = 0; for (VarSymbol param : method.sym().getParameters()) { if (!param.getSimpleName().contentEquals(name)) { idx++; continue; } ExpressionTree arg = method.argument(idx); if (arg != null) { Symbol sym = ASTHelpers.getSymbol(arg); if (sym instanceof VarSymbol) { return (VarSymbol) sym; } } return param; } return null; } @Nullable @Override public Symbol resolveTypeLiteral(ExpressionTree expr) { checkGuardedBy(expr instanceof IdentifierTree, "bad type literal: %s", expr); IdentifierTree ident = (IdentifierTree) expr; Symbol type = resolveType(ident.getName().toString(), SearchSuperTypes.YES); if (type instanceof Symbol.ClassSymbol) { return type; } return null; } private enum SearchSuperTypes { YES, NO } /** * Resolves a simple name as a type. Considers super classes, lexically enclosing classes, and * then arbitrary types available in the current environment. */ private Symbol resolveType(String name, SearchSuperTypes searchSuperTypes) { Symbol type = null; if (searchSuperTypes == SearchSuperTypes.YES) { type = getSuperType(enclosingClass, name); } if (enclosingClass.getSimpleName().contentEquals(name)) { type = enclosingClass; } if (type == null) { type = getLexicallyEnclosing(enclosingClass, name); } if (type == null) { type = attribIdent(name); } checkGuardedBy( !(type instanceof Symbol.PackageSymbol), "All we could find for '%s' was a package symbol.", name); return type; } @Nullable private Symbol getSuperType(Symbol symbol, String name) { for (Type t : types.closure(symbol.type)) { if (t.asElement().getSimpleName().contentEquals(name)) { return t.asElement(); } } return null; } @Nullable private static Symbol getLexicallyEnclosing(ClassSymbol symbol, String name) { Symbol current = symbol.owner; while (true) { if (current == null || current.getSimpleName().contentEquals(name)) { return current; } if (current != current.owner && current.owner instanceof Symbol.ClassSymbol) { current = current.owner; } else { return null; } } } private Symbol attribIdent(String name) { Attr attr = Attr.instance(context); TreeMaker tm = visitorState.getTreeMaker(); return attr.attribIdent(tm.Ident(visitorState.getName(name)), compilationUnit); } @Nullable @Override public Symbol resolveEnclosingClass(ExpressionTree expr) { checkGuardedBy(expr instanceof IdentifierTree, "bad type literal: %s", expr); IdentifierTree ident = (IdentifierTree) expr; Symbol type = resolveType(ident.getName().toString(), SearchSuperTypes.NO); if (type instanceof Symbol.ClassSymbol) { return type; } return null; } /** Information about a method that is associated with a {@link GuardedBy} annotation. */ @AutoValue abstract static class MethodInfo { /** The method symbol. */ abstract MethodSymbol sym(); /** * The method arguments, if the site is a method invocation expression for a method annotated * with {@code @GuardedBy}. */ @Nullable abstract ImmutableList<ExpressionTree> arguments(); @Nullable ExpressionTree argument(int idx) { if (arguments() == null) { return null; } // handle a varargs parameter with no corresponding arguments if (idx == arguments().size()) { checkState(sym().isVarArgs()); return null; } return arguments().get(idx); } static MethodInfo create(MethodSymbol sym) { return create(sym, null); } static MethodInfo create(MethodSymbol sym, ImmutableList<ExpressionTree> arguments) { checkArgument( arguments == null || arguments.size() == sym.getParameters().size() // If the method is varargs, there can be one fewer arguments than parameters if no // arguments are passed for the varargs parameter. || (sym.isVarArgs() && arguments.size() >= sym.getParameters().size() - 1), "arguments (%s) don't match parameters (%s)", arguments, sym.getParameters()); return new AutoValue_GuardedBySymbolResolver_MethodInfo(sym, arguments); } @Nullable static MethodInfo create(Tree tree, VisitorState visitorState) { Symbol sym = ASTHelpers.getSymbol(tree); if (!(sym instanceof MethodSymbol)) { return null; } MethodSymbol methodSym = (MethodSymbol) sym; Tree parent = visitorState.getPath().getParentPath().getLeaf(); if (!(parent instanceof MethodInvocationTree)) { return create(methodSym); } MethodInvocationTree invocation = (MethodInvocationTree) parent; if (!invocation.getMethodSelect().equals(tree)) { return create(methodSym); } return create( methodSym, ImmutableList.copyOf(((MethodInvocationTree) parent).getArguments())); } } }
12,440
31.23057
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadPriorityCheck.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.threadsafety; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; 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.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; /** * Bug checker to detect usage of {@code Thread.stop()}, {@code Thread.yield()}, and changing thread * priorities. * * @author siyuanl@google.com (Siyuan Liu) * @author eleanorh@google.com (Eleanor Harris) */ @BugPattern( name = "ThreadPriorityCheck", summary = "Relying on the thread scheduler is discouraged.", severity = WARNING) public class ThreadPriorityCheck extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> THREAD_MATCHERS = anyOf( Matchers.staticMethod().onClass("java.lang.Thread").named("yield"), Matchers.instanceMethod().onDescendantOf("java.lang.Thread").named("setPriority")); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return THREAD_MATCHERS.matches(tree, state) ? describeMatch(tree) : Description.NO_MATCH; } }
2,158
38.254545
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/WellKnownThreadSafety.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.threadsafety; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.errorprone.ErrorProneFlags; import java.util.List; import javax.inject.Inject; /** A collection of types with known thread safety. */ public final class WellKnownThreadSafety implements ThreadSafety.KnownTypes { @Inject WellKnownThreadSafety(ErrorProneFlags flags, WellKnownMutability wellKnownMutability) { List<String> knownThreadSafe = flags.getList("ThreadSafe:KnownThreadSafe").orElse(ImmutableList.of()); this.knownThreadSafeClasses = buildThreadSafeClasses(knownThreadSafe, wellKnownMutability); this.knownUnsafeClasses = wellKnownMutability.getKnownMutableClasses(); } public static WellKnownThreadSafety fromFlags(ErrorProneFlags flags) { return new WellKnownThreadSafety(flags, WellKnownMutability.fromFlags(flags)); } public ImmutableMap<String, AnnotationInfo> getKnownThreadSafeClasses() { return knownThreadSafeClasses; } @Override public ImmutableMap<String, AnnotationInfo> getKnownSafeClasses() { return getKnownThreadSafeClasses(); } @Override public ImmutableSet<String> getKnownUnsafeClasses() { return knownUnsafeClasses; } /** Types that are known to be threadsafe. */ private final ImmutableMap<String, AnnotationInfo> knownThreadSafeClasses; @SuppressWarnings("UnnecessarilyFullyQualified") // intentional private static ImmutableMap<String, AnnotationInfo> buildThreadSafeClasses( List<String> extraKnownThreadSafe, WellKnownMutability mutability) { return // Things should only be added here when there is a good reason to think that annotating // them is infeasible (e.g. the type is defined in the JDK or some third party package), // in all other cases the class itself should be annotated. new MapBuilder() .addAll(mutability.getKnownImmutableClasses()) .addStrings(extraKnownThreadSafe) .add(ClassLoader.class) .add(Thread.class) .add(java.util.Random.class) .add(java.util.concurrent.atomic.AtomicBoolean.class) .add(java.util.concurrent.atomic.AtomicInteger.class) .add(java.util.concurrent.atomic.AtomicIntegerArray.class) .add(java.util.concurrent.atomic.AtomicLong.class) .add(java.util.concurrent.atomic.AtomicLongArray.class) .add(java.util.concurrent.atomic.AtomicMarkableReference.class) .add(java.util.concurrent.atomic.AtomicReference.class, "V") .add(java.util.concurrent.atomic.DoubleAccumulator.class) .add(java.util.concurrent.atomic.DoubleAdder.class) .add(java.util.concurrent.atomic.LongAccumulator.class) .add(java.util.concurrent.atomic.LongAdder.class) .add(java.util.concurrent.BlockingDeque.class, "E") .add(java.util.concurrent.BlockingQueue.class, "E") .add(java.util.concurrent.LinkedBlockingDeque.class, "E") .add(java.util.concurrent.LinkedBlockingQueue.class, "E") .add(java.util.concurrent.PriorityBlockingQueue.class, "E") .add(java.util.concurrent.ConcurrentLinkedDeque.class, "E") .add(java.util.concurrent.ConcurrentLinkedQueue.class, "E") .add(java.util.concurrent.ConcurrentHashMap.class, "K", "V") .add(java.util.concurrent.ConcurrentMap.class, "K", "V") .add(java.util.concurrent.ConcurrentNavigableMap.class, "K", "V") .add(java.util.concurrent.ConcurrentSkipListMap.class, "K", "V") .add(java.util.concurrent.ConcurrentSkipListSet.class, "E") .add(java.util.concurrent.CopyOnWriteArrayList.class, "E") .add(java.util.concurrent.CopyOnWriteArraySet.class, "E") .add(java.util.concurrent.CountDownLatch.class) .add(java.util.concurrent.Executor.class) .add(java.util.concurrent.ExecutorService.class) .add(java.util.concurrent.Future.class, "V") .add(java.util.concurrent.Semaphore.class) .add(java.util.concurrent.ScheduledExecutorService.class) .add(java.util.concurrent.locks.Condition.class) .add(java.util.concurrent.locks.Lock.class) .add(java.util.concurrent.locks.ReadWriteLock.class) .add(java.util.concurrent.locks.ReentrantLock.class) .add(java.util.concurrent.locks.ReentrantReadWriteLock.class) .add(java.security.SecureRandom.class) .add("com.google.common.time.Clock") .add("com.google.common.time.TimeSource") .add("com.google.common.util.concurrent.AtomicLongMap", "K") .add("com.google.common.util.concurrent.CheckedFuture", "V", "X") .add("com.google.common.util.concurrent.ListeningExecutorService") .add("com.google.common.util.concurrent.ListenableFuture", "V") .add("com.google.common.util.concurrent.ListeningScheduledExecutorService") .add("com.google.common.util.concurrent.RateLimiter") .add("com.google.common.util.concurrent.RateObserver") .add("com.google.common.util.concurrent.SettableFuture", "V") .add("com.google.common.util.concurrent.Striped", "L") .add("com.google.common.cache.LoadingCache", "K", "V") .add("com.google.common.cache.AsyncLoadingCache", "K", "V") .add("com.google.common.cache.Cache", "K", "V") .add("com.google.common.collect.ConcurrentHashMultiset", "E") .add("dagger.Lazy", "T") .add("org.reactivestreams.Publisher", "T") .add("org.reactivestreams.Processor", "T", "R") .add("io.reactivex.Maybe", "T") .add("io.reactivex.Single", "T") .add("io.reactivex.Flowable", "T") .add(Throwable.class) // Unsafe due to initCause, but generally used across threads .add("java.lang.ThreadLocal") .add("java.lang.invoke.MethodHandle") .add(java.lang.reflect.Method.class) .add(java.lang.reflect.Field.class) .add("com.github.benmanes.caffeine.cache.Cache", "K", "V") .add("com.github.benmanes.caffeine.cache.LoadingCache", "K", "V") .add("com.github.benmanes.caffeine.cache.AsyncLoadingCache", "K", "V") .add("kotlinx.coroutines.CoroutineDispatcher") .add("kotlinx.coroutines.CoroutineScope") .add("kotlinx.coroutines.ExecutorCoroutineDispatcher") .add("kotlinx.coroutines.sync.Mutex") .add("kotlinx.coroutines.sync.Semaphore") .add("kotlin.Unit") .build(); } /** Types that are known to be mutable. */ private final ImmutableSet<String> knownUnsafeClasses; }
7,233
47.878378
95
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByChecker.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.threadsafety; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.bugpatterns.threadsafety.HeldLockAnalyzer.INVOKES_LAMBDAS_IMMEDIATELY; import static com.google.errorprone.matchers.Description.NO_MATCH; import com.google.common.base.Joiner; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.LambdaExpressionTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.bugpatterns.threadsafety.GuardedByExpression.Kind; import com.google.errorprone.bugpatterns.threadsafety.GuardedByExpression.Select; import com.google.errorprone.bugpatterns.threadsafety.GuardedByUtils.GuardedByValidationResult; import com.google.errorprone.matchers.Description; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Type; import org.checkerframework.checker.nullness.qual.Nullable; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( name = "GuardedBy", altNames = "GuardedByChecker", summary = "Checks for unguarded accesses to fields and methods with @GuardedBy annotations", severity = ERROR) public class GuardedByChecker extends BugChecker implements VariableTreeMatcher, MethodTreeMatcher, LambdaExpressionTreeMatcher, MemberReferenceTreeMatcher { private static final String JUC_READ_WRITE_LOCK = "java.util.concurrent.locks.ReadWriteLock"; private final GuardedByFlags flags = GuardedByFlags.allOn(); @Override public Description matchMethod(MethodTree tree, VisitorState state) { // Constructors (and field initializers, instance initializers, and class initializers) are free // to mutate guarded state without holding the necessary locks. It is assumed that all objects // (and classes) are thread-local during initialization. if (ASTHelpers.getSymbol(tree).isConstructor()) { return NO_MATCH; } analyze(state); return validate(tree, state); } @Override public Description matchLambdaExpression(LambdaExpressionTree tree, VisitorState state) { var parent = state.getPath().getParentPath().getLeaf(); if (parent instanceof MethodInvocationTree && INVOKES_LAMBDAS_IMMEDIATELY.matches((ExpressionTree) parent, state)) { return NO_MATCH; } analyze(state.withPath(new TreePath(state.getPath(), tree.getBody()))); return NO_MATCH; } @Override public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) { var parent = state.getPath().getParentPath().getLeaf(); if (parent instanceof MethodInvocationTree && INVOKES_LAMBDAS_IMMEDIATELY.matches((ExpressionTree) parent, state)) { return NO_MATCH; } analyze(state); return NO_MATCH; } private void analyze(VisitorState state) { HeldLockAnalyzer.analyze( state, (tree, guard, live) -> report(checkGuardedAccess(tree, guard, live, state), state), tree -> isSuppressed(tree, state), flags); } @Override public Description matchVariable(VariableTree tree, VisitorState state) { // We only want to check field declarations for @GuardedBy usage. The VariableTree might be // for a local or a parameter, but they won't have @GuardedBy annotations. // // Field initializers (like constructors) are not checked for accesses of guarded fields. return validate(tree, state); } protected Description checkGuardedAccess( Tree tree, GuardedByExpression guard, HeldLockSet locks, VisitorState state) { // TODO(cushon): support ReadWriteLocks // // A common pattern with ReadWriteLocks is to create a copy (either a field or a local // variable) to refer to the read and write locks. The analysis currently can't // recognize that locking the copies is equivalent to locking the read or write // locks directly. // // Also - there are currently no annotations to specify an access policy for // members guarded by ReadWriteLocks. We could allow accesses when either the // read or write locks are held, but that's not much better than enforcing // nothing. if (isRwLock(guard, state)) { return NO_MATCH; } if (locks.allLocks().contains(guard)) { return NO_MATCH; } return buildDescription(tree).setMessage(buildMessage(guard, locks)).build(); } /** * Construct a diagnostic message, e.g.: * * <ul> * <li>This access should be guarded by 'this', which is not currently held * <li>This access should be guarded by 'this'; instead found 'mu' * <li>This access should be guarded by 'this'; instead found: 'mu1', 'mu2' * </ul> */ private static String buildMessage(GuardedByExpression guard, HeldLockSet locks) { int heldLocks = locks.allLocks().size(); StringBuilder message = new StringBuilder(); Select enclosing = findOuterInstance(guard); if (enclosing != null && !enclosingInstance(guard)) { if (guard == enclosing) { message.append( String.format( "Access should be guarded by enclosing instance '%s' of '%s'," + " which is not accessible in this scope", enclosing.sym().owner, enclosing.base())); } else { message.append( String.format( "Access should be guarded by '%s' in enclosing instance '%s' of '%s'," + " which is not accessible in this scope", guard.sym(), enclosing.sym().owner, enclosing.base())); } if (heldLocks > 0) { message.append( String.format("; instead found: '%s'", Joiner.on("', '").join(locks.allLocks()))); } return message.toString(); } message.append(String.format("This access should be guarded by '%s'", guard)); if (guard.kind() == GuardedByExpression.Kind.ERROR) { message.append(", which could not be resolved"); return message.toString(); } if (heldLocks == 0) { message.append(", which is not currently held"); } else { message.append( String.format("; instead found: '%s'", Joiner.on("', '").join(locks.allLocks()))); } return message.toString(); } private static @Nullable Select findOuterInstance(GuardedByExpression expr) { while (expr.kind() == Kind.SELECT) { Select select = (Select) expr; if (select.sym().name.contentEquals(GuardedByExpression.ENCLOSING_INSTANCE_NAME)) { return select; } expr = select.base(); } return null; } private static boolean enclosingInstance(GuardedByExpression expr) { while (expr.kind() == Kind.SELECT) { expr = ((Select) expr).base(); if (expr.kind() == Kind.THIS) { return true; } } return false; } /** * Returns true if the lock expression corresponds to a {@code * java.util.concurrent.locks.ReadWriteLock}. */ private static boolean isRwLock(GuardedByExpression guard, VisitorState state) { Type guardType = guard.type(); if (guardType == null) { return false; } Symbol rwLockSymbol = JAVA_UTIL_CONCURRENT_LOCKS_READWRITELOCK.get(state); if (rwLockSymbol == null) { return false; } return state.getTypes().isSubtype(guardType, rwLockSymbol.type); } // TODO(cushon) - this is a hack. Provide an abstraction for matchers that need to do // stateful visiting? (e.g. a traversal that passes along a set of held locks...) private static void report(Description description, VisitorState state) { if (description == null || description == NO_MATCH) { return; } state.reportMatch(description); } /** Validates that {@code @GuardedBy} strings can be resolved. */ private Description validate(Tree tree, VisitorState state) { GuardedByValidationResult result = GuardedByUtils.isGuardedByValid(tree, state, flags); if (result.isValid()) { return Description.NO_MATCH; } return buildDescription(tree) .setMessage(String.format("Invalid @GuardedBy expression: %s", result.message())) .build(); } private static final Supplier<Symbol> JAVA_UTIL_CONCURRENT_LOCKS_READWRITELOCK = VisitorState.memoize(state -> state.getSymbolFromString(JUC_READ_WRITE_LOCK)); }
9,707
37.832
106
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/DoubleCheckedLocking.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.threadsafety; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import static com.google.errorprone.util.ASTHelpers.stripParentheses; import com.google.auto.value.AutoValue; 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.IfTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IfTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.SynchronizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.util.SimpleTreeVisitor; import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAssign; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; import java.util.List; import java.util.Objects; import javax.annotation.Nullable; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ // TODO(cushon): allow @LazyInit on fields as a suppression mechanism? @BugPattern( name = "DoubleCheckedLocking", summary = "Double-checked locking on non-volatile fields is unsafe", severity = WARNING, tags = StandardTags.FRAGILE_CODE) public class DoubleCheckedLocking extends BugChecker implements IfTreeMatcher { @Override public Description matchIf(IfTree outerIf, VisitorState state) { DCLInfo info = findDcl(outerIf); if (info == null) { return Description.NO_MATCH; } switch (info.sym().getKind()) { case FIELD: return handleField(info.outerIf(), info.sym(), state); case LOCAL_VARIABLE: return handleLocal(info, state); default: return Description.NO_MATCH; } } /** * Report a {@link Description} if a field used in double-checked locking is not volatile. * * <p>If the AST node for the field declaration can be located in the current compilation unit, * suggest adding the volatile modifier. */ private Description handleField(IfTree outerIf, VarSymbol sym, VisitorState state) { if (sym.getModifiers().contains(Modifier.VOLATILE)) { return Description.NO_MATCH; } if (isImmutable(sym.type, state)) { return Description.NO_MATCH; } Description.Builder builder = buildDescription(outerIf); JCTree fieldDecl = findFieldDeclaration(state.getPath(), sym); if (fieldDecl != null) { builder.addFix( SuggestedFixes.addModifiers(fieldDecl, state, Modifier.VOLATILE) .orElse(SuggestedFix.emptyFix())); } return builder.build(); } private static final ImmutableSet<String> IMMUTABLE_PRIMITIVES = ImmutableSet.of( java.lang.Boolean.class.getName(), java.lang.Byte.class.getName(), java.lang.Short.class.getName(), java.lang.Integer.class.getName(), java.lang.Character.class.getName(), java.lang.Float.class.getName(), java.lang.String.class.getName()); /** * Recognize a small set of known-immutable types that are safe for DCL even without a volatile * field. */ private static boolean isImmutable(Type type, VisitorState state) { switch (type.getKind()) { case BOOLEAN: case BYTE: case SHORT: case INT: case CHAR: case FLOAT: return true; case LONG: case DOUBLE: // double-width primitives aren't written atomically return true; default: break; } return IMMUTABLE_PRIMITIVES.contains( state.getTypes().erasure(type).tsym.getQualifiedName().toString()); } /** * Report a diagnostic for an instance of DCL on a local variable. A match is only reported if a * non-volatile field is written to the variable after acquiring the lock and before the second * null-check on the local. * * <p>e.g. * * <pre>{@code * if ($X == null) { * synchronized (...) { * $X = myNonVolatileField; * if ($X == null) { * ... * } * ... * } * } * }</pre> */ private Description handleLocal(DCLInfo info, VisitorState state) { JCExpressionStatement expr = getChild(info.synchTree().getBlock(), JCExpressionStatement.class); if (expr == null) { return Description.NO_MATCH; } if (expr.getStartPosition() > getStartPosition(info.innerIf())) { return Description.NO_MATCH; } if (!(expr.getExpression() instanceof JCAssign)) { return Description.NO_MATCH; } JCAssign assign = (JCAssign) expr.getExpression(); if (!Objects.equals(ASTHelpers.getSymbol(assign.getVariable()), info.sym())) { return Description.NO_MATCH; } Symbol sym = ASTHelpers.getSymbol(assign.getExpression()); if (!(sym instanceof VarSymbol)) { return Description.NO_MATCH; } VarSymbol fvar = (VarSymbol) sym; if (fvar.getKind() != ElementKind.FIELD) { return Description.NO_MATCH; } return handleField(info.outerIf(), fvar, state); } /** Information about an instance of DCL. */ @AutoValue abstract static class DCLInfo { /** The outer if statement */ abstract IfTree outerIf(); /** The synchronized statement */ abstract SynchronizedTree synchTree(); /** The inner if statement */ abstract IfTree innerIf(); /** The variable (local or field) that is double-checked */ abstract VarSymbol sym(); static DCLInfo create( IfTree outerIf, SynchronizedTree synchTree, IfTree innerIf, VarSymbol sym) { return new AutoValue_DoubleCheckedLocking_DCLInfo(outerIf, synchTree, innerIf, sym); } } /** * Matches an instance of DCL. The canonical pattern is: * * <pre>{@code * if ($X == null) { * synchronized (...) { * if ($X == null) { * ... * } * ... * } * } * }</pre> * * Gaps before the synchronized or inner 'if' statement are ignored, and the operands in the * null-checks are accepted in either order. */ @Nullable private static DCLInfo findDcl(IfTree outerIf) { // TODO(cushon): Optional.ifPresent... ExpressionTree outerIfTest = getNullCheckedExpression(outerIf.getCondition()); if (outerIfTest == null) { return null; } SynchronizedTree synchTree = getChild(outerIf.getThenStatement(), SynchronizedTree.class); if (synchTree == null) { return null; } IfTree innerIf = getChild(synchTree.getBlock(), IfTree.class); if (innerIf == null) { return null; } ExpressionTree innerIfTest = getNullCheckedExpression(innerIf.getCondition()); if (innerIfTest == null) { return null; } Symbol outerSym = ASTHelpers.getSymbol(outerIfTest); if (!Objects.equals(outerSym, ASTHelpers.getSymbol(innerIfTest))) { return null; } if (!(outerSym instanceof VarSymbol)) { return null; } VarSymbol var = (VarSymbol) outerSym; return DCLInfo.create(outerIf, synchTree, innerIf, var); } /** * Matches comparisons to null (e.g. {@code foo == null}) and returns the expression being tested. */ @Nullable private static ExpressionTree getNullCheckedExpression(ExpressionTree condition) { condition = stripParentheses(condition); if (!(condition instanceof BinaryTree)) { return null; } BinaryTree bin = (BinaryTree) condition; ExpressionTree other; if (bin.getLeftOperand().getKind() == Kind.NULL_LITERAL) { other = bin.getRightOperand(); } else if (bin.getRightOperand().getKind() == Kind.NULL_LITERAL) { other = bin.getLeftOperand(); } else { return null; } return other; } /** * Visits (possibly nested) block statements and returns the first child statement with the given * class. */ private static <T> T getChild(StatementTree tree, Class<T> clazz) { return tree.accept( new SimpleTreeVisitor<T, Void>() { @Override protected T defaultAction(Tree node, Void p) { if (clazz.isInstance(node)) { return clazz.cast(node); } return null; } @Override public T visitBlock(BlockTree node, Void p) { return visit(node.getStatements()); } private T visit(List<? extends Tree> tx) { for (Tree t : tx) { T r = t.accept(this, null); if (r != null) { return r; } } return null; } }, null); } /** * Performs a best-effort search for the AST node of a field declaration. * * <p>It will only find fields declared in a lexically enclosing scope of the current location. * Since double-checked locking should always be used on a private field, this should be * reasonably effective. */ @Nullable private static JCTree findFieldDeclaration(TreePath path, VarSymbol var) { for (TreePath curr = path; curr != null; curr = curr.getParentPath()) { Tree leaf = curr.getLeaf(); if (!(leaf instanceof JCClassDecl)) { continue; } for (JCTree tree : ((JCClassDecl) leaf).getMembers()) { if (Objects.equals(var, ASTHelpers.getSymbol(tree))) { return tree; } } } return null; } }
10,780
31.868902
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafeChecker.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.threadsafety; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.common.collect.Sets.SetView; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.annotations.ThreadSafe; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.TypeParameterTreeMatcher; import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.Violation; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeParameterTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.TypeVariableSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree.JCMemberReference; import com.sun.tools.javac.tree.JCTree.JCNewClass; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import javax.inject.Inject; import org.checkerframework.checker.nullness.qual.Nullable; /** * A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. * * @author mboyington@google.com (Marcos Boyington) */ @BugPattern( name = "ThreadSafe", summary = "Type declaration annotated with @ThreadSafe is not thread safe", severity = ERROR) public class ThreadSafeChecker extends BugChecker implements ClassTreeMatcher, NewClassTreeMatcher, TypeParameterTreeMatcher, MethodInvocationTreeMatcher, MemberReferenceTreeMatcher { private final WellKnownThreadSafety wellKnownThreadSafety; private final boolean checkElementUsage; @Inject ThreadSafeChecker(WellKnownThreadSafety wellKnownThreadSafety, ErrorProneFlags flags) { this.wellKnownThreadSafety = wellKnownThreadSafety; this.checkElementUsage = flags.getBoolean("ThreadSafeChecker:CheckElementUsage").orElse(true); } // check instantiations of `@ThreadSafe`s in method references @Override public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) { return checkInvocation( tree, ((JCMemberReference) tree).referentType, state, ASTHelpers.getSymbol(tree)); } // check instantiations of `@ThreadSafe`s in method invocations @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return checkInvocation( tree, ASTHelpers.getType(tree.getMethodSelect()), state, ASTHelpers.getSymbol(tree)); } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { // check instantiations of `@ThreadSafe.TypeParameter`s in generic constructor invocations checkInvocation( tree, ((JCNewClass) tree).constructorType, state, ((JCNewClass) tree).constructor); // check instantiations of `@ThreadSafe.TypeParameter`s in class constructor invocations ThreadSafeAnalysis analysis = new ThreadSafeAnalysis(this, state, wellKnownThreadSafety); Violation info = analysis.checkInstantiation( ASTHelpers.getSymbol(tree.getIdentifier()).getTypeParameters(), ASTHelpers.getType(tree).getTypeArguments()); if (info.isPresent()) { state.reportMatch(buildDescription(tree).setMessage(info.message()).build()); } return NO_MATCH; } private Description checkInvocation( Tree tree, Type methodType, VisitorState state, Symbol symbol) { ThreadSafeAnalysis analysis = new ThreadSafeAnalysis(this, state, wellKnownThreadSafety); Violation info = analysis.checkInvocation(methodType, symbol); if (info.isPresent()) { state.reportMatch(buildDescription(tree).setMessage(info.message()).build()); } return NO_MATCH; } @Override public Description matchTypeParameter(TypeParameterTree tree, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(tree); if (sym == null) { return NO_MATCH; } switch (sym.owner.getKind()) { case METHOD: case CONSTRUCTOR: return NO_MATCH; default: // fall out } ThreadSafeAnalysis analysis = new ThreadSafeAnalysis(this, state, wellKnownThreadSafety); if (analysis.hasThreadSafeTypeParameterAnnotation((TypeVariableSymbol) sym)) { if (analysis.getThreadSafeAnnotation(sym.owner, state) == null) { return buildDescription(tree) .setMessage("@ThreadSafe.TypeParameter is only supported on threadsafe classes") .build(); } } if (checkElementUsage && analysis.hasThreadSafeElementAnnotation((TypeVariableSymbol) sym)) { if (analysis.getThreadSafeAnnotation(sym.owner, state) == null) { return buildDescription(tree) .setMessage("@ThreadSafe.Element is only supported on threadsafe classes") .build(); } } return NO_MATCH; } @Override public Description matchClass(ClassTree tree, VisitorState state) { ThreadSafeAnalysis analysis = new ThreadSafeAnalysis(this, state, wellKnownThreadSafety); if (tree.getSimpleName().length() == 0) { // anonymous classes have empty names // TODO(cushon): once Java 8 happens, require @ThreadSafe on anonymous classes return handleAnonymousClass(tree, state, analysis); } AnnotationInfo annotation = analysis.getThreadSafeAnnotation(tree, state); if (annotation == null) { // If the type isn't annotated we don't check for thread safety, but we do // report an error if it extends/implements any @ThreadSafe-annotated types. return checkSubtype(tree, state); } // Special-case visiting declarations of known-threadsafe types; these uses // of the annotation are "trusted". if (wellKnownThreadSafety.getKnownThreadSafeClasses().containsValue(annotation)) { return NO_MATCH; } // Check that the types in containerOf actually exist Map<String, TypeVariableSymbol> typarams = new HashMap<>(); for (TypeParameterTree typaram : tree.getTypeParameters()) { typarams.put( typaram.getName().toString(), (TypeVariableSymbol) ASTHelpers.getSymbol(typaram)); } SetView<String> difference = Sets.difference(annotation.containerOf(), typarams.keySet()); if (!difference.isEmpty()) { return buildDescription(tree) .setMessage( String.format( "could not find type(s) referenced by containerOf: %s", Joiner.on("', '").join(difference))) .build(); } ImmutableSet<String> threadSafeAndContainer = typarams.entrySet().stream() .filter( e -> annotation.containerOf().contains(e.getKey()) && analysis.hasThreadSafeTypeParameterAnnotation(e.getValue())) .map(Entry::getKey) .collect(toImmutableSet()); if (!threadSafeAndContainer.isEmpty()) { return buildDescription(tree) .setMessage( String.format( "using both @ThreadSafe.TypeParameter and @ThreadSafe.Element is redundant: %s", Joiner.on("', '").join(threadSafeAndContainer))) .build(); } // Main path for @ThreadSafe-annotated types: // // Check that the fields (including inherited fields) are threadsafe, and // validate the type hierarchy superclass. Violation info = analysis.checkForThreadSafety( Optional.of(tree), analysis.threadSafeTypeParametersInScope(ASTHelpers.getSymbol(tree)), ASTHelpers.getType(tree)); if (!info.isPresent()) { return NO_MATCH; } String message = "type annotated with @ThreadSafe could not be proven threadsafe: " + info.message(); return buildDescription(tree).setMessage(message).build(); } // Anonymous classes /** Check anonymous implementations of {@code @ThreadSafe} types. */ private Description handleAnonymousClass( ClassTree tree, VisitorState state, ThreadSafeAnalysis analysis) { ClassSymbol sym = ASTHelpers.getSymbol(tree); if (sym == null) { return NO_MATCH; } Type superType = threadSafeSupertype(sym, state); if (superType == null) { return NO_MATCH; } // We don't need to check that the superclass has a threadsafe instantiation. // The anonymous instance can only be referred to using a superclass type, so // the type arguments will be validated at any type use site where we care about // the instance's threadsafety. ImmutableSet<String> typarams = analysis.threadSafeTypeParametersInScope(sym); Violation info = analysis.areFieldsThreadSafe(Optional.of(tree), typarams, ASTHelpers.getType(tree)); if (!info.isPresent()) { return NO_MATCH; } String reason = Joiner.on(", ").join(info.path()); String message = String.format( "Class extends @ThreadSafe type %s, but is not threadsafe: %s", superType, reason); return buildDescription(tree).setMessage(message).build(); } // Strong behavioural subtyping /** Check for classes without {@code @ThreadSafe} that have threadsafe supertypes. */ private Description checkSubtype(ClassTree tree, VisitorState state) { ClassSymbol sym = ASTHelpers.getSymbol(tree); if (sym == null) { return NO_MATCH; } Type superType = threadSafeSupertype(sym, state); if (superType == null) { return NO_MATCH; } if (ASTHelpers.hasAnnotation(sym, Immutable.class, state)) { // If the superclass is @ThreadSafe and the subclass is @Immutable, then the subclass is // effectively also @ThreadSafe, and we defer to the @Immutable plugin. return NO_MATCH; } String message = String.format( "Class extends @ThreadSafe type %s, but is not annotated as threadsafe", superType); SuggestedFix.Builder fix = SuggestedFix.builder(); String typeName = SuggestedFixes.qualifyType(state, fix, ThreadSafe.class.getName()); fix.prefixWith(tree, "@" + typeName + " "); return buildDescription(tree).setMessage(message).addFix(fix.build()).build(); } /** * Returns the type of the first superclass or superinterface in the hierarchy annotated with * {@code @ThreadSafe}, or {@code null} if no such super type exists. */ private static @Nullable Type threadSafeSupertype(Symbol sym, VisitorState state) { for (Type superType : state.getTypes().closure(sym.type)) { if (superType.asElement().equals(sym)) { continue; } // Don't use getThreadSafeAnnotation here: subtypes of trusted types are // also trusted, only check for explicitly annotated supertypes. if (ASTHelpers.hasAnnotation(superType.tsym, ThreadSafe.class, state)) { return superType; } // We currently trust that @interface annotations are threadsafe, but don't enforce that // custom interface implementations are also threadsafe. That means the check can be // defeated by writing a custom mutable annotation implementation, and passing it around // using the superclass type. // // TODO(b/25630189): fix this // // if (superType.tsym.getKind() == ElementKind.ANNOTATION_TYPE) { // return superType; // } } return null; } }
13,008
40.167722
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/WellKnownMutability.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.threadsafety; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.primitives.Primitives; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.bugpatterns.ImmutableCollections; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.suppliers.Suppliers; import com.sun.tools.javac.code.Type; import java.util.List; import java.util.stream.Stream; import javax.inject.Inject; /** A collection of types with known mutability. */ @Immutable public final class WellKnownMutability implements ThreadSafety.KnownTypes { /** Types that are known to be immutable. */ private final ImmutableMap<String, AnnotationInfo> knownImmutableClasses; /** Types that are known to be mutable. */ private final ImmutableSet<String> knownMutableClasses; @Inject WellKnownMutability(ErrorProneFlags flags) { List<String> immutable = flags.getList("Immutable:KnownImmutable").orElse(ImmutableList.of()); ImmutableList<String> mutable = // Please use "KnownMutable", as it's a bit clearer what we mean. "KnownUnsafe" is kept // for a while for backwards compatibility. Stream.of("Immutable:KnownMutable", "Immutable:KnownUnsafe") .flatMap(f -> flags.getList(f).orElse(ImmutableList.of()).stream()) .collect(toImmutableList()); this.knownImmutableClasses = buildImmutableClasses(immutable); this.knownMutableClasses = buildMutableClasses(mutable); } public static WellKnownMutability fromFlags(ErrorProneFlags flags) { return new WellKnownMutability(flags); } public ImmutableMap<String, AnnotationInfo> getKnownImmutableClasses() { return knownImmutableClasses; } /** * @deprecated {@link #getKnownImmutableClasses()} is clearer if you're dealing with this specific * class. */ @Override @Deprecated public ImmutableMap<String, AnnotationInfo> getKnownSafeClasses() { return getKnownImmutableClasses(); } public ImmutableSet<String> getKnownMutableClasses() { return knownMutableClasses; } /** * @deprecated {@link #getKnownMutableClasses()} is clearer if you're dealing with this specific * class. */ @Override @Deprecated public ImmutableSet<String> getKnownUnsafeClasses() { return getKnownMutableClasses(); } // TODO(b/35724557): share this list with other code analyzing types for immutability // TODO(cushon): generate this at build-time to get type-safety without added compile-time deps @SuppressWarnings("UnnecessarilyFullyQualified") // intentional private static ImmutableMap<String, AnnotationInfo> buildImmutableClasses( List<String> extraKnownImmutables) { return new MapBuilder() .addStrings(extraKnownImmutables) .addClasses(Primitives.allPrimitiveTypes()) .addClasses(Primitives.allWrapperTypes()) .add("com.github.zafarkhaja.semver.Version") .add("com.google.protobuf.ByteString") .add("com.google.protobuf.Descriptors$Descriptor") .add("com.google.protobuf.Descriptors$EnumDescriptor") .add("com.google.protobuf.Descriptors$EnumValueDescriptor") .add("com.google.protobuf.Descriptors$FieldDescriptor") .add("com.google.protobuf.Descriptors$FileDescriptor") .add("com.google.protobuf.Descriptors$OneofDescriptor") .add("com.google.protobuf.Descriptors$ServiceDescriptor") .add("com.google.protobuf.Extension") .add("com.google.protobuf.ExtensionRegistry$ExtensionInfo") // NOTE: GeneratedMessage is included here for external tests that use this class for // checking whether classes are immutable. Within error prone, protos are verified // using isProto2MessageClass from this class. .add("com.google.protobuf.GeneratedMessage") .add("com.google.re2j.Pattern") .add("com.google.inject.TypeLiteral") .add("com.google.inject.Key") .add(com.google.common.base.CharMatcher.class) .add(com.google.common.base.Converter.class) .add(com.google.common.base.Joiner.class) .add(com.google.common.base.Optional.class, "T") .add(com.google.common.base.Splitter.class) .add(com.google.common.collect.ContiguousSet.class, "C") .add(com.google.common.collect.ImmutableBiMap.class, "K", "V") .add(com.google.common.collect.ImmutableCollection.class, "E") .add(com.google.common.collect.ImmutableList.class, "E") .add(com.google.common.collect.ImmutableListMultimap.class, "K", "V") .add(com.google.common.collect.ImmutableMap.class, "K", "V") .add(com.google.common.collect.ImmutableMultimap.class, "K", "V") .add(com.google.common.collect.ImmutableMultiset.class, "E") .add(com.google.common.collect.ImmutableRangeMap.class, "K", "V") .add(com.google.common.collect.ImmutableRangeSet.class, "C") .add(com.google.common.collect.ImmutableSet.class, "E") .add(com.google.common.collect.ImmutableSetMultimap.class, "K", "V") .add(com.google.common.collect.ImmutableSortedMap.class, "K", "V") .add(com.google.common.collect.ImmutableSortedMultiset.class, "E") .add(com.google.common.collect.ImmutableSortedSet.class, "E") .add(com.google.common.collect.ImmutableTable.class, "R", "C", "V") .add(com.google.common.collect.Range.class, "C") .add(com.google.common.graph.ImmutableGraph.class, "N") .add(com.google.common.graph.ImmutableNetwork.class, "N", "E") .add(com.google.common.graph.ImmutableValueGraph.class, "N", "V") .add("com.google.common.hash.AbstractHashFunction") // package-private .add(com.google.common.hash.HashCode.class) .add(com.google.common.io.BaseEncoding.class) .add(com.google.common.net.MediaType.class) .add(com.google.common.primitives.UnsignedInteger.class) .add(com.google.common.primitives.UnsignedLong.class) .add("com.ibm.icu.number.LocalizedNumberFormatter") .add("com.ibm.icu.number.LocalizedNumberRangeFormatter") .add("com.ibm.icu.number.UnlocalizedNumberFormatter") .add("com.ibm.icu.number.UnlocalizedNumberRangeFormatter") .add("com.ibm.icu.util.Currency") .add("com.ibm.icu.util.ULocale") .add(java.lang.Class.class) .add(java.lang.Enum.class, "E") .add(java.lang.String.class) .add(java.lang.annotation.Annotation.class) .add(java.math.BigDecimal.class) .add(java.math.BigInteger.class) .add(java.net.Inet4Address.class) .add(java.net.Inet6Address.class) .add(java.net.InetAddress.class) .add(java.net.URI.class) .add(java.net.http.HttpClient.class) .add(java.nio.ByteOrder.class) .add(java.nio.charset.Charset.class) .add(java.nio.file.Path.class) .add(java.nio.file.WatchEvent.class) .add(java.nio.file.attribute.AclEntry.class) .add(java.nio.file.attribute.FileTime.class) .add(java.util.UUID.class) .add(java.util.Locale.class) .add(java.util.regex.Pattern.class) .add("android.net.Uri") .add("android.util.Size") .add("java.awt.Color") .add("java.lang.invoke.MethodHandle") .add("java.util.AbstractMap$SimpleImmutableEntry", "K", "V") .add("java.util.Optional", "T") .add("java.util.OptionalDouble") .add("java.util.OptionalInt") .add("java.util.OptionalLong") .add("java.time.Clock") .add("java.time.Duration") .add("java.time.Instant") .add("java.time.LocalDate") .add("java.time.LocalDateTime") .add("java.time.LocalTime") .add("java.time.MonthDay") .add("java.time.OffsetDateTime") .add("java.time.OffsetTime") .add("java.time.Period") .add("java.time.Year") .add("java.time.YearMonth") .add("java.time.ZoneId") .add("java.time.ZoneOffset") .add("java.time.ZonedDateTime") .add("java.time.chrono.AbstractChronology") .add("java.time.chrono.ChronoLocalDate") .add("java.time.chrono.ChronoLocalDateTime", "D") .add("java.time.chrono.ChronoPeriod") .add("java.time.chrono.ChronoZonedDateTime", "D") .add("java.time.chrono.Chronology") .add("java.time.chrono.Era") .add("java.time.chrono.HijrahChronology") .add("java.time.chrono.HijrahDate") .add("java.time.chrono.IsoChronology") .add("java.time.chrono.JapaneseChronology") .add("java.time.chrono.JapaneseDate") .add("java.time.chrono.JapaneseEra") .add("java.time.chrono.MinguoChronology") .add("java.time.chrono.MinguoDate") .add("java.time.chrono.ThaiBuddhistChronology") .add("java.time.chrono.ThaiBuddhistDate") .add("java.time.format.DateTimeFormatter") .add("java.time.format.DecimalStyle") .add("java.time.temporal.TemporalField") .add("java.time.temporal.TemporalUnit") .add("java.time.temporal.ValueRange") .add("java.time.temporal.WeekFields") .add("java.time.zone.ZoneOffsetTransition") .add("java.time.zone.ZoneOffsetTransitionRule") .add("java.time.zone.ZoneRules") .add("java.time.zone.ZoneRulesProvider") .add("kotlin.Unit") .add("kotlin.Pair", "A", "B") .add("kotlin.Triple", "A", "B", "C") .add("kotlin.time.Duration") .add("org.threeten.bp.Duration") .add("org.threeten.bp.Instant") .add("org.threeten.bp.LocalDate") .add("org.threeten.bp.LocalDateTime") .add("org.threeten.bp.LocalTime") .add("org.threeten.bp.MonthDay") .add("org.threeten.bp.OffsetDateTime") .add("org.threeten.bp.OffsetTime") .add("org.threeten.bp.Period") .add("org.threeten.bp.Year") .add("org.threeten.bp.YearMonth") .add("org.threeten.bp.ZoneId") .add("org.threeten.bp.ZoneOffset") .add("org.threeten.bp.ZonedDateTime") .add("org.threeten.bp.chrono.AbstractChronology") .add("org.threeten.bp.chrono.ChronoLocalDate") .add("org.threeten.bp.chrono.ChronoLocalDateTime", "D") .add("org.threeten.bp.chrono.ChronoPeriod") .add("org.threeten.bp.chrono.ChronoZonedDateTime", "D") .add("org.threeten.bp.chrono.Chronology") .add("org.threeten.bp.chrono.Era") .add("org.threeten.bp.chrono.HijrahChronology") .add("org.threeten.bp.chrono.HijrahDate") .add("org.threeten.bp.chrono.IsoChronology") .add("org.threeten.bp.chrono.JapaneseChronology") .add("org.threeten.bp.chrono.JapaneseDate") .add("org.threeten.bp.chrono.JapaneseEra") .add("org.threeten.bp.chrono.MinguoChronology") .add("org.threeten.bp.chrono.MinguoDate") .add("org.threeten.bp.chrono.ThaiBuddhistChronology") .add("org.threeten.bp.chrono.ThaiBuddhistDate") .add("org.threeten.bp.format.DateTimeFormatter") .add("org.threeten.bp.format.DecimalStyle") .add("org.threeten.bp.temporal.TemporalField") .add("org.threeten.bp.temporal.TemporalUnit") .add("org.threeten.bp.temporal.ValueRange") .add("org.threeten.bp.temporal.WeekFields") .add("org.threeten.bp.zone.ZoneOffsetTransition") .add("org.threeten.bp.zone.ZoneOffsetTransitionRule") .add("org.threeten.bp.zone.ZoneRules") .add("org.threeten.bp.zone.ZoneRulesProvider") .add("org.threeten.extra.DayOfMonth") .add("org.threeten.extra.DayOfYear") .add("org.threeten.extra.Days") .add("org.threeten.extra.Hours") .add("org.threeten.extra.Interval") .add("org.threeten.extra.LocalDateRange") .add("org.threeten.extra.Minutes") .add("org.threeten.extra.Months") .add("org.threeten.extra.PeriodDuration") .add("org.threeten.extra.Seconds") .add("org.threeten.extra.Weeks") .add("org.threeten.extra.YearQuarter") .add("org.threeten.extra.YearWeek") .add("org.threeten.extra.Years") .add("org.joda.time.DateTime") .add("org.joda.time.DateTimeZone") .add("org.joda.time.Days") .add("org.joda.time.Duration") .add("org.joda.time.Instant") .add("org.joda.time.Interval") .add("org.joda.time.LocalDate") .add("org.joda.time.LocalDateTime") .add("org.joda.time.Period") .add("org.joda.time.format.DateTimeFormatter") .add("org.openqa.selenium.Dimension") .add("org.openqa.selenium.DeviceRotation") .add("org.openqa.selenium.ImmutableCapabilities") .build(); } private static ImmutableSet<String> buildMutableClasses(List<String> knownMutables) { return ImmutableSet.<String>builder() .addAll(knownMutables) .addAll(ImmutableCollections.MUTABLE_TO_IMMUTABLE_CLASS_NAME_MAP.keySet()) .add("com.google.common.util.concurrent.AtomicDouble") .add("com.google.protobuf.util.FieldMaskUtil.MergeOptions") .add(java.util.BitSet.class.getName()) .add(java.util.Calendar.class.getName()) .add(java.lang.Iterable.class.getName()) .add(java.lang.Object.class.getName()) .add("java.text.DateFormat") .add(java.util.ArrayList.class.getName()) .add(java.util.Collection.class.getName()) .add(java.util.EnumMap.class.getName()) .add(java.util.EnumSet.class.getName()) .add(java.util.List.class.getName()) .add(java.util.logging.Logger.class.getName()) .add(java.util.Map.class.getName()) .add(java.util.HashMap.class.getName()) .add(java.util.HashSet.class.getName()) .add(java.util.NavigableMap.class.getName()) .add(java.util.NavigableSet.class.getName()) .add(java.util.Random.class.getName()) .add(java.util.TreeMap.class.getName()) .add(java.util.TreeSet.class.getName()) .add(java.util.Vector.class.getName()) .add(java.util.Set.class.getName()) .add(java.util.concurrent.atomic.AtomicBoolean.class.getName()) .add(java.util.concurrent.atomic.AtomicReference.class.getName()) .add(java.util.concurrent.atomic.AtomicLong.class.getName()) .build(); } // ProtocolSupport matches Message (not MessageLite) for legacy reasons private static final Supplier<Type> MESSAGE_TYPE = Suppliers.typeFromString("com.google.protobuf.MessageLite"); private static final Supplier<Type> MUTABLE_MESSAGE_TYPE = Suppliers.typeFromString("com.google.protobuf.MutableMessageLite"); private static final Supplier<Type> PROTOCOL_MESSAGE_TYPE = Suppliers.typeFromString("com.google.io.protocol.ProtocolMessage"); private static boolean isAssignableTo(Type type, Supplier<Type> supplier, VisitorState state) { Type to = supplier.get(state); if (to == null) { // the type couldn't be loaded return false; } to = state.getTypes().erasure(to); return state.getTypes().isAssignable(type, to); } /** * Compile-time equivalent of {@code com.google.io.protocol.ProtocolSupport#isProto2MessageClass}. */ public static boolean isProto2MessageClass(VisitorState state, Type type) { checkNotNull(type); return isAssignableTo(type, MESSAGE_TYPE, state) && !isAssignableTo(type, PROTOCOL_MESSAGE_TYPE, state); } /** * Compile-time equivalent of {@code * com.google.io.protocol.ProtocolSupport#isProto2MutableMessageClass}. */ public static boolean isProto2MutableMessageClass(VisitorState state, Type type) { checkNotNull(type); return isAssignableTo(type, MUTABLE_MESSAGE_TYPE, state) && !isAssignableTo(type, PROTOCOL_MESSAGE_TYPE, state); } /** Returns true if the type is an annotation. */ public static boolean isAnnotation(VisitorState state, Type type) { return isAssignableTo(type, Suppliers.ANNOTATION_TYPE, state); } }
17,063
44.023747
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByBinder.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.threadsafety; import static com.google.errorprone.bugpatterns.threadsafety.IllegalGuardedBy.checkGuardedBy; import static com.google.errorprone.util.ASTHelpers.isStatic; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.threadsafety.GuardedByExpression.Kind; 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.MemberReferenceTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.Names; import java.util.Optional; import javax.lang.model.element.Name; import org.checkerframework.checker.nullness.qual.Nullable; /** * A binder from {@code @GuardedBy} annotations to {@link GuardedByExpression}s. * * @author cushon@google.com (Liam Miller-Cushon) */ public final class GuardedByBinder { /** * Creates a {@link GuardedByExpression} from a bound AST node, or returns {@code * Optional.empty()} if the AST node doesn't correspond to a 'simple' lock expression. */ public static Optional<GuardedByExpression> bindExpression( JCTree.JCExpression exp, VisitorState visitorState, GuardedByFlags flags) { try { return Optional.of( bind( exp, BinderContext.of( ALREADY_BOUND_RESOLVER, ASTHelpers.getSymbol(visitorState.findEnclosing(ClassTree.class)), visitorState.getTypes(), visitorState.getNames(), flags))); } catch (IllegalGuardedBy expected) { return Optional.empty(); } } /** Creates a {@link GuardedByExpression} from a string, given the resolution context. */ public static Optional<GuardedByExpression> bindString( String string, GuardedBySymbolResolver resolver, GuardedByFlags flags) { try { return Optional.of( bind( GuardedByUtils.parseString(string, resolver.context()), BinderContext.of( resolver, resolver.enclosingClass(), resolver.visitorState().getTypes(), resolver.visitorState().getNames(), flags))); } catch (IllegalGuardedBy expected) { return Optional.empty(); } } private static class BinderContext { final Resolver resolver; final ClassSymbol thisClass; final Types types; final Names names; final GuardedByFlags flags; public BinderContext( Resolver resolver, ClassSymbol thisClass, Types types, Names names, GuardedByFlags flags) { this.resolver = resolver; this.thisClass = thisClass; this.types = types; this.names = names; this.flags = flags; } public static BinderContext of( Resolver resolver, ClassSymbol thisClass, Types types, Names names, GuardedByFlags flags) { return new BinderContext(resolver, thisClass, types, names, flags); } } private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) { GuardedByExpression expr = BINDER.visit(exp, context); checkGuardedBy(expr != null, String.valueOf(exp)); checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp); return expr; } /** * A context containing the information necessary to resolve a {@link * com.sun.tools.javac.code.Symbol} from an AST node. * * <p>Guard expressions can be bound from the string value of an {@code @GuardedBy} annotation, or * from an actual java expression. In the first case, the string is parsed into an AST which will * not have any semantic information attached. */ public interface Resolver { Symbol resolveIdentifier(IdentifierTree node); Symbol.MethodSymbol resolveMethod(MethodInvocationTree node, Name name); Symbol.MethodSymbol resolveMethod( MethodInvocationTree node, GuardedByExpression base, Name identifier); Symbol resolveSelect(GuardedByExpression base, MemberSelectTree node); Symbol resolveMemberReference(GuardedByExpression base, MemberReferenceTree node); Symbol resolveTypeLiteral(ExpressionTree expression); Symbol resolveEnclosingClass(ExpressionTree expression); } /** A resolver for AST nodes that have already been bound by javac. */ static final Resolver ALREADY_BOUND_RESOLVER = new Resolver() { @Override public Symbol resolveIdentifier(IdentifierTree node) { return ASTHelpers.getSymbol(node); } @Override public Symbol.MethodSymbol resolveMethod(MethodInvocationTree node, Name name) { return ASTHelpers.getSymbol(node); } @Override public Symbol.MethodSymbol resolveMethod( MethodInvocationTree node, GuardedByExpression base, Name identifier) { return ASTHelpers.getSymbol(node); } @Override public Symbol resolveSelect(GuardedByExpression base, MemberSelectTree node) { return ASTHelpers.getSymbol(node); } @Override public Symbol resolveMemberReference(GuardedByExpression base, MemberReferenceTree node) { return ASTHelpers.getSymbol(node); } @Override public Symbol resolveTypeLiteral(ExpressionTree expression) { return ASTHelpers.getSymbol(expression); } @Override public Symbol resolveEnclosingClass(ExpressionTree expression) { return ASTHelpers.getSymbol(expression); } }; private static final GuardedByExpression.Factory F = new GuardedByExpression.Factory(); private static final SimpleTreeVisitor<GuardedByExpression, BinderContext> BINDER = new SimpleTreeVisitor<GuardedByExpression, BinderContext>() { @Override public GuardedByExpression visitMethodInvocation( MethodInvocationTree node, BinderContext context) { checkGuardedBy( node.getArguments().isEmpty() && node.getTypeArguments().isEmpty(), "Only nullary methods are allowed."); ExpressionTree methodSelect = node.getMethodSelect(); switch (methodSelect.getKind()) { case IDENTIFIER: { IdentifierTree identifier = (IdentifierTree) methodSelect; Symbol.MethodSymbol method = context.resolver.resolveMethod(node, identifier.getName()); checkGuardedBy(method != null, identifier.toString()); return bindSelect(computeBase(context, method), method); } case MEMBER_SELECT: { MemberSelectTree select = (MemberSelectTree) methodSelect; GuardedByExpression base = visit(select.getExpression(), context); checkGuardedBy(base != null, select.getExpression().toString()); Symbol.MethodSymbol method = context.resolver.resolveMethod(node, base, select.getIdentifier()); checkGuardedBy(method != null, select.toString()); return bindSelect(normalizeBase(context, method, base), method); } default: throw new IllegalGuardedBy(methodSelect.getKind().toString()); } } @Override public GuardedByExpression visitMemberSelect(MemberSelectTree node, BinderContext context) { String name = node.getIdentifier().toString(); if (name.equals("this")) { Symbol base = context.resolver.resolveEnclosingClass(node.getExpression()); if (context.thisClass == base) { return F.thisliteral(); } return F.qualifiedThis(context.names, context.thisClass, base); } if (name.equals("class")) { Symbol base = context.resolver.resolveTypeLiteral(node.getExpression()); return F.classLiteral(base); } GuardedByExpression base = visit(node.getExpression(), context); checkGuardedBy(base != null, "Bad expression: %s", node.getExpression()); Symbol sym = context.resolver.resolveSelect(base, node); checkGuardedBy(sym != null, "Could not resolve: %s", node); boolean condition = sym instanceof Symbol.VarSymbol || sym instanceof Symbol.MethodSymbol; checkGuardedBy(condition, "Bad member symbol: %s", sym.getClass()); return bindSelect(normalizeBase(context, sym, base), sym); } @Override public GuardedByExpression visitMemberReference( MemberReferenceTree node, BinderContext context) { GuardedByExpression base = visit(node.getQualifierExpression(), context); checkGuardedBy(base != null, node.getQualifierExpression().toString()); Symbol method = context.resolver.resolveMemberReference(base, node); checkGuardedBy(method != null, node.toString()); return bindSelect(normalizeBase(context, method, base), method); } private GuardedByExpression bindSelect(GuardedByExpression base, Symbol sym) { if (base.kind().equals(Kind.TYPE_LITERAL) && !isStatic(sym)) { throw new IllegalGuardedBy("Instance access on static: " + base + ", " + sym); } // TODO(cushon) - forbid static access on instance? return F.select(base, sym); } @Override public GuardedByExpression visitIdentifier(IdentifierTree node, BinderContext context) { Symbol symbol = context.resolver.resolveIdentifier(node); checkGuardedBy(symbol != null, "Could not resolve %s", node); if (symbol instanceof Symbol.VarSymbol) { Symbol.VarSymbol varSymbol = (Symbol.VarSymbol) symbol; switch (varSymbol.getKind()) { case LOCAL_VARIABLE: case PARAMETER: return F.localVariable(varSymbol); case FIELD: { if (symbol.name.contentEquals("this")) { return F.thisliteral(); } return F.select(computeBase(context, varSymbol), varSymbol); } default: throw new IllegalGuardedBy(varSymbol.getKind().toString()); } } else if (symbol instanceof Symbol.MethodSymbol) { Symbol.MethodSymbol methodSymbol = (Symbol.MethodSymbol) symbol; return F.select(computeBase(context, symbol), methodSymbol); } else if (symbol instanceof Symbol.ClassSymbol) { if (node.getName().contentEquals("this")) { return F.thisliteral(); } else { return F.typeLiteral(symbol); } } throw new IllegalGuardedBy(symbol.getClass().toString()); } @Override public GuardedByExpression visitParenthesized( ParenthesizedTree node, BinderContext context) { return node.getExpression().accept(this, context); } /** * Determines the implicit receiver of a select expression that accesses the given symbol by * simple name in the given resolution context. */ private GuardedByExpression computeBase(BinderContext context, Symbol symbol) { return normalizeBase(context, symbol, null); } /** * Normalizes the receiver of a select expression so that accesses on 'this' are divided * into type names (for static accesses), qualified this accesses (for members of a * lexically enclosing scope), or simple this accesses for members of the current class. */ private GuardedByExpression normalizeBase( BinderContext context, Symbol symbol, GuardedByExpression base) { if (isStatic(symbol)) { return F.typeLiteral(symbol.owner.enclClass()); } if (base != null && base.kind() != GuardedByExpression.Kind.THIS) { return base; } if (symbol.isMemberOf(context.thisClass.type.tsym, context.types)) { return F.thisliteral(); } Symbol lexicalOwner = isEnclosedIn(context.thisClass, symbol, context.types); if (lexicalOwner != null) { return F.qualifiedThis(context.names, context.thisClass, lexicalOwner); } throw new IllegalGuardedBy("Could not find the implicit receiver."); } /** * Returns the owner if the given member is declared in a lexically enclosing scope, and * {@code null} otherwise. */ private @Nullable ClassSymbol isEnclosedIn( ClassSymbol startingClass, Symbol member, Types types) { for (ClassSymbol scope = startingClass.owner.enclClass(); scope != null; scope = scope.owner.enclClass()) { if (member.isMemberOf(scope.type.tsym, types)) { return scope; } } return null; } }; private GuardedByBinder() {} }
14,145
38.513966
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByUtils.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.threadsafety; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isStatic; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.threadsafety.GuardedByExpression.Select; import com.google.errorprone.util.MoreAnnotations; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.parser.JavacParser; import com.sun.tools.javac.parser.ParserFactory; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.Context; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import javax.lang.model.element.ElementKind; import org.checkerframework.checker.nullness.qual.Nullable; /** * @author cushon@google.com (Liam Miller-Cushon) */ public final class GuardedByUtils { public static ImmutableSet<String> getGuardValues(Symbol sym) { return getAnnotationValueAsStrings(sym); } static ImmutableSet<String> getGuardValues(Tree tree, VisitorState state) { Symbol sym = getSymbol(tree); if (sym == null) { return ImmutableSet.of(); } return getAnnotationValueAsStrings(sym); } private static ImmutableSet<String> getAnnotationValueAsStrings(Symbol sym) { List<Attribute.Compound> rawAttributes = sym.getRawAttributes(); if (rawAttributes.isEmpty()) { return ImmutableSet.of(); } return rawAttributes.stream() .filter(a -> a.getAnnotationType().asElement().getSimpleName().contentEquals("GuardedBy")) .flatMap( a -> MoreAnnotations.getValue(a, "value") .map(MoreAnnotations::asStrings) .orElse(Stream.empty())) .collect(toImmutableSet()); } static JCTree.JCExpression parseString(String guardedByString, Context context) { JavacParser parser = ParserFactory.instance(context) .newParser( guardedByString, /* keepDocComments= */ false, /* keepEndPos= */ true, /* keepLineMap= */ false); JCTree.JCExpression exp; try { exp = parser.parseExpression(); } catch (RuntimeException e) { throw new IllegalGuardedBy(e.getMessage()); } int len = (parser.getEndPos(exp) - exp.getStartPosition()); if (len != guardedByString.length()) { throw new IllegalGuardedBy("Didn't parse entire string."); } return exp; } @AutoValue abstract static class GuardedByValidationResult { abstract String message(); abstract Boolean isValid(); static GuardedByValidationResult invalid(String message) { return new AutoValue_GuardedByUtils_GuardedByValidationResult(message, false); } static GuardedByValidationResult ok() { return new AutoValue_GuardedByUtils_GuardedByValidationResult("", true); } } public static GuardedByValidationResult isGuardedByValid( Tree tree, VisitorState state, GuardedByFlags flags) { ImmutableSet<String> guards = GuardedByUtils.getGuardValues(tree, state); if (guards.isEmpty()) { return GuardedByValidationResult.ok(); } List<GuardedByExpression> boundGuards = new ArrayList<>(); for (String guard : guards) { Optional<GuardedByExpression> boundGuard = GuardedByBinder.bindString(guard, GuardedBySymbolResolver.from(tree, state), flags); if (!boundGuard.isPresent()) { return GuardedByValidationResult.invalid("could not resolve guard"); } boundGuards.add(boundGuard.get()); } Symbol treeSym = getSymbol(tree); if (treeSym == null) { // this shouldn't happen unless the compilation had already failed. return GuardedByValidationResult.ok(); } for (GuardedByExpression boundGuard : boundGuards) { GuardedByExpression boundGuardRoot = boundGuard.kind() == GuardedByExpression.Kind.SELECT ? ((Select) boundGuard).root() : boundGuard; boolean parameterGuard = boundGuardRoot.sym() != null && boundGuardRoot.sym().getKind() == ElementKind.PARAMETER; boolean staticGuard = boundGuard.kind() == GuardedByExpression.Kind.CLASS_LITERAL || (boundGuard.sym() != null && isStatic(boundGuard.sym())); if (isStatic(treeSym) && !staticGuard && !parameterGuard) { return GuardedByValidationResult.invalid("static member guarded by instance"); } } return GuardedByValidationResult.ok(); } public static @Nullable Symbol bindGuardedByString( Tree tree, String guard, VisitorState visitorState, GuardedByFlags flags) { Optional<GuardedByExpression> bound = GuardedByBinder.bindString(guard, GuardedBySymbolResolver.from(tree, visitorState), flags); if (!bound.isPresent()) { return null; } return bound.get().sym(); } private GuardedByUtils() {} }
5,805
34.839506
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/HeldLockAnalyzer.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.threadsafety; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.staticMethod; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.threadsafety.GuardedByExpression.Kind; import com.google.errorprone.bugpatterns.threadsafety.GuardedByExpression.Select; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.SynchronizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TryTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePathScanner; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCNewClass; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import javax.lang.model.element.Modifier; /** * A method body analyzer. Responsible for tracking the set of held locks, and checking accesses to * guarded members. * * @author cushon@google.com (Liam Miller-Cushon) */ public final class HeldLockAnalyzer { /** Methods which invoke lambdas on the same thread. */ static final Matcher<ExpressionTree> INVOKES_LAMBDAS_IMMEDIATELY = anyOf( instanceMethod() .onExactClass("java.util.Optional") .namedAnyOf( "ifPresent", "ifPresentOrElse", "filter", "map", "flatMap", "or", "orElseGet", "orElseThrow"), instanceMethod() .onDescendantOf("java.util.Map") .namedAnyOf("forEach", "replaceAll", "computeIfAbsent", "computeIfPresent", "merge"), instanceMethod().onDescendantOf("java.util.List").named("replaceAll"), instanceMethod().onDescendantOf("java.util.Iterable").named("forEach"), instanceMethod().onDescendantOf("java.util.Iterator").named("forEachRemaining"), staticMethod() .onClass("com.google.common.collect.Iterables") .namedAnyOf("tryFind", "any", "all", "indexOf")); /** Listener interface for accesses to guarded members. */ public interface LockEventListener { /** * Handles a guarded member access. * * @param tree The member access expression. * @param guard The member's guard expression. * @param locks The set of held locks. */ void handleGuardedAccess(ExpressionTree tree, GuardedByExpression guard, HeldLockSet locks); } /** * Analyzes a method body, tracking the set of held locks and checking accesses to guarded * members. */ public static void analyze( VisitorState state, LockEventListener listener, Predicate<Tree> isSuppressed, GuardedByFlags flags) { HeldLockSet locks = HeldLockSet.empty(); locks = handleMonitorGuards(state, locks, flags); new LockScanner(state, listener, isSuppressed, flags).scan(state.getPath(), locks); } // Don't use Class#getName() for inner classes, we don't want `Monitor$Guard` private static final String MONITOR_GUARD_CLASS = "com.google.common.util.concurrent.Monitor.Guard"; private static HeldLockSet handleMonitorGuards( VisitorState state, HeldLockSet locks, GuardedByFlags flags) { JCNewClass newClassTree = ASTHelpers.findEnclosingNode(state.getPath(), JCNewClass.class); if (newClassTree == null) { return locks; } Symbol clazzSym = ASTHelpers.getSymbol(newClassTree.clazz); if (!(clazzSym instanceof ClassSymbol)) { return locks; } if (!((ClassSymbol) clazzSym).fullname.contentEquals(MONITOR_GUARD_CLASS)) { return locks; } Optional<GuardedByExpression> lockExpression = GuardedByBinder.bindExpression( Iterables.getOnlyElement(newClassTree.getArguments()), state, flags); if (!lockExpression.isPresent()) { return locks; } return locks.plus(lockExpression.get()); } private static class LockScanner extends TreePathScanner<Void, HeldLockSet> { private final VisitorState visitorState; private final LockEventListener listener; private final Predicate<Tree> isSuppressed; private final GuardedByFlags flags; private static final GuardedByExpression.Factory F = new GuardedByExpression.Factory(); private LockScanner( VisitorState visitorState, LockEventListener listener, Predicate<Tree> isSuppressed, GuardedByFlags flags) { this.visitorState = visitorState; this.listener = listener; this.isSuppressed = isSuppressed; this.flags = flags; } @Override public Void visitMethod(MethodTree tree, HeldLockSet locks) { if (isSuppressed.test(tree)) { return null; } // Synchronized instance methods hold the 'this' lock; synchronized static methods // hold the Class lock for the enclosing class. Set<Modifier> mods = tree.getModifiers().getFlags(); if (mods.contains(Modifier.SYNCHRONIZED)) { Symbol owner = (((JCTree.JCMethodDecl) tree).sym.owner); GuardedByExpression lock = mods.contains(Modifier.STATIC) ? F.classLiteral(owner) : F.thisliteral(); locks = locks.plus(lock); } // @GuardedBy annotations on methods are trusted for declarations, and checked // for invocations. for (String guard : GuardedByUtils.getGuardValues(tree, visitorState)) { Optional<GuardedByExpression> bound = GuardedByBinder.bindString( guard, GuardedBySymbolResolver.from(tree, visitorState), flags); if (bound.isPresent()) { locks = locks.plus(bound.get()); } } return super.visitMethod(tree, locks); } @Override public Void visitTry(TryTree tree, HeldLockSet locks) { scan(tree.getResources(), locks); List<? extends Tree> resources = tree.getResources(); scan(resources, locks); // Cheesy try/finally heuristic: assume that all locks released in the finally // are held for the entirety of the try and catch statements. Collection<GuardedByExpression> releasedLocks = ReleasedLockFinder.find(tree.getFinallyBlock(), visitorState, flags); // TODO(cushon) - recognize common try-with-resources patterns. Currently there is no // standard implementation of an AutoCloseable lock resource to detect. scan(tree.getBlock(), locks.plusAll(releasedLocks)); scan(tree.getCatches(), locks.plusAll(releasedLocks)); scan(tree.getFinallyBlock(), locks); return null; } @Override public Void visitSynchronized(SynchronizedTree tree, HeldLockSet locks) { // The synchronized expression is held in the body of the synchronized statement: Optional<GuardedByExpression> lockExpression = GuardedByBinder.bindExpression((JCExpression) tree.getExpression(), visitorState, flags); scan(tree.getBlock(), lockExpression.isPresent() ? locks.plus(lockExpression.get()) : locks); return null; } @Override public Void visitMemberSelect(MemberSelectTree tree, HeldLockSet locks) { checkMatch(tree, locks); return super.visitMemberSelect(tree, locks); } @Override public Void visitIdentifier(IdentifierTree tree, HeldLockSet locks) { checkMatch(tree, locks); return super.visitIdentifier(tree, locks); } @Override public Void visitNewClass(NewClassTree tree, HeldLockSet locks) { scan(tree.getEnclosingExpression(), locks); scan(tree.getIdentifier(), locks); scan(tree.getTypeArguments(), locks); scan(tree.getArguments(), locks); // Don't descend into bodies of anonymous class declarations; // their method declarations will be analyzed separately. return null; } @Override public Void visitLambdaExpression(LambdaExpressionTree node, HeldLockSet heldLockSet) { var parent = getCurrentPath().getParentPath().getLeaf(); if (parent instanceof MethodInvocationTree && INVOKES_LAMBDAS_IMMEDIATELY.matches((ExpressionTree) parent, visitorState)) { return super.visitLambdaExpression(node, heldLockSet); } // Don't descend into lambdas; they will be analyzed separately. return null; } @Override public Void visitMemberReference(MemberReferenceTree tree, HeldLockSet locks) { checkMatch(tree, locks); scan(tree.getQualifierExpression(), locks); return null; } @Override public Void visitVariable(VariableTree node, HeldLockSet locks) { return isSuppressed.test(node) ? null : super.visitVariable(node, locks); } @Override public Void visitClass(ClassTree node, HeldLockSet locks) { return isSuppressed.test(node) ? null : super.visitClass(node, locks); } private void checkMatch(ExpressionTree tree, HeldLockSet locks) { for (String guardString : GuardedByUtils.getGuardValues(tree, visitorState)) { Optional<GuardedByExpression> guard = GuardedByBinder.bindString( guardString, GuardedBySymbolResolver.from(tree, visitorState.withPath(getCurrentPath())), flags); if (!guard.isPresent()) { invalidLock(tree, locks, guardString); continue; } Optional<GuardedByExpression> boundGuard = ExpectedLockCalculator.from( (JCTree.JCExpression) tree, guard.get(), visitorState, flags); if (!boundGuard.isPresent()) { // We couldn't resolve a guarded by expression in the current scope, so we can't // guarantee the access is protected and must report an error to be safe. invalidLock(tree, locks, guardString); continue; } listener.handleGuardedAccess(tree, boundGuard.get(), locks); } } private void invalidLock(ExpressionTree tree, HeldLockSet locks, String guardString) { listener.handleGuardedAccess( tree, new GuardedByExpression.Factory().error(guardString), locks); } } /** An abstraction over the lock classes we understand. */ @AutoValue abstract static class LockResource { /** The fully-qualified name of the lock class. */ abstract String className(); /** The method that releases the lock. */ abstract String unlockMethod(); public Matcher<ExpressionTree> createUnlockMatcher() { return instanceMethod().onDescendantOf(className()).named(unlockMethod()); } static LockResource create(String className, String unlockMethod) { return new AutoValue_HeldLockAnalyzer_LockResource(className, unlockMethod); } } /** The set of supported lock classes. */ private static final ImmutableList<LockResource> LOCK_RESOURCES = ImmutableList.of( LockResource.create("java.util.concurrent.locks.Lock", "unlock"), LockResource.create("com.google.common.util.concurrent.Monitor", "leave"), LockResource.create("java.util.concurrent.Semaphore", "release")); private static class LockOperationFinder extends TreeScanner<Void, Void> { static Collection<GuardedByExpression> find( Tree tree, VisitorState state, Matcher<ExpressionTree> lockOperationMatcher, GuardedByFlags flags) { if (tree == null) { return Collections.emptyList(); } LockOperationFinder finder = new LockOperationFinder(state, lockOperationMatcher, flags); tree.accept(finder, null); return finder.locks; } private static final String READ_WRITE_LOCK_CLASS = "java.util.concurrent.locks.ReadWriteLock"; private final Matcher<ExpressionTree> lockOperationMatcher; private final GuardedByFlags flags; /** Matcher for ReadWriteLock lock accessors. */ private static final Matcher<ExpressionTree> READ_WRITE_ACCESSOR_MATCHER = Matchers.<ExpressionTree>anyOf( instanceMethod().onDescendantOf(READ_WRITE_LOCK_CLASS).named("readLock"), instanceMethod().onDescendantOf(READ_WRITE_LOCK_CLASS).named("writeLock")); private final VisitorState state; private final Set<GuardedByExpression> locks = new HashSet<>(); private LockOperationFinder( VisitorState state, Matcher<ExpressionTree> lockOperationMatcher, GuardedByFlags flags) { this.state = state; this.lockOperationMatcher = lockOperationMatcher; this.flags = flags; } @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { handleReleasedLocks(tree); return null; } /** * Checks for locks that are released directly. Currently only {@link * java.util.concurrent.locks.Lock#unlock()} is supported. * * <p>TODO(cushon): Semaphores, CAS, ... ? */ private void handleReleasedLocks(MethodInvocationTree tree) { if (!lockOperationMatcher.matches(tree, state)) { return; } Optional<GuardedByExpression> node = GuardedByBinder.bindExpression((JCExpression) tree, state, flags); if (node.isPresent()) { GuardedByExpression receiver = ((GuardedByExpression.Select) node.get()).base(); locks.add(receiver); // The analysis interprets members guarded by {@link ReadWriteLock}s as requiring that // either the read or write lock is held for all accesses, but doesn't enforce a policy // for which of the two is held. Technically the write lock should be required while // writing to the guarded member and the read lock should be used for all other accesses, // but in practice the write lock is frequently held while performing a mutating operation // on the object stored in the field (e.g. inserting into a List). // TODO(cushon): investigate a better way to specify the contract for ReadWriteLocks. if ((tree.getMethodSelect() instanceof MemberSelectTree) && READ_WRITE_ACCESSOR_MATCHER.matches(ASTHelpers.getReceiver(tree), state)) { locks.add(((Select) receiver).base()); } } } } /** * Find the locks that are released in the given tree. (e.g. the 'finally' clause of a * try/finally) */ static final class ReleasedLockFinder { /** Matcher for methods that release lock resources. */ private static final Matcher<ExpressionTree> UNLOCK_MATCHER = Matchers.<ExpressionTree>anyOf(unlockMatchers()); private static Iterable<Matcher<ExpressionTree>> unlockMatchers() { return Iterables.transform(LOCK_RESOURCES, LockResource::createUnlockMatcher); } static Collection<GuardedByExpression> find( Tree tree, VisitorState state, GuardedByFlags flags) { return LockOperationFinder.find(tree, state, UNLOCK_MATCHER, flags); } private ReleasedLockFinder() {} } /** * Utility for discovering the lock expressions that needs to be held when accessing specific * guarded members. */ public static final class ExpectedLockCalculator { private static final GuardedByExpression.Factory F = new GuardedByExpression.Factory(); /** * Determine the lock expression that needs to be held when accessing a specific guarded member. * * <p>If the lock expression resolves to an instance member, the result will be a select * expression with the same base as the original guarded member access. * * <p>For example: * * <pre>{@code * class MyClass { * final Object mu = new Object(); * @GuardedBy("mu") * int x; * } * void m(MyClass myClass) { * myClass.x++; * } * }</pre> * * To determine the lock that must be held when accessing myClass.x, from is called with * "myClass.x" and "mu", and returns "myClass.mu". */ public static Optional<GuardedByExpression> from( JCTree.JCExpression guardedMemberExpression, GuardedByExpression guard, VisitorState state, GuardedByFlags flags) { if (isGuardReferenceAbsolute(guard)) { return Optional.of(guard); } Optional<GuardedByExpression> guardedMember = GuardedByBinder.bindExpression(guardedMemberExpression, state, flags); if (!guardedMember.isPresent()) { return Optional.empty(); } GuardedByExpression memberBase = ((GuardedByExpression.Select) guardedMember.get()).base(); return Optional.of(helper(guard, memberBase)); } /** * Returns true for guard expressions that require an 'absolute' reference, i.e. where the * expression to access the lock is always the same, regardless of how the guarded member is * accessed. * * <p>E.g.: * * <ul> * <li>class object: 'TypeName.class' * <li>static access: 'TypeName.member' * <li>enclosing instance: 'Outer.this' * <li>enclosing instance member: 'Outer.this.member' * </ul> */ private static boolean isGuardReferenceAbsolute(GuardedByExpression guard) { GuardedByExpression instance = guard.kind() == Kind.SELECT ? getSelectInstance(guard) : guard; return instance.kind() != Kind.THIS; } /** Gets the base expression of a (possibly nested) member select expression. */ private static GuardedByExpression getSelectInstance(GuardedByExpression guard) { if (guard instanceof Select) { return getSelectInstance(((Select) guard).base()); } return guard; } private static GuardedByExpression helper( GuardedByExpression lockExpression, GuardedByExpression memberAccess) { switch (lockExpression.kind()) { case SELECT: { GuardedByExpression.Select lockSelect = (GuardedByExpression.Select) lockExpression; return F.select(helper(lockSelect.base(), memberAccess), lockSelect.sym()); } case THIS: return memberAccess; default: throw new IllegalGuardedBy(lockExpression.toString()); } } private ExpectedLockCalculator() {} } private HeldLockAnalyzer() {} }
19,831
36.847328
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/StaticGuardedByInstance.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.threadsafety; import static com.google.errorprone.util.ASTHelpers.isStatic; import static com.google.errorprone.util.ASTHelpers.stripParentheses; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; 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.SynchronizedTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.SynchronizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.UnaryTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import java.util.Map; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( name = "StaticGuardedByInstance", summary = "Writes to static fields should not be guarded by instance locks", severity = SeverityLevel.WARNING, tags = StandardTags.FRAGILE_CODE) public class StaticGuardedByInstance extends BugChecker implements SynchronizedTreeMatcher { @Override public Description matchSynchronized(SynchronizedTree tree, VisitorState state) { Symbol lock = ASTHelpers.getSymbol(stripParentheses(tree.getExpression())); if (!(lock instanceof VarSymbol)) { return Description.NO_MATCH; } if (isStatic(lock)) { return Description.NO_MATCH; } Multimap<VarSymbol, Tree> writes = WriteVisitor.scan(tree.getBlock()); for (Map.Entry<VarSymbol, Tree> write : writes.entries()) { if (!write.getKey().isStatic()) { continue; } state.reportMatch( buildDescription(write.getValue()) .setMessage( String.format( "Write to static variable should not be guarded by instance lock '%s'", lock)) .build()); } return Description.NO_MATCH; } static class WriteVisitor extends TreeScanner<Void, Void> { static SetMultimap<VarSymbol, Tree> scan(Tree tree) { WriteVisitor visitor = new WriteVisitor(); tree.accept(visitor, null); return visitor.writes; } private final SetMultimap<VarSymbol, Tree> writes = LinkedHashMultimap.create(); private void recordWrite(ExpressionTree variable) { Symbol sym = ASTHelpers.getSymbol(variable); if (sym instanceof VarSymbol) { writes.put((VarSymbol) sym, variable); } } @Override public Void visitAssignment(AssignmentTree node, Void unused) { recordWrite(node.getVariable()); return super.visitAssignment(node, null); } @Override public Void visitCompoundAssignment(CompoundAssignmentTree node, Void unused) { recordWrite(node.getVariable()); return super.visitCompoundAssignment(node, null); } @Override public Void visitUnary(UnaryTree node, Void unused) { switch (node.getKind()) { case PREFIX_DECREMENT: case PREFIX_INCREMENT: case POSTFIX_DECREMENT: case POSTFIX_INCREMENT: recordWrite(node.getExpression()); break; default: break; } return super.visitUnary(node, null); } @Override public Void visitSynchronized(SynchronizedTree node, Void unused) { // don't descend into nested synchronized blocks return null; } @Override public Void visitNewClass(NewClassTree node, Void unused) { // don't descend into nested synchronized blocks return null; } } }
4,653
33.992481
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/AnnotationInfo.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.threadsafety; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.Immutable; import java.util.Set; /** * Specifies information about a type which may be a container specified by generic type arguments, * e.g. {@link com.google.errorprone.annotations.Immutable}. * * <p>Useful for providing information for immutable classes we can't easily annotate, e.g. those in * the JDK. */ @AutoValue @Immutable public abstract class AnnotationInfo { public abstract String typeName(); public Set<String> containerOf() { return internalContainerOf(); } abstract ImmutableSet<String> internalContainerOf(); public static AnnotationInfo create(String typeName, Iterable<String> containerOf) { return new AutoValue_AnnotationInfo(typeName, ImmutableSet.copyOf(containerOf)); } public static AnnotationInfo create(String typeName) { return create(typeName, ImmutableSet.<String>of()); } }
1,640
31.82
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByExpression.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.threadsafety; import static com.google.errorprone.bugpatterns.threadsafety.IllegalGuardedBy.checkGuardedBy; import com.google.auto.value.AutoValue; 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 com.sun.tools.javac.util.Names; import java.util.Objects; import javax.lang.model.element.ElementKind; /** * The lock expression of an {@code @GuardedBy} annotation. * * @author cushon@google.com (Liam Miller-Cushon) */ public abstract class GuardedByExpression { public abstract Kind kind(); public abstract Symbol sym(); public abstract Type type(); static final String ENCLOSING_INSTANCE_NAME = "outer$"; /** A 'class' literal: ClassName.class */ @AutoValue public abstract static class ClassLiteral extends GuardedByExpression { public static ClassLiteral create(Symbol owner) { return new AutoValue_GuardedByExpression_ClassLiteral(Kind.CLASS_LITERAL, owner, owner.type); } } /** * The base expression for a static member select on a class literal (e.g. ClassName.fieldName). */ @AutoValue public abstract static class TypeLiteral extends GuardedByExpression { public static TypeLiteral create(Symbol owner) { return new AutoValue_GuardedByExpression_TypeLiteral(Kind.TYPE_LITERAL, owner, owner.type); } } /** A local variable (or parameter), resolved as part of a lock access expression. */ @AutoValue public abstract static class LocalVariable extends GuardedByExpression { public static LocalVariable create(Symbol owner) { return new AutoValue_GuardedByExpression_LocalVariable( Kind.LOCAL_VARIABLE, owner, owner.type); } } /** A guarded by expression that could not be resolved. */ public static class Erroneous extends GuardedByExpression { private final String guardString; Erroneous(String guardString) { this.guardString = guardString; } @Override public Kind kind() { return Kind.ERROR; } @Override public Symbol sym() { return null; } @Override public Type type() { return null; } public String guardString() { return guardString; } } /** A simple 'this literal. */ // Don't use AutoValue here, since sym and type need to be 'null'. (And since // it's a singleton we don't need to implement equals() or hashCode()). public static class ThisLiteral extends GuardedByExpression { static final ThisLiteral INSTANCE = new ThisLiteral(); @Override public Kind kind() { return Kind.THIS; } @Override public Symbol sym() { return null; } @Override public Type type() { return null; } private ThisLiteral() {} } /** The member access expression for a field or method. */ @AutoValue public abstract static class Select extends GuardedByExpression { public abstract GuardedByExpression base(); public static Select create(GuardedByExpression base, Symbol sym, Type type) { return new AutoValue_GuardedByExpression_Select(Kind.SELECT, sym, type, base); } /** Finds this {@link Select}'s nearest non-Select ancestor. */ public GuardedByExpression root() { GuardedByExpression exp = this.base(); while (exp.kind() == Kind.SELECT) { exp = ((Select) exp).base(); } return exp; } } /** Makes {@link GuardedByExpression}s. */ public static class Factory { ThisLiteral thisliteral() { return ThisLiteral.INSTANCE; } /** * Synthesizes the {@link GuardedByExpression} for an enclosing class access. The access is * represented as a chain of field accesses from an instance of the current class to its * enclosing ancestor. At each level, the enclosing class is accessed via a magic 'outer$' * field. * * <p>Example: * * <pre> * <code> * class Outer { * final Object lock = new Object(); * class Middle { * class Inner { * {@code @}GuardedBy("lock") // resolves to 'this.outer$.outer$.lock' * int x; * } * } * } * </code> * </pre> * * @param access the inner class where the access occurs. * @param enclosing the lexically enclosing class. */ GuardedByExpression qualifiedThis(Names names, ClassSymbol access, Symbol enclosing) { GuardedByExpression base = thisliteral(); Symbol curr = access; do { curr = curr.owner.enclClass(); if (curr == null) { break; } base = select(base, new EnclosingInstanceSymbol(names, curr)); } while (!curr.equals(enclosing)); checkGuardedBy(curr != null, "Expected an enclosing class."); return base; } private static class EnclosingInstanceSymbol extends VarSymbol { public EnclosingInstanceSymbol(Names names, Symbol curr) { super( Flags.SYNTHETIC, names.fromString(GuardedByExpression.ENCLOSING_INSTANCE_NAME), curr.type, curr); } @Override public int hashCode() { return Objects.hash(ENCLOSING_INSTANCE_NAME, owner.hashCode()); } @Override public boolean equals(Object other) { if (!(other instanceof VarSymbol)) { return false; } VarSymbol that = (VarSymbol) other; if (!that.getSimpleName().contentEquals(ENCLOSING_INSTANCE_NAME)) { return false; } return owner.equals(that.owner); } } ClassLiteral classLiteral(Symbol clazz) { return ClassLiteral.create(clazz); } TypeLiteral typeLiteral(Symbol type) { return TypeLiteral.create(type); } Select select(GuardedByExpression base, Symbol member) { if (member instanceof VarSymbol) { return select(base, (VarSymbol) member); } if (member instanceof MethodSymbol) { return select(base, (MethodSymbol) member); } throw new IllegalStateException("Bad select expression: expected symbol " + member.getKind()); } Select select(GuardedByExpression base, Symbol.VarSymbol member) { return Select.create(base, member, member.type); } Select select(GuardedByExpression base, Symbol.MethodSymbol member) { return Select.create(base, member, member.getReturnType()); } GuardedByExpression select(GuardedByExpression base, Select select) { return Select.create(base, select.sym(), select.type()); } LocalVariable localVariable(Symbol.VarSymbol varSymbol) { return LocalVariable.create(varSymbol); } Erroneous error(String guardString) { return new Erroneous(guardString); } } /** {@link GuardedByExpression} kind. */ public enum Kind { THIS, CLASS_LITERAL, TYPE_LITERAL, LOCAL_VARIABLE, SELECT, ERROR; } @Override public String toString() { return PrettyPrinter.print(this); } public String debugPrint() { return DebugPrinter.print(this); } /** Pretty printer for lock expressions. */ private static class PrettyPrinter { public static String print(GuardedByExpression exp) { StringBuilder sb = new StringBuilder(); pprint(exp, sb); return sb.toString(); } private static void pprint(GuardedByExpression exp, StringBuilder sb) { switch (exp.kind()) { case CLASS_LITERAL: sb.append(String.format("%s.class", exp.sym().name)); break; case THIS: sb.append("this"); break; case TYPE_LITERAL: case LOCAL_VARIABLE: sb.append(exp.sym().name); break; case SELECT: pprintSelect((Select) exp, sb); break; case ERROR: sb.append(((Erroneous) exp).guardString()); break; } } private static void pprintSelect(Select exp, StringBuilder sb) { if (exp.sym().name.contentEquals(ENCLOSING_INSTANCE_NAME)) { GuardedByExpression curr = exp.base(); while (curr.kind() == Kind.SELECT) { curr = ((Select) curr).base(); if (curr.kind() == Kind.THIS) { break; } } if (curr.kind() == Kind.THIS) { sb.append(String.format("%s.this", exp.sym().owner.name)); } else { pprint(exp.base(), sb); sb.append(".this$0"); } } else { pprint(exp.base(), sb); sb.append(String.format(".%s", exp.sym().name)); if (exp.sym().getKind() == ElementKind.METHOD) { sb.append("()"); } } } } /** s-exp pretty printer for lock expressions. */ private static class DebugPrinter { public static String print(GuardedByExpression exp) { StringBuilder sb = new StringBuilder(); pprint(exp, sb); return sb.toString(); } private static void pprint(GuardedByExpression exp, StringBuilder sb) { switch (exp.kind()) { case TYPE_LITERAL: case CLASS_LITERAL: case LOCAL_VARIABLE: sb.append(String.format("(%s %s)", exp.kind(), exp.sym())); break; case THIS: sb.append("(THIS)"); break; case SELECT: pprintSelect((Select) exp, sb); break; case ERROR: sb.append("(ERROR)"); break; } } private static void pprintSelect(Select exp, StringBuilder sb) { sb.append(String.format("(%s ", exp.kind())); pprint(exp.base(), sb); if (exp.sym().name.contentEquals(ENCLOSING_INSTANCE_NAME)) { sb.append(String.format(" %s%s)", ENCLOSING_INSTANCE_NAME, exp.sym().owner)); } else { sb.append(String.format(" %s)", exp.sym())); } } } }
10,646
27.620968
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafeAnalysis.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.threadsafety; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.Violation; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; 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.TypeVariableSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ClassType; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.type.TypeKind; /** Analyzes types for deep thread safety. */ public class ThreadSafeAnalysis { private final BugChecker bugChecker; private final VisitorState state; private final WellKnownThreadSafety wellKnownThreadSafety; private final ThreadSafety threadSafety; public ThreadSafeAnalysis( BugChecker bugChecker, VisitorState state, WellKnownThreadSafety wellKnownThreadSafety) { this.bugChecker = bugChecker; this.state = state; this.wellKnownThreadSafety = wellKnownThreadSafety; this.threadSafety = ThreadSafety.threadSafeBuilder(wellKnownThreadSafety).build(state); } boolean hasThreadSafeTypeParameterAnnotation(TypeVariableSymbol sym) { return threadSafety.hasThreadSafeTypeParameterAnnotation(sym); } boolean hasThreadSafeElementAnnotation(TypeVariableSymbol sym) { return threadSafety.hasThreadSafeElementAnnotation(sym); } Violation checkInstantiation( Collection<TypeVariableSymbol> classTypeParameters, Collection<Type> typeArguments) { return threadSafety.checkInstantiation(classTypeParameters, typeArguments); } public Violation checkInvocation(Type methodType, Symbol symbol) { return threadSafety.checkInvocation(methodType, symbol); } /** * Check that an {@code @ThreadSafe}-annotated class: * * <ul> * <li>does not declare or inherit any fields which are not thread safe, * <li>any threadsafe supertypes are instantiated with threadsafe type arguments as required by * their containerOf spec, and * <li>any enclosing instances are threadsafe. * </ul> * * requiring supertypes to be annotated threadsafe would be too restrictive. */ public Violation checkForThreadSafety( Optional<ClassTree> tree, ImmutableSet<String> threadSafeTypeParams, ClassType type) { Violation info = areFieldsThreadSafe(tree, threadSafeTypeParams, type); if (info.isPresent()) { return info; } for (Type interfaceType : state.getTypes().interfaces(type)) { AnnotationInfo interfaceAnnotation = threadSafety.getMarkerOrAcceptedAnnotation(interfaceType.tsym, state); if (interfaceAnnotation == null) { continue; } Violation interfaceInfo = threadSafety.checkSuperInstantiation( threadSafeTypeParams, interfaceAnnotation, interfaceType); if (interfaceInfo.isPresent()) { return interfaceInfo.plus( String.format( "'%s' extends '%s'", threadSafety.getPrettyName(type.tsym), threadSafety.getPrettyName(interfaceType.tsym))); } } Violation superInfo = checkSuper(threadSafeTypeParams, type); if (superInfo.isPresent()) { return superInfo; } Type mutableEnclosing = threadSafety.mutableEnclosingInstance(tree, type); if (mutableEnclosing != null) { return Violation.of( String.format( "'%s' has non-thread-safe enclosing instance '%s'", threadSafety.getPrettyName(type.tsym), mutableEnclosing)); } return Violation.absent(); } private Violation checkSuper(ImmutableSet<String> threadSafeTypeParams, ClassType type) { ClassType superType = (ClassType) state.getTypes().supertype(type); if (superType.getKind() == TypeKind.NONE || state.getTypes().isSameType(state.getSymtab().objectType, superType)) { return Violation.absent(); } if (WellKnownMutability.isAnnotation(state, type)) { // TODO(b/25630189): add enforcement return Violation.absent(); } AnnotationInfo superannotation = threadSafety.getMarkerOrAcceptedAnnotation(superType.tsym, state); if (superannotation != null) { // If the superclass does happen to be threadsafe, we don't need to recursively // inspect it. We just have to check that it's instantiated correctly: Violation info = threadSafety.checkSuperInstantiation(threadSafeTypeParams, superannotation, superType); if (!info.isPresent()) { return Violation.absent(); } return info.plus( String.format( "'%s' extends '%s'", threadSafety.getPrettyName(type.tsym), threadSafety.getPrettyName(superType.tsym))); } // Recursive case: check if the supertype is 'effectively' threadsafe. Violation info = checkForThreadSafety(Optional.empty(), threadSafeTypeParams, superType); if (!info.isPresent()) { return Violation.absent(); } return info.plus( String.format( "'%s' extends '%s'", threadSafety.getPrettyName(type.tsym), threadSafety.getPrettyName(superType.tsym))); } /** * Check a single class' fields for thread safety. * * @param threadSafeTypeParams the in-scope threadsafe type parameters * @param classType the type to check the fields of */ Violation areFieldsThreadSafe( Optional<ClassTree> tree, ImmutableSet<String> threadSafeTypeParams, ClassType classType) { ClassSymbol classSym = (ClassSymbol) classType.tsym; if (classSym.members() == null) { return Violation.absent(); } Predicate<Symbol> instanceFieldFilter = symbol -> symbol.getKind() == ElementKind.FIELD; Map<Symbol, Tree> declarations = new HashMap<>(); if (tree.isPresent()) { for (Tree member : tree.get().getMembers()) { Symbol sym = ASTHelpers.getSymbol(member); if (sym != null) { declarations.put(sym, member); } } } // javac gives us members in reverse declaration order // handling them in declaration order leads to marginally better diagnostics List<Symbol> members = ImmutableList.copyOf(ASTHelpers.scope(classSym.members()).getSymbols(instanceFieldFilter)) .reverse(); for (Symbol member : members) { Optional<Tree> memberTree = Optional.ofNullable(declarations.get(member)); Violation info = isFieldThreadSafe( memberTree, threadSafeTypeParams, classSym, classType, (VarSymbol) member); if (info.isPresent()) { return info; } } return Violation.absent(); } /** Check a single field for thread safe. */ private Violation isFieldThreadSafe( Optional<Tree> tree, Set<String> threadSafeTypeParams, ClassSymbol classSym, ClassType classType, VarSymbol var) { if (bugChecker.isSuppressed(var) || bugChecker.customSuppressionAnnotations().stream() .map(a -> ASTHelpers.hasAnnotation(var, a, state)) .anyMatch(v -> v)) { return Violation.absent(); } if (var.getModifiers().contains(Modifier.STATIC)) { return Violation.absent(); } if (!GuardedByUtils.getGuardValues(var).isEmpty()) { return Violation.absent(); } if (!var.getModifiers().contains(Modifier.FINAL) && !ASTHelpers.hasAnnotation(var, LazyInit.class, state)) { return processModifier(tree, classSym, var, Modifier.FINAL, "'%s' has non-final field '%s'"); } Type varType = state.getTypes().memberType(classType, var); Violation info = threadSafety.isThreadSafeType( /* allowContainerTypeParameters= */ true, threadSafeTypeParams, varType); if (info.isPresent()) { if (tree.isPresent()) { // If we have a tree to attach diagnostics to, report the error immediately instead of // accumulating the path to the error from the top-level class being checked state.reportMatch( bugChecker .buildDescription(tree.get()) .setMessage(info.plus("@ThreadSafe class has non-thread-safe field").message()) .build()); return Violation.absent(); } return info.plus( String.format( "'%s' has field '%s' of type '%s'", threadSafety.getPrettyName(classSym), var.getSimpleName(), varType)); } return Violation.absent(); } private Violation processModifier( Optional<Tree> tree, ClassSymbol classSym, VarSymbol var, Modifier modifier, String message) { if (tree.isPresent()) { // If we have a tree to attach diagnostics to, report the error immediately instead of // accumulating the path to the error from the top-level class being checked state.reportMatch( bugChecker .buildDescription(tree.get()) .setMessage( "@ThreadSafe class fields should be final or annotated with @GuardedBy. See " + "https://errorprone.info/bugpattern/ThreadSafe for details.") .addFix(SuggestedFixes.addModifiers(tree.get(), state, modifier)) .build()); return Violation.absent(); } return Violation.of( String.format(message, threadSafety.getPrettyName(classSym), var.getSimpleName())); } /** * Gets the {@link Tree}'s {@code @ThreadSafe} annotation info, either from an annotation on the * symbol or from the list of well-known immutable types. */ AnnotationInfo getThreadSafeAnnotation(Tree tree, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(tree); return getThreadSafeAnnotation(sym, state); } AnnotationInfo getThreadSafeAnnotation(Symbol sym, VisitorState state) { String nameStr = sym.flatName().toString(); AnnotationInfo known = wellKnownThreadSafety.getKnownThreadSafeClasses().get(nameStr); if (known != null) { return known; } return threadSafety.getInheritedAnnotation(sym, state); } public ImmutableSet<String> threadSafeTypeParametersInScope(Symbol sym) { return ImmutableSet.copyOf(threadSafety.threadSafeTypeParametersInScope(sym)); } }
11,485
37.804054
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableChecker.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.threadsafety; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Streams.stream; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getReceiverType; 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.isLocal; import static com.google.errorprone.util.ASTHelpers.isSameType; import static com.google.errorprone.util.ASTHelpers.isStatic; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static com.google.errorprone.util.ASTHelpers.targetType; import static java.lang.String.format; import static java.util.stream.Collectors.joining; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSet; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import com.google.common.collect.Sets.SetView; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.LambdaExpressionTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.Violation; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeParameterTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.TypeSymbol; 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.Type.ClassType; import com.sun.tools.javac.tree.JCTree.JCMemberReference; import com.sun.tools.javac.tree.JCTree.JCNewClass; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.inject.Inject; import javax.lang.model.element.ElementKind; import org.checkerframework.checker.nullness.qual.Nullable; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( name = "Immutable", summary = "Type declaration annotated with @Immutable is not immutable", severity = ERROR, documentSuppression = false) public class ImmutableChecker extends BugChecker implements ClassTreeMatcher, LambdaExpressionTreeMatcher, NewClassTreeMatcher, MethodInvocationTreeMatcher, MethodTreeMatcher, MemberReferenceTreeMatcher { private final WellKnownMutability wellKnownMutability; private final ImmutableSet<String> immutableAnnotations; @Inject ImmutableChecker(WellKnownMutability wellKnownMutability) { this(wellKnownMutability, ImmutableSet.of(Immutable.class.getName())); } ImmutableChecker( WellKnownMutability wellKnownMutability, ImmutableSet<String> immutableAnnotations) { this.wellKnownMutability = wellKnownMutability; this.immutableAnnotations = immutableAnnotations; } @Override public Description matchLambdaExpression(LambdaExpressionTree tree, VisitorState state) { TypeSymbol lambdaType = getType(tree).tsym; ImmutableAnalysis analysis = createImmutableAnalysis(state); Violation info = analysis.checkInstantiation( lambdaType.getTypeParameters(), getType(tree).getTypeArguments()); if (info.isPresent()) { state.reportMatch(buildDescription(tree).setMessage(info.message()).build()); } if (!hasImmutableAnnotation(lambdaType, state)) { return NO_MATCH; } checkClosedTypes(tree, state, lambdaType, analysis); return NO_MATCH; } private boolean hasImmutableAnnotation(TypeSymbol tsym, VisitorState state) { return immutableAnnotations.stream() .anyMatch(annotation -> hasAnnotation(tsym, annotation, state)); } @Override public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) { // check instantiations of `@ImmutableTypeParameter`s in method references checkInvocation(tree, getSymbol(tree), ((JCMemberReference) tree).referentType, state); ImmutableAnalysis analysis = createImmutableAnalysis(state); TypeSymbol memberReferenceType = targetType(state).type().tsym; Violation info = analysis.checkInstantiation( memberReferenceType.getTypeParameters(), getType(tree).getTypeArguments()); if (info.isPresent()) { state.reportMatch(buildDescription(tree).setMessage(info.message()).build()); } if (!hasImmutableAnnotation(memberReferenceType, state)) { return NO_MATCH; } if (getSymbol(getReceiver(tree)) instanceof ClassSymbol) { return NO_MATCH; } var receiverType = getReceiverType(tree); ImmutableSet<String> typarams = immutableTypeParametersInScope(getSymbol(tree), state, analysis); var violation = analysis.isThreadSafeType(/* allowContainerTypeParameters= */ true, typarams, receiverType); if (violation.isPresent()) { return buildDescription(tree) .setMessage( "This method reference implements @Immutable interface " + memberReferenceType.getSimpleName() + ", but " + violation.message()) .build(); } return NO_MATCH; } // check instantiations of `@ImmutableTypeParameter`s in method invocations @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { checkInvocation(tree, getSymbol(tree), ASTHelpers.getType(tree.getMethodSelect()), state); return NO_MATCH; } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { // check instantiations of `@ImmutableTypeParameter`s in generic constructor invocations checkInvocation(tree, getSymbol(tree), ((JCNewClass) tree).constructorType, state); // check instantiations of `@ImmutableTypeParameter`s in class constructor invocations checkInstantiation( tree, state, getSymbol(tree.getIdentifier()).getTypeParameters(), ASTHelpers.getType(tree).getTypeArguments()); ClassTree classBody = tree.getClassBody(); // Only anonymous classes have a body next to the new operator. if (classBody != null) { // check instantiations of `@ImmutableTypeParameter`s in anonymous class constructor // invocations checkClassTreeInstantiation(classBody, state, createImmutableAnalysis(state)); } return NO_MATCH; } @Override public Description matchMethod(MethodTree tree, VisitorState state) { checkInstantiation( tree, state, getSymbol(tree).getTypeParameters(), ASTHelpers.getType(tree).getTypeArguments()); return NO_MATCH; } private ImmutableAnalysis createImmutableAnalysis(VisitorState state) { return new ImmutableAnalysis( this::isSuppressed, state, wellKnownMutability, immutableAnnotations); } private void checkInvocation( Tree tree, MethodSymbol symbol, Type methodType, VisitorState state) { ImmutableAnalysis analysis = createImmutableAnalysis(state); Violation info = analysis.checkInvocation(methodType, symbol); if (info.isPresent()) { state.reportMatch(buildDescription(tree).setMessage(info.message()).build()); } } private void checkInstantiation( Tree tree, VisitorState state, ImmutableAnalysis analysis, Collection<TypeVariableSymbol> typeParameters, Collection<Type> typeArguments) { Violation info = analysis.checkInstantiation(typeParameters, typeArguments); if (info.isPresent()) { state.reportMatch(buildDescription(tree).setMessage(info.message()).build()); } } private void checkInstantiation( Tree tree, VisitorState state, Collection<TypeVariableSymbol> typeParameters, Collection<Type> typeArguments) { checkInstantiation(tree, state, createImmutableAnalysis(state), typeParameters, typeArguments); } @Override public Description matchClass(ClassTree tree, VisitorState state) { ImmutableAnalysis analysis = createImmutableAnalysis(state); checkClassTreeInstantiation(tree, state, analysis); if (tree.getSimpleName().length() == 0) { // anonymous classes have empty names return handleAnonymousClass(tree, state, analysis); } AnnotationInfo annotation = getImmutableAnnotation(analysis, tree, state); if (annotation == null) { // If the type isn't annotated, and doesn't extend anything annotated, there's nothing to do. // An earlier version of the check required an explicit annotation on classes that extended // @Immutable classes, but didn't enforce the subtyping requirement for interfaces. We now // don't require the explicit annotations on any subtypes. return NO_MATCH; } // Special-case visiting declarations of known-immutable types; these uses // of the annotation are "trusted". if (wellKnownMutability.getKnownImmutableClasses().containsValue(annotation)) { return NO_MATCH; } // Check that the types in containerOf actually exist Map<String, TypeVariableSymbol> typarams = new HashMap<>(); for (TypeParameterTree typaram : tree.getTypeParameters()) { typarams.put(typaram.getName().toString(), (TypeVariableSymbol) getSymbol(typaram)); } SetView<String> difference = Sets.difference(annotation.containerOf(), typarams.keySet()); if (!difference.isEmpty()) { return buildDescription(tree) .setMessage( format( "could not find type(s) referenced by containerOf: %s", Joiner.on("', '").join(difference))) .build(); } ImmutableSet<String> immutableAndContainer = typarams.entrySet().stream() .filter( e -> annotation.containerOf().contains(e.getKey()) && analysis.hasThreadSafeTypeParameterAnnotation(e.getValue())) .map(Map.Entry::getKey) .collect(toImmutableSet()); if (!immutableAndContainer.isEmpty()) { return buildDescription(tree) .setMessage( format( "using both @ImmutableTypeParameter and containerOf is redundant: %s", Joiner.on("', '").join(immutableAndContainer))) .build(); } // Main path for @Immutable-annotated types: // // Check that the fields (including inherited fields) are immutable, and // validate the type hierarchy superclass. ClassSymbol sym = getSymbol(tree); Violation info = analysis.checkForImmutability( Optional.of(tree), immutableTypeParametersInScope(getSymbol(tree), state, analysis), ASTHelpers.getType(tree), (Tree matched, Violation violation) -> describeClass(matched, sym, annotation, violation)); Type superType = immutableSupertype(sym, state); if (superType != null && isLocal(sym)) { checkClosedTypes(tree, state, superType.tsym, analysis); } if (!info.isPresent()) { return NO_MATCH; } return describeClass(tree, sym, annotation, info).build(); } private void checkClassTreeInstantiation( ClassTree tree, VisitorState state, ImmutableAnalysis analysis) { for (Tree implementTree : tree.getImplementsClause()) { checkInstantiation( tree, state, analysis, getSymbol(implementTree).getTypeParameters(), ASTHelpers.getType(implementTree).getTypeArguments()); } Tree extendsClause = tree.getExtendsClause(); if (extendsClause != null) { checkInstantiation( tree, state, analysis, getSymbol(extendsClause).getTypeParameters(), ASTHelpers.getType(extendsClause).getTypeArguments()); } } private Description.Builder describeClass( Tree tree, ClassSymbol sym, AnnotationInfo annotation, Violation info) { String message; if (sym.getQualifiedName().contentEquals(annotation.typeName())) { message = "type annotated with @Immutable could not be proven immutable: " + info.message(); } else { message = format( "Class extends @Immutable type %s, but is not immutable: %s", annotation.typeName(), info.message()); } return buildDescription(tree).setMessage(message); } // Anonymous classes /** Check anonymous implementations of {@code @Immutable} types. */ private Description handleAnonymousClass( ClassTree tree, VisitorState state, ImmutableAnalysis analysis) { ClassSymbol sym = getSymbol(tree); Type superType = immutableSupertype(sym, state); if (superType == null) { return NO_MATCH; } checkClosedTypes(tree, state, superType.tsym, analysis); // We don't need to check that the superclass has an immutable instantiation. // The anonymous instance can only be referred to using a superclass type, so // the type arguments will be validated at any type use site where we care about // the instance's immutability. // // Also, we have no way to express something like: // // public static <@Immutable T> ImmutableBox<T> create(T t) { // return new ImmutableBox<>(t); // } ImmutableSet<String> typarams = immutableTypeParametersInScope(sym, state, analysis); Violation info = analysis.areFieldsImmutable( Optional.of(tree), typarams, ASTHelpers.getType(tree), (t, i) -> describeAnonymous(t, superType, i)); if (!info.isPresent()) { return NO_MATCH; } return describeAnonymous(tree, superType, info).build(); } private void checkClosedTypes( Tree lambdaOrAnonymousClass, VisitorState state, TypeSymbol lambdaType, ImmutableAnalysis analysis) { Set<VarSymbol> variablesClosed = new HashSet<>(); SetMultimap<ClassSymbol, MethodSymbol> typesClosed = LinkedHashMultimap.create(); Set<VarSymbol> variablesOwnedByLambda = new HashSet<>(); new TreePathScanner<Void, Void>() { @Override public Void visitVariable(VariableTree tree, Void unused) { var symbol = getSymbol(tree); variablesOwnedByLambda.add(symbol); return super.visitVariable(tree, null); } @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { if (getReceiver(tree) == null) { var symbol = getSymbol(tree); if (!symbol.isStatic() && !symbol.isConstructor()) { effectiveTypeOfThis(symbol, getCurrentPath(), state) .filter(t -> !isSameType(t.type, getType(lambdaOrAnonymousClass), state)) .ifPresent(t -> typesClosed.put(t, symbol)); } } return super.visitMethodInvocation(tree, null); } @Override public Void visitMemberSelect(MemberSelectTree tree, Void unused) { // Note: member selects are not intrinsically problematic; the issue is what might be on the // LHS of them, which is going to be handled by another visit* method. // If we're only seeing a field access, don't complain about the fact we closed around // `this`. This is special-case as it would otherwise be vexing to complain about accessing // a field of type ImmutableList. if (tree.getExpression() instanceof IdentifierTree && getSymbol(tree) instanceof VarSymbol && ((IdentifierTree) tree.getExpression()).getName().contentEquals("this")) { handleIdentifier(getSymbol(tree)); return null; } return super.visitMemberSelect(tree, null); } @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { handleIdentifier(getSymbol(tree)); return super.visitIdentifier(tree, null); } private void handleIdentifier(Symbol symbol) { if (symbol instanceof VarSymbol && !variablesOwnedByLambda.contains(symbol) && !isStatic(symbol)) { variablesClosed.add((VarSymbol) symbol); } } }.scan(state.getPath(), null); ImmutableSet<String> typarams = immutableTypeParametersInScope(getSymbol(lambdaOrAnonymousClass), state, analysis); for (VarSymbol closedVariable : variablesClosed) { Violation v = checkClosedVariable(closedVariable, lambdaOrAnonymousClass, typarams, analysis); if (!v.isPresent()) { continue; } String message = format( "%s, but closes over '%s', which is not @Immutable because %s", formAnonymousReason(lambdaOrAnonymousClass, lambdaType), closedVariable, v.message()); state.reportMatch(buildDescription(lambdaOrAnonymousClass).setMessage(message).build()); } for (var entry : typesClosed.asMap().entrySet()) { var classSymbol = entry.getKey(); var methods = entry.getValue(); if (!hasImmutableAnnotation(classSymbol.type.tsym, state)) { String message = format( "%s, but accesses instance method(s) '%s' on '%s' which is not @Immutable.", formAnonymousReason(lambdaOrAnonymousClass, lambdaType), methods.stream().map(Symbol::getSimpleName).collect(joining(", ")), classSymbol.getSimpleName()); state.reportMatch(buildDescription(lambdaOrAnonymousClass).setMessage(message).build()); } } } /** * Gets the effective type of `this`, had the bare invocation of {@code symbol} been qualified * with it. */ private static Optional<ClassSymbol> effectiveTypeOfThis( MethodSymbol symbol, TreePath currentPath, VisitorState state) { return stream(currentPath.iterator()) .filter(ClassTree.class::isInstance) .map(t -> ASTHelpers.getSymbol((ClassTree) t)) .filter(c -> isSubtype(c.type, symbol.owner.type, state)) .findFirst(); } private Violation checkClosedVariable( VarSymbol closedVariable, Tree tree, ImmutableSet<String> typarams, ImmutableAnalysis analysis) { if (!closedVariable.getKind().equals(ElementKind.FIELD)) { return analysis.isThreadSafeType(false, typarams, closedVariable.type); } return analysis.isFieldImmutable( Optional.empty(), typarams, (ClassSymbol) closedVariable.owner, (ClassType) closedVariable.owner.type, closedVariable, (t, v) -> buildDescription(tree)); } private static String formAnonymousReason(Tree tree, TypeSymbol typeSymbol) { return "This " + (tree instanceof LambdaExpressionTree ? "lambda" : "anonymous class") + " implements @Immutable interface '" + typeSymbol.getSimpleName() + "'"; } private Description.Builder describeAnonymous(Tree tree, Type superType, Violation info) { String message = format( "Class extends @Immutable type %s, but is not immutable: %s", superType, info.message()); return buildDescription(tree).setMessage(message); } // Strong behavioural subtyping /** * Check for classes with {@code @Immutable}, or that inherited it from a super class or * interface. */ private @Nullable AnnotationInfo getImmutableAnnotation( ImmutableAnalysis analysis, ClassTree tree, VisitorState state) { AnnotationInfo annotation = analysis.getImmutableAnnotation(tree, state); if (annotation != null) { return annotation; } // getImmutableAnnotation inherits annotations from classes, but not interfaces. ClassSymbol sym = getSymbol(tree); Type superType = immutableSupertype(sym, state); if (superType != null) { return analysis.getImmutableAnnotation(superType.tsym, state); } return null; } /** * Returns the type of the first superclass or superinterface in the hierarchy annotated with * {@code @Immutable}, or {@code null} if no such super type exists. */ private @Nullable Type immutableSupertype(Symbol sym, VisitorState state) { for (Type superType : state.getTypes().closure(sym.type)) { if (superType.tsym.equals(sym.type.tsym)) { continue; } // Don't use getImmutableAnnotation here: subtypes of trusted types are // also trusted, only check for explicitly annotated supertypes. if (hasImmutableAnnotation(superType.tsym, state)) { return superType; } // We currently trust that @interface annotations are immutable, but don't enforce that // custom interface implementations are also immutable. That means the check can be // defeated by writing a custom mutable annotation implementation, and passing it around // using the superclass type. // // TODO(b/25630189): fix this // // if (superType.tsym.getKind() == ElementKind.ANNOTATION_TYPE) { // return superType; // } } return null; } /** * Gets the set of in-scope immutable type parameters from the containerOf specs on * {@code @Immutable} annotations. * * <p>Usually only the immediately enclosing declaration is searched, but it's possible to have * cases like: * * <pre> * {@code @}Immutable(containerOf="T") class C<T> { * class Inner extends ImmutableCollection<T> {} * } * </pre> */ private static ImmutableSet<String> immutableTypeParametersInScope( Symbol sym, VisitorState state, ImmutableAnalysis analysis) { if (sym == null) { return ImmutableSet.of(); } ImmutableSet.Builder<String> result = ImmutableSet.builder(); OUTER: for (Symbol s = sym; s.owner != null; s = s.owner) { switch (s.getKind()) { case INSTANCE_INIT: continue; case PACKAGE: break OUTER; default: break; } AnnotationInfo annotation = analysis.getImmutableAnnotation(s, state); if (annotation == null) { continue; } for (TypeVariableSymbol typaram : s.getTypeParameters()) { String name = typaram.getSimpleName().toString(); if (annotation.containerOf().contains(name)) { result.add(name); } } if (isStatic(s)) { break; } } return result.build(); } }
24,559
37.616352
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/HeldLockSet.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.threadsafety; import com.google.errorprone.annotations.CheckReturnValue; import java.util.Collection; import org.pcollections.Empty; import org.pcollections.PSet; /** * A set of held locks. * * <p>Wrapper around a {@link PSet} of {@link GuardedByExpression}s. Using a persistent collection * makes it easy to handle adding locks to the set only while visiting the scope where those locks * are held, without mutating the underlying collection. * * @author cushon@google.com (Liam Miller-Cushon) */ class HeldLockSet { final PSet<GuardedByExpression> locks; private HeldLockSet() { this(Empty.<GuardedByExpression>set()); } private HeldLockSet(PSet<GuardedByExpression> locks) { this.locks = locks; } static HeldLockSet empty() { return new HeldLockSet(); } @CheckReturnValue public HeldLockSet plus(GuardedByExpression lock) { return new HeldLockSet(locks.plus(lock)); } @CheckReturnValue public HeldLockSet plusAll(Collection<GuardedByExpression> locks) { return new HeldLockSet(this.locks.plusAll(locks)); } public Collection<GuardedByExpression> allLocks() { return locks; } @Override public String toString() { return locks.toString(); } }
1,877
26.617647
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.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.threadsafety; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.errorprone.util.ASTHelpers.isStatic; import com.google.auto.value.AutoValue; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.common.collect.Sets.SetView; import com.google.common.collect.Streams; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.annotations.ThreadSafe; import com.google.errorprone.bugpatterns.CanBeStaticAnalyzer; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.MoreAnnotations; import com.sun.source.tree.ClassTree; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.Attribute.Compound; 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.TypeVariableSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ArrayType; import com.sun.tools.javac.code.Type.ClassType; import com.sun.tools.javac.code.Type.TypeVar; import com.sun.tools.javac.code.Type.WildcardType; import com.sun.tools.javac.code.TypeTag; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.util.Name; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Target; import java.lang.reflect.TypeVariable; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import javax.lang.model.element.ElementKind; import javax.lang.model.type.TypeKind; import org.pcollections.ConsPStack; /** * A class which gives information about the annotation of types; if a type isn't annotated, {@link * Violation} gives information as to why it is not. */ public final class ThreadSafety { private final VisitorState state; private final Purpose purpose; private final KnownTypes knownTypes; private final ImmutableSet<String> markerAnnotations; private final ImmutableSet<String> acceptedAnnotations; private final ImmutableSet<String> containerOfAnnotation; private final ImmutableSet<String> suppressAnnotation; private final ImmutableSet<String> typeParameterAnnotation; /** Stores recursive invocations of {@link #isTypeParameterThreadSafe} */ private final Set<TypeVariableSymbol> recursiveThreadSafeTypeParameter = new HashSet<>(); public static Builder builder() { return new Builder(); } public static ThreadSafety.Builder threadSafeBuilder( WellKnownThreadSafety wellKnownThreadSafety) { ThreadSafety.Builder builder = ThreadSafety.builder() .setPurpose(Purpose.FOR_THREAD_SAFE_CHECKER) .knownTypes(wellKnownThreadSafety) .markerAnnotations(ImmutableSet.of(ThreadSafe.class.getName())) .acceptedAnnotations(ImmutableSet.of(Immutable.class.getName())); return builder; } /** * The {@link ThreadSafety} utility class can be used by either the bug checker that enforces * immutability or by the bug checker that enforces thread-safety. Depending on which of these bug * checkers is using this utility, different messages become appropriate. */ public enum Purpose { /** This is being used by the immutability bug checker */ FOR_IMMUTABLE_CHECKER { @Override String mutableOrNonThreadSafe() { return "mutable"; } @Override String mutableOrNotThreadSafe() { return "mutable"; } }, /** This is being used by the thread-safety bug checker */ FOR_THREAD_SAFE_CHECKER { @Override String mutableOrNonThreadSafe() { return "non-thread-safe"; } @Override String mutableOrNotThreadSafe() { return "not thread-safe"; } }, ; /** * Returns either the string {@code "mutable"} or {@code "non-thread-safe"} depending on the * purpose. */ abstract String mutableOrNonThreadSafe(); /** * Returns either the string {@code "mutable"} or {@code "not thread-safe"} depending on the * purpose. */ abstract String mutableOrNotThreadSafe(); } /** {@link ThreadSafety}Builder */ public static class Builder { private Builder() {} private Purpose purpose = Purpose.FOR_IMMUTABLE_CHECKER; private KnownTypes knownTypes; private ImmutableSet<String> markerAnnotations; private ImmutableSet<String> acceptedAnnotations = ImmutableSet.of(); private ImmutableSet<String> containerOfAnnotation = ImmutableSet.of(); private ImmutableSet<String> suppressAnnotation = ImmutableSet.of(); private ImmutableSet<String> typeParameterAnnotation = ImmutableSet.of(); /** See {@link Purpose}. */ @CanIgnoreReturnValue public Builder setPurpose(Purpose purpose) { this.purpose = purpose; return this; } /** Information about known types and whether they're known to be safe or unsafe. */ @CanIgnoreReturnValue public Builder knownTypes(KnownTypes knownTypes) { this.knownTypes = knownTypes; return this; } /** * Annotations that will cause a class to be tested with this {@link ThreadSafety} instance; for * example, when testing a class for immutability, this should be @Immutable. */ @CanIgnoreReturnValue public Builder markerAnnotations(Iterable<String> markerAnnotations) { checkNotNull(markerAnnotations); this.markerAnnotations = ImmutableSet.copyOf(markerAnnotations); return this; } /** * Annotations that do *not* cause a class to be tested, but which are treated as valid * annotations to pass the test; for example, if @ThreadSafe is the marker * annotation, @Immutable would be included in this list, as an immutable class is by definition * thread-safe. */ @CanIgnoreReturnValue public Builder acceptedAnnotations(Iterable<String> acceptedAnnotations) { checkNotNull(acceptedAnnotations); this.acceptedAnnotations = ImmutableSet.copyOf(acceptedAnnotations); return this; } /** An annotation which marks a generic parameter as a container type. */ @CanIgnoreReturnValue public Builder containerOfAnnotation(Class<? extends Annotation> containerOfAnnotation) { checkNotNull(containerOfAnnotation); this.containerOfAnnotation = ImmutableSet.of(containerOfAnnotation.getName()); return this; } /** An annotation which marks a generic parameter as a container type. */ @CanIgnoreReturnValue public Builder containerOfAnnotation(Iterable<String> containerOfAnnotation) { checkNotNull(containerOfAnnotation); this.containerOfAnnotation = ImmutableSet.copyOf(containerOfAnnotation); return this; } /** An annotation which, when found on a class, should suppress the test */ @CanIgnoreReturnValue public Builder suppressAnnotation(Class<? extends Annotation> suppressAnnotation) { checkNotNull(suppressAnnotation); this.suppressAnnotation = ImmutableSet.of(suppressAnnotation.getName()); return this; } /** An annotation which, when found on a class, should suppress the test */ @CanIgnoreReturnValue public Builder suppressAnnotation(Iterable<String> suppressAnnotation) { checkNotNull(suppressAnnotation); this.suppressAnnotation = ImmutableSet.copyOf(suppressAnnotation); return this; } /** * An annotation which, when found on a type parameter, indicates that the type parameter may * only be instantiated with thread-safe types. */ @CanIgnoreReturnValue public Builder typeParameterAnnotation(Class<? extends Annotation> typeParameterAnnotation) { checkNotNull(typeParameterAnnotation); checkArgument( Arrays.stream(typeParameterAnnotation.getAnnotation(Target.class).value()) .anyMatch(ElementType.TYPE_PARAMETER::equals), "%s must be applicable to type parameters", typeParameterAnnotation); this.typeParameterAnnotation = ImmutableSet.of(typeParameterAnnotation.getName()); return this; } /** * An annotation which, when found on a type parameter, indicates that the type parameter may * only be instantiated with thread-safe types. */ @CanIgnoreReturnValue public Builder typeParameterAnnotation(Iterable<String> typeParameterAnnotation) { checkNotNull(typeParameterAnnotation); this.typeParameterAnnotation = ImmutableSet.copyOf(typeParameterAnnotation); return this; } public ThreadSafety build(VisitorState state) { checkNotNull(knownTypes); checkNotNull(markerAnnotations); return new ThreadSafety( state, purpose, knownTypes, markerAnnotations, acceptedAnnotations, containerOfAnnotation, suppressAnnotation, typeParameterAnnotation); } } private ThreadSafety( VisitorState state, Purpose purpose, KnownTypes knownTypes, Set<String> markerAnnotations, Set<String> acceptedAnnotations, Set<String> containerOfAnnotation, Set<String> suppressAnnotation, Set<String> typeParameterAnnotation) { this.state = checkNotNull(state); this.purpose = purpose; this.knownTypes = checkNotNull(knownTypes); this.markerAnnotations = ImmutableSet.copyOf(checkNotNull(markerAnnotations)); this.acceptedAnnotations = ImmutableSet.copyOf(checkNotNull(acceptedAnnotations)); this.containerOfAnnotation = ImmutableSet.copyOf(checkNotNull(containerOfAnnotation)); this.suppressAnnotation = ImmutableSet.copyOf(checkNotNull(suppressAnnotation)); this.typeParameterAnnotation = ImmutableSet.copyOf(checkNotNull(typeParameterAnnotation)); } /** Information about known types and whether they're known to be safe or unsafe. */ public interface KnownTypes { /** * Types that are known to be safe even if they're not annotated with an expected annotation. */ ImmutableMap<String, AnnotationInfo> getKnownSafeClasses(); /** Types that are known to be unsafe and don't need testing. */ ImmutableSet<String> getKnownUnsafeClasses(); /** Helper for building maps of classes to {@link AnnotationInfo}. */ final class MapBuilder { final ImmutableMap.Builder<String, AnnotationInfo> mapBuilder = ImmutableMap.builder(); @CanIgnoreReturnValue public MapBuilder addClasses(Set<Class<?>> clazzs) { clazzs.forEach(this::add); return this; } @CanIgnoreReturnValue public MapBuilder addStrings(List<String> classNames) { classNames.forEach(this::add); return this; } @CanIgnoreReturnValue public MapBuilder addAll(ImmutableMap<String, AnnotationInfo> map) { mapBuilder.putAll(map); return this; } @CanIgnoreReturnValue public MapBuilder add(Class<?> clazz, String... containerOf) { ImmutableSet<String> containerTyParams = ImmutableSet.copyOf(containerOf); HashSet<String> actualTyParams = new HashSet<>(); for (TypeVariable<?> x : clazz.getTypeParameters()) { actualTyParams.add(x.getName()); } SetView<String> difference = Sets.difference(containerTyParams, actualTyParams); if (!difference.isEmpty()) { throw new AssertionError( String.format( "For %s, please update the type parameter(s) from %s to %s", clazz, difference, actualTyParams)); } mapBuilder.put( clazz.getName(), AnnotationInfo.create(clazz.getName(), ImmutableList.copyOf(containerOf))); return this; } @CanIgnoreReturnValue public MapBuilder add(String className, String... containerOf) { mapBuilder.put( className, AnnotationInfo.create(className, ImmutableList.copyOf(containerOf))); return this; } public ImmutableMap<String, AnnotationInfo> build() { return mapBuilder.buildKeepingLast(); } } } /** * A human-friendly explanation of a thread safety violations. * * <p>An absent explanation indicates either an annotated type with no violations, or a type * without the annotation. */ @AutoValue public abstract static class Violation { public static Violation create(ConsPStack<String> path) { return new AutoValue_ThreadSafety_Violation(path); } /** * @return true if a violation was found */ public boolean isPresent() { return !path().isEmpty(); } /** * @return the explanation */ public String message() { return Joiner.on(", ").join(path()); } /** * The list of steps in the explanation. * * <p>Example: ["Foo has field 'xs' of type 'int[]'", "arrays are not thread-safe"] */ public abstract ConsPStack<String> path(); /** Adds a step. */ public Violation plus(String edge) { return create(path().plus(edge)); } /** Creates an explanation with one step. */ public static Violation of(String reason) { return create(ConsPStack.singleton(reason)); } /** An empty explanation. */ public static Violation absent() { return create(ConsPStack.empty()); } } /** * Check that a type-use of an {@code @ThreadSafe}-annotated type is instantiated with threadsafe * type arguments where required by its annotation's containerOf element. * * @param containerTypeParameters the in-scope threadsafe type parameters, declared on some * enclosing class. * @param annotation the type's {@code @ThreadSafe} info * @param type the type to check */ public Violation threadSafeInstantiation( Set<String> containerTypeParameters, AnnotationInfo annotation, Type type) { for (int i = 0; i < type.tsym.getTypeParameters().size(); i++) { TypeVariableSymbol typaram = type.tsym.getTypeParameters().get(i); boolean immutableTypeParameter = hasThreadSafeTypeParameterAnnotation(typaram); if (annotation.containerOf().contains(typaram.getSimpleName().toString()) || immutableTypeParameter) { if (type.getTypeArguments().isEmpty()) { return Violation.of( String.format( "'%s' required instantiation of '%s' with type parameters, but was raw", getPrettyName(type.tsym), typaram)); } Type tyarg = type.getTypeArguments().get(i); // Don't check whether wildcard types' erasure is safe. Wildcards can only be used where // the type isn't being instantiated, and we can rely on instantiations all being checked. if (immutableTypeParameter && tyarg instanceof WildcardType) { continue; } if (suppressAnnotation != null && tyarg.getAnnotationMirrors().stream() .anyMatch( a -> suppressAnnotation.contains( ((ClassSymbol) a.getAnnotationType().asElement()) .flatName() .toString()))) { continue; } Violation info = isThreadSafeType(!immutableTypeParameter, containerTypeParameters, tyarg); if (info.isPresent()) { return info.plus( String.format( "'%s' was instantiated with %s type for '%s'", getPrettyName(type.tsym), purpose.mutableOrNonThreadSafe(), typaram.getSimpleName())); } } } return Violation.absent(); } /** * Check that the super-type of a {@code @ThreadSafe}-annotated type is instantiated with * threadsafe type arguments where required by its annotation's containerOf element, and that any * type arguments that correspond to containerOf type parameters on the sub-type are also in the * super-type's containerOf spec. * * @param containerTypeParameters the in-scope threadsafe type parameters, declared on some * enclosing class. * @param annotation the type's {@code @ThreadSafe} info * @param type the type to check */ public Violation checkSuperInstantiation( Set<String> containerTypeParameters, AnnotationInfo annotation, Type type) { Violation info = threadSafeInstantiation(containerTypeParameters, annotation, type); if (info.isPresent()) { return info; } return Streams.zip( type.asElement().getTypeParameters().stream(), type.getTypeArguments().stream(), (typaram, argument) -> { if (containerOfSubtyping(containerTypeParameters, annotation, typaram, argument)) { return Violation.of( String.format( "'%s' is not a container of '%s'", annotation.typeName(), typaram)); } return Violation.absent(); }) .filter(Violation::isPresent) .findFirst() .orElse(Violation.absent()); } // Enforce strong behavioral subtyping for containers. // If: // (1) a generic super type is instantiated with a type argument that is a type variable // declared by the current class, and // (2) the current class is a container of that type parameter, then // (3) require the super-class to also be a container of its corresponding type parameter. private boolean containerOfSubtyping( Set<String> containerTypeParameters, AnnotationInfo annotation, TypeVariableSymbol typaram, Type tyargument) { // (1) if (!tyargument.hasTag(TypeTag.TYPEVAR)) { return false; } // (2) if (!containerTypeParameters.contains(tyargument.asElement().getSimpleName().toString()) || isTypeParameterThreadSafe( (TypeVariableSymbol) tyargument.asElement(), containerTypeParameters)) { return false; } // (3) if (annotation.containerOf().contains(typaram.getSimpleName().toString())) { return false; } return true; } /** * Returns an {@link Violation} explaining whether the type is threadsafe. * * @param allowContainerTypeParameters true when checking the instantiation of an {@code * typeParameterAnnotation}-annotated type parameter; indicates that {@code * containerTypeParameters} should be ignored * @param containerTypeParameters type parameters in enclosing elements' containerOf * specifications * @param type to check for thread-safety */ public Violation isThreadSafeType( boolean allowContainerTypeParameters, Set<String> containerTypeParameters, Type type) { return type.accept( new ThreadSafeTypeVisitor(allowContainerTypeParameters, containerTypeParameters), null); } private class ThreadSafeTypeVisitor extends Types.SimpleVisitor<Violation, Void> { private final boolean allowContainerTypeParameters; private final Set<String> containerTypeParameters; private ThreadSafeTypeVisitor( boolean allowContainerTypeParameters, Set<String> containerTypeParameters) { this.allowContainerTypeParameters = allowContainerTypeParameters; this.containerTypeParameters = !allowContainerTypeParameters ? ImmutableSet.of() : containerTypeParameters; } @Override public Violation visitWildcardType(WildcardType type, Void s) { return state.getTypes().wildUpperBound(type).accept(this, null); } @Override public Violation visitArrayType(ArrayType t, Void s) { return Violation.of(String.format("arrays are %s", purpose.mutableOrNotThreadSafe())); } @Override public Violation visitTypeVar(TypeVar type, Void s) { TypeVariableSymbol tyvar = (TypeVariableSymbol) type.tsym; if (containerTypeParameters.contains(tyvar.getSimpleName().toString())) { return Violation.absent(); } if (isTypeParameterThreadSafe(tyvar, containerTypeParameters)) { return Violation.absent(); } String message; if (!allowContainerTypeParameters) { message = String.format("'%s' is not annotated @ImmutableTypeParameter", tyvar.getSimpleName()); } else if (!containerTypeParameters.isEmpty()) { message = String.format( "'%s' is a %s type variable (not in '%s')", tyvar.getSimpleName(), purpose.mutableOrNonThreadSafe(), Joiner.on(", ").join(containerTypeParameters)); } else { message = String.format( "'%s' is a %s type variable", tyvar.getSimpleName(), purpose.mutableOrNonThreadSafe()); } return Violation.of(message); } @Override public Violation visitType(Type type, Void s) { switch (type.tsym.getKind()) { case ANNOTATION_TYPE: // assume annotations are always immutable // TODO(b/25630189): add enforcement return Violation.absent(); case ENUM: // assume enums are always immutable // TODO(b/25630186): add enforcement return Violation.absent(); case INTERFACE: case CLASS: break; default: if (type.tsym.getKind().name().equals("RECORD")) { break; } throw new AssertionError(String.format("Unexpected type kind %s", type.tsym.getKind())); } if (WellKnownMutability.isAnnotation(state, type)) { // annotation implementations may not have ANNOTATION_TYPE kind, assume they are immutable // TODO(b/25630189): add enforcement return Violation.absent(); } AnnotationInfo annotation = getMarkerOrAcceptedAnnotation(type.tsym, state); if (annotation != null) { return threadSafeInstantiation(containerTypeParameters, annotation, type); } String nameStr = type.tsym.flatName().toString(); if (knownTypes.getKnownUnsafeClasses().contains(nameStr)) { return Violation.of( String.format( "'%s' is %s", type.tsym.getSimpleName(), purpose.mutableOrNotThreadSafe())); } if (WellKnownMutability.isProto2MessageClass(state, type)) { if (WellKnownMutability.isProto2MutableMessageClass(state, type)) { return Violation.of( String.format("'%s' is a mutable proto message", type.tsym.getSimpleName())); } return Violation.absent(); } return Violation.of( String.format( "the declaration of type '%s' is not annotated with %s", type, Streams.concat(markerAnnotations.stream(), acceptedAnnotations.stream()) .map(a -> "@" + a) .collect(Collectors.joining(" or ")))); } } /** * Returns whether the given type parameter's declaration is annotated with {@link * #typeParameterAnnotation} indicating it will only ever be instantiated with thread-safe types. */ public boolean hasThreadSafeTypeParameterAnnotation(TypeVariableSymbol symbol) { return symbol.getAnnotationMirrors().stream() .anyMatch(t -> typeParameterAnnotation.contains(t.type.tsym.flatName().toString())); } /** * Returns whether the given type parameter's declaration is annotated with {@link * #containerOfAnnotation} indicating its type-safety determines the type-safety of the outer * class. */ public boolean hasThreadSafeElementAnnotation(TypeVariableSymbol symbol) { return symbol.getAnnotationMirrors().stream() .anyMatch(t -> containerOfAnnotation.contains(t.type.tsym.flatName().toString())); } /** * Returns whether a type parameter is thread-safe. * * <p>This is true if either the type parameter's declaration is annotated with {@link * #typeParameterAnnotation} (indicating it can only be instantiated with thread-safe types), or * the type parameter has a thread-safe upper bound (sub-classes of thread-safe types are also * thread-safe). * * <p>If a type has a recursive bound, we recursively assume that this type satisfies all * thread-safety constraints. Recursion can only happen with type variables that have recursive * type bounds. These type variables do not need to be called out in the "containerOf" attribute * or annotated with {@link #typeParameterAnnotation}. * * <p>Recursion does not apply to other kinds of types because all declared types must be * annotated thread-safe, which means that thread-safety checkers don't need to analyze all * referenced types recursively. */ private boolean isTypeParameterThreadSafe( TypeVariableSymbol symbol, Set<String> containerTypeParameters) { if (!recursiveThreadSafeTypeParameter.add(symbol)) { return true; } // TODO(b/77695285): Prevent type variables that are immutable because of an immutable upper // bound to be marked thread-safe via containerOf or typeParameterAnnotation. try { for (Type bound : symbol.getBounds()) { if (!isThreadSafeType(true, containerTypeParameters, bound).isPresent()) { // A type variable is thread-safe if any upper bound is thread-safe. return true; } } return hasThreadSafeTypeParameterAnnotation(symbol); } finally { recursiveThreadSafeTypeParameter.remove(symbol); } } /** * Gets the {@link Symbol}'s annotation info, either from a marker annotation on the symbol, from * an accepted annotation on the symbol, or from the list of well-known types. */ public AnnotationInfo getMarkerOrAcceptedAnnotation(Symbol sym, VisitorState state) { String nameStr = sym.flatName().toString(); AnnotationInfo known = knownTypes.getKnownSafeClasses().get(nameStr); if (known != null) { return known; } return getAnnotation( sym, ImmutableSet.copyOf(Sets.union(markerAnnotations, acceptedAnnotations)), state); } /** Returns an enclosing instance for the specified type if it is thread-safe. */ @Nullable public Type mutableEnclosingInstance(Optional<ClassTree> tree, ClassType type) { if (tree.isPresent() && !CanBeStaticAnalyzer.referencesOuter( tree.get(), ASTHelpers.getSymbol(tree.get()), state)) { return null; } Type enclosing = type.getEnclosingType(); while (!enclosing.getKind().equals(TypeKind.NONE)) { if (getMarkerOrAcceptedAnnotation(enclosing.tsym, state) == null && isThreadSafeType( /* allowContainerTypeParameters= */ false, /* containerTypeParameters= */ ImmutableSet.of(), enclosing) .isPresent()) { return enclosing; } enclosing = enclosing.getEnclosingType(); } return null; } /** * Gets the set of in-scope threadsafe type parameters from the containerOf specs on annotations. * * <p>Usually only the immediately enclosing declaration is searched, but it's possible to have * cases like: * * <pre>{@code * @MarkerAnnotation(containerOf="T") class C<T> { * class Inner extends ThreadSafeCollection<T> {} * } * }</pre> */ public Set<String> threadSafeTypeParametersInScope(Symbol sym) { if (sym == null) { return ImmutableSet.of(); } ImmutableSet.Builder<String> result = ImmutableSet.builder(); OUTER: for (Symbol s = sym; s.owner != null; s = s.owner) { switch (s.getKind()) { case INSTANCE_INIT: continue; case PACKAGE: break OUTER; default: break; } AnnotationInfo annotation = getMarkerOrAcceptedAnnotation(s, state); if (annotation == null) { continue; } for (TypeVariableSymbol typaram : s.getTypeParameters()) { String name = typaram.getSimpleName().toString(); if (annotation.containerOf().contains(name)) { result.add(name); } } if (isStatic(s)) { break; } } return result.build(); } @Nullable private AnnotationInfo getAnnotation( Symbol sym, ImmutableSet<String> annotationsToCheck, VisitorState state) { if (sym == null) { return null; } Optional<Compound> attr = sym.getRawAttributes().stream() .filter(a -> annotationsToCheck.contains(a.type.tsym.getQualifiedName().toString())) .findAny(); if (attr.isPresent()) { ImmutableList<String> containerElements = containerOf(state, attr.get()); if (!containerOfAnnotation.isEmpty() && containerElements.isEmpty()) { containerElements = sym.getTypeParameters().stream() .filter( p -> p.getAnnotationMirrors().stream() .anyMatch( a -> containerOfAnnotation.contains( a.type.tsym.flatName().toString()))) .map(p -> p.getSimpleName().toString()) .collect(toImmutableList()); } return AnnotationInfo.create(sym.getQualifiedName().toString(), containerElements); } // @ThreadSafe is inherited from supertypes if (!(sym instanceof ClassSymbol)) { return null; } Type superClass = ((ClassSymbol) sym).getSuperclass(); AnnotationInfo superAnnotation = getInheritedAnnotation(superClass.asElement(), state); if (superAnnotation == null) { return null; } // If an annotated super-type was found, look for any type arguments to the super-type that // are in the super-type's containerOf spec, and where the arguments are type parameters // of the current class. // E.g. for `Foo<X> extends Super<X>` if `Super<Y>` is annotated // `@ThreadSafeContainerAnnotation Y` // then `Foo<X>` is has X implicitly annotated `@ThreadSafeContainerAnnotation X` ImmutableList.Builder<String> containerOf = ImmutableList.builder(); for (int i = 0; i < superClass.getTypeArguments().size(); i++) { Type arg = superClass.getTypeArguments().get(i); TypeVariableSymbol formal = superClass.asElement().getTypeParameters().get(i); if (!arg.hasTag(TypeTag.TYPEVAR)) { continue; } TypeSymbol argSym = arg.asElement(); if (argSym.owner == sym && superAnnotation.containerOf().contains(formal.getSimpleName().toString())) { containerOf.add(argSym.getSimpleName().toString()); } } return AnnotationInfo.create(superAnnotation.typeName(), containerOf.build()); } /** * Gets the possibly inherited marker annotation on the given symbol, and reverse-propagates * containerOf spec's from super-classes. */ public AnnotationInfo getInheritedAnnotation(Symbol sym, VisitorState state) { return getAnnotation(sym, markerAnnotations, state); } private static ImmutableList<String> containerOf(VisitorState state, Compound attr) { Attribute m = attr.member(CONTAINEROF.get(state)); if (m == null) { return ImmutableList.of(); } return MoreAnnotations.asStrings(m).collect(toImmutableList()); } /** Gets a human-friendly name for the given {@link Symbol} to use in diagnostics. */ public String getPrettyName(Symbol sym) { if (!sym.getSimpleName().isEmpty()) { return sym.getSimpleName().toString(); } if (sym.getKind() == ElementKind.ENUM) { // anonymous classes for enum constants are identified by the enclosing constant // declaration return sym.owner.getSimpleName().toString(); } // anonymous classes have an empty name, but a recognizable superclass or interface // e.g. refer to `new Runnable() { ... }` as "Runnable" Type superType = state.getTypes().supertype(sym.type); if (state.getTypes().isSameType(superType, state.getSymtab().objectType)) { superType = Iterables.getFirst(state.getTypes().interfaces(sym.type), superType); } return superType.tsym.getSimpleName().toString(); } public Violation checkInstantiation( Collection<TypeVariableSymbol> typeParameters, Collection<Type> typeArguments) { return Streams.zip( typeParameters.stream(), typeArguments.stream(), (sym, type) -> checkInstantiation(sym, ImmutableList.of(type))) .filter(Violation::isPresent) .findFirst() .orElse(Violation.absent()); } /** Checks that any thread-safe type parameters are instantiated with thread-safe types. */ public Violation checkInstantiation( TypeVariableSymbol typeParameter, Collection<Type> instantiations) { if (!hasThreadSafeTypeParameterAnnotation(typeParameter)) { return Violation.absent(); } for (Type instantiation : instantiations) { Violation info = isThreadSafeType( /* allowContainerTypeParameters= */ true, /* containerTypeParameters= */ ImmutableSet.of(), instantiation); if (info.isPresent()) { return info.plus( String.format( "instantiation of '%s' is %s", typeParameter, purpose.mutableOrNotThreadSafe())); } } return Violation.absent(); } /** Checks the instantiation of any thread-safe type parameters in the current invocation. */ public Violation checkInvocation(Type methodType, Symbol symbol) { if (methodType == null) { return Violation.absent(); } List<TypeVariableSymbol> typeParameters = symbol.getTypeParameters(); if (typeParameters.stream().noneMatch(this::hasThreadSafeTypeParameterAnnotation)) { // fast path return Violation.absent(); } ImmutableListMultimap<TypeVariableSymbol, Type> instantiation = ASTHelpers.getTypeSubstitution(methodType, symbol); for (TypeVariableSymbol typeParameter : typeParameters) { Violation violation = checkInstantiation(typeParameter, instantiation.get(typeParameter)); if (violation.isPresent()) { return violation; } } return Violation.absent(); } private static final Supplier<Name> CONTAINEROF = VisitorState.memoize(state -> state.getName("containerOf")); }
35,767
37.501615
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableAnalysis.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.threadsafety; import static com.google.errorprone.util.ASTHelpers.isStatic; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.CheckReturnValue; import com.google.errorprone.annotations.ImmutableTypeParameter; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.Purpose; import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.Violation; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; 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.Type.ClassType; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.BiPredicate; import java.util.function.Predicate; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.type.TypeKind; import org.checkerframework.checker.nullness.qual.Nullable; /** Analyzes types for deep immutability. */ public final class ImmutableAnalysis { private final BiPredicate<Symbol, VisitorState> suppressionChecker; private final VisitorState state; private final WellKnownMutability wellKnownMutability; private final ThreadSafety threadSafety; ImmutableAnalysis( BiPredicate<Symbol, VisitorState> suppressionChecker, VisitorState state, WellKnownMutability wellKnownMutability, ImmutableSet<String> immutableAnnotations) { this.suppressionChecker = suppressionChecker; this.state = state; this.wellKnownMutability = wellKnownMutability; this.threadSafety = ThreadSafety.builder() .setPurpose(Purpose.FOR_IMMUTABLE_CHECKER) .knownTypes(wellKnownMutability) .markerAnnotations(immutableAnnotations) .typeParameterAnnotation(ImmutableTypeParameter.class) .build(state); } Violation isThreadSafeType( boolean allowContainerTypeParameters, Set<String> containerTypeParameters, Type type) { return threadSafety.isThreadSafeType( allowContainerTypeParameters, containerTypeParameters, type); } boolean hasThreadSafeTypeParameterAnnotation(TypeVariableSymbol sym) { return threadSafety.hasThreadSafeTypeParameterAnnotation(sym); } Violation checkInstantiation( Collection<TypeVariableSymbol> classTypeParameters, Collection<Type> typeArguments) { return threadSafety.checkInstantiation(classTypeParameters, typeArguments); } public Violation checkInvocation(Type methodType, Symbol symbol) { return threadSafety.checkInvocation(methodType, symbol); } /** Accepts {@link Violation violations} that are found during the analysis. */ @FunctionalInterface public interface ViolationReporter { Description.Builder describe(Tree tree, Violation info); @CheckReturnValue default Description report(Tree tree, Violation info, Optional<SuggestedFix> suggestedFix) { Description.Builder description = describe(tree, info); suggestedFix.ifPresent(description::addFix); return description.build(); } } /** * Check that an {@code @Immutable}-annotated class: * * <ul> * <li>does not declare or inherit any mutable fields, * <li>any immutable supertypes are instantiated with immutable type arguments as required by * their containerOf spec, and * <li>any enclosing instances are immutable. * </ul> * * requiring supertypes to be annotated immutable would be too restrictive. */ public Violation checkForImmutability( Optional<ClassTree> tree, ImmutableSet<String> immutableTyParams, ClassType type, ViolationReporter reporter) { Violation info = areFieldsImmutable(tree, immutableTyParams, type, reporter); if (info.isPresent()) { return info; } for (Type interfaceType : state.getTypes().interfaces(type)) { AnnotationInfo interfaceAnnotation = getImmutableAnnotation(interfaceType.tsym, state); if (interfaceAnnotation == null) { continue; } Violation superInfo = threadSafety.checkSuperInstantiation( immutableTyParams, interfaceAnnotation, interfaceType); if (superInfo.isPresent()) { return superInfo.plus( String.format( "'%s' extends '%s'", threadSafety.getPrettyName(type.tsym), threadSafety.getPrettyName(interfaceType.tsym))); } } if (!type.asElement().isEnum()) { // don't check enum super types here to avoid double-reporting errors Violation superInfo = checkSuper(immutableTyParams, type, reporter); if (superInfo.isPresent()) { return superInfo; } } Type mutableEnclosing = threadSafety.mutableEnclosingInstance(tree, type); if (mutableEnclosing != null) { return Violation.of( String.format( "'%s' has mutable enclosing instance '%s'", threadSafety.getPrettyName(type.tsym), mutableEnclosing)); } return Violation.absent(); } private Violation checkSuper( ImmutableSet<String> immutableTyParams, ClassType type, ViolationReporter reporter) { ClassType superType = (ClassType) state.getTypes().supertype(type); if (superType.getKind() == TypeKind.NONE || state.getTypes().isSameType(state.getSymtab().objectType, superType)) { return Violation.absent(); } if (WellKnownMutability.isAnnotation(state, type)) { // TODO(b/25630189): add enforcement return Violation.absent(); } AnnotationInfo superannotation = getImmutableAnnotation(superType.tsym, state); String message = String.format( "'%s' extends '%s'", threadSafety.getPrettyName(type.tsym), threadSafety.getPrettyName(superType.tsym)); if (superannotation != null) { // If the superclass does happen to be immutable, we don't need to recursively // inspect it. We just have to check that it's instantiated correctly: Violation info = threadSafety.checkSuperInstantiation(immutableTyParams, superannotation, superType); if (!info.isPresent()) { return Violation.absent(); } return info.plus(message); } // Recursive case: check if the supertype is 'effectively' immutable. Violation info = checkForImmutability(Optional.<ClassTree>empty(), immutableTyParams, superType, reporter); if (!info.isPresent()) { return Violation.absent(); } return info.plus(message); } /** * Check a single class' fields for immutability. * * @param immutableTyParams the in-scope immutable type parameters * @param classType the type to check the fields of */ Violation areFieldsImmutable( Optional<ClassTree> tree, ImmutableSet<String> immutableTyParams, ClassType classType, ViolationReporter reporter) { ClassSymbol classSym = (ClassSymbol) classType.tsym; if (classSym.members() == null) { return Violation.absent(); } Predicate<Symbol> instanceFieldFilter = symbol -> symbol.getKind() == ElementKind.FIELD && !isStatic(symbol); Map<Symbol, Tree> declarations = new HashMap<>(); if (tree.isPresent()) { for (Tree member : tree.get().getMembers()) { Symbol sym = ASTHelpers.getSymbol(member); if (sym != null) { declarations.put(sym, member); } } } // javac gives us members in reverse declaration order // handling them in declaration order leads to marginally better diagnostics ImmutableList<Symbol> members = ImmutableList.copyOf(ASTHelpers.scope(classSym.members()).getSymbols(instanceFieldFilter)) .reverse(); for (Symbol member : members) { Optional<Tree> memberTree = Optional.ofNullable(declarations.get(member)); Violation info = isFieldImmutable( memberTree, immutableTyParams, classSym, classType, (VarSymbol) member, reporter); if (info.isPresent()) { return info; } } return Violation.absent(); } /** Check a single field for immutability. */ Violation isFieldImmutable( Optional<Tree> tree, ImmutableSet<String> immutableTyParams, ClassSymbol classSym, ClassType classType, VarSymbol var, ViolationReporter reporter) { if (suppressionChecker.test(var, state)) { return Violation.absent(); } if (!var.getModifiers().contains(Modifier.FINAL) && !ASTHelpers.hasAnnotation(var, LazyInit.class, state)) { Violation info = Violation.of( String.format( "'%s' has non-final field '%s'", threadSafety.getPrettyName(classSym), var.getSimpleName())); if (tree.isPresent()) { // If we have a tree to attach diagnostics to, report the error immediately instead of // accumulating the path to the error from the top-level class being checked state.reportMatch( reporter.report( tree.get(), info, SuggestedFixes.addModifiers(tree.get(), state, Modifier.FINAL))); return Violation.absent(); } return info; } Type varType = state.getTypes().memberType(classType, var); Violation info = threadSafety.isThreadSafeType( /* allowContainerTypeParameters= */ true, immutableTyParams, varType); if (info.isPresent()) { info = info.plus( String.format( "'%s' has field '%s' of type '%s'", threadSafety.getPrettyName(classSym), var.getSimpleName(), varType)); if (tree.isPresent()) { // If we have a tree to attach diagnostics to, report the error immediately instead of // accumulating the path to the error from the top-level class being checked state.reportMatch(reporter.report(tree.get(), info, Optional.empty())); return Violation.absent(); } return info; } return Violation.absent(); } /** * Gets the {@link Symbol}'s {@code @Immutable} annotation info, either from an annotation on the * symbol or from the list of well-known immutable types. */ AnnotationInfo getImmutableAnnotation(Symbol sym, VisitorState state) { String nameStr = sym.flatName().toString(); AnnotationInfo known = wellKnownMutability.getKnownImmutableClasses().get(nameStr); if (known != null) { return known; } return threadSafety.getInheritedAnnotation(sym, state); } /** * Gets the {@link Tree}'s {@code @Immutable} annotation info, either from an annotation on the * symbol or from the list of well-known immutable types. */ @Nullable AnnotationInfo getImmutableAnnotation(Tree tree, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(tree); return sym == null ? null : threadSafety.getMarkerOrAcceptedAnnotation(sym, state); } }
12,158
37.235849
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableRefactoring.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.threadsafety; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import static com.google.errorprone.util.ASTHelpers.getAnnotationsWithSimpleName; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ImportTree; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; import java.util.HashSet; import java.util.Optional; import java.util.Set; import javax.inject.Inject; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( name = "ImmutableRefactoring", summary = "Refactors uses of the JSR 305 @Immutable to Error Prone's annotation", severity = SUGGESTION) public class ImmutableRefactoring extends BugChecker implements CompilationUnitTreeMatcher { private final WellKnownMutability wellKnownMutability; @Inject ImmutableRefactoring(WellKnownMutability wellKnownMutability) { this.wellKnownMutability = wellKnownMutability; } @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { ImmutableChecker immutableChecker = new ImmutableChecker( wellKnownMutability, ImmutableSet.of( javax.annotation.concurrent.Immutable.class.getName(), com.google.errorprone.annotations.Immutable.class.getName())); Optional<? extends ImportTree> immutableImport = tree.getImports().stream() .filter( i -> { Symbol s = ASTHelpers.getSymbol(i.getQualifiedIdentifier()); return s != null && s.getQualifiedName() .contentEquals(javax.annotation.concurrent.Immutable.class.getName()); }) .findFirst(); if (!immutableImport.isPresent()) { return Description.NO_MATCH; } Set<ClassTree> notOk = new HashSet<>(); new TreePathScanner<Void, Void>() { @Override public Void visitClass(ClassTree node, Void unused) { if (!ASTHelpers.hasAnnotation( node, javax.annotation.concurrent.Immutable.class.getName(), state)) { return super.visitClass(node, null); } boolean violator = immutableChecker.matchClass( node, VisitorState.createConfiguredForCompilation( state.context, description -> notOk.add(node), ImmutableMap.of(), state.errorProneOptions()) .withPath(getCurrentPath())) != Description.NO_MATCH; if (violator) { notOk.add(node); } return super.visitClass(node, null); } }.scan(state.getPath(), null); SuggestedFix.Builder fixBuilder = SuggestedFix.builder() .removeImport(javax.annotation.concurrent.Immutable.class.getName()) .addImport(com.google.errorprone.annotations.Immutable.class.getName()); for (ClassTree classTree : notOk) { getAnnotationsWithSimpleName(classTree.getModifiers().getAnnotations(), "Immutable") .forEach(fixBuilder::delete); fixBuilder.prefixWith( classTree, "// This class was annotated with javax.annotation.concurrent.Immutable, but didn't seem" + " to be provably immutable." + "\n"); } return describeMatch(immutableImport.get(), fixBuilder.build()); } }
4,679
39.344828
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByFlags.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.threadsafety; import com.google.auto.value.AutoValue; /** * Flags that control the behavior of threadsafety utils to facilitate rolling out new * functionality. * * <p>This has no flags for now, but is still plumbed through to make it easier to flag guard * changes to {@link GuardedByChecker} in the future. Otherwise, it's rather difficult. */ @AutoValue public abstract class GuardedByFlags { public static GuardedByFlags allOn() { return new AutoValue_GuardedByFlags(); } }
1,135
34.5
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/PackagesRule.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.checkreturnvalue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.checkreturnvalue.ResultUseRule.SymbolRule; import com.google.errorprone.suppliers.Supplier; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.PackageSymbol; import com.sun.tools.javac.util.Name; import java.util.Optional; /** * A rule that enables checking for methods belonging to a set of packages or any of their * subpackages. */ // TODO(chaorenl): Why does this have METHOD scope in addition to ENCLOSING_ELEMENTS, when it only // ever considers packages? public final class PackagesRule extends SymbolRule<VisitorState, Symbol> { /** * Returns a new rule using the given package {@code patterns}. Each pattern string must either be * the fully qualified name of a package (to enable checking for methods in that package and its * subpackages) or a {@code -} character followed by the fully qualified name of a package (to * disable checking for methods in that package and its subpackages). */ public static PackagesRule fromPatterns(Iterable<String> patterns) { return new PackagesRule(ImmutableList.copyOf(patterns)); } private final Supplier<ImmutableMap<Name, Boolean>> packagesSupplier; private PackagesRule(ImmutableList<String> patterns) { this.packagesSupplier = VisitorState.memoize( state -> { ImmutableMap.Builder<Name, Boolean> builder = ImmutableMap.builder(); for (String pattern : patterns) { if (pattern.charAt(0) == '-') { builder.put(state.getName(pattern.substring(1)), false); } else { builder.put(state.getName(pattern), true); } } return builder.buildOrThrow(); }); } @Override public final String id() { return "Packages"; } @Override public Optional<ResultUsePolicy> evaluate(Symbol symbol, VisitorState state) { while (symbol instanceof PackageSymbol) { Boolean value = packagesSupplier.get(state).get(((PackageSymbol) symbol).fullname); if (value != null) { return value ? Optional.of(ResultUsePolicy.EXPECTED) // stop evaluating if the package matched a negative pattern : Optional.empty(); } symbol = symbol.owner; } return Optional.empty(); } }
3,170
36.305882
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/ResultUsePolicy.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.checkreturnvalue; /** Policy for use of a method or constructor's result. */ public enum ResultUsePolicy { /** * Use of the result is expected except in certain contexts where the method is being used in a * way such that not using the result is likely correct. Examples include when the result type at * the callsite is {@code java.lang.Void} and when the surrounding context seems to be testing * that the method throws an exception. */ EXPECTED, /** Use of the result is optional. */ OPTIONAL, /** It is unspecified whether the result should be used or not. */ UNSPECIFIED, }
1,258
37.151515
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/ResultUsePolicyAnalyzer.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.checkreturnvalue; import com.google.common.collect.ImmutableMap; import java.util.Set; /** * An object that can report on the behavior of a CRV-related check for analysis purposes. * * @param <E> the type of an expression node in the AST * @param <C> the type of the context object used during AST analysis */ public interface ResultUsePolicyAnalyzer<E, C> { /** The canonical name of the check. */ String canonicalName(); /** * Returns all of the name strings that this checker should respect as part of a * {@code @SuppressWarnings} annotation. */ Set<String> allNames(); /** * Returns whether this checker makes any determination about whether the given expression's * return value should be used or not. Most checkers either determine that an expression is CRV or * make no determination. */ boolean isCovered(E expression, C context); /** Returns the {@link ResultUsePolicy} for the method used in the given {@code expression}. */ ResultUsePolicy getMethodPolicy(E expression, C context); /** Returns a map of optional metadata about why this check matched the given expression. */ default ImmutableMap<String, ? extends Object> getMatchMetadata(E expression, C context) { return ImmutableMap.of(); } }
1,917
35.188679
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/ProtoRules.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.checkreturnvalue; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.errorprone.predicates.TypePredicates.isDescendantOfAny; import com.google.common.collect.ImmutableSet; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.checkreturnvalue.Rules.ErrorProneMethodRule; import com.google.errorprone.predicates.TypePredicate; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; import java.util.Optional; import java.util.regex.Pattern; /** Rules for methods on proto messages and builders. */ public final class ProtoRules { private ProtoRules() {} /** * Returns a rule that handles proto builders, making their fluent setter methods' results * ignorable. */ public static ResultUseRule<VisitorState, Symbol> protoBuilders() { return new ProtoRule( isDescendantOfAny(ImmutableSet.of("com.google.protobuf.MessageLite.Builder")), "PROTO_BUILDER"); } /** * Returns a rule that handles mutable protos, making their fluent setter methods' results * ignorable. */ public static ResultUseRule<VisitorState, Symbol> mutableProtos() { return new ProtoRule( isDescendantOfAny(ImmutableSet.of("com.google.protobuf.AbstractMutableMessageLite")), "MUTABLE_PROTO"); } // TODO(cgdecker): Move proto rules from IgnoredPureGetter and ReturnValueIgnored here /** Rules for methods on protos. */ private static final class ProtoRule extends ErrorProneMethodRule { // Methods that start this way produce a modification to the proto, and either return this // or return the parameter given, for chaining purposes. private static final Pattern NAMED_MUTATOR_METHOD = Pattern.compile("(add|clear|insert|merge|remove|set|put).*"); private final TypePredicate typePredicate; private final String id; ProtoRule(TypePredicate typePredicate, String id) { this.typePredicate = checkNotNull(typePredicate); this.id = checkNotNull(id); } @Override public String id() { return id; } @Override public Optional<ResultUsePolicy> evaluateMethod(MethodSymbol method, VisitorState state) { /* * TODO(cpovirk): Would it be faster to check the method name before checking the type * hierarchy, at least if we could do so without converting from Name to String and without * using regex matching? */ if (isProtoSubtype(method.owner.type, state)) { String methodName = method.name.toString(); if (NAMED_MUTATOR_METHOD.matcher(methodName).matches()) { return Optional.of(ResultUsePolicy.OPTIONAL); } if (isMutatingAccessorMethod(methodName) && isProtoSubtype(method.getReturnType(), state)) { return Optional.of(ResultUsePolicy.OPTIONAL); } } return Optional.empty(); } private boolean isProtoSubtype(Type ownerType, VisitorState state) { return typePredicate.apply(ownerType, state); } private static boolean isMutatingAccessorMethod(String name) { // TODO(glorioso): Any other naming conventions to check? // TODO(glorioso): Maybe worth making this a regex instead? But think about performance if (name.startsWith("get")) { // fooBuilder.getBarBuilder() mutates the builder such that foo.hasBar() is now true. return (name.endsWith("Builder") && !name.endsWith("OrBuilder")) // mutableFoo.getMutableBar() mutates Foo so that mutableFoo.hasBar() is now true || name.startsWith("getMutable"); } return false; } } }
4,348
36.817391
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/ResultUsePolicyEvaluator.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.checkreturnvalue; import static com.google.common.collect.ImmutableListMultimap.toImmutableListMultimap; import static com.google.errorprone.bugpatterns.checkreturnvalue.ResultUsePolicy.UNSPECIFIED; import static com.google.errorprone.bugpatterns.checkreturnvalue.ResultUseRule.RuleScope.ENCLOSING_ELEMENTS; import static com.google.errorprone.bugpatterns.checkreturnvalue.ResultUseRule.RuleScope.GLOBAL; import static java.util.Map.entry; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.bugpatterns.checkreturnvalue.ResultUseRule.Evaluation; import com.google.errorprone.bugpatterns.checkreturnvalue.ResultUseRule.RuleScope; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map.Entry; import java.util.Optional; import java.util.stream.Stream; /** * Evaluates methods and their enclosing classes and packages to determine a {@link ResultUsePolicy} * for the methods. * * @param <C> the type of the context object used during evaluation * @param <S> the type of symbols * @param <M> the type of method symbols */ public final class ResultUsePolicyEvaluator<C, S, M extends S> { /** * Returns a new {@link Builder} for creating a {@link ResultUsePolicyEvaluator}. * * @param <C> the type of the context object used during evaluation * @param <S> the type of symbols * @param <M> the type of method symbols */ public static <C, S, M extends S> ResultUsePolicyEvaluator.Builder<C, S, M> builder( MethodInfo<C, S, M> methodInfo) { return new Builder<>(methodInfo); } /** * Delegate to return information about a method symbol. * * @param <C> the type of the context object used during evaluation * @param <S> the type of symbols * @param <M> the type of method symbols */ public interface MethodInfo<C, S, M extends S> { /** Returns an ordered stream of elements in this scope relative to the given {@code method}. */ Stream<S> scopeMembers(RuleScope scope, M method, C context); /** Returns the kind of the given method. */ MethodKind getMethodKind(M method); /** Returns the scopes that apply for the given method. */ default ImmutableList<RuleScope> scopes(M method) { return getMethodKind(method).scopes; } /** What kind a method symbol is, and what scopes apply to it. */ enum MethodKind { /** An actual method, not a constructor. */ METHOD(RuleScope.METHOD, ENCLOSING_ELEMENTS, GLOBAL), /** A constructor. */ // TODO(cgdecker): Constructors in particular (though really all methods I think) should // not be able to get a policy of OPTIONAL from enclosing elements. Only defaults should // come from enclosing elements, and there should only be one default policy (EXPECTED). CONSTRUCTOR(RuleScope.METHOD, ENCLOSING_ELEMENTS, GLOBAL), /** Neither a method nor a constructor. */ OTHER(), ; private final ImmutableList<RuleScope> scopes; MethodKind(RuleScope... scopes) { this.scopes = ImmutableList.copyOf(scopes); } } } /** All the rules for this evaluator, indexed by the scopes they apply to. */ private final ImmutableListMultimap<RuleScope, ResultUseRule<C, S>> rules; private final MethodInfo<C, S, M> methodInfo; private ResultUsePolicyEvaluator(Builder<C, S, M> builder) { this.rules = builder.rules.stream() .flatMap(rule -> rule.scopes().stream().map(scope -> entry(scope, rule))) .collect(toImmutableListMultimap(Entry::getKey, Entry::getValue)); this.methodInfo = builder.methodInfo; } /** * Evaluates the given {@code method} and returns a single {@link ResultUsePolicy} that should * apply to it. */ public ResultUsePolicy evaluate(M method, C state) { return evaluateAcrossScopes( method, state, (rule, scope, symbol, context) -> rule.evaluate(symbol, context)) .findFirst() .orElse(UNSPECIFIED); } /** * Returns a stream of {@link Evaluation}s made by rules starting from the given {@code method}. */ public Stream<Evaluation<S>> evaluations(M method, C state) { return evaluateAcrossScopes(method, state, ResultUseRule::evaluate); } /** * Evaluates all rules for each scope against all members of the scope for scopes appropriate to * the {@code method}. */ private <R> Stream<R> evaluateAcrossScopes( M method, C state, ScopeEvaluator<C, S, R> scopeEvaluator) { return methodInfo.scopes(method).stream() .flatMap(scope -> evaluateForScope(method, state, scopeEvaluator, scope)); } /** * Evaluates all rules in a {@code scope} for each member of the {@code scope} for the {@code * method}. */ private <R> Stream<R> evaluateForScope( M method, C state, ScopeEvaluator<C, S, R> scopeEvaluator, RuleScope scope) { ImmutableList<ResultUseRule<C, S>> scopeRules = rules.get(scope); return methodInfo .scopeMembers(scope, method, state) .flatMap( symbol -> scopeRules.stream() .map(rule -> scopeEvaluator.evaluateForScope(rule, scope, symbol, state))) .flatMap(Optional::stream); } @FunctionalInterface private interface ScopeEvaluator<C, S, R> { /** Evaluates a {@code rule} on a {@code symbol} that is within a {@code scope} for a method. */ Optional<R> evaluateForScope(ResultUseRule<C, S> rule, RuleScope scope, S symbol, C context); } /** * Builder for {@link ResultUsePolicyEvaluator}. * * @param <C> the type of the context object used during evaluation * @param <S> the type of symbols * @param <M> the type of method symbols */ // TODO(dpb): Consider using @AutoBuilder. public static final class Builder<C, S, M extends S> { private final List<ResultUseRule<C, S>> rules = new ArrayList<>(); private final MethodInfo<C, S, M> methodInfo; private Builder(MethodInfo<C, S, M> methodInfo) { this.methodInfo = methodInfo; } /** Adds the given {@code rule}. */ @CanIgnoreReturnValue public Builder<C, S, M> addRule(ResultUseRule<C, S> rule) { this.rules.add(rule); return this; } /** Adds all the given {@code rules}. */ @CanIgnoreReturnValue public Builder<C, S, M> addRules(ResultUseRule<C, S>... rules) { return addRules(Arrays.asList(rules)); } /** Adds all the given {@code rules}. */ @CanIgnoreReturnValue public Builder<C, S, M> addRules(Iterable<? extends ResultUseRule<C, S>> rules) { rules.forEach(this::addRule); return this; } /** Builds a new {@link ResultUsePolicyEvaluator}. */ public ResultUsePolicyEvaluator<C, S, M> build() { return new ResultUsePolicyEvaluator<>(this); } } }
7,585
35.825243
108
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/AutoValueRules.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.checkreturnvalue; import static com.google.errorprone.bugpatterns.checkreturnvalue.ResultUsePolicy.EXPECTED; import static com.google.errorprone.bugpatterns.checkreturnvalue.ResultUsePolicy.OPTIONAL; import static com.google.errorprone.util.ASTHelpers.enclosingClass; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.isAbstract; import static com.google.errorprone.util.ASTHelpers.isSameType; import static com.google.errorprone.util.ASTHelpers.streamSuperMethods; import static java.util.stream.Stream.concat; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.checkreturnvalue.Rules.ErrorProneMethodRule; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import java.util.Optional; import java.util.stream.Stream; /** Rules for {@code @AutoValue}, {@code @AutoValue.Builder}, and {@code @AutoBuilder} types. */ public final class AutoValueRules { private AutoValueRules() {} /** Returns a rule for {@code abstract} methods on {@code @AutoValue} types. */ public static ResultUseRule<VisitorState, Symbol> autoValues() { return new ValueRule(); } /** Returns a rule for {@code abstract} methods on {@code @AutoValue.Builder} types. */ public static ResultUseRule<VisitorState, Symbol> autoValueBuilders() { return new BuilderRule("AutoValue.Builder"); } /** Returns a rule for {@code abstract} methods on {@code @AutoBuilder} types. */ public static ResultUseRule<VisitorState, Symbol> autoBuilders() { return new BuilderRule("AutoBuilder"); } private static final class ValueRule extends AbstractAutoRule { ValueRule() { super("AutoValue"); } @Override protected ResultUsePolicy autoMethodPolicy( MethodSymbol abstractMethod, ClassSymbol autoClass, VisitorState state) { return EXPECTED; } } private static final class BuilderRule extends AbstractAutoRule { BuilderRule(String annotation) { super(annotation); } @Override protected ResultUsePolicy autoMethodPolicy( MethodSymbol abstractMethod, ClassSymbol autoClass, VisitorState state) { return abstractMethod.getParameters().size() == 1 && isSameType(abstractMethod.getReturnType(), autoClass.type, state) ? OPTIONAL : EXPECTED; } } private abstract static class AbstractAutoRule extends ErrorProneMethodRule { private static final String PACKAGE = "com.google.auto.value."; private final String simpleAnnotation; private final String qualifiedAnnotation; AbstractAutoRule(String simpleAnnotation) { this.simpleAnnotation = simpleAnnotation; this.qualifiedAnnotation = PACKAGE + simpleAnnotation; } @Override public String id() { return '@' + simpleAnnotation; } protected abstract ResultUsePolicy autoMethodPolicy( MethodSymbol abstractMethod, ClassSymbol autoClass, VisitorState state); @Override public Optional<ResultUsePolicy> evaluateMethod(MethodSymbol method, VisitorState state) { /* * Sometimes, calls are made on an object whose static type is one of the AutoValue generated * classes: * * - A variable is declared with a type like `AutoValue_Foo`, or it implicitly has that type * because it's declared with `var`. * * - An AutoValue extension's Builder class's methods delegates to supermethods also * generated by AutoValue.Builder. * * To handle this, we walk up the type hierarchy. */ return concat(Stream.of(method), streamSuperMethods(method, state.getTypes())) .filter( m -> isAbstract(m) && hasAnnotation(enclosingClass(m), qualifiedAnnotation, state)) .findFirst() .map(methodSymbol -> autoMethodPolicy(methodSymbol, enclosingClass(methodSymbol), state)); } } }
4,672
36.99187
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/ErrorMessages.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.checkreturnvalue; import static java.util.stream.Collectors.joining; import java.util.List; /** Error messages used by {@link com.google.errorprone.bugpatterns.CheckReturnValue}. */ public class ErrorMessages { private ErrorMessages() {} /** * Error message for when an annotation used by {@link Rules#mapAnnotationSimpleName} is applied * to a void-returning method. * * @param elementType the plural of the {@link java.lang.annotation.ElementType} of the annotated * element (e.g., "methods"). */ public static String annotationOnVoid(String annotation, String elementType) { return String.format("@%s may not be applied to void-returning %s", annotation, elementType); } /** * Error message for when annotations mapped to conflicting {@link ResultUsePolicy}s are applied * to the same element. * * @param elementType the {@link java.lang.annotation.ElementType} of the annotated element (e.g., * "method" or "class"). */ public static String conflictingAnnotations(List<String> annotations, String elementType) { return annotations.stream().map(a -> "@" + a).collect(joining(" and ")) + " cannot be applied to the same " + elementType; } /** * Error message for when * * <ol> * <li>the result of a method or constructor invocation is ignored, and * <li>the {@link ResultUsePolicy} of the invoked method or constructor evaluates to {@link * ResultUsePolicy#EXPECTED}. * </ol> */ public static String invocationResultIgnored( String shortCall, String assignmentToUnused, String apiTrailer) { String shortCallWithoutNew = removeNewPrefix(shortCall); return String.format( "The result of `%s` must be used\n" + "If you really don't want to use the result, then assign it to a variable:" + " `%s`.\n" + "\n" + "If callers of `%s` shouldn't be required to use its result," + " then annotate it with `@CanIgnoreReturnValue`.\n" + "%s", shortCall, assignmentToUnused, shortCallWithoutNew, apiTrailer); } /** * Error message for when * * <ol> * <li>a method or constructor is referenced in such a way that its return value would be * ignored if invoked through the reference, and * <li>the {@link ResultUsePolicy} of the referenced method or constructor evaluates to {@link * ResultUsePolicy#EXPECTED}. * </ol> */ public static String methodReferenceIgnoresResult( String shortCall, String methodReference, String implementedMethod, String assignmentLambda, String apiTrailer) { String shortCallWithoutNew = removeNewPrefix(shortCall); return String.format( "The result of `%s` must be used\n" + "`%s` acts as an implementation of `%s`" + " -- which is a `void` method, so it doesn't use the result of `%s`.\n" + "\n" + "To use the result, you may need to restructure your code.\n" + "\n" + "If you really don't want to use the result, then switch to a lambda that assigns" + " it to a variable: `%s`.\n" + "\n" + "If callers of `%s` shouldn't be required to use its result," + " then annotate it with `@CanIgnoreReturnValue`.\n" + "%s", shortCall, methodReference, implementedMethod, shortCall, assignmentLambda, shortCallWithoutNew, apiTrailer); } private static String removeNewPrefix(String shortCall) { if (shortCall.startsWith("new ")) { return shortCall.substring("new ".length()); } else { return shortCall; } } }
4,410
35.454545
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/Rules.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.checkreturnvalue; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.errorprone.util.ASTHelpers.hasDirectAnnotationWithSimpleName; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.checkreturnvalue.ResultUseRule.GlobalRule; import com.google.errorprone.bugpatterns.checkreturnvalue.ResultUseRule.MethodRule; import com.google.errorprone.bugpatterns.checkreturnvalue.ResultUseRule.SymbolRule; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import java.util.Optional; import java.util.function.BiPredicate; /** Factories for common kinds of {@link ResultUseRule}s. */ public final class Rules { private Rules() {} /** A {@link MethodRule} for Error Prone. */ abstract static class ErrorProneMethodRule extends MethodRule<VisitorState, Symbol, MethodSymbol> { ErrorProneMethodRule() { super(MethodSymbol.class); } } /** * Returns a simple global rule that always returns the given defaults for methods and * constructors. */ public static ResultUseRule<VisitorState, Symbol> globalDefault( Optional<ResultUsePolicy> methodDefault, Optional<ResultUsePolicy> constructorDefault) { return new SimpleGlobalRule("GLOBAL_DEFAULT", methodDefault, constructorDefault); } /** * Returns a {@link ResultUseRule} that maps annotations with the given {@code simpleName} to the * given {@code policy}. */ public static ResultUseRule<VisitorState, Symbol> mapAnnotationSimpleName( String simpleName, ResultUsePolicy policy) { return new SimpleRule( "ANNOTATION @" + simpleName, (sym, st) -> hasDirectAnnotationWithSimpleName(sym, simpleName), policy); } private static final class SimpleRule extends SymbolRule<VisitorState, Symbol> { private final String name; private final BiPredicate<Symbol, VisitorState> predicate; private final ResultUsePolicy policy; private SimpleRule( String name, BiPredicate<Symbol, VisitorState> predicate, ResultUsePolicy policy) { this.name = name; this.predicate = predicate; this.policy = policy; } @Override public String id() { return name; } @Override public Optional<ResultUsePolicy> evaluate(Symbol symbol, VisitorState state) { return predicate.test(symbol, state) ? Optional.of(policy) : Optional.empty(); } } private static final class SimpleGlobalRule extends GlobalRule<VisitorState, Symbol> { private final String id; private final Optional<ResultUsePolicy> methodDefault; private final Optional<ResultUsePolicy> constructorDefault; private SimpleGlobalRule( String id, Optional<ResultUsePolicy> methodDefault, Optional<ResultUsePolicy> constructorDefault) { this.id = checkNotNull(id); this.methodDefault = methodDefault; this.constructorDefault = constructorDefault; } @Override public String id() { return id; } @Override public Optional<ResultUsePolicy> evaluate(Symbol symbol, VisitorState context) { return symbol.isConstructor() ? constructorDefault : methodDefault; } } }
3,882
33.362832
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/BuilderReturnThis.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.checkreturnvalue; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.fixes.SuggestedFixes.qualifyType; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isSameType; import static com.google.errorprone.util.ASTHelpers.isSubtype; 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.MethodTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.tree.ConditionalExpressionTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.TypeCastTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; /** Discourages builder instance methods that do not return 'this'. */ @BugPattern(summary = "Builder instance method does not return 'this'", severity = WARNING) public class BuilderReturnThis extends BugChecker implements MethodTreeMatcher { private static final String CRV = "com.google.errorprone.annotations.CheckReturnValue"; @Override public Description matchMethod(MethodTree tree, VisitorState state) { MethodSymbol sym = getSymbol(tree); if (tree.getBody() == null) { return NO_MATCH; } if (!instanceReturnsBuilder(sym, state)) { return NO_MATCH; } if (!nonThisReturns(tree, state)) { return NO_MATCH; } SuggestedFix.Builder fix = SuggestedFix.builder(); String crvName = qualifyType(state, fix, CRV); fix.prefixWith(tree, "@" + crvName + "\n"); return describeMatch(tree, fix.build()); } private static boolean instanceReturnsBuilder(MethodSymbol sym, VisitorState state) { // instance methods if (sym.isStatic()) { return false; } // declared in a class with the simple name that contains Builder ClassSymbol enclosingClass = sym.owner.enclClass(); if (!enclosingClass.getSimpleName().toString().endsWith("Builder")) { return false; } // whose return type is the exact type of this // or perhaps "a non-Object supertype of the this-type", for interfaces Type returnType = sym.getReturnType(); if (!isSubtype(enclosingClass.asType(), returnType, state) || isSameType(returnType, state.getSymtab().objectType, state)) { return false; } return true; } // TODO(b/236055787): consolidate heuristics for 'return this;' boolean nonThisReturns(MethodTree tree, VisitorState state) { boolean[] result = {false}; new TreeScanner<Void, Void>() { @Override public Void visitLambdaExpression(LambdaExpressionTree tree, Void unused) { return null; } @Override public Void visitMethod(MethodTree tree, Void unused) { return null; } @Override public Void visitReturn(ReturnTree tree, Void unused) { if (!returnsThis(tree.getExpression())) { result[0] = true; } return super.visitReturn(tree, null); } private boolean returnsThis(ExpressionTree tree) { return firstNonNull( new TreeScanner<Boolean, Void>() { @Override public Boolean visitIdentifier(IdentifierTree tree, Void unused) { return tree.getName().contentEquals("this"); } @Override public Boolean visitMethodInvocation(MethodInvocationTree tree, Void unused) { return instanceReturnsBuilder(getSymbol(tree), state); } @Override public Boolean visitConditionalExpression( ConditionalExpressionTree tree, Void unused) { return TRUE.equals(tree.getFalseExpression().accept(this, null)) && TRUE.equals(tree.getTrueExpression().accept(this, null)); } @Override public Boolean visitParenthesized(ParenthesizedTree tree, Void unused) { return tree.getExpression().accept(this, null); } @Override public Boolean visitTypeCast(TypeCastTree tree, Void unused) { return tree.getExpression().accept(this, null); } }.scan(tree, null), false); } }.scan(tree.getBody(), null); return result[0]; } }
5,678
36.609272
92
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/NoCanIgnoreReturnValueOnClasses.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.checkreturnvalue; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.fixes.SuggestedFixes.qualifyType; import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE; import static com.google.errorprone.matchers.Matchers.annotations; import static com.google.errorprone.matchers.Matchers.isType; 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.isConsideredFinal; import static com.google.errorprone.util.ASTHelpers.isGeneratedConstructor; import static com.google.errorprone.util.ASTHelpers.isVoidType; import com.google.common.annotations.VisibleForTesting; import com.google.errorprone.BugPattern; 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.matchers.MultiMatcher; import com.google.errorprone.matchers.MultiMatcher.MultiMatchResult; import com.sun.source.tree.AnnotationTree; 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.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeCastTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; /** * Checker that "pushes" the {@code @CanIgnoreReturnValue} annotation down from classes to methods. */ @BugPattern( summary = "@CanIgnoreReturnValue should not be applied to classes as it almost always overmatches (as" + " it applies to constructors and all methods), and the CIRVness isn't conferred to" + " its subclasses.", documentSuppression = false, suppressionAnnotations = {}, severity = ERROR) public final class NoCanIgnoreReturnValueOnClasses extends BugChecker implements ClassTreeMatcher { private static final String CRV = "com.google.errorprone.annotations.CheckReturnValue"; private static final String CIRV = "com.google.errorprone.annotations.CanIgnoreReturnValue"; private static final String EXTRA_SUFFIX = ""; @VisibleForTesting static final String METHOD_COMMENT = " // pushed down from class to method;" + EXTRA_SUFFIX; @VisibleForTesting static final String CTOR_COMMENT = " // pushed down from class to constructor;" + EXTRA_SUFFIX; private static final MultiMatcher<ClassTree, AnnotationTree> HAS_CIRV_ANNOTATION = annotations(AT_LEAST_ONE, isType(CIRV)); @Override public Description matchClass(ClassTree tree, VisitorState state) { MultiMatchResult<AnnotationTree> cirvAnnotation = HAS_CIRV_ANNOTATION.multiMatchResult(tree, state); // if the class isn't directly annotated w/ @CIRV, bail out if (!cirvAnnotation.matches()) { return Description.NO_MATCH; } SuggestedFix.Builder fix = SuggestedFix.builder(); String cirvName = qualifyType(state, fix, CIRV); // remove @CIRV from the class fix.delete(cirvAnnotation.onlyMatchingNode()); // theoretically, we could also add @CRV to the class, since all APIs will have CIRV pushed down // onto them, but it's very likely that a larger enclosing scope will already be @CRV (otherwise // why did the user annotate this class as @CIRV?) // scan the tree and add @CIRV to all non-void method declarations that aren't already annotated // with @CIRV or @CRV new TreePathScanner<Void, Void>() { @Override public Void visitClass(ClassTree classTree, Void unused) { // stop descending when we reach a class that's marked @CRV return hasAnnotation(classTree, CRV, state) ? null : super.visitClass(classTree, unused); } @Override public Void visitMethod(MethodTree methodTree, Void unused) { if (shouldAddCirv(methodTree, state)) { String trailingComment = null; if (methodTree.getReturnType() == null) { // constructor trailingComment = CTOR_COMMENT; } else if (alwaysReturnsThis()) { trailingComment = ""; } else { trailingComment = METHOD_COMMENT; } fix.prefixWith(methodTree, "@" + cirvName + trailingComment + "\n"); } // TODO(kak): we could also consider removing CRV from individual methods (since the // enclosing class is now annotated as CRV. return null; } private boolean alwaysReturnsThis() { // TODO(b/236055787): share this TreePathScanner AtomicBoolean allReturnThis = new AtomicBoolean(true); AtomicBoolean atLeastOneReturn = new AtomicBoolean(false); new TreePathScanner<Void, Void>() { private final Set<VarSymbol> thises = new HashSet<>(); @Override public Void visitVariable(VariableTree variableTree, Void unused) { VarSymbol symbol = getSymbol(variableTree); if (isConsideredFinal(symbol) && maybeCastThis(variableTree.getInitializer())) { thises.add(symbol); } return super.visitVariable(variableTree, null); } @Override public Void visitReturn(ReturnTree returnTree, Void unused) { atLeastOneReturn.set(true); if (!isThis(returnTree.getExpression())) { allReturnThis.set(false); // once we've set allReturnThis to false, no need to descend further return null; } return super.visitReturn(returnTree, null); } /** Returns whether the given {@link ExpressionTree} is {@code this}. */ private boolean isThis(ExpressionTree returnExpression) { return maybeCastThis(returnExpression) || thises.contains(getSymbol(returnExpression)); } @Override public Void visitLambdaExpression(LambdaExpressionTree node, Void unused) { // don't descend into lambdas return null; } @Override public Void visitNewClass(NewClassTree node, Void unused) { // don't descend into declarations of anonymous classes return null; } private boolean maybeCastThis(Tree tree) { return firstNonNull( new SimpleTreeVisitor<Boolean, Void>() { @Override public Boolean visitParenthesized(ParenthesizedTree tree, Void unused) { return visit(tree.getExpression(), null); } @Override public Boolean visitTypeCast(TypeCastTree tree, Void unused) { return visit(tree.getExpression(), null); } @Override public Boolean visitIdentifier(IdentifierTree tree, Void unused) { return tree.getName().contentEquals("this"); } @Override public Boolean visitMethodInvocation(MethodInvocationTree tree, Void unused) { return getSymbol(tree).getSimpleName().contentEquals("self") || getSymbol(tree).getSimpleName().contentEquals("getThis"); } }.visit(tree, null), false); } }.scan(getCurrentPath(), null); return allReturnThis.get() && atLeastOneReturn.get(); } private boolean shouldAddCirv(MethodTree methodTree, VisitorState state) { if (isVoidType(getType(methodTree.getReturnType()), state)) { // void return types return false; } if (hasAnnotation(methodTree, CIRV, state)) { return false; } if (hasAnnotation(methodTree, CRV, state)) { return false; } // if the constructor is implicit, don't add CIRV (we can't annotate a synthetic node!) if (isGeneratedConstructor(methodTree)) { return false; } // if the method is inside an AV or AV.Builder and is abstract (no body), don't add CIRV ClassSymbol enclosingClass = enclosingClass(getSymbol(methodTree)); if (hasAnnotation(enclosingClass, "com.google.auto.value.AutoValue", state) || hasAnnotation(enclosingClass, "com.google.auto.value.AutoValue.Builder", state)) { if (methodTree.getBody() == null) { return false; } } // TODO(kak): should we also return false for private methods? I'm betting most of them are // "accidentally" CIRV'ed by the enclosing class; any compile errors would be caught by // building the enclosing class anyways. return true; } @Override public Void visitLambdaExpression(LambdaExpressionTree node, Void unused) { // don't descend into lambdas return null; } @Override public Void visitNewClass(NewClassTree node, Void unused) { // don't descend into declarations of anonymous classes return null; } }.scan(state.getPath(), null); return describeMatch(tree, fix.build()); } }
10,680
40.722656
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/Api.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.checkreturnvalue; import static com.google.common.base.CharMatcher.whitespace; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.Character.isJavaIdentifierPart; import static java.lang.Character.isJavaIdentifierStart; import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.CompileTimeConstant; /** * Represents a Java method or constructor. * * <p>Provides a method to parse an API from a string format, and emit an API as the same sting. */ // TODO(kak): do we want to be able to represent classes in addition to methods/constructors? // TODO(kak): if not, then consider renaming to `MethodSignature` or something @AutoValue public abstract class Api { private static final Joiner COMMA_JOINER = Joiner.on(','); /** Returns the fully qualified type that contains the given method/constructor. */ public abstract String className(); /** * Returns the simple name of the method. If the API is a constructor (i.e., {@code * isConstructor() == true}), then {@code "<init>"} is returned. */ public abstract String methodName(); /** Returns the list of fully qualified parameter types for the given method/constructor. */ public abstract ImmutableList<String> parameterTypes(); @Override public final String toString() { return String.format( "%s#%s(%s)", className(), methodName(), COMMA_JOINER.join(parameterTypes())); } /** Returns whether this API represents a constructor or not. */ boolean isConstructor() { return methodName().equals("<init>"); } /** * Parses an API string into an {@link Api}, ignoring trailing or inner whitespace between names. * * <p>Example API strings are: * * <ul> * <li>a constructor (e.g., {@code java.net.URI#<init>(java.lang.String)}) * <li>a static method (e.g., {@code java.net.URI#create(java.lang.String)}) * <li>an instance method (e.g., {@code java.util.List#get(int)}) * <li>an instance method with types erased (e.g., {@code java.util.List#add(java.lang.Object)}) * </ul> * * @throws IllegalArgumentException when {@code api} is not well-formed */ @VisibleForTesting public static Api parse(String api) { return parse(api, false); } /** * Parses an API string that was already known to not include any leading, trailing, or inner * whitespace. * * <p>If the API string contains whitespace, this method may produce an API object with extraneous * spaces attached, or may treat it as malformed (and throw an exception). * * @throws IllegalArgumentException when {@code api} is not well-formed */ // TODO(glorioso): Refactoring has shown the folly of this method. It's probably not useful, since // if we're _parsing_ into API objects, there's not as much of a performance concern for // touching whitespaces. If we use bare string identifiers instead, whitespaces are problematic, // but this code wouldn't be involved. static Api parseFromStringWithoutWhitespace(String api) { return parse(api, true); } static Api internalCreate(String className, String methodName, ImmutableList<String> params) { return new AutoValue_Api(className, methodName, params); } /** * Parses an API string into an {@link Api}. Example API strings are: * * <ul> * <li>a constructor (e.g., {@code java.net.URI#<init>(java.lang.String)}) * <li>a static method (e.g., {@code java.net.URI#create(java.lang.String)}) * <li>an instance method (e.g., {@code java.util.List#get(int)}) * <li>an instance method with types erased (e.g., {@code java.util.List#add(java.lang.Object)}) * </ul> */ private static Api parse(String api, boolean assumeNoWhitespace) { Parser p = new Parser(api, assumeNoWhitespace); // Let's parse this in 3 parts: // * Fully-qualified owning name, followed by # // * method name, or "<init>", followed by ( // * Any number of parameter types, all but the last followed by a ',', Finishing with ) // * and nothing at the end. String className = p.owningType(); String methodName = p.methodName(); ImmutableList<String> paramList = p.parameters(); p.ensureNoMoreCharacters(); return internalCreate(className, methodName, paramList); } private static final class Parser { private final String api; private final boolean assumeNoWhitespace; private int position = -1; Parser(String api, boolean assumeNoWhitespace) { this.api = api; this.assumeNoWhitespace = assumeNoWhitespace; } String owningType() { StringBuilder buffer = new StringBuilder(api.length()); token: do { char next = nextLookingFor('#'); switch (next) { case '#': // We've hit the end of the leading type, break out. break token; case '.': // OK, separator break; case '-': // OK, used in Kotlin JvmName to prevent Java users. break; default: checkArgument( isJavaIdentifierPart(next), "Unable to parse '%s' because '%s' is not a valid identifier", api, next); } buffer.append(next); } while (true); String type = buffer.toString(); check(!type.isEmpty(), api, "class name cannot be empty"); check( isJavaIdentifierStart(type.charAt(0)), api, "the class name must start with a valid character"); return type; } String methodName() { StringBuilder buffer = new StringBuilder(api.length() - position); boolean isConstructor = false; boolean finishedConstructor = false; // match "<init>", or otherwise a normal method name token: do { char next = nextLookingFor('('); switch (next) { case '(': // We've hit the end of the method name, break out. break token; case '<': // Starting a constructor check(!isConstructor, api, "Only one '<' is allowed"); check(buffer.length() == 0, api, "'<' must come directly after '#'"); isConstructor = true; break; case '>': check(isConstructor, api, "'<' must come before '>'"); check(!finishedConstructor, api, "Only one '>' is allowed"); finishedConstructor = true; break; default: checkArgument( isJavaIdentifierPart(next), "Unable to parse '%s' because '%s' is not a valid identifier", api, next); } buffer.append(next); } while (true); String methodName = buffer.toString(); if (isConstructor) { check(finishedConstructor, api, "found '<' without closing '>"); // Must be "<init>" exactly checkArgument( methodName.equals("<init>"), "Unable to parse '%s' because %s is an invalid method name", api, methodName); } else { check(!methodName.isEmpty(), api, "method name cannot be empty"); check( isJavaIdentifierStart(methodName.charAt(0)), api, "the method name must start with a valid character"); } return methodName; } ImmutableList<String> parameters() { // Text until the next ',' or ')' represents the parameter type. // If the first token is ')', then we have an empty parameter list. StringBuilder buffer = new StringBuilder(api.length() - position); ImmutableList.Builder<String> paramBuilder = ImmutableList.builder(); boolean emptyList = true; paramList: do { char next = nextLookingFor(')'); switch (next) { case ')': if (emptyList) { return ImmutableList.of(); } // We've hit the end of the whole list, bail out. paramBuilder.add(consumeParam(buffer)); break paramList; case ',': // We've hit the middle of a parameter, consume it paramBuilder.add(consumeParam(buffer)); break; case '[': case ']': case '.': // . characters are separators, [ and ] are array characters, they're checked @ the end buffer.append(next); break; default: checkArgument( isJavaIdentifierPart(next), "Unable to parse '%s' because '%s' is not a valid identifier", api, next); emptyList = false; buffer.append(next); } } while (true); return paramBuilder.build(); } private String consumeParam(StringBuilder buffer) { String parameter = buffer.toString(); buffer.setLength(0); // reset the buffer check(!parameter.isEmpty(), api, "parameters cannot be empty"); check( isJavaIdentifierStart(parameter.charAt(0)), api, "parameters must start with a valid character"); // Array specs must be in balanced pairs at the *end* of the parameter. boolean parsingArrayStart = false; boolean hasArraySpecifiers = false; for (int k = 1; k < parameter.length(); k++) { char c = parameter.charAt(k); switch (c) { case '[': check(!parsingArrayStart, api, "multiple consecutive ["); hasArraySpecifiers = true; parsingArrayStart = true; break; case ']': check(parsingArrayStart, api, "unbalanced ] in array type"); parsingArrayStart = false; break; default: check( !hasArraySpecifiers, api, "types with array specifiers should end in those specifiers"); } } check(!parsingArrayStart, api, "[ without closing ] at the end of a parameter type"); return parameter; } // skip whitespace characters and give the next non-whitespace character. If we hit the end // without a non-whitespace character, throw expecting the delimiter. private char nextLookingFor(char delimiter) { char next; do { position++; checkArgument( position < api.length(), "Could not parse '%s' as it must contain an '%s'", api, delimiter); next = api.charAt(position); } while (!assumeNoWhitespace && whitespace().matches(next)); return next; } void ensureNoMoreCharacters() { if (assumeNoWhitespace) { return; } while (++position < api.length()) { check(whitespace().matches(api.charAt(position)), api, "it should end in ')'"); } } // The @CompileTimeConstant is for performance - reason should be constant and not eagerly // constructed. private static void check(boolean condition, String api, @CompileTimeConstant String reason) { checkArgument(condition, "Unable to parse '%s' because %s", api, reason); } } }
12,041
34.417647
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/ExternalCanIgnoreReturnValue.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.checkreturnvalue; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSetMultimap.toImmutableSetMultimap; import static com.google.errorprone.bugpatterns.checkreturnvalue.ApiFactory.fullyErasedAndUnannotatedType; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Iterables; import com.google.common.io.CharSource; import com.google.common.io.MoreFiles; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.checkreturnvalue.Rules.ErrorProneMethodRule; import com.google.errorprone.suppliers.Supplier; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.util.List; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Paths; import java.util.Optional; import java.util.stream.Stream; /** External source of information about @CanIgnoreReturnValue-equivalent API's. */ public final class ExternalCanIgnoreReturnValue extends ErrorProneMethodRule { /** Returns a rule using an external list of APIs to ignore. */ public static ResultUseRule<VisitorState, Symbol> externalIgnoreList() { return new ExternalCanIgnoreReturnValue(); } private ExternalCanIgnoreReturnValue() {} private static final String EXTERNAL_API_EXCLUSION_LIST = "CheckReturnValue:ApiExclusionList"; private static final String EXCLUSION_LIST_PARSER = "CheckReturnValue:ApiExclusionListParser"; private static final Supplier<MethodPredicate> EXTERNAL_RULE_EVALUATOR = VisitorState.memoize( state -> state .errorProneOptions() .getFlags() .get(EXTERNAL_API_EXCLUSION_LIST) .filter(s -> !s.isEmpty()) .map( filename -> loadConfigListFromFile( filename, state .errorProneOptions() .getFlags() .getEnum(EXCLUSION_LIST_PARSER, ConfigParser.class) .orElse(ConfigParser.AS_STRINGS))) .orElse((m, s) -> false)); @Override public String id() { return "EXTERNAL_API_EXCLUSION_LIST"; } @Override public Optional<ResultUsePolicy> evaluateMethod(MethodSymbol method, VisitorState state) { return EXTERNAL_RULE_EVALUATOR.get(state).methodMatches(method, state) ? Optional.of(ResultUsePolicy.UNSPECIFIED) : Optional.empty(); } /** Encapsulates asking "does this API match the list of APIs I care about"? */ @FunctionalInterface interface MethodPredicate { boolean methodMatches(MethodSymbol methodSymbol, VisitorState state); } // TODO(b/232240203): Api Parsing at analysis time is expensive - there are many ways to // load and use the config file. // Decide on what works best, taking into account hit rate, load time, etc. enum ConfigParser { AS_STRINGS { @Override MethodPredicate load(String file) throws IOException { return configByInterpretingMethodsAsStrings(MoreFiles.asCharSource(Paths.get(file), UTF_8)); } }, PARSE_TOKENS { @Override MethodPredicate load(String file) throws IOException { return configByParsingApiObjects(MoreFiles.asCharSource(Paths.get(file), UTF_8)); } }; abstract MethodPredicate load(String file) throws IOException; } static MethodPredicate loadConfigListFromFile(String filename, ConfigParser configParser) { try { return configParser.load(filename); } catch (IOException e) { throw new UncheckedIOException( "Could not load external resource for CanIgnoreReturnValue", e); } } private static MethodPredicate configByInterpretingMethodsAsStrings(CharSource file) throws IOException { ImmutableSet<String> apis; // NB: No whitespace stripping here try (Stream<String> lines = file.lines()) { apis = lines.collect(toImmutableSet()); } return new MethodPredicate() { @Override public boolean methodMatches(MethodSymbol methodSymbol, VisitorState state) { // Construct an API identifier for this method, which involves erasing parameter types return apis.contains(apiSignature(methodSymbol, state.getTypes())); } private String apiSignature(MethodSymbol methodSymbol, Types types) { return methodSymbol.owner.getQualifiedName() + "#" + methodNameAndParams(methodSymbol, types); } }; } private static MethodPredicate configByParsingApiObjects(CharSource file) throws IOException { ImmutableSetMultimap<String, Api> apis; try (Stream<String> lines = file.lines()) { apis = lines.map(Api::parse).collect(toImmutableSetMultimap(Api::className, api -> api)); } return (methodSymbol, state) -> apis.get(surroundingClass(methodSymbol)).stream() .anyMatch( api -> methodSymbol.getSimpleName().contentEquals(api.methodName()) && methodParametersMatch( api.parameterTypes(), methodSymbol.params(), state.getTypes())); } public static String surroundingClass(MethodSymbol methodSymbol) { return methodSymbol.enclClass().getQualifiedName().toString(); } public static String methodNameAndParams(MethodSymbol methodSymbol, Types types) { return methodSymbol.name + "(" + paramsString(types, methodSymbol.params()) + ")"; } private static boolean methodParametersMatch( ImmutableList<String> parameters, List<VarSymbol> methodParams, Types types) { return Iterables.elementsEqual( parameters, Iterables.transform(methodParams, p -> fullyErasedAndUnannotatedType(p.type, types))); } private static String paramsString(Types types, List<VarSymbol> params) { if (params.isEmpty()) { return ""; } return String.join( ",", Iterables.transform(params, p -> fullyErasedAndUnannotatedType(p.type, types))); } }
7,113
38.087912
106
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/ResultUseRule.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.checkreturnvalue; import static com.google.errorprone.bugpatterns.checkreturnvalue.ResultUseRule.RuleScope.ENCLOSING_ELEMENTS; import static com.google.errorprone.bugpatterns.checkreturnvalue.ResultUseRule.RuleScope.GLOBAL; import static com.google.errorprone.bugpatterns.checkreturnvalue.ResultUseRule.RuleScope.METHOD; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Optional; /** * A rule for determining {@link ResultUsePolicy} for methods and/or constructors. * * @param <C> the type of the context object used during evaluation * @param <S> the type of symbols */ public abstract class ResultUseRule<C, S> { // TODO(cgdecker): Switching to a model where scopes can only either be in a "marked" or // "unmarked" state and only methods can have a specific policy will simplify all of this a lot. /** An ID for uniquely identifying this rule. */ public abstract String id(); /** The scopes this rule applies to. */ public abstract ImmutableSet<RuleScope> scopes(); // TODO(dpb): Reorder parameters for the following methods so they have the same initial // parameters. /** Evaluates the given {@code symbol} and optionally returns a {@link ResultUsePolicy} for it. */ public abstract Optional<ResultUsePolicy> evaluate(S symbol, C context); /** Evaluates the given symbol and optionally returns an {@link Evaluation} of it. */ public final Optional<Evaluation<S>> evaluate(RuleScope scope, S symbol, C context) { return evaluate(symbol, context).map(policy -> Evaluation.create(this, scope, symbol, policy)); } @Override public final String toString() { return id(); } /** * A rule that evaluates methods and constructors to determine a {@link ResultUsePolicy} for them. * * @param <C> the type of the context object used during evaluation * @param <S> the type of symbols * @param <M> the type of method symbols */ public abstract static class MethodRule<C, S, M extends S> extends ResultUseRule<C, S> { private static final ImmutableSet<RuleScope> SCOPES = ImmutableSet.of(METHOD); private final Class<M> methodSymbolClass; protected MethodRule(Class<M> methodSymbolClass) { this.methodSymbolClass = methodSymbolClass; } @Override public final ImmutableSet<RuleScope> scopes() { return SCOPES; } /** * Evaluates the given {@code method} and optionally returns a {@link ResultUsePolicy} for it. */ public abstract Optional<ResultUsePolicy> evaluateMethod(M method, C context); @Override public final Optional<ResultUsePolicy> evaluate(S symbol, C context) { return methodSymbolClass.isInstance(symbol) ? evaluateMethod(methodSymbolClass.cast(symbol), context) : Optional.empty(); } } /** * A rule that evaluates symbols of any kind to determine a {@link ResultUsePolicy} to associate * with them. * * @param <C> the type of the context object used during evaluation * @param <S> the type of symbols */ public abstract static class SymbolRule<C, S> extends ResultUseRule<C, S> { private static final ImmutableSet<RuleScope> SCOPES = ImmutableSet.of(METHOD, ENCLOSING_ELEMENTS); @Override public final ImmutableSet<RuleScope> scopes() { return SCOPES; } } /** * A global rule that is evaluated when none of the more specific rules determine a {@link * ResultUsePolicy} for a method. * * @param <C> the type of the context object used during evaluation * @param <S> the type of symbols */ public abstract static class GlobalRule<C, S> extends ResultUseRule<C, S> { private static final ImmutableSet<RuleScope> SCOPES = ImmutableSet.of(GLOBAL); @Override public final ImmutableSet<RuleScope> scopes() { return SCOPES; } } /** Scope to which a rule may apply. */ public enum RuleScope { /** The specific method or constructor for which a {@link ResultUsePolicy} is being chosen. */ METHOD, /** * Classes and package that enclose a <i>method</i> for which a {@link ResultUsePolicy} is being * chosen. */ ENCLOSING_ELEMENTS, /** The global scope. */ GLOBAL, } /** * An evaluation that a rule makes. * * @param <S> the type of symbols */ @AutoValue public abstract static class Evaluation<S> { /** Creates a new {@link Evaluation}. */ public static <S> Evaluation<S> create( ResultUseRule<?, S> rule, RuleScope scope, S element, ResultUsePolicy policy) { return new AutoValue_ResultUseRule_Evaluation<>(rule, scope, element, policy); } /** The rule that made this evaluation. */ public abstract ResultUseRule<?, S> rule(); /** The scope at which the evaluation was made. */ public abstract RuleScope scope(); /** The specific element in the scope for which the evaluation was made. */ public abstract S element(); /** The policy the rule selected. */ public abstract ResultUsePolicy policy(); } }
5,716
33.233533
108
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/UnnecessarilyUsedValue.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.checkreturnvalue; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; 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 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.VariableTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TryTree; import com.sun.source.tree.VariableTree; import javax.lang.model.element.Name; /** * Checker that warns when capturing the result of an ignorable API into an {@code unused} variable. */ @BugPattern( summary = "The result of this API is ignorable, so it does not need to be captured / assigned into an" + " `unused` variable.", severity = WARNING) public final class UnnecessarilyUsedValue extends BugChecker implements AssignmentTreeMatcher, VariableTreeMatcher { @Override public Description matchAssignment(AssignmentTree assignmentTree, VisitorState state) { if (isTryResource(assignmentTree, state)) { return Description.NO_MATCH; } ExpressionTree expressionTree = assignmentTree.getExpression(); if (isMethodInvocationLike(expressionTree) && assignmentTree.getVariable() instanceof IdentifierTree && isIgnorable(expressionTree, ((IdentifierTree) assignmentTree.getVariable()).getName())) { return describeMatch( assignmentTree, SuggestedFix.replace(assignmentTree, state.getSourceForNode(expressionTree))); } return Description.NO_MATCH; } @Override public Description matchVariable(VariableTree variableTree, VisitorState state) { if (isTryResource(variableTree, state)) { return Description.NO_MATCH; } ExpressionTree initializer = variableTree.getInitializer(); if (isMethodInvocationLike(initializer) && isIgnorable(initializer, variableTree.getName())) { return describeMatch( variableTree, SuggestedFix.replace(variableTree, state.getSourceForNode(initializer) + ";")); } return Description.NO_MATCH; } private static boolean isMethodInvocationLike(ExpressionTree initializer) { return (initializer instanceof MethodInvocationTree || initializer instanceof NewClassTree); } private static boolean isTryResource(Tree expression, VisitorState state) { TryTree tryTree = findEnclosingNode(state.getPath(), TryTree.class); return (tryTree != null) && tryTree.getResources().contains(expression); } private static boolean isIgnorable(ExpressionTree methodInvocationTree, Name name) { // TODO(kak): use the ResultUsePolicyEvaluator from the CheckReturnValue checker return hasDirectAnnotationWithSimpleName( getSymbol(methodInvocationTree), "CanIgnoreReturnValue") // match unused[0-9]*, since those are likely intentional CRV-related suppressions (captured // into an unused variable), as opposed to a "normal" variable like `long unusedBalance`. && name.toString().matches("unused\\d*"); } }
4,284
41.009804
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/CanIgnoreReturnValueSuggester.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.checkreturnvalue; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.fixes.SuggestedFixes.qualifyType; import static com.google.errorprone.util.ASTHelpers.getAnnotationWithSimpleName; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getReturnType; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasAnnotation; import static com.google.errorprone.util.ASTHelpers.isAbstract; import static com.google.errorprone.util.ASTHelpers.isSameType; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static com.google.errorprone.util.ASTHelpers.shouldKeep; import static com.google.errorprone.util.ASTHelpers.stripParentheses; 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.MethodTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeCastTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; import java.util.HashSet; import java.util.Set; /** * Checker that recommends annotating a method with {@code @CanIgnoreReturnValue} if the method * returns {@code this}, returns an effectively final input param, or if it looks like a builder * method (that is likely to return {@code this}). */ @BugPattern( summary = "Methods with ignorable return values (including methods that always 'return this') should" + " be annotated with @com.google.errorprone.annotations.CanIgnoreReturnValue", severity = WARNING) public final class CanIgnoreReturnValueSuggester extends BugChecker implements MethodTreeMatcher { private static final String AUTO_VALUE = "com.google.auto.value.AutoValue"; private static final String IMMUTABLE = "com.google.errorprone.annotations.Immutable"; private static final String CRV = "com.google.errorprone.annotations.CheckReturnValue"; private static final String CIRV = "com.google.errorprone.annotations.CanIgnoreReturnValue"; private static final Supplier<Type> PROTO_BUILDER = VisitorState.memoize(s -> s.getTypeFromString("com.google.protobuf.MessageLite.Builder")); private static final ImmutableSet<String> BANNED_METHOD_PREFIXES = ImmutableSet.of("get", "is", "has", "new", "clone", "copy"); @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { MethodSymbol methodSymbol = getSymbol(methodTree); // if the method is already directly annotated w/ @CRV or @CIRV, bail out if (hasAnnotation(methodSymbol, CRV, state) || hasAnnotation(methodSymbol, CIRV, state)) { return Description.NO_MATCH; } // if the method is annotated with an annotation that is @Keep, bail out if (shouldKeep(methodTree)) { return Description.NO_MATCH; } // if the method looks like an accessor, bail out String methodName = methodSymbol.getSimpleName().toString(); // TODO(kak): we also may want to check if methodSymbol.getParameters().isEmpty() if (BANNED_METHOD_PREFIXES.stream().anyMatch(methodName::startsWith)) { return Description.NO_MATCH; } // if the method always return a single input param (of the same type), make it CIRV if (methodAlwaysReturnsInputParam(methodTree, state)) { return annotateWithCanIgnoreReturnValue(methodTree, state); } // We have a number of preconditions we can check early to ensure that this method could // possibly be @CIRV-suggestible, before attempting a deeper scan of the method. if (methodSymbol.isStatic() // the return type must be the same as the enclosing type (this skips void methods too) || !isSameType(methodSymbol.owner.type, methodSymbol.getReturnType(), state) // nb: these methods should probably be @CheckReturnValue! // They'd likely be excluded naturally by the isSimpleReturnThisMethod check below, but we // check for them explicitly here. || isDefinitionOfZeroArgSelf(methodSymbol) // Constructors can't "return", and generally shouldn't be @CIRV || methodTree.getReturnType() == null // b/236423646 - These methods that do nothing *but* `return this;` are likely to be // overridden in other contexts, and we've decided that these methods shouldn't be annotated // automatically. || isSimpleReturnThisMethod(methodTree) // TODO(kak): This appears to be a performance optimization for refactoring passes? || isSubtype(methodSymbol.owner.type, PROTO_BUILDER.get(state), state)) { return Description.NO_MATCH; } // skip @AutoValue and @AutoBuilder methods if (isAbstractAutoValueOrAutoBuilderMethod(methodSymbol, state)) { return Description.NO_MATCH; } // if the method looks like a builder, or if it always returns `this`, then make it @CIRV if (classLooksLikeBuilder(methodSymbol.owner, state) || methodReturnsIgnorableValues(methodTree, state)) { return annotateWithCanIgnoreReturnValue(methodTree, state); } return Description.NO_MATCH; } private Description annotateWithCanIgnoreReturnValue(MethodTree methodTree, VisitorState state) { SuggestedFix.Builder fix = SuggestedFix.builder(); // if the method is annotated with @RIU, we need to remove it before adding @CIRV AnnotationTree riuAnnotation = getAnnotationWithSimpleName( methodTree.getModifiers().getAnnotations(), "ResultIgnorabilityUnspecified"); if (riuAnnotation != null) { fix.delete(riuAnnotation); } // now annotate it with @CanIgnoreReturnValue fix.prefixWith(methodTree, "@" + qualifyType(state, fix, CIRV) + "\n"); return describeMatch(methodTree, fix.build()); } private static boolean isAbstractAutoValueOrAutoBuilderMethod( MethodSymbol methodSymbol, VisitorState state) { Symbol owner = methodSymbol.owner; // TODO(kak): use ResultEvaluator instead of duplicating _some_ of the logic (right now we only // exclude @AutoValue.Builder's and @AutoBuilder's) return isAbstract(methodSymbol) && (hasAnnotation(owner, AUTO_VALUE + ".Builder", state) || hasAnnotation(owner, "com.google.auto.value.AutoBuilder", state)); } private static boolean classLooksLikeBuilder(Symbol owner, VisitorState state) { boolean classIsImmutable = hasAnnotation(owner, IMMUTABLE, state) || hasAnnotation(owner, AUTO_VALUE, state); return owner.getSimpleName().toString().endsWith("Builder") && !classIsImmutable; } private static boolean isSimpleReturnThisMethod(MethodTree methodTree) { if (methodTree.getBody() != null && methodTree.getBody().getStatements().size() == 1) { StatementTree onlyStatement = methodTree.getBody().getStatements().get(0); if (onlyStatement instanceof ReturnTree) { return returnsThisOrSelf((ReturnTree) onlyStatement); } } return false; } private static boolean isIdentifier(ExpressionTree expr, String identifierName) { expr = stripParentheses(expr); if (expr instanceof IdentifierTree) { return ((IdentifierTree) expr).getName().contentEquals(identifierName); } return false; } /** Returns whether or not the given {@link ReturnTree} returns exactly {@code this}. */ private static boolean returnsThisOrSelf(ReturnTree returnTree) { return maybeCastThis(returnTree.getExpression()); } private static boolean maybeCastThis(Tree tree) { return firstNonNull( new SimpleTreeVisitor<Boolean, Void>() { @Override public Boolean visitParenthesized(ParenthesizedTree tree, Void unused) { return visit(tree.getExpression(), null); } @Override public Boolean visitTypeCast(TypeCastTree tree, Void unused) { return visit(tree.getExpression(), null); } @Override public Boolean visitIdentifier(IdentifierTree tree, Void unused) { return tree.getName().contentEquals("this"); // TODO(cpovirk): Or a field that is always set to `this`, as in SelfAlwaysReturnsThis. } @Override public Boolean visitMethodInvocation(MethodInvocationTree tree, Void unused) { return getSymbol(tree).getSimpleName().contentEquals("self") || getSymbol(tree).getSimpleName().contentEquals("getThis"); } }.visit(tree, null), false); } private static boolean isDefinitionOfZeroArgSelf(MethodSymbol methodSymbol) { return (methodSymbol.getSimpleName().contentEquals("self") || methodSymbol.getSimpleName().contentEquals("getThis")) && methodSymbol.getParameters().isEmpty(); } private static boolean methodReturnsIgnorableValues(MethodTree tree, VisitorState state) { class ReturnValuesFromMethodAreIgnorable extends TreeScanner<Void, Void> { private final VisitorState state; private final Type enclosingClassType; private final Type methodReturnType; private boolean atLeastOneReturn = false; private boolean allReturnsIgnorable = true; private ReturnValuesFromMethodAreIgnorable(VisitorState state, MethodSymbol methSymbol) { this.state = state; this.methodReturnType = methSymbol.getReturnType(); this.enclosingClassType = methSymbol.enclClass().type; } @Override public Void visitReturn(ReturnTree returnTree, Void unused) { atLeastOneReturn = true; if (!returnsThisOrSelf(returnTree) && !isIgnorableMethodCallOnSameInstance(returnTree, state)) { allReturnsIgnorable = false; } // Don't descend deeper into returns, since we already checked the body of this return. return null; } private boolean isIgnorableMethodCallOnSameInstance( ReturnTree returnTree, VisitorState state) { if (returnTree.getExpression() instanceof MethodInvocationTree) { MethodInvocationTree mit = (MethodInvocationTree) returnTree.getExpression(); ExpressionTree receiver = getReceiver(mit); MethodSymbol calledMethod = getSymbol(mit); if ((receiver == null && !calledMethod.isStatic()) || isIdentifier(receiver, "this") || isIdentifier(receiver, "super")) { // If the method we're calling is @CIRV and the enclosing class could be represented by // the object being returned by the other method, then it's probable that the other // method is likely to // be an ignorable result. return hasAnnotation(calledMethod, CIRV, state) && isSubtype(enclosingClassType, methodReturnType, state) && isSubtype(enclosingClassType, getReturnType(mit), state); } } return false; } @Override public Void visitLambdaExpression(LambdaExpressionTree node, Void unused) { // don't descend into lambdas return null; } @Override public Void visitNewClass(NewClassTree node, Void unused) { // don't descend into declarations of anonymous classes return null; } } var scanner = new ReturnValuesFromMethodAreIgnorable(state, getSymbol(tree)); scanner.scan(tree, null); return scanner.atLeastOneReturn && scanner.allReturnsIgnorable; } private static boolean methodAlwaysReturnsInputParam(MethodTree methodTree, VisitorState state) { // short-circuit if the method has no parameters if (methodTree.getParameters().isEmpty()) { return false; } class AllReturnsAreInputParams extends TreeScanner<Void, Void> { private final Set<Symbol> returnedSymbols = new HashSet<>(); @Override public Void visitReturn(ReturnTree returnTree, Void unused) { // even for cases where getExpression() or getSymbol() returns null, we still want to add // those to the returnedSymbols set (that's important if there's > 1 returns) returnedSymbols.add(getSymbol(stripParentheses(returnTree.getExpression()))); return null; } @Override public Void visitLambdaExpression(LambdaExpressionTree node, Void unused) { // don't descend into lambdas return null; } @Override public Void visitNewClass(NewClassTree node, Void unused) { // don't descend into declarations of anonymous classes return null; } } AllReturnsAreInputParams scanner = new AllReturnsAreInputParams(); scanner.scan(methodTree, null); // if we have more than 1 returned symbol, then the value isn't ignorable if (scanner.returnedSymbols.size() != 1) { return false; } Symbol returnedSymbol = getOnlyElement(scanner.returnedSymbols); if (returnedSymbol == null) { return false; } MethodSymbol methodSymbol = getSymbol(methodTree); return isSameType(returnedSymbol.type, methodSymbol.getReturnType(), state) && methodSymbol.getParameters().stream() .filter(ASTHelpers::isConsideredFinal) .anyMatch(returnedSymbol::equals); } }
14,968
42.263006
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/UsingJsr305CheckReturnValue.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.checkreturnvalue; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; 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; import com.google.errorprone.bugpatterns.BugChecker.ImportTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.ImportTree; import com.sun.tools.javac.code.Type; /** * Checker that recommends using ErrorProne's version of {@code @CheckReturnValue} over the version * in JSR305 (which is defunct). */ @BugPattern( summary = "Prefer ErrorProne's @CheckReturnValue over JSR305's version.", severity = WARNING) public final class UsingJsr305CheckReturnValue extends BugChecker implements ImportTreeMatcher { private static final String EP_CRV = "com.google.errorprone.annotations.CheckReturnValue"; private static final String JSR305_CRV = "javax.annotation.CheckReturnValue"; private static final Supplier<Type> JSR305_TYPE = VisitorState.memoize(state -> state.getTypeFromString(JSR305_CRV)); @Override public Description matchImport(ImportTree tree, VisitorState state) { Type jsr305Type = JSR305_TYPE.get(state); if (isSameType(getType(tree.getQualifiedIdentifier()), jsr305Type, state)) { // TODO(kak): the JSR305 version of @CheckReturnValue has an element named `when` and the // ErrorProne version does not. Technically, this means the import swap is not 100% safe, // but we have never actually seen `when` get used in practice. SuggestedFix fix = SuggestedFix.builder().removeImport(JSR305_CRV).addImport(EP_CRV).build(); return describeMatch(tree, fix); } return Description.NO_MATCH; } // TODO(kak): we also may want to match on fully qualified JSR305 CRV annotations, for example: // @javax.annotation.CheckReturnValue public String frobber() { ... } // To do so, we'd need to look for IdentifierTrees and MemberSelectTrees. // However, that style is very very uncommon. }
2,909
43.769231
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/ApiFactory.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.checkreturnvalue; import static com.google.common.collect.ImmutableList.toImmutableList; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.StructuralTypeMapping; import com.sun.tools.javac.code.TypeMetadata; import com.sun.tools.javac.code.Types; import java.lang.reflect.Method; /** Utility method to produce {@link Api} objects from javac {@link MethodSymbol}. */ public final class ApiFactory { /** Returns the {@code Api} representation of the given {@code symbol}. */ public static Api fromSymbol(MethodSymbol symbol, Types types) { return Api.internalCreate( symbol.owner.getQualifiedName().toString(), symbol.name.toString(), symbol.getParameters().stream() .map(p -> fullyErasedAndUnannotatedType(p.type, types)) .collect(toImmutableList())); } static String fullyErasedAndUnannotatedType(Type type, Types types) { // Removes type arguments, replacing w/ upper bounds Type erasedType = types.erasureRecursive(type); Type unannotatedType = erasedType.accept(ANNOTATION_REMOVER, null); return unannotatedType.toString(); } /** * Removes type metadata (e.g.: type annotations) from types, as well as from "containing * structures" like arrays. Notably, this annotation remover doesn't handle Type parameters, as it * only attempts to handle erased types. */ private static final StructuralTypeMapping<Void> ANNOTATION_REMOVER = new StructuralTypeMapping<>() { @Override public Type visitType(Type t, Void unused) { return t.baseType(); } @Override public Type visitClassType(Type.ClassType t, Void unused) { return super.visitClassType((Type.ClassType) cloneWithoutMetadata(t), unused); } // Remove annotations from all enclosing containers @Override public Type visitArrayType(Type.ArrayType t, Void unused) { return super.visitArrayType((Type.ArrayType) cloneWithoutMetadata(t), unused); } }; public static Type cloneWithoutMetadata(Type type) { try { try { Method method = Type.class.getMethod("cloneWithMetadata", TypeMetadata.class); return (Type) method.invoke(type, TypeMetadata.class.getField("EMPTY").get(null)); } catch (NoSuchMethodException e) { Class<?> annotations = Class.forName("com.sun.tools.javac.code.TypeMetadata$Annotations"); Method method = Type.class.getMethod("dropMetadata", Class.class); return (Type) method.invoke(type, annotations); } } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } private ApiFactory() {} }
3,424
37.483146
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/ElementPredicates.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.inject; import static com.google.auto.common.MoreElements.asType; import static com.google.common.collect.ImmutableList.toImmutableList; import static javax.lang.model.util.ElementFilter.constructorsIn; import com.google.common.collect.ImmutableList; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Arrays; import java.util.Comparator; import java.util.List; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; /** Predicates for {@link Element} objects related to dependency injection. */ public final class ElementPredicates { public static boolean isFinalField(Element element) { return element.getKind().equals(ElementKind.FIELD) && element.getModifiers().contains(Modifier.FINAL); } public static boolean isFirstConstructorOfMultiInjectedClass(Element injectedMember) { if (injectedMember.getKind() == ElementKind.CONSTRUCTOR) { List<ExecutableElement> injectConstructors = getConstructorsWithAnnotations( injectedMember, Arrays.asList("javax.inject.Inject", "com.google.inject.Inject")); if (injectConstructors.size() > 1 && injectConstructors.get(0).equals(injectedMember)) { return true; } } return false; } public static boolean doesNotHaveRuntimeRetention(Element element) { return effectiveRetentionPolicy(element) != RetentionPolicy.RUNTIME; } public static boolean hasSourceRetention(Element element) { return effectiveRetentionPolicy(element) == RetentionPolicy.SOURCE; } private static RetentionPolicy effectiveRetentionPolicy(Element element) { RetentionPolicy retentionPolicy = RetentionPolicy.CLASS; Retention retentionAnnotation = element.getAnnotation(Retention.class); if (retentionAnnotation != null) { retentionPolicy = retentionAnnotation.value(); } return retentionPolicy; } private static ImmutableList<ExecutableElement> getConstructorsWithAnnotations( Element exploringConstructor, List<String> annotations) { return constructorsIn(exploringConstructor.getEnclosingElement().getEnclosedElements()).stream() .filter(constructor -> hasAnyOfAnnotation(constructor, annotations)) .sorted(Comparator.comparing((e -> e.getSimpleName().toString()))) .collect(toImmutableList()); } private static boolean hasAnyOfAnnotation(ExecutableElement input, List<String> annotations) { return input.getAnnotationMirrors().stream() .map(annotationMirror -> asType(annotationMirror.getAnnotationType().asElement())) .anyMatch(type -> typeInAnnotations(type, annotations)); } private static boolean typeInAnnotations(TypeElement t, List<String> annotations) { return annotations.stream() .anyMatch(annotation -> t.getQualifiedName().contentEquals(annotation)); } private ElementPredicates() {} }
3,700
38.795699
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/package-info.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. */ /** * Bug patterns related to <a href="http://en.wikipedia.org/wiki/Dependency_injection">dependency * injection</a> and <a href="https://jcp.org/en/jsr/detail?id=330">JSR 330</a>. See the various * subpackages for checks related to specific DI frameworks. */ package com.google.errorprone.bugpatterns.inject;
923
39.173913
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/AutoFactoryAtInject.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.inject; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.InjectMatchers.IS_APPLICATION_OF_AT_INJECT; import static com.google.errorprone.matchers.Matchers.hasAnnotation; import static com.google.errorprone.matchers.Matchers.methodIsConstructor; import static com.google.errorprone.util.ASTHelpers.findEnclosingNode; import static com.google.errorprone.util.ASTHelpers.getConstructors; import static com.sun.source.tree.Tree.Kind.CLASS; import static com.sun.source.tree.Tree.Kind.METHOD; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; /** * @author ronshapiro@google.com (Ron Shapiro) */ @BugPattern( summary = "@AutoFactory and @Inject should not be used in the same type.", severity = ERROR) public class AutoFactoryAtInject extends BugChecker implements AnnotationTreeMatcher { private static final Matcher<Tree> HAS_AUTO_FACTORY_ANNOTATION = hasAnnotation("com.google.auto.factory.AutoFactory"); @Override public final Description matchAnnotation(AnnotationTree annotationTree, VisitorState state) { if (!IS_APPLICATION_OF_AT_INJECT.matches(annotationTree, state)) { return Description.NO_MATCH; } Tree annotatedTree = getCurrentlyAnnotatedNode(state); if (!annotatedTree.getKind().equals(METHOD) || !methodIsConstructor().matches((MethodTree) annotatedTree, state)) { return Description.NO_MATCH; } ClassTree classTree = findEnclosingNode(state.getPath(), ClassTree.class); ImmutableList<Tree> potentiallyAnnotatedTrees = ImmutableList.<Tree>builder().add(classTree).addAll(getConstructors(classTree)).build(); for (Tree potentiallyAnnotatedTree : potentiallyAnnotatedTrees) { if (HAS_AUTO_FACTORY_ANNOTATION.matches(potentiallyAnnotatedTree, state) && (potentiallyAnnotatedTree.getKind().equals(CLASS) || potentiallyAnnotatedTree.equals(annotatedTree))) { return describeMatch(annotationTree, SuggestedFix.delete(annotationTree)); } } return Description.NO_MATCH; } // TODO(ronshapiro): consolidate uses private static Tree getCurrentlyAnnotatedNode(VisitorState state) { return state.getPath().getParentPath().getParentPath().getLeaf(); } }
3,431
40.349398
96
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/ScopeOrQualifierAnnotationRetention.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns.inject; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.bugpatterns.inject.ElementPredicates.doesNotHaveRuntimeRetention; import static com.google.errorprone.bugpatterns.inject.ElementPredicates.hasSourceRetention; import static com.google.errorprone.matchers.InjectMatchers.DAGGER_MAP_KEY_ANNOTATION; import static com.google.errorprone.matchers.InjectMatchers.GUICE_BINDING_ANNOTATION; import static com.google.errorprone.matchers.InjectMatchers.GUICE_MAP_KEY_ANNOTATION; import static com.google.errorprone.matchers.InjectMatchers.GUICE_SCOPE_ANNOTATION; import static com.google.errorprone.matchers.InjectMatchers.JAVAX_QUALIFIER_ANNOTATION; import static com.google.errorprone.matchers.InjectMatchers.JAVAX_SCOPE_ANNOTATION; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.hasAnnotation; import static com.google.errorprone.matchers.Matchers.kindIs; import static com.sun.source.tree.Tree.Kind.ANNOTATION_TYPE; 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.ClassTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.InjectMatchers; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ClassTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import java.lang.annotation.Retention; import javax.annotation.Nullable; // TODO(b/180081278): Rename this check to MissingRuntimeRetention /** * @author sgoldfeder@google.com (Steven Goldfeder) */ @BugPattern( name = "InjectScopeOrQualifierAnnotationRetention", summary = "Scoping and qualifier annotations must have runtime retention.", severity = ERROR) public class ScopeOrQualifierAnnotationRetention extends BugChecker implements ClassTreeMatcher { private static final String RETENTION_ANNOTATION = "java.lang.annotation.Retention"; /** Matches classes that are qualifier, scope annotation or map binding keys. */ private static final Matcher<ClassTree> SCOPE_OR_QUALIFIER_ANNOTATION_MATCHER = allOf( kindIs(ANNOTATION_TYPE), anyOf( hasAnnotation(GUICE_SCOPE_ANNOTATION), hasAnnotation(JAVAX_SCOPE_ANNOTATION), hasAnnotation(GUICE_BINDING_ANNOTATION), hasAnnotation(JAVAX_QUALIFIER_ANNOTATION), hasAnnotation(GUICE_MAP_KEY_ANNOTATION), hasAnnotation(DAGGER_MAP_KEY_ANNOTATION))); @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (SCOPE_OR_QUALIFIER_ANNOTATION_MATCHER.matches(classTree, state)) { ClassSymbol classSymbol = ASTHelpers.getSymbol(classTree); if (hasSourceRetention(classSymbol)) { return describe(classTree, state, ASTHelpers.getAnnotation(classSymbol, Retention.class)); } // TODO(glorioso): This is a poor hack to exclude android apps that are more likely to not // have reflective DI than normal java. JSR spec still says the annotations should be // runtime-retained, but this reduces the instances that are flagged. if (!state.isAndroidCompatible() && doesNotHaveRuntimeRetention(classSymbol)) { // Is this in a dagger component? ClassTree outer = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class); if (outer != null && allOf(InjectMatchers.IS_DAGGER_COMPONENT_OR_MODULE).matches(outer, state)) { return Description.NO_MATCH; } return describe(classTree, state, ASTHelpers.getAnnotation(classSymbol, Retention.class)); } } return Description.NO_MATCH; } private Description describe( ClassTree classTree, VisitorState state, @Nullable Retention retention) { if (retention == null) { AnnotationTree annotation = Iterables.getLast(classTree.getModifiers().getAnnotations()); return describeMatch( classTree, SuggestedFix.builder() .addImport("java.lang.annotation.Retention") .addStaticImport("java.lang.annotation.RetentionPolicy.RUNTIME") .postfixWith(annotation, "@Retention(RUNTIME)") .build()); } AnnotationTree retentionNode = null; for (AnnotationTree annotation : classTree.getModifiers().getAnnotations()) { if (ASTHelpers.getSymbol(annotation).equals(JAVA_LANG_ANNOTATION_RETENTION.get(state))) { retentionNode = annotation; } } return describeMatch( retentionNode, SuggestedFix.builder() .addImport("java.lang.annotation.Retention") .addStaticImport("java.lang.annotation.RetentionPolicy.RUNTIME") .replace(retentionNode, "@Retention(RUNTIME)") .build()); } private static final Supplier<Symbol> JAVA_LANG_ANNOTATION_RETENTION = VisitorState.memoize(state -> state.getSymbolFromString(RETENTION_ANNOTATION)); }
6,052
46.289063
101
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectedConstructorAnnotations.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.inject; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.InjectMatchers.GUICE_BINDING_ANNOTATION; import static com.google.errorprone.matchers.InjectMatchers.GUICE_INJECT_ANNOTATION; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.booleanLiteral; import static com.google.errorprone.matchers.Matchers.hasAnnotation; import static com.google.errorprone.matchers.Matchers.hasArgumentWithValue; import static com.google.errorprone.matchers.Matchers.isType; import static com.google.errorprone.matchers.Matchers.methodIsConstructor; import static com.google.errorprone.matchers.Matchers.symbolHasAnnotation; 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.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.MethodTree; /** A checker for injected constructors with @Inject(optional=true) or binding annotations. */ @BugPattern( summary = "Injected constructors cannot be optional nor have binding annotations", severity = WARNING) public class InjectedConstructorAnnotations extends BugChecker implements MethodTreeMatcher { // A matcher of @Inject{optional=true} private static final Matcher<AnnotationTree> OPTIONAL_INJECTION_MATCHER = allOf( isType(GUICE_INJECT_ANNOTATION), hasArgumentWithValue("optional", booleanLiteral(true))); // A matcher of binding annotations private static final Matcher<AnnotationTree> BINDING_ANNOTATION_MATCHER = new Matcher<AnnotationTree>() { @Override public boolean matches(AnnotationTree annotationTree, VisitorState state) { return symbolHasAnnotation(GUICE_BINDING_ANNOTATION) .matches(annotationTree.getAnnotationType(), state); } }; /** * Matches injected constructors annotated with @Inject(optional=true) or binding annotations. * Suggests fixes to remove the argument {@code optional=true} or binding annotations. */ @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { SuggestedFix.Builder fix = null; if (isInjectedConstructor(methodTree, state)) { for (AnnotationTree annotationTree : methodTree.getModifiers().getAnnotations()) { if (OPTIONAL_INJECTION_MATCHER.matches(annotationTree, state)) { // Replace the annotation with "@Inject" if (fix == null) { fix = SuggestedFix.builder(); } fix = fix.replace(annotationTree, "@Inject"); } else if (BINDING_ANNOTATION_MATCHER.matches(annotationTree, state)) { // Remove the binding annotation if (fix == null) { fix = SuggestedFix.builder(); } fix = fix.delete(annotationTree); } } } if (fix == null) { return Description.NO_MATCH; } else { return describeMatch(methodTree, fix.build()); } } private static boolean isInjectedConstructor(MethodTree methodTree, VisitorState state) { return allOf(methodIsConstructor(), hasAnnotation(GUICE_INJECT_ANNOTATION)) .matches(methodTree, state); } }
4,130
41.587629
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/MoreThanOneInjectableConstructor.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.inject; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.bugpatterns.inject.ElementPredicates.isFirstConstructorOfMultiInjectedClass; import static com.google.errorprone.matchers.InjectMatchers.IS_APPLICATION_OF_GUICE_INJECT; import static com.google.errorprone.matchers.InjectMatchers.IS_APPLICATION_OF_JAVAX_INJECT; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.util.ASTHelpers.getSymbol; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; 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.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.Tree; /** * Matches classes that have two or more constructors annotated with @Inject. * * @author sgoldfeder@google.com (Steven Goldfeder) */ @BugPattern( summary = "This class has more than one @Inject-annotated constructor. Please remove the @Inject" + " annotation from all but one of them.", severity = ERROR, altNames = {"inject-constructors", "InjectMultipleAtInjectConstructors"}) public class MoreThanOneInjectableConstructor extends BugChecker implements AnnotationTreeMatcher { private static final Matcher<AnnotationTree> IS_EITHER_INJECT = anyOf(IS_APPLICATION_OF_GUICE_INJECT, IS_APPLICATION_OF_JAVAX_INJECT); @Override public Description matchAnnotation(AnnotationTree tree, VisitorState state) { if (IS_EITHER_INJECT.matches(tree, state)) { Tree injectedMember = state.getPath().getParentPath().getParentPath().getLeaf(); if (isFirstConstructorOfMultiInjectedClass(getSymbol(injectedMember))) { return describeMatch(ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class)); } } return Description.NO_MATCH; } }
2,739
41.8125
112
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/AssistedInjectAndInjectOnSameConstructor.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.inject; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.InjectMatchers.ASSISTED_INJECT_ANNOTATION; import static com.google.errorprone.matchers.InjectMatchers.GUICE_INJECT_ANNOTATION; import static com.google.errorprone.matchers.InjectMatchers.JAVAX_INJECT_ANNOTATION; import static com.google.errorprone.matchers.InjectMatchers.hasInjectAnnotation; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.hasAnnotation; import static com.google.errorprone.matchers.Matchers.isType; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher; 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.AnnotationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; /** * @author sgoldfeder@google.com (Steven Goldfeder) */ @BugPattern( summary = "@AssistedInject and @Inject cannot be used on the same constructor.", severity = WARNING) public class AssistedInjectAndInjectOnSameConstructor extends BugChecker implements AnnotationTreeMatcher { /** Matches a method/constructor that is annotated with an @AssistedInject annotation. */ private static final Matcher<MethodTree> HAS_ASSISTED_INJECT_MATCHER = hasAnnotation(ASSISTED_INJECT_ANNOTATION); /** Matches the @Inject and @Assisted inject annotations. */ private static final Matcher<AnnotationTree> injectOrAssistedInjectMatcher = anyOf( isType(JAVAX_INJECT_ANNOTATION), isType(GUICE_INJECT_ANNOTATION), isType(ASSISTED_INJECT_ANNOTATION)); @Override public Description matchAnnotation(AnnotationTree annotationTree, VisitorState state) { if (injectOrAssistedInjectMatcher.matches(annotationTree, state)) { Tree treeWithAnnotation = state.getPath().getParentPath().getParentPath().getLeaf(); if (ASTHelpers.getSymbol(treeWithAnnotation).isConstructor() && hasInjectAnnotation().matches(treeWithAnnotation, state) && HAS_ASSISTED_INJECT_MATCHER.matches((MethodTree) treeWithAnnotation, state)) { return describeMatch(annotationTree, SuggestedFix.delete(annotationTree)); } } return Description.NO_MATCH; } }
3,212
43.013699
91
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/MisplacedScopeAnnotations.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.inject; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE; import static com.google.errorprone.matchers.InjectMatchers.IS_APPLICATION_OF_AT_INJECT; import static com.google.errorprone.matchers.InjectMatchers.IS_BINDING_ANNOTATION; import static com.google.errorprone.matchers.InjectMatchers.IS_SCOPING_ANNOTATION; import static com.google.errorprone.matchers.InjectMatchers.hasProvidesAnnotation; import static com.google.errorprone.matchers.Matchers.annotations; 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.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.MultiMatcher; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; import java.util.List; /** * Bug checker for when a scope annotation is used at injection site, which does not have any effect * on the injected values. */ @BugPattern( summary = "Scope annotations used as qualifier annotations don't have any effect." + " Move the scope annotation to the binding location or delete it.", severity = SeverityLevel.ERROR) public class MisplacedScopeAnnotations extends BugChecker implements MethodTreeMatcher, VariableTreeMatcher { private static final MultiMatcher<VariableTree, AnnotationTree> IS_SCOPE_ANNOTATION = annotations(AT_LEAST_ONE, IS_SCOPING_ANNOTATION); private static final MultiMatcher<MethodTree, AnnotationTree> HAS_INJECT = annotations(AT_LEAST_ONE, IS_APPLICATION_OF_AT_INJECT); private static final Matcher<MethodTree> HAS_PROVIDES = hasProvidesAnnotation(); @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (!HAS_INJECT.matches(tree, state) && !HAS_PROVIDES.matches(tree, state)) { return Description.NO_MATCH; } ImmutableList<AnnotationTree> scopeAnnotations = tree.getParameters().stream() .flatMap( variable -> IS_SCOPE_ANNOTATION.multiMatchResult(variable, state).matchingNodes().stream()) .filter(annotation -> !IS_BINDING_ANNOTATION.matches(annotation, state)) .collect(toImmutableList()); if (scopeAnnotations.isEmpty()) { return Description.NO_MATCH; } return deleteAll(scopeAnnotations); } @Override public Description matchVariable(VariableTree tree, VisitorState state) { boolean hasInject = tree.getModifiers().getAnnotations().stream() .anyMatch(annotation -> IS_APPLICATION_OF_AT_INJECT.matches(annotation, state)); if (!hasInject) { return Description.NO_MATCH; } ImmutableList<AnnotationTree> scopeAnnotations = tree.getModifiers().getAnnotations().stream() .filter(annotation -> IS_SCOPING_ANNOTATION.matches(annotation, state)) .filter(annotation -> !IS_BINDING_ANNOTATION.matches(annotation, state)) .collect(toImmutableList()); if (scopeAnnotations.isEmpty()) { return Description.NO_MATCH; } return deleteAll(scopeAnnotations); } private Description deleteAll(List<AnnotationTree> scopeAnnotations) { SuggestedFix.Builder fixBuilder = SuggestedFix.builder(); scopeAnnotations.forEach(fixBuilder::delete); return describeMatch(scopeAnnotations.get(0), fixBuilder.build()); } }
4,524
41.28972
100
java