Skip to content

Commit 109dfd0

Browse files
Report an error in a loop body only with invariants proved on every path
An error that stops the check of a loop body leaves the candidate invariants unchecked on the paths after it, and the error showed them as facts. The statement where the check stopped is now skipped in the next checks, as if it changed anything it may change, until the candidates reach a fixpoint; the body is then checked again to report the error. A statement that cannot be skipped drops all candidates. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 3e46ea2 commit 109dfd0

4 files changed

Lines changed: 152 additions & 3 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package testSuite;
2+
3+
import liquidjava.specification.Refinement;
4+
5+
// The error stops the check of the body before total <= 0 is found not kept by an iteration, but i >= 0 is kept
6+
@SuppressWarnings("unused")
7+
public class ErrorLoopUnprovedInvariant {
8+
static int read() {
9+
return 1;
10+
}
11+
12+
static void nonNeg(@Refinement("_ >= 0") int x) {}
13+
14+
static void accumulate() {
15+
int total = 0;
16+
for (int i = 0; i < 100; i++) {
17+
nonNeg(i);
18+
total = total + read();
19+
nonNeg(total); // Expect: Refinement Error
20+
}
21+
}
22+
}

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

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
package liquidjava.processor.refinement_checker;
22

33
import java.util.ArrayList;
4+
import java.util.Collections;
45
import java.util.IdentityHashMap;
56
import java.util.LinkedHashMap;
67
import java.util.List;
78
import java.util.Map;
89
import java.util.Optional;
10+
import java.util.Set;
911

1012
import liquidjava.diagnostics.errors.LJError;
1113
import liquidjava.processor.context.RefinedVariable;
@@ -16,6 +18,7 @@
1618
import spoon.reflect.code.CtExpression;
1719
import spoon.reflect.code.CtFor;
1820
import spoon.reflect.code.CtLoop;
21+
import spoon.reflect.code.CtStatement;
1922
import spoon.reflect.code.CtWhile;
2023

