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