Skip to content

Commit

Permalink
Warn when accepting or returning object arrays in public APIs. See[]
Browse files Browse the repository at this point in the history
[]

#klippy4apis

PiperOrigin-RevId: 496131604
  • Loading branch information
kluever authored and Error Prone Team committed Dec 17, 2022
1 parent cd35449 commit bdfd015
Show file tree
Hide file tree
Showing 6 changed files with 465 additions and 20 deletions.
23 changes: 23 additions & 0 deletions check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
Original file line number Diff line number Diff line change
Expand Up @@ -2455,6 +2455,29 @@ public static boolean isStatic(Symbol symbol) {
}
}

/**
* Returns true if the given method symbol is public (both the method and the enclosing class) and
* does <i>not</i> have a super-method (i.e., it is not an {@code @Override}).
*
* <p>This method is useful (in part) for determining whether to suggest API improvements or not.
*/
public static boolean methodIsPublicAndNotAnOverride(MethodSymbol method, VisitorState state) {
// don't match non-public APIs
Symbol symbol = method;
while (symbol != null && !(symbol instanceof PackageSymbol)) {
if (!symbol.getModifiers().contains(Modifier.PUBLIC)) {
return false;
}
symbol = symbol.owner;
}

// don't match overrides (even "effective overrides")
if (!findSuperMethods(method, state.getTypes()).isEmpty()) {
return false;
}
return true;
}

/**
* Returns true if the given method symbol is abstract.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.errorprone.bugpatterns;

import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFixes.prettyType;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.hasModifier;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.methodHasArity;
import static com.google.errorprone.matchers.Matchers.methodHasParameters;
import static com.google.errorprone.matchers.Matchers.methodHasVisibility;
import static com.google.errorprone.matchers.Matchers.methodIsNamed;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import static com.google.errorprone.matchers.MethodVisibility.Visibility.PUBLIC;
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.isSameType;
import static com.google.errorprone.util.ASTHelpers.methodIsPublicAndNotAnOverride;
import static java.util.function.Predicate.isEqual;
import static javax.lang.model.element.Modifier.STATIC;

import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Suppliers;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ArrayType;
import javax.lang.model.element.ElementKind;

/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Object arrays are inferior to collections in almost every way. Prefer immutable"
+ " collections (e.g., ImmutableSet, ImmutableList, etc.) over an object array whenever"
+ " possible.",
severity = WARNING)
public class AvoidObjectArrays extends BugChecker implements MethodTreeMatcher {
private static final ImmutableSet<String> ANNOTATIONS_TO_IGNORE =
ImmutableSet.of(
"com.tngtech.java.junit.dataprovider.DataProvider",
"org.junit.runners.Parameterized.Parameters",
"org.junit.experimental.theories.DataPoints",
"junitparams.Parameters");

// copied from SystemExitOutsideMain
private static final Matcher<MethodTree> MAIN_METHOD =
allOf(
methodHasArity(1),
methodHasVisibility(PUBLIC),
hasModifier(STATIC),
methodReturns(Suppliers.VOID_TYPE),
methodIsNamed("main"),
methodHasParameters(isSameType(Suppliers.arrayOf(Suppliers.STRING_TYPE))));

@Override
public Description matchMethod(MethodTree method, VisitorState state) {
if (shouldApplyApiChecks(method, state)) {
// check the return type
if (isObjectArray(method.getReturnType())) {
state.reportMatch(
createDescription(method.getReturnType(), state, "returning", "ImmutableList"));
}

// check each method parameter
for (int i = 0; i < method.getParameters().size(); i++) {
VariableTree varTree = method.getParameters().get(i);
if (isObjectArray(varTree)) {
// we allow an object array if it's the last parameter and it's var args
if (getSymbol(method).isVarArgs() && i == method.getParameters().size() - 1) {
continue;
}

// we _may_ want to eventually allow `String[] args` as a method param, since folks
// sometimes pass around command-line arguments to other methods
state.reportMatch(createDescription(varTree.getType(), state, "accepting", "Iterable"));
}
}
}
return NO_MATCH;
}

private Description createDescription(
Tree tree, VisitorState state, String verb, String newType) {
Type type = getType(tree);

String message = String.format("Avoid %s a %s", verb, prettyType(type, state));

if (type instanceof ArrayType) {
type = ((ArrayType) type).getComponentType();
boolean isMultiDimensional = (type instanceof ArrayType);
if (!isMultiDimensional) {
message += String.format("; consider an %s<%s> instead", newType, prettyType(type, state));
}
}

return buildDescription(tree).setMessage(message).build();
}

/** Returns whether the tree represents an object array or not. */
private static boolean isObjectArray(Tree tree) {
Type type = getType(tree);
return (type instanceof ArrayType) && !((ArrayType) type).getComponentType().isPrimitive();
}