2124
/**
@@ -29,6 +32,12 @@
2932
* Where the continues of the body join, at its end, the values of what the loop changes are forgotten. The facts proved
3033
* at every continue and at the end of the body are kept there: the candidates, and whether each variable grew or shrank
3134
* since the loop head.
35+
*
36+
* <p>
37+
* An error that stops a check of the body leaves the candidates unchecked on the paths after it, so it is not reported
38+
* with them. The statement of the body where it stopped is skipped in the next checks, as if it changed anything it may
39+
* change, until a check drops no candidate; then the body is checked again without skipping it, which reports the error
40+
* with candidates proved on every path. If the statement cannot be skipped, all candidates are dropped.
3241
*/
3342
class LoopInvariants {
3443

@@ -49,6 +58,12 @@ class LoopInvariants {
4958
private boolean reachable;
5059
// the facts proved at every continue reached so far, null if none was reached
5160
private List<Predicate> atContinues;
61+
// the statements of the body whose check stopped at an error, skipped in the checks that prove the candidates
62+
private final Set<CtStatement> skipped = Collections.newSetFromMap(new IdentityHashMap<>());
63+
// the statement of the body where an error stopped the iteration being checked, if any
64+
private CtStatement stoppedAt;
65+
// whether the iteration being checked follows a fixpoint reached with statements skipped, to report their error
66+
private boolean reporting;
5267

5368
/**
5469
* Keeps the candidates that the facts before the loop prove; to be created before what the loop changes is
@@ -78,6 +93,7 @@ void startIteration() {
7893
dropped = false;
7994
reachable = true;
8095
atContinues = null;
96+
stoppedAt = null;
8197
}
8298

8399
void recordContinue() {
@@ -127,11 +143,55 @@ void recordNextIteration() {
127143
* checks dropped some, all are dropped.
128144
*/
129145
boolean reachedFixpoint() {
146+
reporting = false;
130147
if (dropped && ++rounds >= MAX_ROUNDS)
131148
candidates.clear();
132149
return !dropped;
133150
}
134151

152+
/**
153+
* At a fixpoint reached with statements skipped: the next iteration checks them, to report their error
154+
*
155+
* @return whether the body is to be checked again
156+
*/
157+
boolean checkSkippedAgain() {
158+
if (skipped.isEmpty())
159+
return false;
160+
skipped.clear();
161+
reporting = true;
162+
return true;
163+
}
164+
165+
/** Whether a statement of the body is skipped in the iteration being checked */
166+
boolean skips(CtStatement statement) {
167+
return skipped.contains(statement);
168+
}
169+
170+
/** Records the statement of the body where an error stops the iteration being checked */
171+
void stoppedAt(CtStatement statement) {
172+
if (stoppedAt == null)
173+
stoppedAt = statement;
174+
}
175+
176+
/**
177+
* After an error stopped the iteration being checked: skips the statement where it stopped, if it can be skipped,
178+
* else drops all candidates
179+
*
180+
* @return whether the body is to be checked again, else the error is reported: it was found from candidates proved
181+
* on every path, or from none and with no statement skipped
182+
*/
183+
boolean checkAgainAfterError(java.util.function.Predicate<CtStatement> canSkip) {
184+
if (reporting || (candidates.isEmpty() && skipped.isEmpty()))
185+
return false;
186+
if (!candidates.isEmpty() && stoppedAt != null && canSkip.test(stoppedAt)) {
187+
skipped.add(stoppedAt);
188+
} else {
189+
candidates.clear();
190+
skipped.clear();
191+
}
192+
return true;
193+
}
194+
135195
/** The candidates, and that each variable grew or shrank since the loop head, that are proved here */
136196
private List<Predicate> provedForNextIteration() {
137197
List<Predicate> facts = new ArrayList<>(candidates);

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

Lines changed: 63 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1025,8 +1025,9 @@ private void visitLoop(CtLoop loop, Consumer<LoopTypestates> iteration) {
10251025
*
10261026
* <p>
10271027
* An earlier check starts from fewer states and more invariants than the last one, so an error that stops it is
1028-
* also an error of the last one. Only the last check keeps the errors recorded without stopping it (e.g. in a
1029-
* lambda).
1028+
* also an error of the last one. It is only reported once the invariants it assumes are proved, with the statement
1029+
* where it stopped skipped (see {@link LoopInvariants}). Only the last check keeps the errors recorded without
1030+
* stopping it (e.g. in a lambda).
10301031
*/
10311032
private void checkUntilFixpoint(LoopTypestates states, LoopInvariants loopInvariants,
10321033
Consumer<LoopTypestates> iteration) {
@@ -1041,12 +1042,17 @@ private void checkUntilFixpoint(LoopTypestates states, LoopInvariants loopInvari
10411042
iteration.accept(states);
10421043
states.recordNextIteration();
10431044
loopInvariants.recordNextIteration();
1045+
} catch (LJError e) {
1046+
if (!loopInvariants.checkAgainAfterError(statement -> canSkip(statement, states)))
1047+
throw e;
1048+
diagnostics.getErrors().retainAll(errors);
1049+
continue;
10441050
} finally {
10451051
context.exitContext();
10461052
vcChecker.replacePathVariables(pathVariables);
10471053
}
10481054
boolean typestatesStable = states.reachedFixpoint();
1049-
if (loopInvariants.reachedFixpoint() && typestatesStable)
1055+
if (loopInvariants.reachedFixpoint() && typestatesStable && !loopInvariants.checkSkippedAgain())
10501056
return;
10511057
diagnostics.getErrors().retainAll(errors);
10521058
}
@@ -1091,6 +1097,60 @@ private void recordExit(LoopTypestates states, CtExpression<Boolean> condition)
10911097
vcChecker.removePathVariable(conditionIsFalse);
10921098
}
10931099

1100+
@Override
1101+
public void scan(CtElement element) {
1102+
LoopInvariants loopInvariants = element instanceof CtStatement statement ? invariantsOfBodyWith(statement)
1103+
: null;
1104+
if (loopInvariants == null) {
1105+
super.scan(element);
1106+
return;
1107+
}
1108+
CtStatement statement = (CtStatement) element;
1109+
if (loopInvariants.skips(statement)) {
1110+
skip(statement);
1111+
return;
1112+
}
1113+
try {
1114+
super.scan(statement);
1115+
} catch (LJError e) {
1116+
loopInvariants.stoppedAt(statement);
1117+
throw e;
1118+
}
1119+
}
1120+
1121+
/** The invariants of the loop being checked whose body is {@code statement} or a block of it, if any */
1122+
private LoopInvariants invariantsOfBodyWith(CtStatement statement) {
1123+
if (invariants.isEmpty() || !statement.isParentInitialized())
1124+
return null;
1125+
CtElement parent = statement.getParent();
1126+
if (parent instanceof CtBlock<?> && parent.isParentInitialized() && parent.getParent()instanceof CtLoop loop
1127+
&& loop.getBody() == parent)
1128+
return invariants.get(loop);
1129+
return parent instanceof CtLoop loop && loop.getBody() == statement ? invariants.get(loop) : null;
1130+
}
1131+
1132+
/**
1133+
* Whether a statement of a loop body can be skipped, as if it changed anything it may change: it is not a local
1134+
* class, continues no loop outside it (whose next iteration would be missed), and changes no object whose
1135+
* typestates the loop follows
1136+
*/
1137+
private boolean canSkip(CtStatement statement, LoopTypestates states) {
1138+
return !(statement instanceof CtClass<?>)
1139+
&& statement.getElements(new TypeFilter<>(CtContinue.class)).stream().allMatch(jump -> {
1140+
CtElement target = jumpTarget(jump);
1141+
return target == statement || target.hasParent(statement);
1142+
}) && changedIn(statement, statement).stream().noneMatch(states.tracked()::contains);
1143+
}
1144+
1145+
/** Instead of checking a statement, forgets what it may change, and declares the variable it declares, if any */
1146+
private void skip(CtStatement statement) {
1147+
for (String name : changedIn(statement, statement))
1148+
forgetChanges(name, new Predicate(), statement);
1149+
if (statement instanceof CtLocalVariable<?> localVariable)
1150+
context.addVarToContext(localVariable.getSimpleName(), localVariable.getType(),
1151+
getRefinementFromAnnotation(localVariable).orElse(new Predicate()), localVariable);
1152+
}
1153+
10941154
/** Checks the body of a loop, up to the point after it where its continues join */
10951155
private void scanBody(CtLoop loop, LoopTypestates states) {
10961156
List<RefinedVariable> pathVariables = vcChecker.getPathVariables();

‎liquidjava-verifier/src/test/java/liquidjava/api/tests/TestCounterexamples.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,13 @@ void indexIntoLocalArrayShowsTheIndexAndNotTheArray() {
234234
assertAssignments(error, assignment("k", "-1"));
235235
}
236236

237+
@Test
238+
void errorInLoopBodyShowsNoUnprovedInvariant() {
239+
RefinementError error = verify("ErrorLoopUnprovedInvariant.java");
240+
String found = error.getFound().getImplication().toPredicate().toString();
241+
assertFalse(found.contains("<= 0"), found);
242+
}
243+
237244
private static RefinementError verify(String test) {
238245
CommandLineLauncher.launch(TEST_SUITE + test);
239246
List<LJError> errors = Diagnostics.getInstance().getErrors().stream().toList();

0 commit comments

Comments
 (0)