You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
False error: a counter updated in a loop is only known by the loop condition (for (int i = 0; i < 10; i++) does not prove i >= 0) #537
A local variable that a loop body updates is known inside the body only through the loop condition. Everything else that holds for it (its initial value, and that the update keeps it in range) is forgotten, so an ordinary counter such as for (int i = 0; i < 10; i++) is not known to be >= 0 inside the loop.
Refinement Error: found `i < 10` but expected `i >= 0`
5 | static void fill() {
6 | for (int i = 0; i < 10; i++) {
7 | use(i);
| ^^^^^^^
8 | }
9 | }
--> Counterexample: `i == -1`
Expected: Correct! Passed Verification. The counterexample i == -1 cannot happen: i starts at 0 and only grows.
The same happens with a while loop and an accumulator:
inttotal = 0;
while (total < 1024) {
use(total); // found `total < 1024` but expected `total >= 0`total = total + 1;
}
Workaround
Annotating the variable gives the verifier the invariant, and the loop is then accepted:
@Refinement("_ >= 0") inttotal = 0;
The message does not suggest this, and for a for loop counter it is unusual to write.
Why it matters
This is the standard way to fill a buffer from a stream:
inttotal = 0;
while (total < limit) {
intn = in.read(buf, total, limit - total); // off is refined with _ >= 0if (n < 0) break;
total += n;
}
With a spec that refines read(byte[] b, int off, int len) with off >= 0, this loop is rejected. In a small experiment where coding agents implemented a method against such a spec, 23 of 30 implementations that behaved correctly were rejected for this loop alone, and with the verifier available every agent needed one or more extra rounds to rewrite correct code.
Possible directions: keep i >= c (or <= c) for a variable that starts at a constant and is only incremented (decremented) in the body; or, when the error is on a variable assigned in an enclosing loop, say in the message that the loop forgets what was known about it and that a @Refinement on the variable's declaration states the invariant.
Related: #479 (the list's ghost is also forgotten at the loop head; it notes the missing i >= 0 in passing), #306 (loop condition assumed in the body, fixed).
Activity
Keep path conditions on the old value when a variable is reassigned (#…
Add the candidate invariants of the int locals a loop changes (#550)