Repository navigation
SONARJAVA-1217 Rule: Multiple loops over the same set #353
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| { | ||
| 'project:java/awt/Frame.java':[ | ||
| 1144, | ||
| ], | ||
| 'project:java/awt/Window.java':[ | ||
| 1614, | ||
| ], | ||
| 'project:java/lang/ApplicationShutdownHooks.java':[ | ||
| 104, | ||
| ], | ||
| 'project:java/lang/ProcessEnvironment.java':[ | ||
| 279, | ||
| ], | ||
| 'project:javax/swing/colorchooser/ColorPanel.java':[ | ||
| 96, | ||
| ], | ||
| 'project:javax/swing/plaf/synth/SynthDesktopPaneUI.java':[ | ||
| 219, | ||
| ], | ||
| } |
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
122 changes: 122 additions & 0 deletions
122
java-checks/src/main/java/org/sonar/java/checks/LoopsOnSameSetCheck.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,122 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) 2012 SonarSource | ||
| * sonarqube@googlegroups.com | ||
| * | ||
| * This program is free software; you can redistribute it and/or | ||
| * modify it under the terms of the GNU Lesser General Public | ||
| * License as published by the Free Software Foundation; either | ||
| * version 3 of the License, or (at your option) any later version. | ||
| * | ||
| * 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 GNU | ||
| * Lesser General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU Lesser General Public | ||
| * License along with this program; if not, write to the Free Software | ||
| * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import com.google.common.collect.ImmutableList; | ||
| import org.sonar.api.server.rule.RulesDefinition; | ||
| import org.sonar.check.Priority; | ||
| import org.sonar.check.Rule; | ||
| import org.sonar.java.checks.helpers.ExpressionsHelper; | ||
| import org.sonar.java.model.JavaTree; | ||
| import org.sonar.java.model.SyntacticEquivalence; | ||
| import org.sonar.java.syntaxtoken.FirstSyntaxTokenFinder; | ||
| import org.sonar.plugins.java.api.semantic.Symbol; | ||
| import org.sonar.plugins.java.api.tree.BaseTreeVisitor; | ||
| import org.sonar.plugins.java.api.tree.BlockTree; | ||
| import org.sonar.plugins.java.api.tree.ExpressionTree; | ||
| import org.sonar.plugins.java.api.tree.ForEachStatement; | ||
| import org.sonar.plugins.java.api.tree.IdentifierTree; | ||
| import org.sonar.plugins.java.api.tree.Tree; | ||
| import org.sonar.squidbridge.annotations.SqaleConstantRemediation; | ||
| import org.sonar.squidbridge.annotations.SqaleSubCharacteristic; | ||
|
|
||
| import java.util.HashMap; | ||
| import java.util.HashSet; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Set; | ||
|
|
||
| @Rule( | ||
| key = "S3047", | ||
| name = "Multiple loops over the same set should be combined", | ||
| tags = {"performance"}, | ||
| priority = Priority.MAJOR) | ||
| @SqaleSubCharacteristic(RulesDefinition.SubCharacteristics.CPU_EFFICIENCY) | ||
| @SqaleConstantRemediation("20min") | ||
| public class LoopsOnSameSetCheck extends SubscriptionBaseVisitor { | ||
|
|
||
| @Override | ||
| public List<Tree.Kind> nodesToVisit() { | ||
| // raise issues only when they appear in the same block | ||
| return ImmutableList.of(Tree.Kind.BLOCK); | ||
| } | ||
|
|
||
| @Override | ||
| public void visitNode(Tree tree) { | ||
| Map<Symbol, Integer> forEachSymbols = new HashMap<>(); | ||
| Set<Tree> forEachIterables = new HashSet<>(); | ||
| for (Tree item : ((BlockTree) tree).body()) { | ||
| if (item.is(Tree.Kind.FOR_EACH_STATEMENT)) { | ||
| checkForEach(forEachSymbols, forEachIterables, (ForEachStatement) item); | ||
| } else { | ||
| item.accept(new InvalidatorVisitor(forEachSymbols)); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private void checkForEach(Map<Symbol, Integer> forEachSymbols, Set<Tree> forEachIterables, ForEachStatement item) { | ||
| ExpressionTree expressionTree = ExpressionsHelper.skipParentheses(item.expression()); | ||
| if (expressionTree.is(Tree.Kind.IDENTIFIER)) { | ||
| checkForEachIdentifier(forEachSymbols, (IdentifierTree) expressionTree); | ||
| } else { | ||
| checkForEachExpression(forEachIterables, expressionTree); | ||
| } | ||
| } | ||
|
|
||
| private void checkForEachExpression(Set<Tree> forEachIterables, ExpressionTree expressionTree) { | ||
| for (Tree subTree : forEachIterables) { | ||
| if (SyntacticEquivalence.areEquivalent(expressionTree, subTree)) { | ||
| addIssue(expressionTree, FirstSyntaxTokenFinder.firstSyntaxToken(subTree).line()); | ||
| return; | ||
| } | ||
| } | ||
| forEachIterables.add(expressionTree); | ||
| } | ||
|
|
||
| private void checkForEachIdentifier(Map<Symbol, Integer> forEachSymbols, IdentifierTree node) { | ||
| Symbol symbol = node.symbol(); | ||
| if (forEachSymbols.containsKey(symbol)) { | ||
| addIssue(node, forEachSymbols.get(symbol)); | ||
| } else { | ||
| forEachSymbols.put(symbol, ((JavaTree) node).getLine()); | ||
| } | ||
| } | ||
|
|
||
| private void addIssue(Tree tree, int line) { | ||
| addIssue(tree, "Combine this loop with the one that starts on line " + line + "."); | ||
| } | ||
|
|
||
| private static class InvalidatorVisitor extends BaseTreeVisitor { | ||
| private final Map<Symbol, Integer> forEachSymbols; | ||
|
|
||
| InvalidatorVisitor(Map<Symbol, Integer> forEachSymbols) { | ||
| this.forEachSymbols = forEachSymbols; | ||
| } | ||
|
|
||
| @Override | ||
| public void visitIdentifier(IdentifierTree tree) { | ||
| Symbol symbol = tree.symbol(); | ||
| if (forEachSymbols.containsKey(symbol)) { | ||
| forEachSymbols.remove(symbol); | ||
| } | ||
| super.visitIdentifier(tree); | ||
| } | ||
| } | ||
| } | ||
28 changes: 28 additions & 0 deletions
28
java-checks/src/main/resources/org/sonar/l10n/java/rules/squid/S3047.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,28 @@ | ||
| <p> | ||
| When a method loops multiple over the same set of data, | ||
| whether it's a list or a set of numbers, | ||
| it is highly likely that the method could be made more efficient by combining | ||
| the loops into a single set of iterations. | ||
| </p> | ||
|
|
||
| <h2>Noncompliant Code Example</h2> | ||
| <pre> | ||
| public void doSomethingToAList(List<String> strings) { | ||
| for (String str : strings) { | ||
| doStep1(str); | ||
| } | ||
| for (String str : strings) { // Noncompliant | ||
| doStep2(str); | ||
| } | ||
| } | ||
| </pre> | ||
|
|
||
| <h2>Compliant Solution</h2> | ||
| <pre> | ||
| public void doSomethingToAList(List<String> strings) { | ||
| for (String str : strings) { | ||
| doStep1(str); | ||
| doStep2(str); | ||
| } | ||
| } | ||
| </pre> |
39 changes: 39 additions & 0 deletions
39
java-checks/src/test/files/checks/LoopsOnSameSetCheck.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,39 @@ | ||
|
|
||
| import java.lang.Object; | ||
| import java.util.List; | ||
|
|
||
| public class A { | ||
| private List<String> getList() { | ||
| return null; | ||
| } | ||
|
|
||
| public void doSomethingToAList(List<String> strings, List<String> strings2) { | ||
| for (String str : strings); | ||
| for (String str : strings); // Noncompliant {{Combine this loop with the one that starts on line 11.}} | ||
| strings = null; | ||
| for (String str : strings); // strings get reassigned | ||
| for (String str : getList()); | ||
| for (String str : getList()); // Noncompliant {{Combine this loop with the one that starts on line 15.}} | ||
| for (String str : foo()); | ||
| List<String> list = null; | ||
| for (String str : list); | ||
| for (String str : list); // Noncompliant {{Combine this loop with the one that starts on line 19.}} | ||
| if (list.size() > 10) { | ||
| list.remove(0); | ||
| } | ||
| for (String str : list); | ||
| if (true) { | ||
| for (String str : strings2); | ||
| } else { | ||
| for (String str : strings2); | ||
| } | ||
| getList().remove(0); | ||
| Object obj = new Object() { | ||
| void foo() { | ||
| for (String str : strings) { | ||
| doStep2(str); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| } |
32 changes: 32 additions & 0 deletions
32
java-checks/src/test/java/org/sonar/java/checks/LoopsOnSameSetCheckTest.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,32 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) 2012 SonarSource | ||
| * sonarqube@googlegroups.com | ||
| * | ||
| * This program is free software; you can redistribute it and/or | ||
| * modify it under the terms of the GNU Lesser General Public | ||
| * License as published by the Free Software Foundation; either | ||
| * version 3 of the License, or (at your option) any later version. | ||
| * | ||
| * 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 GNU | ||
| * Lesser General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU Lesser General Public | ||
| * License along with this program; if not, write to the Free Software | ||
| * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import org.junit.Test; | ||
| import org.sonar.java.checks.verifier.JavaCheckVerifier; | ||
|
|
||
| public class LoopsOnSameSetCheckTest { | ||
|
|
||
| @Test | ||
| public void test() { | ||
| JavaCheckVerifier.verify("src/test/files/checks/LoopsOnSameSetCheck.java", new LoopsOnSameSetCheck()); | ||
| } | ||
|
|
||
| } |
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.
Instead of casting to a
JavaTreeto get the line , preferably usenode.identifierToken().line()as it will improve the efficiency.