Skip to content

Commit

Permalink
Implement error-prone ObjectsHashCodeUnnecessaryVarargs migration (#1522
Browse files Browse the repository at this point in the history
)

Implement error-prone ObjectsHashCodeUnnecessaryVarargs migration
  • Loading branch information
carterkozak authored Oct 23, 2020
1 parent 55df9b4 commit 3a3eedc
Show file tree
Hide file tree
Showing 6 changed files with 131 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ Safe Logging can be found at [github.com/palantir/safe-logging](https://github.c
- `ExtendsErrorOrThrowable`: Avoid extending Error (or subclasses of it) or Throwable directly.
- `ImmutablesStyleCollision`: Prevent unintentionally voiding immutables Style meta-annotations through the introduction of inline style annotations.
- `TooManyArguments`: Prefer Interface that take few arguments rather than many.
- `ObjectsHashCodeUnnecessaryVarargs`: java.util.Objects.hash(non-varargs) should be replaced with java.util.Objects.hashCode(value) to avoid unnecessary varargs array allocations.
- `PreferStaticLoggers`: Prefer static loggers over instance loggers.
- `LogsafeArgName`: Prevent certain named arguments as being logged as safe. Specify unsafe argument names using `LogsafeArgName:UnsafeArgNames` errorProne flag.
- `ImplicitPublicBuilderConstructor`: Prevent builders from unintentionally leaking public constructors.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* (c) Copyright 2020 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.baseline.errorprone;

import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;

@AutoService(BugChecker.class)
@BugPattern(
name = "ObjectsHashCodeUnnecessaryVarargs",
link = "https://github.com/palantir/gradle-baseline#baseline-error-prone-checks",
linkType = LinkType.CUSTOM,
severity = SeverityLevel.WARNING,
summary = "java.util.Objects.hash(non-varargs) should be replaced with java.util.Objects.hashCode(value) "
+ "to avoid unnecessary varargs array allocations.")
public final class ObjectsHashCodeUnnecessaryVarargs extends BugChecker
implements BugChecker.MethodInvocationTreeMatcher {

private static final Matcher<ExpressionTree> HASH_MATCHER =
MethodMatchers.staticMethod().onClass("java.util.Objects").named("hash");

private static final Matcher<ExpressionTree> ARRAY_MATCHER = Matchers.isArrayType();

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (HASH_MATCHER.matches(tree, state) && tree.getArguments().size() == 1) {
ExpressionTree argument = tree.getArguments().get(0);
if (!ARRAY_MATCHER.matches(argument, state)) {
return buildDescription(tree)
.addFix(SuggestedFixes.renameMethodInvocation(tree, "hashCode", state))
.build();
}
}
return Description.NO_MATCH;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* (c) Copyright 2020 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.baseline.errorprone;

import com.google.errorprone.CompilationTestHelper;
import org.junit.jupiter.api.Test;

class ObjectsHashCodeUnnecessaryVarargsTest {

@Test
public void test() {
fix().addInputLines(
"Test.java",
"import java.util.Objects;",
"public class Test {",
" void f(Object a, Object[] b, String[] c, String d) {",
" Objects.hash(a);",
" Objects.hash(a, a);",
" Objects.hash(b);",
" Objects.hash(c);",
" Objects.hash(d);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Objects;",
"public class Test {",
" void f(Object a, Object[] b, String[] c, String d) {",
" Objects.hashCode(a);",
" Objects.hash(a, a);",
" Objects.hash(b);",
" // BUG: Diagnostic contains: non-varargs call of varargs method",
" Objects.hash(c);",
" Objects.hashCode(d);",
" }",
"}")
.doTest();
}

private RefactoringValidator fix() {
return RefactoringValidator.of(new ObjectsHashCodeUnnecessaryVarargs(), getClass());
}

public CompilationTestHelper helper() {
return CompilationTestHelper.newInstance(ObjectsHashCodeUnnecessaryVarargs.class, getClass());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,15 @@ void doTest() {
delegate.doTest();
helper.compilationHelper
.addSourceLines(helper.outputPath, helper.outputLines)
.matchAllDiagnostics()
.doTest();
}

void doTest(BugCheckerRefactoringTestHelper.TestMode testMode) {
delegate.doTest(testMode);
helper.compilationHelper
.addSourceLines(helper.outputPath, helper.outputLines)
.matchAllDiagnostics()
.doTest();
}

Expand Down
5 changes: 5 additions & 0 deletions changelog/@unreleased/pr-1522.v2.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
type: improvement
improvement:
description: Implement error-prone ObjectsHashCodeUnnecessaryVarargs migration
links:
- https://github.com/palantir/gradle-baseline/pull/1522
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public class BaselineErrorProneExtension {
"LambdaMethodReference",
"LoggerEnclosingClass",
"LogsafeArgName",
"ObjectsHashCodeUnnecessaryVarargs",
"OptionalFlatMapOfNullable",
"OptionalOrElseMethodInvocation",
"PreferBuiltInConcurrentKeySet",
Expand Down

0 comments on commit 3a3eedc

Please sign in to comment.