diff --git a/liquidjava-example/src/main/java/testSuite/CorrectLoopInvariants.java b/liquidjava-example/src/main/java/testSuite/CorrectLoopInvariants.java new file mode 100644 index 00000000..137eea04 --- /dev/null +++ b/liquidjava-example/src/main/java/testSuite/CorrectLoopInvariants.java @@ -0,0 +1,91 @@ +package testSuite; + +import liquidjava.specification.Refinement; + +// Facts about the int locals a loop changes that hold on every iteration are inferred (#537) +@SuppressWarnings("unused") +public class CorrectLoopInvariants { + static boolean next() { + return true; + } + + static int read(byte[] buffer, @Refinement("_ >= 0") int offset, int length) { + return 0; + } + + static void use(@Refinement("_ >= 0") int x) {} + + static void counter() { + for (int i = 0; i < 10; i++) { + use(i); + } + } + + static void accumulator() { + int total = 0; + while (total < 1024) { + use(total); + total = total + 1; + } + } + + static void fill(byte[] buffer, int limit) { + int total = 0; + while (total < limit) { + int n = read(buffer, total, limit - total); + if (n < 0) + break; + total += n; + } + } + + static void symbolicStart(int k) { + if (k < 0) + return; + for (int i = k; i < 100; i++) { + use(i); + } + } + + static void nested() { + for (int i = 0; i < 10; i++) { + for (int j = i; j < 10; j++) { + use(i); + use(j); + } + } + } + + // a continue goes on to the update + static void continueInFor() { + for (int i = 0; i < 10; i++) { + if (next()) + continue; + use(i); + } + } + + static void continueInWhile() { + int i = 0; + while (i < 10) { + use(i); + if (next()) { + i++; + continue; + } + i = i + 2; + } + } + + static void continueInDoWhile() { + int i = 0; + do { + use(i); + if (next()) { + i++; + continue; + } + i = i + 2; + } while (i < 10); + } +} diff --git a/liquidjava-example/src/main/java/testSuite/ErrorLoopInvariants.java b/liquidjava-example/src/main/java/testSuite/ErrorLoopInvariants.java new file mode 100644 index 00000000..089b76f7 --- /dev/null +++ b/liquidjava-example/src/main/java/testSuite/ErrorLoopInvariants.java @@ -0,0 +1,85 @@ +package testSuite; + +import liquidjava.specification.Refinement; + +// Only facts that hold before a loop and are kept by every iteration are inferred for its int locals (#537) +@SuppressWarnings("unused") +public class ErrorLoopInvariants { + static boolean next() { + return true; + } + + static void use(@Refinement("_ >= 0") int x) {} + + static void atMostTen(@Refinement("_ <= 10") int x) {} + + static void decrementing() { + for (int i = 10; i > -5; i--) { + use(i); // Expect: Refinement Error + } + } + + static void resetInBody() { + int i = 0; + while (i < 10) { + use(i); // Expect: Refinement Error + i = i + 1; + if (next()) + i = -1; + } + } + + static void decreasedOnSomePath() { + int i = 0; + while (i < 10) { + use(i); // Expect: Refinement Error + if (next()) + i = i - 2; + else + i++; + } + } + + // i < 10 does not give i <= 10 at the next iteration, as i grows by 3 + static void boundNotKept() { + int i = 0; + while (i < 10) { + i = i + 3; + atMostTen(i); // Expect: Refinement Error + } + } + + static void decreasedBeforeContinue() { + int i = 0; + while (i < 10) { + use(i); // Expect: Refinement Error + if (next()) { + i = i - 1; + continue; + } + i++; + } + } + + // the continue skips the use but not the update, which starts the next iteration from i - 5 + 1 + static void decreasedBeforeContinueInFor() { + for (int i = 0; i < 10; i++) { + if (next()) { + i = i - 5; + continue; + } + use(i); // Expect: Refinement Error + } + } + + static void decreasedInInnerLoop() { + int i = 0; + while (i < 10) { + use(i); // Expect: Refinement Error + for (int j = 0; j < 5; j++) { + i = i - 1; + } + i++; + } + } +} diff --git a/liquidjava-example/src/main/java/testSuite/classes/loop_list_index_correct/ArrayListRefinements.java b/liquidjava-example/src/main/java/testSuite/classes/loop_list_index_correct/ArrayListRefinements.java new file mode 100644 index 00000000..5c9ba441 --- /dev/null +++ b/liquidjava-example/src/main/java/testSuite/classes/loop_list_index_correct/ArrayListRefinements.java @@ -0,0 +1,21 @@ +package testSuite.classes.loop_list_index_correct; + +import liquidjava.specification.ExternalRefinementsFor; +import liquidjava.specification.Ghost; +import liquidjava.specification.Refinement; +import liquidjava.specification.StateRefinement; + +@ExternalRefinementsFor("java.util.ArrayList") +@Ghost("int size") +public interface ArrayListRefinements { + @StateRefinement(to = "size(this) == 0") + void ArrayList(); + + @StateRefinement(to = "size(this) == size(old(this)) + 1") + boolean add(E e); + + E get(@Refinement("_ >= 0 && _ < size(this)") int index); + + @Refinement("_ == size(this) && _ >= 0") + int size(); +} diff --git a/liquidjava-example/src/main/java/testSuite/classes/loop_list_index_correct/Client.java b/liquidjava-example/src/main/java/testSuite/classes/loop_list_index_correct/Client.java new file mode 100644 index 00000000..a1f563ec --- /dev/null +++ b/liquidjava-example/src/main/java/testSuite/classes/loop_list_index_correct/Client.java @@ -0,0 +1,15 @@ +package testSuite.classes.loop_list_index_correct; + +import java.util.ArrayList; + +// A loop over the indices of a list knows the index is non-negative (#479) +public class Client { + public static void main(String[] args) { + ArrayList l = new ArrayList<>(); + l.add("a"); + l.add("b"); + for (int i = 0; i < l.size(); i++) { + String s = l.get(i); + } + } +} 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 new file mode 100644 index 00000000..2568fae8 --- /dev/null +++ b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariants.java @@ -0,0 +1,192 @@ +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. + * + *

