Skip to content

Commit 84dd629

Browse files
Know the invariants and the negated condition after a loop without break (#552)
Stacked on #551; review/merge after it. Fixes #545 Part of the loop invariant inference plan (#542). ## What and why After a loop, the variables it changes were havocked again: only their declared refinements were known, so after `int i = 0; while (i < n) i++;` nothing said `i >= n`. Now, after a loop that can only exit at its head through its condition, the instances after the loop get the invariants inferred in #551 and the negated condition: - `exitsAtHeadThroughCondition`: a `while`, `for` or for-each loop (not a `do`-`while`), with no `break` whose target is the loop (labelled or not), and a condition that writes no variable. - `InvariantCandidates.condition` translates the condition when it is built of `&&`, `||`, `!` and comparisons (`<`, `<=`, `>`, `>=`, `==`, `!=`) of the terms a candidate may mention (int literals, int locals and parameters, `+`, `-`, `*`); otherwise only the invariants are added. - `LoopInvariants.afterLoop` adds them to the post-loop instances (after the existing havoc), like the head facts. Also (found by the Codex review): `TryChecker` starts a catch block from any value a variable had in the try block, including values recorded in loop-body checks that name join instances of a dropped check. The post-loop instance used to be `true`, which hid them; with facts after the loop they surfaced as `Variable #i_11 could not be found` (already the case on main for a refined variable). The variable is now unknown in the catch block when such a value is among them. ## Soundness argument - The invariants hold at the loop head on every visit (#551), including the last one, where the condition is evaluated to false and the loop exits. - For `while`/`for` without `break`, the code after the loop is reached only from that point (a `return`, `throw` or labelled jump to an outer statement does not reach it), and the condition writes nothing, so the state after the loop is the head state where the condition was false: the invariants and the negated condition describe it. - A `do`-`while` exits after its body and condition, where the head invariants need not hold (`do { i = i + 5; } while (i < 3);` keeps `i <= 3` at the head but exits with `i == 5`), so it is excluded. A condition with a side effect (`while (i++ < 10)`) exits in a state after the head, so it is excluded too. - The negated condition is built from the same Java expression with pure terms only, so it means what the condition meant at the exit. - Making a variable unknown in a catch block only removes facts. ## Before / after `int i = 0; while (i < n) i++; atLeast(i, n);` (`@Refinement("_ <= i") int n`): before `Refinement Error` (only `i`'s declared refinement known), after `Correct`. `for (; i < 10; i++) { if (next()) continue; } ten(i);` (`_ == 10`): before `Refinement Error`, after `Correct` (invariant `i <= 10` and `!(i < 10)`). ## Tests - `CorrectLoopExitFacts` (the first two fail on #551 alone): `i >= n` after counting up with `while`; `i == 10` after a `for` whose body has a continue; a loop in a try with a catch (spurious `Not Found Error` without the `TryChecker` change). - `ErrorLoopExitFacts`: no negated condition after a loop with `break`; none after a `do`-`while` (the example above); none after a condition that increments (`while (i++ < 10)` exits with `i == 11`). - `InvariantCandidatesTest.translatesConditionsOverTheSameTerms`: `!`, `||`, `&&`, `==`, `!=` translated; conditions with calls or a literal `true` not. Full suite passes locally. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3e46ea2 commit 84dd629

7 files changed

Lines changed: 161 additions & 1 deletion

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package testSuite;
2+
3+
import liquidjava.specification.Refinement;
4+
5+
// After a loop that only exits through its condition, the invariants hold and the condition is false
6+
@SuppressWarnings("unused")
7+
public class CorrectLoopExitFacts {
8+
static boolean next() {
9+
return true;
10+
}
11+
12+
static void atLeast(int i, @Refinement("_ <= i") int n) {}
13+
14+
static void ten(@Refinement("_ == 10") int x) {}
15+
16+
static void countUp(int n) {
17+
int i = 0;
18+
while (i < n) {
19+
i++;
20+
}
21+
atLeast(i, n);
22+
}
23+
24+
static void countUpWithContinue() {
25+
int i = 0;
26+
for (; i < 10; i++) {
27+
if (next())
28+
continue;
29+
}
30+
ten(i);
31+
}
32+
33+
// the catch block may start from any value i had in the loop
34+
static void loopInTry(boolean fail) {
35+
int i = 0;
36+
try {
37+
while (i < 10) {
38+
if (fail)
39+
throw new RuntimeException();
40+
i++;
41+
}
42+
} catch (RuntimeException e) {
43+
}
44+
if (i != 10)
45+
return;
46+
ten(i);
47+
}
48+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package testSuite;
2+
3+
import liquidjava.specification.Refinement;
4+
5+
// After a loop that may exit elsewhere than at its condition, the condition is not known to be false
6+
@SuppressWarnings("unused")
7+
public class ErrorLoopExitFacts {
8+
static boolean next() {
9+
return true;
10+
}
11+
12+
static void atLeast(int i, @Refinement("_ <= i") int n) {}
13+
14+
static void atMostThree(@Refinement("_ <= 3") int x) {}
15+
16+
static void ten(@Refinement("_ == 10") int x) {}
17+
18+
static void exitByBreak(int n) {
19+
int i = 0;
20+
while (i < n) {
21+
if (next())
22+
break;
23+
i++;
24+
}
25+
atLeast(i, n); // Expect: Refinement Error
26+
}
27+
28+
// i <= 3 holds at the start of each iteration, but the loop exits after the body, with i == 5
29+
static void doWhile() {
30+
int i = 0;
31+
do {
32+
i = i + 5;
33+
} while (i < 3);
34+
atMostThree(i); // Expect: Refinement Error
35+
}
36+
37+
// the condition increments i after it is checked, so the loop exits with i == 11
38+
static void conditionWithUpdate() {
39+
int i = 0;
40+
while (i++ < 10) {
41+
}
42+
ten(i); // Expect: Refinement Error
43+
}
44+
}

‎liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/InvariantCandidates.java‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,36 @@ private static String nonStrict(BinaryOperatorKind kind) {
9696
};
9797
}
9898

99+
/**
100+
* The predicate a loop condition stands for, if it is built of {@code &&}, {@code ||}, {@code !} and comparisons of
101+
* the terms a candidate may mention
102+
*/
103+
static Optional<Predicate> condition(CtExpression<?> condition) {
104+
if (condition instanceof CtUnaryOperator<?> operator && operator.getKind() == UnaryOperatorKind.NOT)
105+
return condition(operator.getOperand()).map(Predicate::negate);
106+
if (!(condition instanceof CtBinaryOperator<?> operator))
107+
return Optional.empty();
108+
String op = switch (operator.getKind()) {
109+
case AND -> Ops.AND;
110+
case OR -> Ops.OR;
111+
case LT -> Ops.LT;
112+
case LE -> Ops.LE;
113+
case GT -> Ops.GT;
114+
case GE -> Ops.GE;
115+
case EQ -> Ops.EQ;
116+
case NE -> Ops.NEQ;
117+
default -> null;
118+
};
119+
boolean logical = operator.getKind() == BinaryOperatorKind.AND || operator.getKind() == BinaryOperatorKind.OR;
120+
Optional<Predicate> left = logical ? condition(operator.getLeftHandOperand())
121+
: term(operator.getLeftHandOperand());
122+
Optional<Predicate> right = logical ? condition(operator.getRightHandOperand())
123+
: term(operator.getRightHandOperand());
124+
if (op == null || left.isEmpty() || right.isEmpty())
125+
return Optional.empty();
126+
return Optional.of(Predicate.createOperation(left.get(), op, right.get()));
127+
}
128+
99129
/** The integer term an expression stands for, if it is built only of what a candidate may mention */
100130
private static Optional<Predicate> term(CtExpression<?> expression) {
101131
if (expression instanceof CtLiteral<?> literal && literal.getValue()instanceof Integer value)

‎liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariants.java‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,16 @@ boolean reachedFixpoint() {
132132
return !dropped;
133133
}
134134

135+
/**
136+
* After a loop that only exits through its condition, once what it changes is forgotten: the variables satisfy the
137+
* invariants, and the condition is false, as at the loop head where it exited
138+
*/
139+
void afterLoop() {
140+
List<Predicate> facts = new ArrayList<>(candidates);
141+
InvariantCandidates.condition(condition(loop)).ifPresent(condition -> facts.add(condition.negate()));
142+
addToLastInstances(facts);
143+
}
144+
135145
/** The candidates, and that each variable grew or shrank since the loop head, that are proved here */
136146
private List<Predicate> provedForNextIteration() {
137147
List<Predicate> facts = new ArrayList<>(candidates);
@@ -180,7 +190,8 @@ private Predicate onLastInstances(Predicate fact) {
180190
return result;
181191
}
182192

183-
private static CtExpression<Boolean> condition(CtLoop loop) {
193+
/** The condition of a loop, or null if it has none */
194+
static CtExpression<Boolean> condition(CtLoop loop) {
184195
if (loop instanceof CtWhile whileLoop)
185196
return whileLoop.getLoopingExpression();
186197
if (loop instanceof CtDo doLoop)

‎liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/RefinementTypeChecker.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1015,6 +1015,8 @@ private void visitLoop(CtLoop loop, Consumer<LoopTypestates> iteration) {
10151015
}
10161016
vcChecker.restorePathVariables(pathVariables);
10171017
havocChangedIn(loop, states.tracked());
1018+
if (exitsAtHeadThroughCondition(loop))
1019+
loopInvariants.afterLoop();
10181020
states.finishLoop();
10191021
}
10201022

@@ -1109,6 +1111,18 @@ private void scanBody(CtLoop loop, LoopTypestates states) {
11091111
loopInvariants.endBody(completes);
11101112
}
11111113

1114+
/**
1115+
* Whether the code after a loop is only reached from its head, where the condition is false: the loop is not a
1116+
* do-while, which exits after its body, no break leaves it, and its condition writes no variable
1117+
*/
1118+
private static boolean exitsAtHeadThroughCondition(CtLoop loop) {
1119+
CtExpression<Boolean> condition = LoopInvariants.condition(loop);
1120+
return !(loop instanceof CtDo)
1121+
&& loop.getElements(new TypeFilter<>(CtBreak.class)).stream()
1122+
.noneMatch(jump -> jumpTarget(jump) == loop)
1123+
&& (condition == null || condition.getElements(new TypeFilter<>(CtVariableWrite.class)).isEmpty());
1124+
}
1125+
11121126
/** The loop being checked that {@code jump} leaves, if any */
11131127
private Optional<LoopTypestates> loopLeftBy(CtLabelledFlowBreak jump) {
11141128
CtElement target = jumpTarget(jump);

‎liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/TryChecker.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,10 @@ private void addAnyOfInstances(Map<Variable, VariableInstance> before,
186186
for (VariableInstance vi : instances)
187187
anyOf = Predicate.createDisjunction(anyOf, vi.getRenamedRefinements(name));
188188
}
189+
// a recorded instance may refer to values of a block that ended (e.g. a loop body checked again), which
190+
// are no longer known: the variable is then unknown
191+
if (anyOf.getVariableNames().stream().anyMatch(n -> !n.equals(name) && !context.hasVariable(n)))
192+
anyOf = new Predicate();
189193
context.addInstanceToContext(name, v.getType(), anyOf, element);
190194
context.addRefinementInstanceToVariable(v.getName(), name);
191195
});

‎liquidjava-verifier/src/test/java/liquidjava/processor/refinement_checker/InvariantCandidatesTest.java‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,15 @@ void atMostAFixedNumberPerVariable() {
6767
.size());
6868
}
6969

70+
@Test
71+
void translatesConditionsOverTheSameTerms() {
72+
// printed without parentheses
73+
assertEquals("!i < n || i == 0 && i != n", InvariantCandidates
74+
.condition(condition("!(i < n) || i == 0 && i != n")).map(Predicate::toString).orElseThrow());
75+
assertEquals(Optional.empty(), InvariantCandidates.condition(condition("i < n && i < size()")));
76+
assertEquals(Optional.empty(), InvariantCandidates.condition(condition("true")));
77+
}
78+
7079
private static List<String> candidates(String variable, String before, String condition) {
7180
return InvariantCandidates.of(variable, Optional.ofNullable(before), condition(condition)).stream()
7281
.map(Predicate::toString).toList();

0 commit comments

Comments
 (0)