-
Notifications
You must be signed in to change notification settings - Fork 725
SONARJAVA-6273 S3706: "stream" should not be used for Collection "forEach" calls #5581
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
Open
NoemieBenard
wants to merge
18
commits into
master
Choose a base branch
from
nb/sonarjava-6273-implement-S3706
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
f881b20
fix incorrect test
NoemieBenard 2a08dab
add tests for regex
NoemieBenard 0d629a7
update tests accordingly to default header
NoemieBenard 7d6bbf4
add default header after rebase
NoemieBenard 09a9494
create files for implementation of S3706
NoemieBenard 5dfa8cd
implement check
NoemieBenard a18788b
add failing test
NoemieBenard fe22485
correct check according to .stream().filter().forEach() test
NoemieBenard 50d8e5d
Replace ofTypes by ofSubTypes to match collection subtypes
NoemieBenard 880cb68
improve tests
NoemieBenard f113647
generate rule metadata from RSPEC
NoemieBenard 2b80a7b
update autoscan diffs
NoemieBenard 43d8858
update expected number of rules
NoemieBenard 2316403
add S3706 file for ruling test
NoemieBenard 7a9a8d5
update code according to the review
NoemieBenard 3fa343d
modify issue location to match stream.forEach
NoemieBenard 72baf2f
update rspec
NoemieBenard 153fe4f
update issue message
NoemieBenard 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
6 changes: 6 additions & 0 deletions
6
its/autoscan/src/test/resources/autoscan/diffs/diff_S3706.json
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,6 @@ | ||
| { | ||
| "ruleKey": "S3706", | ||
| "hasTruePositives": true, | ||
| "falseNegatives": 0, | ||
| "falsePositives": 0 | ||
| } |
12 changes: 12 additions & 0 deletions
12
its/ruling/src/test/resources/sonar-server/java-S3706.json
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,12 @@ | ||
| { | ||
| "org.sonarsource.sonarqube:sonar-server:src/main/java/org/sonar/server/permission/ws/template/SearchTemplatesDataLoader.java": [ | ||
| 96 | ||
| ], | ||
| "org.sonarsource.sonarqube:sonar-server:src/main/java/org/sonar/server/rule/ws/ShowAction.java": [ | ||
| 140 | ||
| ], | ||
| "org.sonarsource.sonarqube:sonar-server:src/test/java/org/sonar/server/qualityprofile/RuleActivatorTest.java": [ | ||
| 863, | ||
| 898 | ||
| ] | ||
| } |
40 changes: 40 additions & 0 deletions
40
java-checks-test-sources/default/src/main/java/checks/StreamForeachCheck.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,40 @@ | ||
| package checks; | ||
|
|
||
| import java.util.Collection; | ||
| import java.util.List; | ||
| import java.util.Set; | ||
| import java.util.stream.Stream; | ||
|
|
||
| public class StreamForeachCheck { | ||
|
|
||
| void unnecessaryStreamForEach(Collection<Integer> collection) { | ||
| collection.stream().forEach(System.out::println); // Noncompliant {{Simplify the code by replacing .stream().forEach() with .forEach().}} | ||
| // ^^^^^^^^^^^^^^^^ | ||
| } | ||
|
|
||
| void compliantCollectionForEach(Collection<Integer> collection) { | ||
| collection.forEach(System.out::println); // Compliant | ||
| } | ||
|
|
||
| void necessaryFilterForEach(Collection<String> col) { | ||
| col.stream().filter(s -> !s.isEmpty()).forEach(System.out::println); | ||
| } | ||
|
|
||
| void unnecessaryForEachOnSet(Set<String> set) { | ||
| set.stream().forEach(e -> System.out.println("Element: " + e)); // Noncompliant | ||
| } | ||
|
|
||
| void unnecessaryForEachOnList(List<String> list) { | ||
| list.stream().forEach(e -> System.out.println("Element: " + e)); // Noncompliant | ||
| } | ||
|
|
||
| void necessaryForEachOnParallelStream(Set<String> set) { | ||
| set.parallelStream().forEach(System.out::println); // Compliant | ||
| } | ||
|
|
||
| void sequentialStreamForEach(Collection<String> col) { | ||
| Stream<String> s = col.stream(); | ||
| s.forEach(System.out::println); // Compliant (the rule ignores this case) | ||
| } | ||
|
|
||
| } | ||
62 changes: 62 additions & 0 deletions
62
java-checks/src/main/java/org/sonar/java/checks/StreamForeachCheck.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,62 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import java.util.List; | ||
| import org.sonar.check.Rule; | ||
| import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; | ||
| import org.sonar.plugins.java.api.semantic.MethodMatchers; | ||
| import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; | ||
| import org.sonar.plugins.java.api.tree.MethodInvocationTree; | ||
| import org.sonar.plugins.java.api.tree.Tree; | ||
|
|
||
| @Rule(key = "S3706") | ||
|
sonar-review-alpha[bot] marked this conversation as resolved.
|
||
| public class StreamForeachCheck extends IssuableSubscriptionVisitor { | ||
|
|
||
| private static final MethodMatchers STREAM_METHOD = MethodMatchers.create() | ||
| .ofSubTypes("java.util.Collection") | ||
| .names("stream") | ||
| .addWithoutParametersMatcher() | ||
| .build(); | ||
|
|
||
| private static final MethodMatchers STREAM_FOREACH_METHOD = MethodMatchers.create() | ||
| .ofSubTypes("java.util.stream.Stream") | ||
| .names("forEach") | ||
| .withAnyParameters() | ||
| .build(); | ||
|
|
||
| @Override | ||
| public List<Tree.Kind> nodesToVisit() { | ||
| return List.of(Tree.Kind.METHOD_INVOCATION); | ||
| } | ||
|
|
||
| @Override | ||
| public void visitNode(Tree tree) { | ||
| if (tree instanceof MethodInvocationTree mit && STREAM_FOREACH_METHOD.matches(mit)) { | ||
| checkUnnecessaryForEach(mit); | ||
| } | ||
| } | ||
|
|
||
| private void checkUnnecessaryForEach(MethodInvocationTree mitForEach) { | ||
| if (mitForEach.methodSelect() instanceof MemberSelectExpressionTree msetForEach | ||
| && msetForEach.expression() instanceof MethodInvocationTree mitStream | ||
| && STREAM_METHOD.matches(mitStream) | ||
| && mitStream.methodSelect() instanceof MemberSelectExpressionTree msetStream) { | ||
| reportIssue(msetStream.identifier(), msetForEach.identifier(), "Simplify the code by replacing .stream().forEach() with .forEach()."); | ||
| } | ||
| } | ||
| } | ||
43 changes: 43 additions & 0 deletions
43
java-checks/src/test/java/org/sonar/java/checks/StreamForeachCheckTest.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,43 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
| import org.sonar.java.checks.verifier.CheckVerifier; | ||
|
|
||
| import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; | ||
|
|
||
| class StreamForeachCheckTest { | ||
| @Test | ||
| void test() { | ||
| StreamForeachCheck check = new StreamForeachCheck(); | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/StreamForeachCheck.java")) | ||
| .withCheck(check) | ||
| .verifyIssues(); | ||
| } | ||
|
NoemieBenard marked this conversation as resolved.
|
||
|
|
||
| @Test | ||
| void testWithoutSemantic() { | ||
| StreamForeachCheck check = new StreamForeachCheck(); | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/StreamForeachCheck.java")) | ||
| .withoutSemantic() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I meant, we should have two tests, one with semantic, one without. |
||
| .withCheck(check) | ||
| .verifyIssues(); | ||
| } | ||
| } | ||
12 changes: 12 additions & 0 deletions
12
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S3706.html
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,12 @@ | ||
| <h2>Why is this an issue?</h2> | ||
| <p>There’s no need to invoke <code>stream()</code> on a <code>Collection</code> before a <code>forEach</code> call because each | ||
| <code>Collection</code> has its own <code>forEach</code> method.</p> | ||
| <h3>Noncompliant code example</h3> | ||
| <pre> | ||
| identifiers.stream().forEach(System.out::println); // Noncompliant | ||
| </pre> | ||
| <h3>Compliant solution</h3> | ||
| <pre> | ||
| identifiers.forEach(System.out::println); // Compliant | ||
| </pre> | ||
|
|
15 changes: 15 additions & 0 deletions
15
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S3706.json
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,15 @@ | ||
| { | ||
| "title": "\"stream\" should not be used for Collection \"forEach\" calls", | ||
| "type": "CODE_SMELL", | ||
| "status": "ready", | ||
| "remediation": { | ||
| "func": "Constant\/Issue", | ||
| "constantCost": "2min" | ||
| }, | ||
| "tags": [], | ||
| "defaultSeverity": "Minor", | ||
| "ruleSpecification": "RSPEC-3706", | ||
| "sqKey": "S3706", | ||
| "scope": "All", | ||
| "quickfix": "unknown" | ||
| } |
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 |
|---|---|---|
|
|
@@ -259,6 +259,7 @@ | |
| "S3599", | ||
| "S3626", | ||
| "S3631", | ||
| "S3706", | ||
| "S3740", | ||
| "S3751", | ||
| "S3752", | ||
|
|
||
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 |
|---|---|---|
|
|
@@ -276,6 +276,7 @@ | |
| "S3599", | ||
| "S3626", | ||
| "S3631", | ||
| "S3706", | ||
| "S3740", | ||
| "S3751", | ||
| "S3752", | ||
|
|
||
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
Oops, something went wrong.
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.
The noncompliant cases cover
Collection,Set, andList, but there is no test for astream().forEach()call where.stream()returns a customStreamproduced by an overriding implementation. More importantly, there is no test using a concreteArrayListor other class that resolves through the fullofSubTypeshierarchy.More critically:
Stream.forEach()carries a weaker contract thanIterable.forEach(). Per the JDK spec,Stream.forEach()is "explicitly nondeterministic" even on sequential streams, whileCollection.forEach()(viaIterable) iterates in encounter order. Code that relies onstream().forEach()for its documented non-determinism guarantee — even if that's unusual — would have its semantics silently changed. Add a test case comment explaining this known limitation, or document it explicitly in the rule description.