+ * 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 variables; + private final List candidates = new ArrayList<>(); + // the instance of each variable at the loop head + private final Map head = new LinkedHashMap<>(); + // the refinement of each instance before facts were added to it + private final Map 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 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 variables) { + this.checker = checker; + this.loop = loop; + this.variables = variables; + for (String variable : variables) { + Optional 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 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 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 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; + } + + /** 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); + 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 facts) { + for (String variable : variables) { + Optional 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 last = checker.getContext().getLastVariableInstance(name); + if (last.isPresent()) + result = result.substituteVariable(name, last.get().getName()); + } + return result; + } + + private static CtExpression 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; + } +} 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 4b680578..1399135f 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 @@ -6,8 +6,10 @@ import java.util.Arrays; import java.util.Deque; import java.util.HashSet; +import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; @@ -102,6 +104,8 @@ public class RefinementTypeChecker extends TypeChecker { Keys.RETURN_VAR_NAME, Keys.STATE_CHANGE, Keys.CALL_RESULT); // the loops being checked, innermost first private final Deque loops = new ArrayDeque<>(); + // the invariants inferred for the loops being checked + private final Map invariants = new IdentityHashMap<>(); public RefinementTypeChecker(Context context, Factory factory) { super(context, factory); @@ -952,6 +956,8 @@ public void visitCtDo(CtDo doLoop) { scanBody(doLoop, states); scan(doLoop.getLoopingExpression()); recordExit(states, doLoop.getLoopingExpression()); + // the next iteration starts only if the condition holds + assumeLoopCondition(doLoop.getLoopingExpression()); }); } @@ -975,14 +981,19 @@ public void visitCtBreak(CtBreak breakStatement) { @Override public void visitCtContinue(CtContinue continueStatement) { super.visitCtContinue(continueStatement); - loopLeftBy(continueStatement).ifPresent(LoopTypestates::recordContinue); + loopLeftBy(continueStatement).ifPresent(states -> { + states.recordContinue(); + invariants.get(states.loop()).recordContinue(); + }); } /** * Checks a loop for any number of iterations. What the loop may change is havocked (keeps only its declared * refinement, which every assignment re-checks) before it and again after it, except the typestates of the local - * objects it may change, which are computed over its iterations (see {@link LoopTypestates}). Path conditions added - * inside the loop (e.g. the loop condition, or an {@code if (...) break;}) are dropped after it. + * objects it may change, which are computed over its iterations (see {@link LoopTypestates}), and the invariants + * inferred for the {@code int} local variables it changes, which hold at its head (see {@link LoopInvariants}). + * Path conditions added inside the loop (e.g. the loop condition, or an {@code if (...) break;}) are dropped after + * it. */ private void visitLoop(CtLoop loop, Consumer iteration) { List pathVariables = vcChecker.getPathVariables(); @@ -991,12 +1002,16 @@ private void visitLoop(CtLoop loop, Consumer iteration) { Set locals = followsJumps(loop) ? changedIn(loop).stream().filter(name -> !isField(name)) .collect(Collectors.toCollection(LinkedHashSet::new)) : Set.of(); LoopTypestates states = new LoopTypestates(this, loop, locals); + LoopInvariants loopInvariants = new LoopInvariants(this, loop, + locals.stream().filter(this::isIntVariable).toList()); havocChangedIn(loop, states.tracked()); loops.push(states); + invariants.put(loop, loopInvariants); try { - checkUntilFixpoint(states, iteration); + checkUntilFixpoint(states, loopInvariants, iteration); } finally { loops.pop(); + invariants.remove(loop); } vcChecker.restorePathVariables(pathVariables); havocChangedIn(loop, states.tracked()); @@ -1004,15 +1019,17 @@ private void visitLoop(CtLoop loop, Consumer iteration) { } /** - * Checks iterations of a loop from the typestates at its head until they stop changing. Every check starts from the - * facts before the loop, with what it changes havocked; only the head typestates differ. What a check adds - * (variables, instances, path conditions, metadata) is dropped before the next one. + * Checks iterations of a loop from the typestates and invariants at its head until they stop changing. Every check + * starts from the facts before the loop, with what it changes havocked; only the head typestates and invariants + * differ. What a check adds (variables, instances, path conditions, metadata) is dropped before the next one. * *

