diff --git a/liquidjava-example/src/main/java/testSuite/ErrorLoopUnprovedInvariant.java b/liquidjava-example/src/main/java/testSuite/ErrorLoopUnprovedInvariant.java new file mode 100644 index 00000000..56a1a237 --- /dev/null +++ b/liquidjava-example/src/main/java/testSuite/ErrorLoopUnprovedInvariant.java @@ -0,0 +1,22 @@ +package testSuite; + +import liquidjava.specification.Refinement; + +// The error stops the check of the body before total <= 0 is found not kept by an iteration, but i >= 0 is kept +@SuppressWarnings("unused") +public class ErrorLoopUnprovedInvariant { + static int read() { + return 1; + } + + static void nonNeg(@Refinement("_ >= 0") int x) {} + + static void accumulate() { + int total = 0; + for (int i = 0; i < 100; i++) { + nonNeg(i); + total = total + read(); + nonNeg(total); // Expect: Refinement Error + } + } +} diff --git a/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariants.java b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariants.java index 2568fae8..c9f06cb6 100644 --- a/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariants.java +++ b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariants.java @@ -1,11 +1,13 @@ package liquidjava.processor.refinement_checker; import java.util.ArrayList; +import java.util.Collections; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import liquidjava.diagnostics.errors.LJError; import liquidjava.processor.context.RefinedVariable; @@ -16,6 +18,7 @@ import spoon.reflect.code.CtExpression; import spoon.reflect.code.CtFor; import spoon.reflect.code.CtLoop; +import spoon.reflect.code.CtStatement; import spoon.reflect.code.CtWhile; /** @@ -29,6 +32,12 @@ * 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. + * + *

