From 62c7908386d583655f7ebb8fd324410ea2b4bfe6 Mon Sep 17 00:00:00 2001 From: Catarina Gamboa Date: Mon, 23 Nov 2026 19:52:28 +0000 Subject: [PATCH 1/3] Start the inference of a nested loop from its last invariants Each check of a loop body starts from no more facts than the one before, so a loop nested in it cannot have more invariants than at its last visit: its next visit only tries those. A check that starts from more facts (one that no longer skips a statement, or a loop starting over) forgets them. Co-Authored-By: Claude Opus 5.5 --- .../refinement_checker/LoopInvariants.java | 34 +++++++++++++++---- .../RefinementTypeChecker.java | 29 ++++++++++++++-- 2 files changed, 53 insertions(+), 10 deletions(-) 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 c9f06cb6..f607196b 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 @@ -8,6 +8,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.stream.Collectors; import liquidjava.diagnostics.errors.LJError; import liquidjava.processor.context.RefinedVariable; @@ -48,6 +49,8 @@ class LoopInvariants { private final CtLoop loop; private final List variables; private final List candidates = new ArrayList<>(); + // the instance of each variable before the loop + private final Map before = new LinkedHashMap<>(); // 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 @@ -71,18 +74,35 @@ class LoopInvariants { * * @param variables * the {@code int} local variables the loop changes + * @param previous + * the invariants inferred at the last visit of the loop (see {@link #inferred}), or null: when the facts + * before the loop are no stronger than then, only these can be invariants again */ - LoopInvariants(RefinementTypeChecker checker, CtLoop loop, List variables) { + LoopInvariants(RefinementTypeChecker checker, CtLoop loop, List variables, Set previous) { 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)) + for (String variable : variables) + checker.getContext().getLastVariableInstance(variable) + .ifPresent(instance -> before.put(variable, instance.getName())); + for (String variable : variables) + for (Predicate candidate : InvariantCandidates.of(variable, Optional.ofNullable(before.get(variable)), + condition(loop))) + if ((previous == null || previous.contains(key(candidate))) && !candidates.contains(candidate) + && proved(candidate)) candidates.add(candidate); - } + } + + /** The invariants inferred, the same across visits of the loop, which name the values before it differently */ + Set inferred() { + return candidates.stream().map(this::key).collect(Collectors.toSet()); + } + + private String key(Predicate candidate) { + Predicate key = candidate; + for (Map.Entry entry : before.entrySet()) + key = key.substituteVariable(entry.getValue(), entry.getKey() + "_before"); + return key.toString(); } /** Starts checking an iteration: the variables at the loop head satisfy the 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 211d41f5..a088e4b1 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 @@ -106,6 +106,11 @@ public class RefinementTypeChecker extends TypeChecker { private final Deque loops = new ArrayDeque<>(); // the invariants inferred for the loops being checked private final Map invariants = new IdentityHashMap<>(); + // the invariants inferred at the last visit of each loop nested in the loops being checked, from which its next + // visit starts: each check of a body starts from no more facts than the one before (fewer invariants, more + // typestates, more statements skipped), so a nested loop cannot have more invariants than at its last visit. A + // check that starts from more facts (skipping fewer statements, or a loop starting over) forgets those nested in it + private final Map> lastInferred = new IdentityHashMap<>(); public RefinementTypeChecker(Context context, Factory factory) { super(context, factory); @@ -1007,16 +1012,22 @@ 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); + Set previous = lastInferred.remove(loop); + if (previous == null) + forgetInferredNestedIn(loop); LoopInvariants loopInvariants = new LoopInvariants(this, loop, - locals.stream().filter(this::isIntVariable).toList()); + locals.stream().filter(this::isIntVariable).toList(), previous); havocChangedIn(loop, states.tracked()); loops.push(states); invariants.put(loop, loopInvariants); try { checkUntilFixpoint(states, loopInvariants, iteration); + lastInferred.put(loop, loopInvariants.inferred()); } finally { loops.pop(); invariants.remove(loop); + if (loops.isEmpty()) + lastInferred.clear(); } vcChecker.restorePathVariables(pathVariables); havocChangedIn(loop, states.tracked()); @@ -1051,18 +1062,30 @@ private void checkUntilFixpoint(LoopTypestates states, LoopInvariants loopInvari if (!loopInvariants.checkAgainAfterError(statement -> canSkip(statement, states))) throw e; diagnostics.getErrors().retainAll(errors); + forgetInferredNestedIn(states.loop()); continue; } finally { context.exitContext(); vcChecker.replacePathVariables(pathVariables); } boolean typestatesStable = states.reachedFixpoint(); - if (loopInvariants.reachedFixpoint() && typestatesStable && !loopInvariants.checkSkippedAgain()) - return; + if (loopInvariants.reachedFixpoint() && typestatesStable) { + if (!loopInvariants.checkSkippedAgain()) + return; + forgetInferredNestedIn(states.loop()); + } diagnostics.getErrors().retainAll(errors); } } + /** + * Forgets the invariants inferred for the loops nested in {@code loop}, before a check of its body that may start + * from more facts than the last one (it no longer skips a statement) + */ + private void forgetInferredNestedIn(CtLoop loop) { + lastInferred.keySet().removeIf(nested -> nested.hasParent(loop)); + } + /** * Removes the metadata that checking a loop puts on its elements: unlike the context it is not scoped, so it could * refer to what an earlier check dropped (e.g. the receiver of a call in a lambda). The parts checked once before From e53524f21003fafd496b6868af3f4d8b79c612b8 Mon Sep 17 00:00:00 2001 From: Catarina Gamboa Date: Mon, 23 Nov 2026 19:52:28 +0000 Subject: [PATCH 2/3] Join the end of a loop body only for its own continues A continue of an inner loop does not reach the end of the outer body, so the values there need not be forgotten. Co-Authored-By: Claude Opus 5.5 --- .../java/testSuite/CorrectLoopInvariants.java | 16 ++++++++++++++++ .../RefinementTypeChecker.java | 3 ++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/liquidjava-example/src/main/java/testSuite/CorrectLoopInvariants.java b/liquidjava-example/src/main/java/testSuite/CorrectLoopInvariants.java index 137eea04..c00c7426 100644 --- a/liquidjava-example/src/main/java/testSuite/CorrectLoopInvariants.java +++ b/liquidjava-example/src/main/java/testSuite/CorrectLoopInvariants.java @@ -88,4 +88,20 @@ static void continueInDoWhile() { i = i + 2; } while (i < 10); } + + static boolean ten(@Refinement("_ == 10") int x) { + return true; + } + + // the continue goes to the inner loop, so the condition still knows the value the body gave i + static void continueOfInnerLoop(int n) { + int i = 0; + do { + i = 10; + for (int j = 0; j < n; j++) { + if (next()) + continue; + } + } while (ten(i) && next()); + } } 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 a088e4b1..db0d17ac 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 @@ -1185,7 +1185,8 @@ private void scanBody(CtLoop loop, LoopTypestates states) { scan(body); boolean completes = canCompleteNormally(body); LoopInvariants loopInvariants = invariants.get(loop); - if (body != null && !body.getElements(new TypeFilter<>(CtContinue.class)).isEmpty()) { + if (body != null && body.getElements(new TypeFilter<>(CtContinue.class)).stream() + .anyMatch(jump -> jumpTarget(jump) == loop)) { // 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); From 227fcfbd565a59b85c09e0cadaf6eaffd5de9cae Mon Sep 17 00:00:00 2001 From: Catarina Gamboa Date: Mon, 23 Nov 2026 20:13:41 +0000 Subject: [PATCH 3/3] Name the value before a loop in a key as no variable can be named Co-Authored-By: Claude Opus 5.5 --- .../processor/refinement_checker/LoopInvariants.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 f607196b..3f0feccb 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 @@ -98,10 +98,11 @@ Set inferred() { return candidates.stream().map(this::key).collect(Collectors.toSet()); } + /** The text of a candidate, with each instance before the loop renamed to a name no Java variable has */ private String key(Predicate candidate) { Predicate key = candidate; for (Map.Entry entry : before.entrySet()) - key = key.substituteVariable(entry.getValue(), entry.getKey() + "_before"); + key = key.substituteVariable(entry.getValue(), entry.getKey() + "#before"); return key.toString(); }