Skip to content

Commit

Permalink
Add the DistinctVarargs BugChecker. This will generate warning when m…
Browse files Browse the repository at this point in the history
…ethod expecting distinct varargs is invoked with same variable argument.

PiperOrigin-RevId: 405668886
  • Loading branch information
java-team-github-bot authored and Error Prone Team committed Oct 26, 2021
1 parent 122e512 commit cdfa8b8
Show file tree
Hide file tree
Showing 4 changed files with 373 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.errorprone.bugpatterns;

import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;

import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import java.util.ArrayList;
import java.util.List;

/**
* ErrorProne checker to generate warning when method expecting distinct varargs is invoked with
* same variable argument.
*/
@BugPattern(
name = "DistinctVarargsChecker",
summary = "Method expects distinct arguments at some/all positions",
severity = WARNING)
public final class DistinctVarargsChecker extends BugChecker
implements MethodInvocationTreeMatcher {

private static final Matcher<ExpressionTree> IMMUTABLE_SET_VARARGS_MATCHER =
anyOf(
staticMethod().onClass("com.google.common.collect.ImmutableSet").named("of"),
staticMethod().onClass("com.google.common.collect.ImmutableSortedSet").named("of"));
private static final Matcher<ExpressionTree> ALL_DISTINCT_ARG_MATCHER =
anyOf(
staticMethod()
.onClass("com.google.common.util.concurrent.Futures")
.withSignature(
"<V>whenAllSucceed(com.google.common.util.concurrent.ListenableFuture<? extends"
+ " V>...)"),
staticMethod()
.onClass("com.google.common.util.concurrent.Futures")
.withSignature(
"<V>whenAllComplete(com.google.common.util.concurrent.ListenableFuture<? extends"
+ " V>...)"),
staticMethod()
.onClass("com.google.common.collect.Ordering")
.withSignature("<T>explicit(T,T...)"));
private static final Matcher<ExpressionTree> EVEN_PARITY_DISTINCT_ARG_MATCHER =
anyOf(
staticMethod().onClass("com.google.common.collect.ImmutableMap").named("of"),
staticMethod().onClass("com.google.common.collect.ImmutableSortedMap").named("of"));
private static final Matcher<ExpressionTree> EVEN_AND_ODD_PARITY_DISTINCT_ARG_MATCHER =
staticMethod().onClass("com.google.common.collect.ImmutableBiMap").named("of");

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
// For ImmutableSet and ImmutableSortedSet fix can be constructed. For all other methods,
// non-distinct arguments will result in the runtime exceptions.
if (IMMUTABLE_SET_VARARGS_MATCHER.matches(tree, state)) {
return checkDistinctArgumentsWithFix(tree, state);
}
if (ALL_DISTINCT_ARG_MATCHER.matches(tree, state)) {
return checkDistinctArguments(tree, tree.getArguments());
}
if (EVEN_PARITY_DISTINCT_ARG_MATCHER.matches(tree, state)) {
List<ExpressionTree> arguments = new ArrayList<>();
for (int index = 0; index < tree.getArguments().size(); index += 2) {
arguments.add(tree.getArguments().get(index));
}
return checkDistinctArguments(tree, arguments);
}
if (EVEN_AND_ODD_PARITY_DISTINCT_ARG_MATCHER.matches(tree, state)) {
List<ExpressionTree> evenParityArguments = new ArrayList<>();
List<ExpressionTree> oddParityArguments = new ArrayList<>();
for (int index = 0; index < tree.getArguments().size(); index++) {
if (index % 2 == 0) {
evenParityArguments.add(tree.getArguments().get(index));
} else {
oddParityArguments.add(tree.getArguments().get(index));
}
}
return checkDistinctArguments(tree, evenParityArguments, oddParityArguments);
}
return Description.NO_MATCH;
}

