-
Notifications
You must be signed in to change notification settings - Fork 135
Add check replacing stream.sorted().findFirst() with stream.min()
#2555
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 all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
4a0f0c8
wip
db49570
Merge branch 'develop' of github.com:palantir/gradle-baseline into ad…
24ec409
add comment
27f3ecb
update comment
7a93259
Add generated changelog entries
svc-changelog e63c1f7
Merge branch 'develop' of github.com:palantir/gradle-baseline into ad…
c287681
review changes
dc8056a
Merge branch 'add-check-sorted-first' of github.com:palantir/gradle-b…
cb54f17
format
0910447
add nl
7541a25
move getStartPosition into private static method
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
115 changes: 115 additions & 0 deletions
115
...-error-prone/src/main/java/com/palantir/baseline/errorprone/SortedStreamFirstElement.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,115 @@ | ||
| /* | ||
| * (c) Copyright 2023 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.fixes.SuggestedFix; | ||
| 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.google.errorprone.util.ASTHelpers; | ||
| import com.sun.source.tree.ExpressionTree; | ||
| import com.sun.source.tree.MethodInvocationTree; | ||
| import com.sun.source.tree.Tree; | ||
| import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; | ||
| import java.util.Comparator; | ||
| import java.util.stream.Stream; | ||
|
|
||
| @AutoService(BugChecker.class) | ||
| @BugPattern( | ||
| link = "https://github.com/palantir/gradle-baseline#baseline-error-prone-checks", | ||
| linkType = BugPattern.LinkType.CUSTOM, | ||
| severity = SeverityLevel.SUGGESTION, | ||
| summary = "Using Stream::min is more efficient than finding the first element of the sorted stream. " | ||
| + "Stream::min performs a linear scan through the stream to find the smallest element.") | ||
| public final class SortedStreamFirstElement extends BugChecker implements BugChecker.MethodInvocationTreeMatcher { | ||
|
|
||
| private static final Matcher<ExpressionTree> STREAM_FIND_FIRST_MATCHER = MethodMatchers.instanceMethod() | ||
| .onDescendantOf(Stream.class.getName()) | ||
| .named("findFirst") | ||
| .withNoParameters(); | ||
|
|
||
| private static final Matcher<MethodInvocationTree> RECEIVER_OF_STREAM_SORTED_NO_PARAMS_MATCHER = | ||
| Matchers.receiverOfInvocation(MethodMatchers.instanceMethod() | ||
| .onDescendantOf(Stream.class.getName()) | ||
| .named("sorted") | ||
| .withNoParameters()); | ||
|
|
||
| private static final Matcher<MethodInvocationTree> RECEIVER_OF_STREAM_SORTED_WITH_COMPARATOR_MATCHER = | ||
| Matchers.receiverOfInvocation(MethodMatchers.instanceMethod() | ||
| .onDescendantOf(Stream.class.getName()) | ||
| .named("sorted") | ||
| .withParameters(Comparator.class.getName())); | ||
|
|
||
| private static final Matcher<MethodInvocationTree> MATCHER = Matchers.allOf( | ||
| STREAM_FIND_FIRST_MATCHER, | ||
| Matchers.anyOf( | ||
| RECEIVER_OF_STREAM_SORTED_NO_PARAMS_MATCHER, RECEIVER_OF_STREAM_SORTED_WITH_COMPARATOR_MATCHER)); | ||
|
|
||
| @Override | ||
| public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { | ||
| if (!MATCHER.matches(tree, state)) { | ||
| return Description.NO_MATCH; | ||
| } | ||
|
|
||
| ExpressionTree sorted = ASTHelpers.getReceiver(tree); | ||
| if (sorted == null) { | ||
| // Not expected. | ||
| return Description.NO_MATCH; | ||
| } | ||
| MethodInvocationTree sortedTree = (MethodInvocationTree) sorted; | ||
| ExpressionTree stream = ASTHelpers.getReceiver(sorted); | ||
| if (stream == null) { | ||
| // Not expected. | ||
| return Description.NO_MATCH; | ||
| } | ||
|
|
||
| if (RECEIVER_OF_STREAM_SORTED_NO_PARAMS_MATCHER.matches(tree, state)) { | ||
| return describeMatch( | ||
| tree, | ||
| SuggestedFix.builder() | ||
| .replace( | ||
| getStartPosition(tree), | ||
| state.getEndPosition(tree), | ||
| state.getSourceForNode(stream) + ".min(Comparator.naturalOrder())") | ||
| .addImport(Comparator.class.getCanonicalName()) | ||
| .build()); | ||
| } else if (RECEIVER_OF_STREAM_SORTED_WITH_COMPARATOR_MATCHER.matches(tree, state)) { | ||
| return describeMatch( | ||
| tree, | ||
| SuggestedFix.builder() | ||
| .replace( | ||
| getStartPosition(tree), | ||
| state.getEndPosition(tree), | ||
| state.getSourceForNode(stream) + ".min(" | ||
| + state.getSourceForNode( | ||
| sortedTree.getArguments().get(0)) + ")") | ||
| .build()); | ||
| } | ||
|
|
||
| return Description.NO_MATCH; | ||
| } | ||
|
|
||
| private static int getStartPosition(Tree tree) { | ||
| return ((JCMethodInvocation) tree).getStartPosition(); | ||
| } | ||
| } |
133 changes: 133 additions & 0 deletions
133
...or-prone/src/test/java/com/palantir/baseline/errorprone/SortedStreamFirstElementTest.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,133 @@ | ||
| /* | ||
| * (c) Copyright 2023 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 java.util.Comparator; | ||
| import java.util.Optional; | ||
| import java.util.stream.Stream; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| public class SortedStreamFirstElementTest { | ||
|
|
||
| @Test | ||
| public void test_basic() { | ||
| fix().addInputLines( | ||
| "TestBasic.java", | ||
| "import " + Optional.class.getCanonicalName() + ";", | ||
| "import " + Stream.class.getCanonicalName() + ";", | ||
| "class TestBasic {", | ||
| " public Optional<Integer> basic(Stream<Integer> s) {", | ||
| " return s.sorted().findFirst();", | ||
| " }", | ||
| "}") | ||
| .addOutputLines( | ||
| "TestBasic.java", | ||
| "import " + Comparator.class.getCanonicalName() + ";", | ||
| "import " + Optional.class.getCanonicalName() + ";", | ||
| "import " + Stream.class.getCanonicalName() + ";", | ||
| "class TestBasic {", | ||
| " public Optional<Integer> basic(Stream<Integer> s) {", | ||
| " return s.min(Comparator.naturalOrder());", | ||
| " }", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void test_comparator_already_imported() { | ||
| fix().addInputLines( | ||
| "TestComparatorAlreadyImported.java", | ||
| "import " + Comparator.class.getCanonicalName() + ";", | ||
| "import " + Optional.class.getCanonicalName() + ";", | ||
| "import " + Stream.class.getCanonicalName() + ";", | ||
| "class TestComparatorAlreadyImported {", | ||
| " public Optional<Integer> f(Stream<Integer> s) {", | ||
| " return s.sorted().findFirst();", | ||
| " }", | ||
| " public Optional<Integer> g(Stream<Integer> s) {", | ||
| " return s.min(Comparator.naturalOrder());", | ||
| " }", | ||
| "}") | ||
| .addOutputLines( | ||
| "TestComparatorAlreadyImported.java", | ||
| "import " + Comparator.class.getCanonicalName() + ";", | ||
| "import " + Optional.class.getCanonicalName() + ";", | ||
| "import " + Stream.class.getCanonicalName() + ";", | ||
| "class TestComparatorAlreadyImported {", | ||
| " public Optional<Integer> f(Stream<Integer> s) {", | ||
| " return s.min(Comparator.naturalOrder());", | ||
| " }", | ||
| " public Optional<Integer> g(Stream<Integer> s) {", | ||
| " return s.min(Comparator.naturalOrder());", | ||
| " }", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void test_templated() { | ||
| fix().addInputLines( | ||
| "TestBasic.java", | ||
| "import " + Optional.class.getCanonicalName() + ";", | ||
| "import " + Stream.class.getCanonicalName() + ";", | ||
| "class TestBasic<T extends Comparable<? super T>> {", | ||
| " public Optional<T> basic(Stream<T> s) {", | ||
| " return s.sorted().findFirst();", | ||
| " }", | ||
| "}") | ||
| .addOutputLines( | ||
| "TestBasic.java", | ||
| "import " + Comparator.class.getCanonicalName() + ";", | ||
| "import " + Optional.class.getCanonicalName() + ";", | ||
| "import " + Stream.class.getCanonicalName() + ";", | ||
| "class TestBasic<T extends Comparable<? super T>> {", | ||
| " public Optional<T> basic(Stream<T> s) {", | ||
| " return s.min(Comparator.naturalOrder());", | ||
| " }", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void test_comparator() { | ||
| fix().addInputLines( | ||
| "TestComparator.java", | ||
| "import " + Comparator.class.getCanonicalName() + ";", | ||
| "import " + Optional.class.getCanonicalName() + ";", | ||
| "import " + Stream.class.getCanonicalName() + ";", | ||
| "class TestComparator {", | ||
| " public Optional<Integer> f(Stream<Integer> s, Comparator c) {", | ||
| " return s.sorted(c).findFirst();", | ||
| " }", | ||
| "}") | ||
| .addOutputLines( | ||
| "TestComparator.java", | ||
| "import " + Comparator.class.getCanonicalName() + ";", | ||
| "import " + Optional.class.getCanonicalName() + ";", | ||
| "import " + Stream.class.getCanonicalName() + ";", | ||
| "class TestComparator {", | ||
| " public Optional<Integer> f(Stream<Integer> s, Comparator c) {", | ||
| " return s.min(c);", | ||
| " }", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| private RefactoringValidator fix() { | ||
| return RefactoringValidator.of(SortedStreamFirstElement.class, getClass()); | ||
| } | ||
| } | ||
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,5 @@ | ||
| type: feature | ||
| feature: | ||
| description: Add check replacing `stream.sorted().findFirst()` with `stream.min()` | ||
| links: | ||
| - https://github.com/palantir/gradle-baseline/pull/2555 |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
great tests!