Skip to content

Commit 0d7f6ce

Browse files
authored
Merge pull request github#5334 from Marcono1234/marcono1234/improve-constant-loop-condition
Java: Improve constant-loop-condition
2 parents d7b9251 + e9e9634 commit 0d7f6ce

File tree

3 files changed

+15
-4
lines changed

3 files changed

+15
-4
lines changed

java/ql/src/Likely Bugs/Termination/ConstantLoopCondition.ql

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,11 @@ where
7979
) and
8080
// And `cond` does not use method calls, field reads, or array reads.
8181
not exists(MethodAccess ma | ma.getParent*() = cond) and
82-
not exists(FieldRead fa | fa.getParent*() = cond) and
82+
not exists(FieldRead fa |
83+
// Ignore if field is final
84+
not fa.getField().isFinal() and
85+
fa.getParent*() = cond
86+
) and
8387
not exists(ArrayAccess aa | aa.getParent*() = cond)
8488
select cond, "$@ might not terminate, as this loop condition is constant within the loop.", loop,
8589
"Loop"

java/ql/test/query-tests/ConstantLoopCondition/A.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
class A {
2+
final boolean cond = otherCond();
3+
24
boolean otherCond() { return 3 > 5; }
35

46
void f(int initx) {
@@ -30,5 +32,9 @@ void f(int initx) {
3032
while(initx > 0) { // OK: loop used as an if-statement
3133
break;
3234
}
35+
36+
while (cond) { // BAD: read of final field
37+
i++;
38+
}
3339
}
3440
}
Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1-
| A.java:6:11:6:15 | !... | $@ might not terminate, as this loop condition is constant within the loop. | A.java:6:5:6:16 | stmt | Loop |
2-
| A.java:13:11:13:15 | ... > ... | $@ might not terminate, as this loop condition is constant within the loop. | A.java:12:5:12:19 | stmt | Loop |
3-
| A.java:27:20:27:32 | ... < ... | $@ might not terminate, as this loop condition is constant within the loop. | A.java:27:5:27:38 | stmt | Loop |
1+
| A.java:8:11:8:15 | !... | $@ might not terminate, as this loop condition is constant within the loop. | A.java:8:5:8:16 | stmt | Loop |
2+
| A.java:15:11:15:15 | ... > ... | $@ might not terminate, as this loop condition is constant within the loop. | A.java:14:5:14:19 | stmt | Loop |
3+
| A.java:29:20:29:32 | ... < ... | $@ might not terminate, as this loop condition is constant within the loop. | A.java:29:5:29:38 | stmt | Loop |
4+
| A.java:36:12:36:15 | cond | $@ might not terminate, as this loop condition is constant within the loop. | A.java:36:5:36:16 | stmt | Loop |

0 commit comments

Comments
 (0)