private Description checkDistinctArgumentsWithFix(MethodInvocationTree tree, VisitorState state) {
SuggestedFix.Builder suggestedFix = SuggestedFix.builder();
for (int index = 1; index < tree.getArguments().size(); index++) {
boolean isDistinctArgument = true;
for (int prevElementIndex = 0; prevElementIndex < index; prevElementIndex++) {
if (ASTHelpers.sameVariable(
tree.getArguments().get(index), tree.getArguments().get(prevElementIndex))) {
isDistinctArgument = false;
break;
}
}
if (!isDistinctArgument) {
suggestedFix.merge(
SuggestedFix.replace(
state.getEndPosition(tree.getArguments().get(index - 1)),
state.getEndPosition(tree.getArguments().get(index)),
""));
}
}
if (suggestedFix.isEmpty()) {
return Description.NO_MATCH;
}
return describeMatch(tree, suggestedFix.build());
}

private Description checkDistinctArguments(
MethodInvocationTree tree, List<? extends ExpressionTree>... argumentsList) {
for (List<? extends ExpressionTree> arguments : argumentsList) {
for (int firstArgumentIndex = 0;
firstArgumentIndex < arguments.size();
firstArgumentIndex++) {
for (int secondArgumentIndex = firstArgumentIndex + 1;
secondArgumentIndex < arguments.size();
secondArgumentIndex++) {
if (ASTHelpers.sameVariable(
arguments.get(firstArgumentIndex), arguments.get(secondArgumentIndex))) {
return describeMatch(tree);
}
}
}
}
return Description.NO_MATCH;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@
import com.google.errorprone.bugpatterns.DescribeMatch;
import com.google.errorprone.bugpatterns.DifferentNameButSame;
import com.google.errorprone.bugpatterns.DiscardedPostfixExpression;
import com.google.errorprone.bugpatterns.DistinctVarargsChecker;
import com.google.errorprone.bugpatterns.DivZero;
import com.google.errorprone.bugpatterns.DoNotCallChecker;
import com.google.errorprone.bugpatterns.DoNotCallSuggester;
Expand Down Expand Up @@ -788,6 +789,7 @@ public static ScannerSupplier errorChecks() {
DefaultCharset.class,
DefaultPackage.class,
DeprecatedVariable.class,
DistinctVarargsChecker.class,
DoNotCallSuggester.class,
DoNotClaimAnnotations.class,
DoNotMockAutoValue.class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.errorprone.bugpatterns;

import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** {@link DistinctVarargsChecker}Test */
@RunWith(JUnit4.class)
public class DistinctVarargsCheckerTest {

private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(DistinctVarargsChecker.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(DistinctVarargsChecker.class, getClass());

@Test
public void distinctVarargsChecker_sameVariableInFuturesVaragsMethods_shouldFlag() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.util.concurrent.Futures;",
"import com.google.common.util.concurrent.ListenableFuture;",
"public class Test {",
" void testFunction() {",
" ListenableFuture firstFuture = null, secondFuture = null;",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" Futures.whenAllSucceed(firstFuture, firstFuture);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" Futures.whenAllSucceed(firstFuture, firstFuture, secondFuture);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" Futures.whenAllComplete(firstFuture, firstFuture);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" Futures.whenAllComplete(firstFuture, firstFuture, secondFuture);",
" }",
"}")
.doTest();
}

@Test
public void distinctVarargsCheckerdifferentVariableInFuturesVaragsMethods_shouldNotFlag() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.util.concurrent.Futures;",
"import com.google.common.util.concurrent.ListenableFuture;",
"public class Test {",
" void testFunction() {",
" ListenableFuture firstFuture = null, secondFuture = null;",
" Futures.whenAllComplete(firstFuture);",
" Futures.whenAllSucceed(firstFuture, secondFuture);",
" Futures.whenAllComplete(firstFuture);",
" Futures.whenAllComplete(firstFuture, secondFuture);",
" }",
"}")
.doTest();
}

