Skip to content

Commit 3fed0e9

Browse files
Know the invariants and the negated condition after a loop
After a while or for loop that only exits at its head, through its condition (no break leaves it and its condition writes no variable), the instances after the loop now satisfy the inferred invariants and the negated condition, when the condition is built of comparisons of the terms a candidate may mention. A do-while exits after its body, where the invariants of the head need not hold, so it keeps only the declared refinements, as do loops with a break. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 3e46ea2 commit 3fed0e9

6 files changed

Lines changed: 140 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
}
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: 10 additions & 0 deletions
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);

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

Lines changed: 15 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,19 @@ 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 = loop instanceof CtWhile whileLoop ? whileLoop.getLoopingExpression()
1120+
: loop instanceof CtFor forLoop ? forLoop.getExpression() : null;
1121+
return !(loop instanceof CtDo)
1122+
&& loop.getElements(new TypeFilter<>(CtBreak.class)).stream()
1123+
.noneMatch(jump -> jumpTarget(jump) == loop)
1124+
&& (condition == null || condition.getElements(new TypeFilter<>(CtVariableWrite.class)).isEmpty());
1125+
}
1126+
11121127
/** The loop being checked that {@code jump} leaves, if any */
11131128
private Optional<LoopTypestates> loopLeftBy(CtLabelledFlowBreak jump) {
11141129
CtElement target = jumpTarget(jump);

‎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)