Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error prone validation to avoid redundant modifiers #1010

Merged
merged 5 commits into from
Nov 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ Safe Logging can be found at [github.com/palantir/safe-logging](https://github.c
- `ReverseDnsLookup`: Calling address.getHostName may result in an unexpected DNS lookup.
- `ReadReturnValueIgnored`: The result of a read call must be checked to know if EOF has been reached or the expected number of bytes have been consumed.
- `FinalClass`: A class should be declared final if all of its constructors are private.
- `RedundantModifier`: Avoid using redundant modifiers.

### Programmatic Application

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* (c) Copyright 2019 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.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.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import java.util.Locale;
import javax.lang.model.element.Modifier;

/**
* In a future change we may want to validate against unnecessary modifiers based on encapsulating
* component visibility, for example there's no reason to allow a public constructor for a private
* class.
*/
@AutoService(BugChecker.class)
@BugPattern(
name = "RedundantModifier",
link = "https://github.com/palantir/gradle-baseline#baseline-error-prone-checks",
linkType = BugPattern.LinkType.CUSTOM,
providesFix = BugPattern.ProvidesFix.REQUIRES_HUMAN_ATTENTION,
severity = BugPattern.SeverityLevel.ERROR,
summary = "Avoid using redundant modifiers")
public final class RedundantModifier extends BugChecker
implements BugChecker.ClassTreeMatcher, BugChecker.MethodTreeMatcher {

private static final Matcher<ClassTree> STATIC_ENUM_OR_INTERFACE = Matchers.allOf(
Matchers.anyOf(Matchers.kindIs(Tree.Kind.ENUM), Matchers.kindIs(Tree.Kind.INTERFACE)),
Matchers.hasModifier(Modifier.STATIC));

private static final Matcher<MethodTree> PRIVATE_ENUM_CONSTRUCTOR = Matchers.allOf(
Matchers.methodIsConstructor(),
Matchers.enclosingClass(Matchers.kindIs(Tree.Kind.ENUM)),
Matchers.hasModifier(Modifier.PRIVATE));

private static final Matcher<MethodTree> STATIC_FINAL_METHOD = Matchers.allOf(
Matchers.isStatic(),
Matchers.hasModifier(Modifier.FINAL));

private static final Matcher<MethodTree> UNNECESSARY_INTERFACE_METHOD_MODIFIERS = Matchers.allOf(
Matchers.enclosingClass(Matchers.kindIs(Tree.Kind.INTERFACE)),
Matchers.not(Matchers.isStatic()),
Matchers.not(Matchers.hasModifier(Modifier.DEFAULT)),
Matchers.anyOf(Matchers.hasModifier(Modifier.PUBLIC), Matchers.hasModifier(Modifier.ABSTRACT)));

private static final Matcher<MethodTree> UNNECESSARY_FINAL_METHOD_ON_FINAL_CLASS = Matchers.allOf(
Matchers.not(Matchers.isStatic()),
Matchers.enclosingClass(Matchers.allOf(
Matchers.kindIs(Tree.Kind.CLASS),
Matchers.hasModifier(Modifier.FINAL))),
Matchers.allOf(
Matchers.hasModifier(Modifier.FINAL),
Matchers.not(Matchers.hasAnnotation(SafeVarargs.class))));

@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (STATIC_ENUM_OR_INTERFACE.matches(tree, state)) {
return buildDescription(tree)
.setMessage(tree.getKind().name().toLowerCase(Locale.ENGLISH)
+ "s are static by default. The 'static' modifier is unnecessary.")
.addFix(SuggestedFixes.removeModifiers(tree, state, Modifier.STATIC))
.build();
}
return Description.NO_MATCH;
}

@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (PRIVATE_ENUM_CONSTRUCTOR.matches(tree, state)) {
return buildDescription(tree)
.setMessage("Enum constructors are private by default. The 'private' modifier is unnecessary.")
.addFix(SuggestedFixes.removeModifiers(tree, state, Modifier.PRIVATE))
.build();
}
if (STATIC_FINAL_METHOD.matches(tree, state)) {
return buildDescription(tree)
.setMessage("Static methods cannot be overridden. The 'final' modifier is unnecessary.")
.addFix(SuggestedFixes.removeModifiers(tree, state, Modifier.FINAL))
.build();
}
if (UNNECESSARY_INTERFACE_METHOD_MODIFIERS.matches(tree, state)) {
return buildDescription(tree)
.setMessage("Interface methods are public and abstract by default. "
+ "The 'public' and 'abstract' modifiers are unnecessary.")
.addFix(SuggestedFixes.removeModifiers(tree, state, Modifier.PUBLIC, Modifier.ABSTRACT))
.build();
}
if (UNNECESSARY_FINAL_METHOD_ON_FINAL_CLASS.matches(tree, state)) {
return buildDescription(tree)
.setMessage("Redundant 'final' modifier on an instance method of a final class.")
.addFix(SuggestedFixes.removeModifiers(tree, state, Modifier.FINAL))
.build();
}
return Description.NO_MATCH;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
/*
* (c) Copyright 2019 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.BugCheckerRefactoringTestHelper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;

@Execution(ExecutionMode.CONCURRENT)
class RedundantModifierTest {

@Test
void fixEnumConstructor() {
fix()
.addInputLines(
"Test.java",
"public enum Test {",
" INSTANCE(\"str\");",
" private final String str;",
" private Test(String str) {",
" this.str = str;",
" }",
"}"
)
.addOutputLines(
"Test.java",
"public enum Test {",
" INSTANCE(\"str\");",
" private final String str;",
" Test(String str) {",
" this.str = str;",
" }",
"}"
).doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH);
}

@Test
@SuppressWarnings("checkstyle:RegexpSinglelineJava")
void fixStaticEnum() {
fix()
.addInputLines(
"Enclosing.java",
"public class Enclosing {",
" public static enum Test {",
" INSTANCE",
" }",
"}"
)
.addOutputLines(
"Enclosing.java",
"public class Enclosing {",
" public enum Test {",
" INSTANCE",
" }",
"}"
).doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH);
}

@Test
void fixStaticInterface() {
fix()
.addInputLines(
"Enclosing.java",
"public class Enclosing {",
" public static interface Test {",
" }",
"}"
)
.addOutputLines(
"Enclosing.java",
"public class Enclosing {",
" public interface Test {",
" }",
"}"
).doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH);
}

@Test
void fixInterfaceMethods() {
fix()
.addInputLines(
"Enclosing.java",
"public class Enclosing {",
" public interface Test {",
" public int a();",
" int b();",
" abstract int c();",
" public abstract int d();",
" }",
"}"
)
.addOutputLines(
"Enclosing.java",
"public class Enclosing {",
" public interface Test {",
" int a();",
" int b();",
" int c();",
" int d();",
" }",
"}"
).doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH);
}

@Test
void fixFinalClassModifiers() {
fix()
.addInputLines(
"Test.java",
"public final class Test {",
" public final void a() {}",
" private final void b() {}",
" final void c() {}",
" @SafeVarargs public final void d(Object... value) {}",
"}"
)
.addOutputLines(
"Test.java",
"public final class Test {",
" public void a() {}",
" private void b() {}",
" void c() {}",
// SafeVarargs is a special case
" @SafeVarargs public final void d(Object... value) {}",
"}"
).doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH);
}

@Test
void fixStaticFinalMethod() {
fix()
.addInputLines(
"Test.java",
"public class Test {",
" public static final int a() {",
" return 1;",
" }",
" private static final int b() {",
" return 1;",
" }",
" static final int c() {",
" return 1;",
" }",
"}"
)
.addOutputLines(
"Test.java",
"public class Test {",
" public static int a() {",
" return 1;",
" }",
" private static int b() {",
" return 1;",
" }",
" static int c() {",
" return 1;",
" }",
"}"
).doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH);
}

private BugCheckerRefactoringTestHelper fix() {
return BugCheckerRefactoringTestHelper.newInstance(new RedundantModifier(), getClass());
}
}
5 changes: 5 additions & 0 deletions changelog/@unreleased/pr-1010.v2.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
type: improvement
improvement:
description: Error prone validation to avoid redundant modifiers
links:
- https://github.com/palantir/gradle-baseline/pull/1010
Original file line number Diff line number Diff line change
Expand Up @@ -370,10 +370,6 @@
<property name="format" value="\bIOUtils\.toString\("/>
<property name="message" value="Prefer Guava''s [CharStreams,Files,Resources].toString to avoid charset/stream closing issues."/>
</module>
<module name="RegexpSinglelineJava">
<property name="format" value="static enum"/>
<property name="message" value="Redundant ''static'' modifier."/>
</module>
<module name="RegexpSinglelineJava">
<property name="format" value="\/\/TODO|\/\/ TODO(?!\([^()\s]+\): )"/>
<property name="message" value="TODO format: // TODO(#issue): explanation"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public class BaselineErrorProneExtension {
"PreferSafeLoggableExceptions",
"PreferSafeLoggingPreconditions",
"ReadReturnValueIgnored",
"RedundantModifier",
"Slf4jLevelCheck",
"Slf4jLogsafeArgs",
"StrictUnusedVariable",
Expand Down