private static boolean shouldApplyApiChecks(MethodTree methodTree, VisitorState state) {
// don't match main methods
if (MAIN_METHOD.matches(methodTree, state)) {
return false;
}

// don't match certain framework-y APIs like parameterized test data providers
for (String annotationName : ANNOTATIONS_TO_IGNORE) {
if (hasAnnotation(methodTree, annotationName, state)) {
return false;
}
}

MethodSymbol method = getSymbol(methodTree);

// don't match methods inside an annotation type
if (state.getTypes().closure(method.owner.type).stream()
.map(superType -> superType.tsym.getKind())
.anyMatch(isEqual(ElementKind.ANNOTATION_TYPE))) {
return false;
}

return methodIsPublicAndNotAnOverride(method, state);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,17 @@
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.findEnclosingNode;
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.methodIsPublicAndNotAnOverride;

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.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import javax.lang.model.element.Modifier;

/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
Expand Down Expand Up @@ -87,27 +84,12 @@ public Description matchMethod(MethodTree tree, VisitorState state) {
return buildDescription(tree).setMessage(message).build();
}

// Copied + modified from GoodTime API checker
// TODO(kak): we should probably move this somewhere that future API checks can use
private static boolean shouldApplyApiChecks(MethodTree tree, VisitorState state) {
for (String annotation : ANNOTATIONS_TO_IGNORE) {
if (hasAnnotation(tree, annotation, state)) {
return false;
}
}
// don't match non-public APIs
if (!getSymbol(tree).getModifiers().contains(Modifier.PUBLIC)) {
return false;
}
// don't match APIs in non-public classes
ClassTree clazz = findEnclosingNode(state.getPath(), ClassTree.class);
if (!getSymbol(clazz).getModifiers().contains(Modifier.PUBLIC)) {
return false;
}
// don't match overrides (even "effective overrides")
if (!findSuperMethods(getSymbol(tree), state.getTypes()).isEmpty()) {
return false;
}
return true;
return methodIsPublicAndNotAnOverride(getSymbol(tree), state);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import com.google.errorprone.bugpatterns.AutoValueFinalMethods;
import com.google.errorprone.bugpatterns.AutoValueImmutableFields;
import com.google.errorprone.bugpatterns.AutoValueSubclassLeaked;
import com.google.errorprone.bugpatterns.AvoidObjectArrays;
import com.google.errorprone.bugpatterns.BadAnnotationImplementation;
import com.google.errorprone.bugpatterns.BadComparable;
import com.google.errorprone.bugpatterns.BadImport;
Expand Down Expand Up @@ -1035,6 +1036,7 @@ public static ScannerSupplier errorChecks() {
AssertFalse.class,
AssistedInjectAndInjectOnConstructors.class,
AutoFactoryAtInject.class,
AvoidObjectArrays.class,
BanSerializableRead.class,
BinderIdentityRestoredDangerously.class, // TODO: enable this by default.
BindingToUnqualifiedCommonType.class,
Expand Down

0 comments on commit bdfd015

Please sign in to comment.