-
Notifications
You must be signed in to change notification settings - Fork 135
Added OptionalOrElseGetConstant error prone check. #1401
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
Merged
Merged
Changes from 5 commits
Commits
Show all changes
34 commits
Select commit
Hold shift + click to select a range
bf17125
Added OptionalOrElseGetConstant error prone check.
aioobe 6cb06f5
Excavator: Upgrade buildscript dependencies (#1402)
svc-excavator-bot f8fa3d1
Excavator: Upgrade buildscript dependencies (#1403)
svc-excavator-bot 09ca77a
--write-locks no longer implicitly runs checkClassUniqueness task (#1…
iamdanfox b99ee1d
Autorelease 3.24.0
svc-autorelease 6604106
Excavator: Upgrade dependencies (#1399)
svc-excavator-bot 93bca37
Improvement: Upgrade Checkstyle to 8.33 (#1404)
robert3005 4407bb5
Autorelease 3.25.0
svc-autorelease d12519d
Fix: Adjust checkstyle config for new version (#1409)
robert3005 0401037
Autorelease 3.25.1
svc-autorelease 329b939
Excavator: Render CircleCI file using template specified in .circleci…
svc-excavator-bot 1eaa6ce
Check now also covers other simple expressions. Readme updated.
aioobe eb4d55b
StrictUnusedVariable handles Java 14 records (#1412)
ferozco 7209e9b
Autorelease 3.26.0
svc-autorelease ce1d2e1
Ran spotlessApply.
aioobe 54f4f32
Added a compile time constant test.
aioobe 03c85a0
Reworded description in README.
aioobe 87eb1ff
Changed to multiple returns.
aioobe c4fd4b2
Don't wrap method declaration (#1416)
hesselink 02303a8
Autorelease 3.27.0
svc-autorelease e9309b7
Excavator: Upgrade buildscript dependencies (#1417)
svc-excavator-bot ac4956d
Excavator: Ensure consistent gradle/publish-(jar|dist).gradle files (…
svc-excavator-bot 1d0cc65
Excavator: Upgrade dependencies (#1419)
svc-excavator-bot 13fc372
Added changelog entry.
aioobe 3bd2a1e
Improve gradle-baseline-java integration with IntelliJ import (#1411)
aldexis f1c1f63
Autorelease 3.28.0
svc-autorelease 3b331f1
Added OptionalOrElseGetConstant error prone check.
aioobe aa20422
Check now also covers other simple expressions. Readme updated.
aioobe 15a48bf
Ran spotlessApply.
aioobe 83993a1
Added a compile time constant test.
aioobe e135dff
Reworded description in README.
aioobe d5e0139
Changed to multiple returns.
aioobe 7ece87b
Added changelog entry.
aioobe 689346f
Merge branch 'orElseGet-constant' of github.com:aioobe/gradle-baselin…
aioobe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
98
...ne-error-prone/src/main/java/com/palantir/baseline/errorprone/OptionalOrElseGetValue.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| /* | ||
| * (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.BugPattern.SeverityLevel; | ||
| import com.google.errorprone.VisitorState; | ||
| import com.google.errorprone.bugpatterns.BugChecker; | ||
| import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; | ||
| import com.google.errorprone.fixes.SuggestedFix; | ||
| import com.google.errorprone.fixes.SuggestedFixes; | ||
| import com.google.errorprone.matchers.CompileTimeConstantExpressionMatcher; | ||
| import com.google.errorprone.matchers.Description; | ||
| import com.google.errorprone.matchers.Matcher; | ||
| import com.google.errorprone.matchers.method.MethodMatchers; | ||
| import com.sun.source.tree.ExpressionTree; | ||
| import com.sun.source.tree.IdentifierTree; | ||
| import com.sun.source.tree.LambdaExpressionTree; | ||
| import com.sun.source.tree.LiteralTree; | ||
| import com.sun.source.tree.MemberSelectTree; | ||
| import com.sun.source.tree.MethodInvocationTree; | ||
| import com.sun.source.tree.Tree; | ||
|
|
||
| @AutoService(BugChecker.class) | ||
| @BugPattern( | ||
| name = "OptionalOrElseGetValue", | ||
| link = "https://github.com/palantir/gradle-baseline#baseline-error-prone-checks", | ||
| linkType = BugPattern.LinkType.CUSTOM, | ||
| providesFix = BugPattern.ProvidesFix.REQUIRES_HUMAN_ATTENTION, | ||
| severity = SeverityLevel.WARNING, | ||
| summary = "If lambda passed to Optional#orElseGet returns a simple expression, use Optional#orElse instead") | ||
| public final class OptionalOrElseGetValue extends BugChecker implements MethodInvocationTreeMatcher { | ||
|
|
||
| private static final long serialVersionUID = 1L; | ||
| private static final Matcher<ExpressionTree> OR_ELSE_GET_METHOD = | ||
| MethodMatchers.instanceMethod().onExactClass("java.util.Optional").named("orElseGet"); | ||
| private static final Matcher<ExpressionTree> COMPILE_TIME_CONSTANT = new CompileTimeConstantExpressionMatcher(); | ||
|
|
||
| @Override | ||
| public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { | ||
| match: | ||
| { | ||
| if (!OR_ELSE_GET_METHOD.matches(tree, state)) { | ||
| break match; | ||
| } | ||
|
|
||
| ExpressionTree orElseGetArg = tree.getArguments().get(0); | ||
|
|
||
| if (orElseGetArg.getKind() != Tree.Kind.LAMBDA_EXPRESSION) { | ||
| break match; | ||
| } | ||
|
|
||
| LambdaExpressionTree lambdaExpressionTree = (LambdaExpressionTree) orElseGetArg; | ||
| LambdaExpressionTree.BodyKind bodyKind = lambdaExpressionTree.getBodyKind(); | ||
|
|
||
| if (bodyKind != LambdaExpressionTree.BodyKind.EXPRESSION) { | ||
| break match; | ||
| } | ||
|
|
||
| ExpressionTree expressionBody = (ExpressionTree) lambdaExpressionTree.getBody(); | ||
| if (COMPILE_TIME_CONSTANT.matches(expressionBody, state) | ||
aioobe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| || isTrivialExpression(expressionBody) | ||
| || isTrivialSelect(expressionBody)) { | ||
| return buildDescription(tree) | ||
| .setMessage("Prefer Optional#orElse instead of Optional#orElseGet for compile time constants") | ||
| .addFix(SuggestedFix.builder() | ||
| .merge(SuggestedFixes.renameMethodInvocation(tree, "orElse", state)) | ||
| .replace(orElseGetArg, state.getSourceForNode(expressionBody)) | ||
| .build()) | ||
| .build(); | ||
| } | ||
| } | ||
| return Description.NO_MATCH; | ||
| } | ||
|
|
||
| private static boolean isTrivialExpression(ExpressionTree tree) { | ||
| return tree instanceof LiteralTree || tree instanceof IdentifierTree; | ||
| } | ||
|
|
||
| private static boolean isTrivialSelect(ExpressionTree tree) { | ||
| return tree instanceof MemberSelectTree && isTrivialExpression(((MemberSelectTree) tree).getExpression()); | ||
| } | ||
| } | ||
150 changes: 150 additions & 0 deletions
150
...rror-prone/src/test/java/com/palantir/baseline/errorprone/OptionalOrElseGetValueTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| /* | ||
| * (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 com.google.errorprone.CompilationTestHelper; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| public final class OptionalOrElseGetValueTest { | ||
|
|
||
| private CompilationTestHelper compilationHelper; | ||
| private RefactoringValidator refactoringTestHelper; | ||
|
|
||
| @BeforeEach | ||
| public void before() { | ||
| compilationHelper = CompilationTestHelper.newInstance(OptionalOrElseGetValue.class, getClass()); | ||
| refactoringTestHelper = RefactoringValidator.of(new OptionalOrElseGetValue(), getClass()); | ||
| } | ||
|
|
||
| @Test | ||
| public void testOrElseGetStringLiteral() { | ||
| compilationHelper | ||
| .addSourceLines( | ||
| "Test.java", | ||
| "import java.util.Optional;", | ||
| "class Test {", | ||
| " // BUG: Diagnostic contains: Prefer Optional#orElse", | ||
| " private final String string = Optional.of(\"hello\").orElseGet(() -> \"world\");", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void testOrElseGetVariable() { | ||
| compilationHelper | ||
| .addSourceLines( | ||
| "Test.java", | ||
| "import java.util.Optional;", | ||
| "class Test {", | ||
| " String s = \"hello\";", | ||
| " // BUG: Diagnostic contains: Prefer Optional#orElse", | ||
| " private final String string = Optional.of(\"hello\").orElseGet(() -> s);", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void testOrElseGetMethodInvocation() { | ||
| compilationHelper | ||
| .addSourceLines( | ||
| "Test.java", | ||
| "import java.util.Optional;", | ||
| "class Test {", | ||
| " String s = \"hello\";", | ||
| " private final String string = Optional.of(\"hello\").orElseGet(() -> s.toString());", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void testOrElseGetConstantString() { | ||
| compilationHelper | ||
| .addSourceLines( | ||
| "Test.java", | ||
| "import java.util.Optional;", | ||
| "class Test {", | ||
| " private static final String constant = \"constant\";", | ||
| " // BUG: Diagnostic contains: Prefer Optional#orElse", | ||
| " private final String string = Optional.of(\"hello\").orElseGet(() -> constant);", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void testOrElseGetThisField() { | ||
| compilationHelper | ||
| .addSourceLines( | ||
| "Test.java", | ||
| "import java.util.Optional;", | ||
| "class Test {", | ||
| " private static double field = Math.random();", | ||
| " // BUG: Diagnostic contains: Prefer Optional#orElse", | ||
| " private final double string = Optional.of(0.1).orElseGet(() -> this.field);", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void testOrElseGetOtherField() { | ||
| compilationHelper | ||
| .addSourceLines( | ||
| "Test.java", | ||
| "import java.util.Optional;", | ||
| "class Test {", | ||
| " private Test test = new Test();", | ||
| " private double field = Math.random();", | ||
| " // BUG: Diagnostic contains: Prefer Optional#orElse", | ||
| " private final double string = Optional.of(0.1).orElseGet(() -> test.field);", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void testOrElseGetCompileTimeConstant() { | ||
| compilationHelper | ||
| .addSourceLines( | ||
| "Test.java", | ||
| "import java.util.Optional;", | ||
| "class Test {", | ||
| " private final String part1 = \"Hello \";", | ||
| " private final String part2 = \"World\";", | ||
| " // BUG: Diagnostic contains: Prefer Optional#orElse", | ||
| " private final String string = Optional.of(\"str\").orElseGet(() -> part1 + part2);", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void testReplacementOfLiteral() { | ||
| refactoringTestHelper | ||
| .addInputLines( | ||
| "Test.java", | ||
| "import java.util.Optional;", | ||
| "class Test {", | ||
| " private final boolean b = Optional.of(true).orElseGet(() -> false);", | ||
| "}") | ||
| .addOutputLines( | ||
| "Test.java", | ||
| "import java.util.Optional;", | ||
| "class Test {", | ||
| " private final boolean b = Optional.of(true).orElse(false);", | ||
| "}") | ||
| .doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.