diff --git a/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java index 00c3094..76b8057 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java @@ -39,6 +39,8 @@ public List nodesToVisit() { @Override public void visitNode(Tree tree) { - reportIssue(tree, MESSAGERULE); + if (tree.parent().is(Kind.EXPRESSION_STATEMENT)) { + reportIssue(tree, MESSAGERULE); + } } } diff --git a/src/test/files/IncrementCheck.java b/src/test/files/IncrementCheck.java index 6e7e6c2..b31ffa8 100644 --- a/src/test/files/IncrementCheck.java +++ b/src/test/files/IncrementCheck.java @@ -18,10 +18,15 @@ class IncrementCheck { IncrementCheck(IncrementCheck mc) { } - + int foo1() { int counter = 0; - return counter++; // Noncompliant {{Use ++i instead of i++}} + return counter++; // Compliant but should raise a java:S2123 and a java:S1854 + } + + private int j = 0; + int foo10() { + return this.j++; // Compliant because maybe the use case needs to return j AND increment it } int foo11() { @@ -29,35 +34,55 @@ int foo11() { return ++counter; } - void foo2(int value) { + int foo2() { int counter = 0; counter++; // Noncompliant {{Use ++i instead of i++}} + return counter; } - void foo22(int value) { + int foo22() { int counter = 0; ++counter; + return counter; } - void foo3(int value) { + int foo3() { int counter = 0; counter = counter + 197845 ; + return counter; } - void foo4(int value) { - int counter =0; + int foo4() { + int counter = 0; counter = counter + 35 + 78 ; + return counter; } - void foo50(int value) { + void foo50() { for (int i=0; i < 10; i++) { // Noncompliant {{Use ++i instead of i++}} - System.out.println(i); + System.out.println(i); //NOSONAR } } - void foo51(int value) { + void foo51() { for (int i=0; i < 10; ++i) { - System.out.println(i); + System.out.println(i); //NOSONAR } } + + void bar61(int value) { + // For test purpose + } + + int foo61() { + int i = 0; + bar61(i++); // Compliant because maybe bar61 needs the unincremented value + return i; + } + + int foo62() { + int i = 0; + bar61(2 + i++); // Compliant because maybe bar61 needs the unincremented value + return i; + } } \ No newline at end of file