+ * An error that stops a check of the body leaves the candidates unchecked on the paths after it, so it is not reported + * with them. The statement of the body where it stopped is skipped in the next checks, as if it changed anything it may + * change, until a check drops no candidate; then the body is checked again without skipping it, which reports the error + * with candidates proved on every path. If the statement cannot be skipped, all candidates are dropped. */ class LoopInvariants { @@ -49,6 +58,12 @@ class LoopInvariants { private boolean reachable; // the facts proved at every continue reached so far, null if none was reached private List atContinues; + // the statements of the body whose check stopped at an error, skipped in the checks that prove the candidates + private final Set skipped = Collections.newSetFromMap(new IdentityHashMap<>()); + // the statement of the body where an error stopped the iteration being checked, if any + private CtStatement stoppedAt; + // whether the iteration being checked follows a fixpoint reached with statements skipped, to report their error + private boolean reporting; /** * 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() { dropped = false; reachable = true; atContinues = null; + stoppedAt = null; } void recordContinue() { @@ -127,11 +143,55 @@ void recordNextIteration() { * checks dropped some, all are dropped. */ boolean reachedFixpoint() { + reporting = false; if (dropped && ++rounds >= MAX_ROUNDS) candidates.clear(); return !dropped; } + /** + * At a fixpoint reached with statements skipped: the next iteration checks them, to report their error + * + * @return whether the body is to be checked again + */ + boolean checkSkippedAgain() { + if (skipped.isEmpty()) + return false; + skipped.clear(); + reporting = true; + return true; + } + + /** Whether a statement of the body is skipped in the iteration being checked */ + boolean skips(CtStatement statement) { + return skipped.contains(statement); + } + + /** Records the statement of the body where an error stops the iteration being checked */ + void stoppedAt(CtStatement statement) { + if (stoppedAt == null) + stoppedAt = statement; + } + + /** + * After an error stopped the iteration being checked: skips the statement where it stopped, if it can be skipped, + * else drops all candidates + * + * @return whether the body is to be checked again, else the error is reported: it was found from candidates proved + * on every path, or from none and with no statement skipped + */ + boolean checkAgainAfterError(java.util.function.Predicate canSkip) { + if (reporting || (candidates.isEmpty() && skipped.isEmpty())) + return false; + if (!candidates.isEmpty() && stoppedAt != null && canSkip.test(stoppedAt)) { + skipped.add(stoppedAt); + } else { + candidates.clear(); + skipped.clear(); + } + return true; + } + /** The candidates, and that each variable grew or shrank since the loop head, that are proved here */ private List provedForNextIteration() { List facts = new ArrayList<>(candidates); diff --git a/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/RefinementTypeChecker.java b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/RefinementTypeChecker.java index 1399135f..211d41f5 100644 --- a/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/RefinementTypeChecker.java +++ b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/RefinementTypeChecker.java @@ -207,10 +207,7 @@ public void visitCtLocalVariable(CtLocalVariable localVariable) { super.visitCtLocalVariable(localVariable); // only declaration, no assignment if (localVariable.getAssignment() == null) { - Optional a = getRefinementFromAnnotation(localVariable); - RefinedVariable v = context.addVarToContext(localVariable.getSimpleName(), localVariable.getType(), - a.orElse(new Predicate()), localVariable); - getMessageFromAnnotation(localVariable).ifPresent(v::setMessage); + declareWithoutValue(localVariable); } else { String varName = localVariable.getSimpleName(); CtExpression e = localVariable.getAssignment(); @@ -226,6 +223,14 @@ public void visitCtLocalVariable(CtLocalVariable localVariable) { } } + /** Adds a local variable to the context with only its declared refinement */ + private void declareWithoutValue(CtLocalVariable localVariable) { + Optional a = getRefinementFromAnnotation(localVariable); + RefinedVariable v = context.addVarToContext(localVariable.getSimpleName(), localVariable.getType(), + a.orElse(new Predicate()), localVariable); + getMessageFromAnnotation(localVariable).ifPresent(v::setMessage); + } + /** Records on the new instance of a local variable the call whose value it was assigned, if any */ private void recordReturnedValue(String name, CtExpression value) { if (value != null && value.getMetadata(Keys.CALL_RESULT)instanceof CallResult result) @@ -1025,8 +1030,9 @@ private void visitLoop(CtLoop loop, Consumer iteration) { * *

* An earlier check starts from fewer states and more invariants than the last one, so an error that stops it is - * also an error of the last one. Only the last check keeps the errors recorded without stopping it (e.g. in a - * lambda). + * also an error of the last one. It is only reported once the invariants it assumes are proved, with the statement + * where it stopped skipped (see {@link LoopInvariants}). Only the last check keeps the errors recorded without + * stopping it (e.g. in a lambda). */ private void checkUntilFixpoint(LoopTypestates states, LoopInvariants loopInvariants, Consumer iteration) { @@ -1041,12 +1047,17 @@ private void checkUntilFixpoint(LoopTypestates states, LoopInvariants loopInvari iteration.accept(states); states.recordNextIteration(); loopInvariants.recordNextIteration(); + } catch (LJError e) { + if (!loopInvariants.checkAgainAfterError(statement -> canSkip(statement, states))) + throw e; + diagnostics.getErrors().retainAll(errors); + continue; } finally { context.exitContext(); vcChecker.replacePathVariables(pathVariables); } boolean typestatesStable = states.reachedFixpoint(); - if (loopInvariants.reachedFixpoint() && typestatesStable) + if (loopInvariants.reachedFixpoint() && typestatesStable && !loopInvariants.checkSkippedAgain()) return; diagnostics.getErrors().retainAll(errors); } @@ -1091,6 +1102,59 @@ private void recordExit(LoopTypestates states, CtExpression condition) vcChecker.removePathVariable(conditionIsFalse); } + @Override + public void scan(CtElement element) { + LoopInvariants loopInvariants = element instanceof CtStatement statement ? invariantsOfBodyWith(statement) + : null; + if (loopInvariants == null) { + super.scan(element); + return; + } + CtStatement statement = (CtStatement) element; + if (loopInvariants.skips(statement)) { + skip(statement); + return; + } + try { + super.scan(statement); + } catch (LJError e) { + loopInvariants.stoppedAt(statement); + throw e; + } + } + + /** The invariants of the loop being checked whose body is {@code statement} or a block of it, if any */ + private LoopInvariants invariantsOfBodyWith(CtStatement statement) { + if (invariants.isEmpty() || !statement.isParentInitialized()) + return null; + CtElement parent = statement.getParent(); + if (parent instanceof CtBlock && parent.isParentInitialized() && parent.getParent()instanceof CtLoop loop + && loop.getBody() == parent) + return invariants.get(loop); + return parent instanceof CtLoop loop && loop.getBody() == statement ? invariants.get(loop) : null; + } + + /** + * Whether a statement of a loop body can be skipped, as if it changed anything it may change: it is not a local + * class, continues no loop outside it (whose next iteration would be missed), and changes no object whose + * typestates the loop follows + */ + private boolean canSkip(CtStatement statement, LoopTypestates states) { + return !(statement instanceof CtClass) + && statement.getElements(new TypeFilter<>(CtContinue.class)).stream().allMatch(jump -> { + CtElement target = jumpTarget(jump); + return target == statement || target.hasParent(statement); + }) && changedIn(statement, statement).stream().noneMatch(states.tracked()::contains); + } + + /** Instead of checking a statement, forgets what it may change, and declares the variable it declares, if any */ + private void skip(CtStatement statement) { + for (String name : changedIn(statement, statement)) + forgetChanges(name, new Predicate(), statement); + if (statement instanceof CtLocalVariable localVariable) + declareWithoutValue(localVariable); + } + /** Checks the body of a loop, up to the point after it where its continues join */ private void scanBody(CtLoop loop, LoopTypestates states) { List pathVariables = vcChecker.getPathVariables(); diff --git a/liquidjava-verifier/src/test/java/liquidjava/api/tests/TestCounterexamples.java b/liquidjava-verifier/src/test/java/liquidjava/api/tests/TestCounterexamples.java index 1a39a2c7..3671abeb 100644 --- a/liquidjava-verifier/src/test/java/liquidjava/api/tests/TestCounterexamples.java +++ b/liquidjava-verifier/src/test/java/liquidjava/api/tests/TestCounterexamples.java @@ -234,6 +234,13 @@ void indexIntoLocalArrayShowsTheIndexAndNotTheArray() { assertAssignments(error, assignment("k", "-1")); } + @Test + void errorInLoopBodyShowsNoUnprovedInvariant() { + RefinementError error = verify("ErrorLoopUnprovedInvariant.java"); + String found = error.getFound().getImplication().toPredicate().toString(); + assertFalse(found.contains("<= 0"), found); + } + private static RefinementError verify(String test) { CommandLineLauncher.launch(TEST_SUITE + test); List errors = Diagnostics.getInstance().getErrors().stream().toList();