Skip to content

Commit a0aee6f

Browse files
Infer loop invariants for the int locals a loop changes
A loop forgot everything about the int locals it changes but their declared refinements, so for (int i = 0; i < 10; i++) use(i) did not know i >= 0. With the Houdini algorithm, the candidate invariants that the facts before the loop prove are added to the instances at the loop head; each check of the body drops those not proved where the next iteration starts (end of the body, after a for's update, after a do-while's condition, which now holds there), until none is dropped, within the loop that already re-checks the body until its typestates are stable. The candidate proofs are silent. Where continues join at the end of the body, the candidates and whether each variable grew or shrank since the head are kept when proved at every continue and at the end of the body. After 8 checks that dropped candidates, all are dropped. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent be89891 commit a0aee6f

4 files changed

Lines changed: 412 additions & 12 deletions

File tree

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package testSuite;
2+
3+
import liquidjava.specification.Refinement;
4+
5+
// Facts about the int locals a loop changes that hold on every iteration are inferred (#537)
6+
@SuppressWarnings("unused")
7+
public class CorrectLoopInvariants {
8+
static boolean next() {
9+
return true;
10+
}
11+
12+
static int read(byte[] buffer, @Refinement("_ >= 0") int offset, int length) {
13+
return 0;
14+
}
15+
16+
static void use(@Refinement("_ >= 0") int x) {}
17+
18+
static void counter() {
19+
for (int i = 0; i < 10; i++) {
20+
use(i);
21+
}
22+
}
23+
24+
static void accumulator() {
25+
int total = 0;
26+
while (total < 1024) {
27+
use(total);
28+
total = total + 1;
29+
}
30+
}
31+
32+
static void fill(byte[] buffer, int limit) {
33+
int total = 0;
34+
while (total < limit) {
35+
int n = read(buffer, total, limit - total);
36+
if (n < 0)
37+
break;
38+
total += n;
39+
}
40+
}
41+
42+
static void symbolicStart(int k) {
43+
if (k < 0)
44+
return;
45+
for (int i = k; i < 100; i++) {
46+
use(i);
47+
}
48+
}
49+
50+
static void nested() {
51+
for (int i = 0; i < 10; i++) {
52+
for (int j = i; j < 10; j++) {
53+
use(i);
54+
use(j);
55+
}
56+
}
57+
}
58+
59+
// a continue goes on to the update
60+
static void continueInFor() {
61+
for (int i = 0; i < 10; i++) {
62+
if (next())
63+
continue;
64+
use(i);
65+
}
66+
}
67+
68+
static void continueInWhile() {
69+
int i = 0;
70+
while (i < 10) {
71+
use(i);
72+
if (next()) {
73+
i++;
74+
continue;
75+
}
76+
i = i + 2;
77+
}
78+
}
79+
80+
static void continueInDoWhile() {
81+
int i = 0;
82+
do {
83+
use(i);
84+
if (next()) {
85+
i++;
86+
continue;
87+
}
88+
i = i + 2;
89+
} while (i < 10);
90+
}
91+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package testSuite;
2+
3+
import liquidjava.specification.Refinement;
4+
5+
// Only facts that hold before a loop and are kept by every iteration are inferred for its int locals (#537)
6+
@SuppressWarnings("unused")
7+
public class ErrorLoopInvariants {
8+
static boolean next() {
9+
return true;
10+
}
11+
12+
static void use(@Refinement("_ >= 0") int x) {}
13+
14+
static void atMostTen(@Refinement("_ <= 10") int x) {}
15+
16+
static void decrementing() {
17+
for (int i = 10; i > -5; i--) {
18+
use(i); // Expect: Refinement Error
19+
}
20+
}
21+
22+
static void resetInBody() {
23+
int i = 0;
24+
while (i < 10) {
25+
use(i); // Expect: Refinement Error
26+
i = i + 1;
27+
if (next())
28+
i = -1;
29+
}
30+
}
31+
32+
static void decreasedOnSomePath() {
33+
int i = 0;
34+
while (i < 10) {
35+
use(i); // Expect: Refinement Error
36+
if (next())
37+
i = i - 2;
38+
else
39+
i++;
40+
}
41+
}
42+
43+
// i < 10 does not give i <= 10 at the next iteration, as i grows by 3
44+
static void boundNotKept() {
45+
int i = 0;
46+
while (i < 10) {
47+
i = i + 3;
48+
atMostTen(i); // Expect: Refinement Error
49+
}
50+
}
51+
52+
static void decreasedBeforeContinue() {
53+
int i = 0;
54+
while (i < 10) {
55+
use(i); // Expect: Refinement Error
56+
if (next()) {
57+
i = i - 1;
58+
continue;
59+
}
60+
i++;
61+
}
62+
}
63+
64+
// the continue skips the use but not the update, which starts the next iteration from i - 5 + 1
65+
static void decreasedBeforeContinueInFor() {
66+
for (int i = 0; i < 10; i++) {
67+
if (next()) {
68+
i = i - 5;
69+
continue;
70+
}
71+
use(i); // Expect: Refinement Error
72+
}
73+
}
74+
75+
static void decreasedInInnerLoop() {
76+
int i = 0;
77+
while (i < 10) {
78+
use(i); // Expect: Refinement Error
79+
for (int j = 0; j < 5; j++) {
80+
i = i - 1;
81+
}
82+
i++;
83+
}
84+
}
85+
}
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
package liquidjava.processor.refinement_checker;
2+
3+
import java.util.ArrayList;
4+
import java.util.IdentityHashMap;
5+
import java.util.LinkedHashMap;
6+
import java.util.List;
7+
import java.util.Map;
8+
import java.util.Optional;
9+
10+
import liquidjava.diagnostics.errors.LJError;
11+
import liquidjava.processor.context.RefinedVariable;
12+
import liquidjava.processor.context.VariableInstance;
13+
import liquidjava.rj_language.Predicate;
14+
import liquidjava.utils.constants.Ops;
15+
import spoon.reflect.code.CtDo;
16+
import spoon.reflect.code.CtExpression;
17+
import spoon.reflect.code.CtFor;
18+
import spoon.reflect.code.CtLoop;
19+
import spoon.reflect.code.CtWhile;
20+
21+
/**
22+
* The invariants inferred for the {@code int} local variables a loop changes, with the Houdini algorithm (Flanagan and
23+
* Leino): of their candidates (see {@link InvariantCandidates}), those that the facts before the loop prove are assumed
24+
* at the loop head; each check of the body drops those not proved where the next iteration starts, until a check drops
25+
* none. What remains holds before the loop and after every iteration that goes on to the next one, so it holds at the
26+
* loop head on every iteration. The proofs are silent: a candidate that is not proved is only dropped.
27+
*
28+
* <p>
29+
* Where the continues of the body join, at its end, the values of what the loop changes are forgotten. The facts proved
30+
* at every continue and at the end of the body are kept there: the candidates, and whether each variable grew or shrank
31+
* since the loop head.
32+
*/
33+
class LoopInvariants {
34+
35+
/** The most checks of the body that drop candidates, after which all are dropped */
36+
static final int MAX_ROUNDS = 8;
37+
38+
private final RefinementTypeChecker checker;
39+
private final CtLoop loop;
40+
private final List<String> variables;
41+
private final List<Predicate> candidates = new ArrayList<>();
42+
// the instance of each variable at the loop head
43+
private final Map<String, VariableInstance> head = new LinkedHashMap<>();
44+
// the refinement of each instance before facts were added to it
45+
private final Map<VariableInstance, Predicate> declared = new IdentityHashMap<>();
46+
private int rounds;
47+
private boolean dropped;
48+
// whether the point of the iteration being checked can be reached
49+
private boolean reachable;
50+
// the facts proved at every continue reached so far, null if none was reached
51+
private List<Predicate> atContinues;
52+
53+
/**
54+
* Keeps the candidates that the facts before the loop prove; to be created before what the loop changes is
55+
* forgotten
56+
*
57+
* @param variables
58+
* the {@code int} local variables the loop changes
59+
*/
60+
LoopInvariants(RefinementTypeChecker checker, CtLoop loop, List<String> variables) {
61+
this.checker = checker;
62+
this.loop = loop;
63+
this.variables = variables;
64+
for (String variable : variables) {
65+
Optional<String> before = checker.getContext().getLastVariableInstance(variable)
66+
.map(RefinedVariable::getName);
67+
for (Predicate candidate : InvariantCandidates.of(variable, before, condition(loop)))
68+
if (!candidates.contains(candidate) && proved(candidate))
69+
candidates.add(candidate);
70+
}
71+
}
72+
73+
/** Starts checking an iteration: the variables at the loop head satisfy the candidates */
74+
void startIteration() {
75+
for (String variable : variables)
76+
checker.getContext().getLastVariableInstance(variable).ifPresent(instance -> head.put(variable, instance));
77+
addToLastInstances(candidates);
78+
dropped = false;
79+
reachable = true;
80+
atContinues = null;
81+
}
82+
83+
void recordContinue() {
84+
List<Predicate> proved = provedForNextIteration();
85+
if (atContinues != null)
86+
proved.retainAll(atContinues);
87+
atContinues = proved;
88+
}
89+
90+
/**
91+
* At the end of the body, where its continues join, before the values there are forgotten
92+
*
93+
* @param completes
94+
* whether the end of the body can be reached without a continue
95+
*
96+
* @return the facts that hold on every path that reaches the join, for {@link #joined}
97+
*/
98+
List<Predicate> atJoin(boolean completes) {
99+
if (completes)
100+
recordContinue();
101+
return atContinues == null ? List.of() : atContinues;
102+
}
103+
104+
/** After the continues joined: the new instances of the variables satisfy the facts {@link #atJoin} returned */
105+
void joined(List<Predicate> facts) {
106+
addToLastInstances(facts);
107+
}
108+
109+
/**
110+
* Marks the end of the body
111+
*
112+
* @param completes
113+
* whether the end of the body can be reached without a continue
114+
*/
115+
void endBody(boolean completes) {
116+
reachable = completes || atContinues != null;
117+
}
118+
119+
/** The next iteration starts here, if this point is reachable: drops the candidates not proved here */
120+
void recordNextIteration() {
121+
if (reachable)
122+
dropped |= candidates.removeIf(candidate -> !proved(candidate));
123+
}
124+
125+
/**
126+
* Whether the iteration just checked dropped no candidate, so it is the last one to check. Once {@link #MAX_ROUNDS}
127+
* checks dropped some, all are dropped.
128+
*/
129+
boolean reachedFixpoint() {
130+
if (dropped && ++rounds >= MAX_ROUNDS)
131+
candidates.clear();
132+
return !dropped;
133+
}
134+
135+
/** The candidates, and that each variable grew or shrank since the loop head, that are proved here */
136+
private List<Predicate> provedForNextIteration() {
137+
List<Predicate> facts = new ArrayList<>(candidates);
138+
head.forEach((variable, instance) -> {
139+
Predicate name = Predicate.createVar(variable), atHead = Predicate.createVar(instance.getName());
140+
facts.add(Predicate.createOperation(name, Ops.GE, atHead));
141+
facts.add(Predicate.createOperation(name, Ops.LE, atHead));
142+
});
143+
facts.removeIf(fact -> !proved(fact));
144+
return facts;
145+
}
146+
147+
/**
148+
* Adds to the last instance of each variable the facts that mention it, on the last instances of the variables.
149+
* Unlike a path condition, the refinement of an instance is not dropped when the variable is assigned.
150+
*/
151+
private void addToLastInstances(List<Predicate> facts) {
152+
for (String variable : variables) {
153+
Optional<VariableInstance> last = checker.getContext().getLastVariableInstance(variable);
154+
if (last.isEmpty())
155+
continue;
156+
Predicate refinement = declared.computeIfAbsent(last.get(), RefinedVariable::getRefinement);
157+
for (Predicate fact : facts)
158+
if (fact.getVariableNames().contains(variable))
159+
refinement = Predicate.createConjunction(refinement, onLastInstances(fact));
160+
last.get().setRefinement(refinement);
161+
}
162+
}
163+
164+
/** Whether a fact on variable names holds for their last instances, from what is known here */
165+
private boolean proved(Predicate fact) {
166+
try {
167+
return checker.checkStateSMT(new Predicate(), onLastInstances(fact), loop.getPosition(), true);
168+
} catch (LJError e) {
169+
return false;
170+
}
171+
}
172+
173+
private Predicate onLastInstances(Predicate fact) {
174+
Predicate result = fact;
175+
for (String name : fact.getVariableNames()) {
176+
Optional<VariableInstance> last = checker.getContext().getLastVariableInstance(name);
177+
if (last.isPresent())
178+
result = result.substituteVariable(name, last.get().getName());
179+
}
180+
return result;
181+
}
182+
183+
private static CtExpression<Boolean> condition(CtLoop loop) {
184+
if (loop instanceof CtWhile whileLoop)
185+
return whileLoop.getLoopingExpression();
186+
if (loop instanceof CtDo doLoop)
187+
return doLoop.getLoopingExpression();
188+
if (loop instanceof CtFor forLoop)
189+
return forLoop.getExpression();
190+
return null;
191+
}
192+
}

0 commit comments

Comments
 (0)