- * An earlier check starts from fewer states 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). + * 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). */ - private void checkUntilFixpoint(LoopTypestates states, Consumer iteration) { + private void checkUntilFixpoint(LoopTypestates states, LoopInvariants loopInvariants, + Consumer iteration) { List pathVariables = vcChecker.getPathVariables(); while (true) { Set errors = new LinkedHashSet<>(diagnostics.getErrors()); @@ -1020,13 +1037,16 @@ private void checkUntilFixpoint(LoopTypestates states, Consumer context.enterContext(); try { states.startIteration(); + loopInvariants.startIteration(); iteration.accept(states); states.recordNextIteration(); + loopInvariants.recordNextIteration(); } finally { context.exitContext(); vcChecker.replacePathVariables(pathVariables); } - if (states.reachedFixpoint()) + boolean typestatesStable = states.reachedFixpoint(); + if (loopInvariants.reachedFixpoint() && typestatesStable) return; diagnostics.getErrors().retainAll(errors); } @@ -1076,12 +1096,17 @@ private void scanBody(CtLoop loop, LoopTypestates states) { List pathVariables = vcChecker.getPathVariables(); CtStatement body = loop.getBody(); // null for an empty statement body, as in for (...); scan(body); + boolean completes = canCompleteNormally(body); + LoopInvariants loopInvariants = invariants.get(loop); if (body != null && !body.getElements(new TypeFilter<>(CtContinue.class)).isEmpty()) { // a continue reaches the end of the body from any point of it, skipping its facts and assignments + List joinedFacts = loopInvariants.atJoin(completes); vcChecker.restorePathVariables(pathVariables); havocChangedIn(loop, states.tracked()); + loopInvariants.joined(joinedFacts); } - states.endBody(canCompleteNormally(body)); + states.endBody(completes); + loopInvariants.endBody(completes); } /** The loop being checked that {@code jump} leaves, if any */ @@ -1181,6 +1206,13 @@ else if (inv.getTarget() != null && AuxStateHandler.isCurrentReceiver(inv.getTar return names; } + /** Whether a name in the context is that of a variable of type {@code int} */ + private boolean isIntVariable(String name) { + RefinedVariable variable = context.getVariableByName(name); + return variable != null && variable.getType() != null + && variable.getType().getQualifiedName().equals(Types.INT); + } + /** Whether a name in the context is that of a field of this */ private static boolean isField(String name) { return name.startsWith(String.format(Formats.THIS, ""));