Skip to content

Commit

Permalink
Improve rule EC67 green-code-initiative#4
Browse files Browse the repository at this point in the history
Ignore rule EC67 when i++ is located within a binary expression
  • Loading branch information
hocinehacherouf committed May 29, 2024
1 parent 716fe9b commit f95b8c0
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@

import org.sonar.check.Rule;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.tree.BinaryExpressionTree;
import org.sonar.plugins.java.api.tree.Tree;
import org.sonar.plugins.java.api.tree.Tree.Kind;
import org.sonar.plugins.java.api.tree.UnaryExpressionTree;
import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey;

@Rule(key = "EC67")
Expand All @@ -39,6 +41,11 @@ public List<Kind> nodesToVisit() {

@Override
public void visitNode(Tree tree) {
var unaryExpressionTree = (UnaryExpressionTree) tree;

if (unaryExpressionTree.parent() instanceof BinaryExpressionTree) {
return;
}
reportIssue(tree, MESSAGERULE);
}
}
31 changes: 31 additions & 0 deletions src/test/files/IncrementCheckBinaryExpression.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs
* Copyright © 2023 Green Code Initiative (https://www.ecocode.io)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class MyClass2 {
MyClass(MyClass mc) {
}
void unaryExpressionWithinBinaryExpression() {
var i = 0;
for (int j=0; j < 10; ++j) {
System.out.println("test" + i++);
System.out.println(2 + i++);
System.out.println(2 - i++);
System.out.println(2 * i++);
System.out.println(2 / i++);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,12 @@ void test() {
.verifyIssues();
}

@Test
void incrementCheck_unaryExpressionWithinBinaryExpression_noIssue() {
CheckVerifier.newVerifier()
.onFile("src/test/files/IncrementCheckBinaryExpression.java")
.withCheck(new IncrementCheck())
.verifyNoIssues();
}

}

0 comments on commit f95b8c0

Please sign in to comment.