@Test
public void distinctVarargsChecker_sameVariableInGuavaVarargMethods_shouldFlag() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Ordering;",
"import com.google.common.collect.ImmutableBiMap;",
"import com.google.common.collect.ImmutableMap;",
"import com.google.common.collect.ImmutableSortedMap;",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.ImmutableSortedSet;",
"public class Test {",
" void testFunction() {",
" int first = 1, second = 2;",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" Ordering.explicit(first, first);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" Ordering.explicit(first, first, second);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" ImmutableMap.of(first, second, first, second);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" ImmutableSortedMap.of(first, second, first, second);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" ImmutableBiMap.of(first, second, first, second);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" ImmutableBiMap.of(first, second, second, second);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" ImmutableSet.of(first, first);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" ImmutableSet.of(first, first, second);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" ImmutableSortedSet.of(first, first);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" ImmutableSortedSet.of(first, first, second);",
" }",
"}")
.doTest();
}

@Test
public void distinctVarargsChecker_differentVariableInGuavaVarargMethods_shouldNotFlag() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Ordering;",
"import com.google.common.collect.ImmutableBiMap;",
"import com.google.common.collect.ImmutableMap;",
"import com.google.common.collect.ImmutableSortedMap;",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.ImmutableSortedSet;",
"public class Test {",
" void testFunction() {",
" int first = 1, second = 2, third = 3, fourth = 4;",
" Ordering.explicit(first);",
" Ordering.explicit(first, second);",
" ImmutableMap.of(first, second);",
" ImmutableSortedMap.of(first, second);",
" ImmutableBiMap.of(first, second, third, fourth);",
" ImmutableSet.of(first);",
" ImmutableSet.of(first, second);",
" ImmutableSortedSet.of(first);",
" ImmutableSortedSet.of(first, second);",
" }",
"}")
.doTest();
}

@Test
public void distinctVarargsChecker_sameVariableInImmutableSetVarargsMethod_shouldRefactor() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.ImmutableSortedSet;",
"public class Test {",
" void testFunction() {",
" int first = 1, second = 2;",
" ImmutableSet.of(first, first);",
" ImmutableSet.of(first, first, second);",
" ImmutableSortedSet.of(first, first);",
" ImmutableSortedSet.of(first, first, second);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.ImmutableSortedSet;",
"public class Test {",
" void testFunction() {",
" int first = 1, second = 2;",
" ImmutableSet.of(first);",
" ImmutableSet.of(first, second);",
" ImmutableSortedSet.of(first);",
" ImmutableSortedSet.of(first, second);",
" }",
"}")
.doTest();
}

@Test
public void distinctVarargsChecker_differentVarsInImmutableSetVarargsMethod_shouldNotRefactor() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.ImmutableSortedSet;",
"public class Test {",
" void testFunction() {",
" int first = 1, second = 2;",
" ImmutableSet.of(first);",
" ImmutableSet.of(first, second);",
" ImmutableSortedSet.of(first);",
" ImmutableSortedSet.of(first, second);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.ImmutableSortedSet;",
"public class Test {",
" void testFunction() {",
" int first = 1, second = 2;",
" ImmutableSet.of(first);",
" ImmutableSet.of(first, second);",
" ImmutableSortedSet.of(first);",
" ImmutableSortedSet.of(first, second);",
" }",
"}")
.doTest();
}
}
18 changes: 18 additions & 0 deletions docs/bugpattern/DistinctVarargsChecker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
Various methods which take variable-length arguments throw the runtime
exceptions like `IllegalArgumentException` when the arguments are not distinct.

This checker warns on using the non-distinct parameters in various varargs
method when the usage is redundant or will either result in the runtime
exception.

Bad:

```java
ImmutableSet.of(first, second, second, third);
```

Good:

```java
ImmutableSet.of(first, second, third);
```

0 comments on commit cdfa8b8

Please sign in to comment.