From dcd0502434b456ed678a1694aeabb192a1af7ddb Mon Sep 17 00:00:00 2001 From: Catarina Gamboa Date: Tue, 24 Nov 2026 12:58:23 +0000 Subject: [PATCH 1/2] Mark inferred loop facts in errors, and hint to state a loop invariant A refinement error now lists, for clients, the facts of Found that loop invariant inference added, with the value they are about, the loop and where in it they hold (start of an iteration, end of the body, after the loop). The message text does not change. A prototype hint is added to an error in a loop whose counterexample is about an unrefined int local the loop changes, when expected holds on the first iteration: it says the loop only keeps what holds on every iteration, and suggests expected as a refinement of the declaration when it can be written for the variable and holds before the loop. Co-Authored-By: Claude Opus 5.5 --- .../java/testSuite/ErrorLoopExitFacts.java | 13 +- .../liquidjava/diagnostics/InferredFacts.java | 31 ++++ .../diagnostics/errors/RefinementError.java | 11 ++ .../liquidjava/diagnostics/hints/Hint.java | 4 +- .../processor/context/VariableInstance.java | 12 ++ .../refinement_checker/LoopInvariantHint.java | 135 ++++++++++++++++++ .../refinement_checker/LoopInvariants.java | 75 ++++++++-- .../RefinementTypeChecker.java | 7 +- .../refinement_checker/VCChecker.java | 23 ++- .../tests/TestLoopInvariantDiagnostics.java | 73 ++++++++++ 10 files changed, 372 insertions(+), 12 deletions(-) create mode 100644 liquidjava-verifier/src/main/java/liquidjava/diagnostics/InferredFacts.java create mode 100644 liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariantHint.java create mode 100644 liquidjava-verifier/src/test/java/liquidjava/api/tests/TestLoopInvariantDiagnostics.java diff --git a/liquidjava-example/src/main/java/testSuite/ErrorLoopExitFacts.java b/liquidjava-example/src/main/java/testSuite/ErrorLoopExitFacts.java index 4efc238d..faf387f2 100644 --- a/liquidjava-example/src/main/java/testSuite/ErrorLoopExitFacts.java +++ b/liquidjava-example/src/main/java/testSuite/ErrorLoopExitFacts.java @@ -2,7 +2,7 @@ import liquidjava.specification.Refinement; -// After a loop that may exit elsewhere than at its condition, the condition is not known to be false +// After a loop only its invariants are known, and that its condition is false if it exits only there @SuppressWarnings("unused") public class ErrorLoopExitFacts { static boolean next() { @@ -15,6 +15,8 @@ static void atMostThree(@Refinement("_ <= 3") int x) {} static void ten(@Refinement("_ == 10") int x) {} + static void atMostTen(@Refinement("_ <= 10") int x) {} + static void exitByBreak(int n) { int i = 0; while (i < n) { @@ -34,6 +36,15 @@ static void doWhile() { atMostThree(i); // Expect: Refinement Error } + // after the loop i >= 0 and !(i < 10) are known, but not i <= 10, as i grows by 3 + static void pastTheBound() { + int i = 0; + while (i < 10) { + i = i + 3; + } + atMostTen(i); // Expect: Refinement Error + } + // the condition increments i after it is checked, so the loop exits with i == 11 static void conditionWithUpdate() { int i = 0; diff --git a/liquidjava-verifier/src/main/java/liquidjava/diagnostics/InferredFacts.java b/liquidjava-verifier/src/main/java/liquidjava/diagnostics/InferredFacts.java new file mode 100644 index 00000000..7b61a424 --- /dev/null +++ b/liquidjava-verifier/src/main/java/liquidjava/diagnostics/InferredFacts.java @@ -0,0 +1,31 @@ +package liquidjava.diagnostics; + +import java.util.List; + +import liquidjava.rj_language.ast.Expression; +import spoon.reflect.cu.SourcePosition; + +/** + * Facts that loop invariant inference gave the value of a variable, which an error shows among the others it found, for + * clients that tell where they come from + * + * @param variable + * the internal name of the value, an instance of an {@code int} local variable the loop changes + * @param facts + * the facts, each a conjunct of the refinement of {@code variable} + * @param loop + * the position of the loop + * @param point + * where in the loop the value is taken + */ +public record InferredFacts(String variable, List facts, SourcePosition loop, Point point) { + + public enum Point { + /** At the start of an iteration: the facts hold on every iteration */ + ITERATION_START, + /** At the end of the body, where its continues join: the facts hold on every path that gets there */ + ITERATION_END, + /** After a loop that exits only through its condition: the facts hold, and the condition is false */ + AFTER_LOOP + } +} diff --git a/liquidjava-verifier/src/main/java/liquidjava/diagnostics/errors/RefinementError.java b/liquidjava-verifier/src/main/java/liquidjava/diagnostics/errors/RefinementError.java index 324f8991..b1d90983 100644 --- a/liquidjava-verifier/src/main/java/liquidjava/diagnostics/errors/RefinementError.java +++ b/liquidjava-verifier/src/main/java/liquidjava/diagnostics/errors/RefinementError.java @@ -12,6 +12,7 @@ import liquidjava.diagnostics.AliasExpansion; import liquidjava.diagnostics.Code; +import liquidjava.diagnostics.InferredFacts; import liquidjava.diagnostics.TranslationTable; import liquidjava.diagnostics.categories.ErrorCategory; import liquidjava.processor.context.AliasWrapper; @@ -48,6 +49,7 @@ public class RefinementError extends LJError { private final List foundAliases; private final List expectedAliases; private final List aliasDeclarations; + private List inferredFacts = List.of(); public RefinementError(SourcePosition position, SourcePosition declarationPosition, Predicate expected, VCSimplificationResult found, TranslationTable translationTable, Counterexample counterexample, @@ -117,6 +119,15 @@ public List getExpectedAliases() { return expectedAliases; } + /** The facts of found that loop invariant inference gave the values it is about */ + public List getInferredFacts() { + return inferredFacts; + } + + public void setInferredFacts(List inferredFacts) { + this.inferredFacts = List.copyOf(inferredFacts); + } + /** A where line declaring each alias the message uses, then the other notes */ @Override public List getMessageNotes() { diff --git a/liquidjava-verifier/src/main/java/liquidjava/diagnostics/hints/Hint.java b/liquidjava-verifier/src/main/java/liquidjava/diagnostics/hints/Hint.java index cb3f7de0..08b44780 100644 --- a/liquidjava-verifier/src/main/java/liquidjava/diagnostics/hints/Hint.java +++ b/liquidjava-verifier/src/main/java/liquidjava/diagnostics/hints/Hint.java @@ -36,7 +36,9 @@ public enum Kind { /** The object can be in any state: the state the failing call needs, and the constructors that create it */ NEEDED_STATE, /** A call whose result, checked right before the failing call, puts the object in a state that allows it */ - GUARD + GUARD, + /** A variable a loop changes, and how to state what holds for it on every iteration */ + LOOP_INVARIANT } public static Hint general(String message) { diff --git a/liquidjava-verifier/src/main/java/liquidjava/processor/context/VariableInstance.java b/liquidjava-verifier/src/main/java/liquidjava/processor/context/VariableInstance.java index 83239886..14f719be 100644 --- a/liquidjava-verifier/src/main/java/liquidjava/processor/context/VariableInstance.java +++ b/liquidjava-verifier/src/main/java/liquidjava/processor/context/VariableInstance.java @@ -1,6 +1,8 @@ package liquidjava.processor.context; import java.util.Optional; + +import liquidjava.diagnostics.InferredFacts; import liquidjava.rj_language.Predicate; import spoon.reflect.reference.CtTypeReference; @@ -9,6 +11,7 @@ public class VariableInstance extends RefinedVariable { private Variable parent; private StateChange stateChange; private CallResult returnedBy; + private InferredFacts inferredFacts; public VariableInstance(String name, CtTypeReference type, Predicate c) { super(name, type, c); @@ -53,6 +56,15 @@ public void setReturnedBy(CallResult returnedBy) { this.returnedBy = returnedBy; } + /** The facts that loop invariant inference added to the refinement of this instance, if any */ + public Optional getInferredFacts() { + return Optional.ofNullable(inferredFacts); + } + + public void setInferredFacts(InferredFacts inferredFacts) { + this.inferredFacts = inferredFacts; + } + public Optional getParent() { return parent == null ? Optional.empty() : Optional.of(parent); } diff --git a/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariantHint.java b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariantHint.java new file mode 100644 index 00000000..bd17149a --- /dev/null +++ b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariantHint.java @@ -0,0 +1,135 @@ +package liquidjava.processor.refinement_checker; + +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import liquidjava.diagnostics.Code; +import liquidjava.diagnostics.SourceReference; +import liquidjava.diagnostics.errors.RefinementError; +import liquidjava.diagnostics.hints.Hint; +import liquidjava.rj_language.Predicate; +import liquidjava.rj_language.ast.formatter.ExpressionFormatter; +import liquidjava.rj_language.ast.formatter.VariableFormatter; +import liquidjava.utils.Pair; +import liquidjava.utils.constants.Keys; +import spoon.reflect.code.CtExpression; +import spoon.reflect.code.CtFor; +import spoon.reflect.code.CtLocalVariable; +import spoon.reflect.code.CtLoop; +import spoon.reflect.code.CtVariableWrite; +import spoon.reflect.cu.SourcePosition; +import spoon.reflect.visitor.filter.TypeFilter; + +/** + * The hint of a refinement error in a loop whose counterexample gives a value to an {@code int} local variable the loop + * changes: the loop keeps only what holds on every iteration (see {@link LoopInvariants}), which a refinement on the + * declaration of the variable states. Expected is suggested as that refinement when it can be written for the variable. + */ +final class LoopInvariantHint { + + private LoopInvariantHint() { + } + + /** + * Adds the hint for the first variable of the counterexample that one of the loops changes, unless the error has + * one already. None is added when the variable is not a local one declared without a refinement, when expected is + * not about it, or when expected does not hold on the first iteration of that loop either, as what the loop forgets + * is then not the cause; nor when the refinement it would suggest does not hold before the loop. + * + * @param loops + * the invariants of the loops being checked, innermost first + */ + static void addTo(RefinementError error, List loops) { + if (error.getHints().stream().anyMatch(hint -> hint.kind() == Hint.Kind.LOOP_INVARIANT)) + return; + for (Pair assignment : error.getCounterexample().assignments()) { + String variable = VariableFormatter.withoutInstance(assignment.first()); + Optional loop = loops.stream() + .filter(invariants -> invariants.variables().contains(variable)).findFirst(); + if (loop.isPresent()) { + Optional> declaration = declaration(variable, loop.get().loop()); + boolean aboutVariable = error.getExpected().getVariableNames().stream() + .anyMatch(name -> VariableFormatter.withoutInstance(name).equals(variable)); + if (declaration.isPresent() && !isRefined(declaration.get()) && aboutVariable + && loop.get().holdsOnFirstIteration(error.getExpected())) + hint(error, declaration.get(), loop.get()).ifPresent(error::addHint); + return; + } + } + } + + private static Optional hint(RefinementError error, CtLocalVariable declaration, + LoopInvariants invariants) { + String variable = declaration.getSimpleName(); + CtLoop loop = invariants.loop(); + SourcePosition position = loop.getPosition(); + String line = "line " + position.getLine(); + String message = String.format( + "%s changes in the loop at %s, and LiquidJava only keeps what holds for it on every iteration. ", + Code.of(variable), line); + Optional refinement = refinementFor(variable, error.getExpected(), loop); + if (refinement.isPresent() && !invariants.holdsBefore(variable, refinement.get())) + return Optional.empty(); + if (refinement.isPresent()) + message += String.format("If %s should hold on every iteration, state it on the declaration: %s", + Code.of(ExpressionFormatter.format(refinement.get().substituteVariable(Keys.WILDCARD, variable))), + Code.of(annotated(declaration, ExpressionFormatter.format(refinement.get()), loop))); + else + message += "To state what holds on every iteration, add a " + Code.of("@Refinement") + + " to its declaration."; + return Optional.of(new Hint(Hint.Kind.LOOP_INVARIANT, message, SourceReference.of(message, line, position))); + } + + /** + * Expected as a refinement of the variable, on {@code _}, if it is about one of its values and otherwise only about + * variables the loop does not write, which the code can name + */ + private static Optional refinementFor(String variable, Predicate expected, CtLoop loop) { + List names = expected.getVariableNames().stream().distinct().toList(); + List values = names.stream().filter(name -> VariableFormatter.withoutInstance(name).equals(variable)) + .toList(); + Set written = loop.getElements(new TypeFilter>(CtVariableWrite.class)).stream() + .map(write -> write.getVariable().getSimpleName()).collect(Collectors.toSet()); + boolean othersNamed = names.stream().filter(name -> !values.contains(name)) + .allMatch(name -> !name.contains("#") && !written.contains(name)); + if (values.size() != 1 || !othersNamed) + return Optional.empty(); + return Optional.of(expected.substituteVariable(values.get(0), Keys.WILDCARD)); + } + + private static boolean isRefined(CtLocalVariable declaration) { + return declaration.getAnnotations().stream().anyMatch(annotation -> annotation.getAnnotationType() + .getQualifiedName().equals("liquidjava.specification.Refinement")); + } + + /** The declaration of a local variable the loop writes */ + private static Optional> declaration(String variable, CtLoop loop) { + return loop.getElements(new TypeFilter>(CtVariableWrite.class)).stream() + .filter(write -> write.getVariable().getSimpleName().equals(variable)) + .map(write -> write.getVariable().getDeclaration()) + .filter(declaration -> declaration instanceof CtLocalVariable) + .> map(declaration -> (CtLocalVariable) declaration).findFirst(); + } + + /** The declaration with the refinement, as written in code, in its for if it is in a for's initialization */ + private static String annotated(CtLocalVariable declaration, String refinement, CtLoop loop) { + CtExpression value = declaration.getDefaultExpression(); + String annotated = String.format("@Refinement(\"%s\") %s %s%s", refinement, + declaration.getType().getSimpleName(), declaration.getSimpleName(), + value == null ? "" : " = " + sourceOf(value)); + boolean inForInit = loop instanceof CtFor forLoop && forLoop.getForInit().contains(declaration); + return inForInit ? "for (" + annotated + "; ...)" : annotated + ";"; + } + + private static String sourceOf(CtExpression expression) { + SourcePosition position = expression.getPosition(); + if (position.isValidPosition() && position.getCompilationUnit() != null) { + String source = position.getCompilationUnit().getOriginalSourceCode(); + if (source != null && position.getSourceEnd() < source.length()) + return source.substring(position.getSourceStart(), position.getSourceEnd() + 1); + } + return expression.toString(); + } +} 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 40e15547..bf9fb255 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 @@ -10,10 +10,15 @@ import java.util.Set; import java.util.stream.Collectors; +import liquidjava.diagnostics.InferredFacts; +import liquidjava.diagnostics.InferredFacts.Point; import liquidjava.diagnostics.errors.LJError; import liquidjava.processor.context.RefinedVariable; import liquidjava.processor.context.VariableInstance; import liquidjava.rj_language.Predicate; +import liquidjava.rj_language.ast.Expression; +import liquidjava.rj_language.opt.VCSimplificationUtils; +import liquidjava.utils.constants.Keys; import liquidjava.utils.constants.Ops; import spoon.reflect.code.CtDo; import spoon.reflect.code.CtExpression; @@ -51,6 +56,8 @@ class LoopInvariants { private final List candidates = new ArrayList<>(); // the instance of each variable before the loop private final Map before = new LinkedHashMap<>(); + // the path conditions before the loop + private final List pathBefore; // 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 @@ -82,6 +89,7 @@ class LoopInvariants { this.checker = checker; this.loop = loop; this.variables = variables; + this.pathBefore = checker.vcChecker.getPathVariables(); for (String variable : variables) checker.getContext().getLastVariableInstance(variable) .ifPresent(instance -> before.put(variable, instance.getName())); @@ -93,6 +101,15 @@ && proved(candidate)) candidates.add(candidate); } + CtLoop loop() { + return loop; + } + + /** The {@code int} local variables the loop changes, for which invariants are inferred */ + List variables() { + return variables; + } + /** 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()); @@ -110,7 +127,7 @@ private String key(Predicate candidate) { void startIteration() { for (String variable : variables) checker.getContext().getLastVariableInstance(variable).ifPresent(instance -> head.put(variable, instance)); - addToLastInstances(candidates); + addToLastInstances(candidates, Point.ITERATION_START); dropped = false; reachable = true; atContinues = null; @@ -140,7 +157,7 @@ List atJoin(boolean completes) { /** After the continues joined: the new instances of the variables satisfy the facts {@link #atJoin} returned */ void joined(List facts) { - addToLastInstances(facts); + addToLastInstances(facts, Point.ITERATION_END); } /** @@ -177,7 +194,7 @@ boolean reachedFixpoint() { void afterLoop() { List facts = new ArrayList<>(candidates); InvariantCandidates.condition(condition(loop)).ifPresent(condition -> facts.add(condition.negate())); - addToLastInstances(facts); + addToLastInstances(facts, Point.AFTER_LOOP); } /** @@ -223,6 +240,36 @@ boolean checkAgainAfterError(java.util.function.Predicate canSkip) return true; } + /** + * Whether a fact holds here in the first iteration, when the variables at the loop head have their values before + * the loop + */ + boolean holdsOnFirstIteration(Predicate fact) { + Predicate first = new Predicate(); + for (Map.Entry entry : head.entrySet()) + if (before.containsKey(entry.getKey())) + first = Predicate.createConjunction(first, + Predicate.createEquals(Predicate.createVar(entry.getValue().getName()), + Predicate.createVar(before.get(entry.getKey())))); + return holds(first, fact); + } + + /** + * Whether a refinement, on {@code _}, holds for the value of a variable before the loop, from what is known there + */ + boolean holdsBefore(String variable, Predicate refinement) { + String instance = before.get(variable); + if (instance == null) + return false; + List pathHere = checker.vcChecker.getPathVariables(); + checker.vcChecker.replacePathVariables(pathBefore); + try { + return holds(new Predicate(), refinement.substituteVariable(Keys.WILDCARD, instance)); + } finally { + checker.vcChecker.replacePathVariables(pathHere); + } + } + /** 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); @@ -237,25 +284,37 @@ private List provedForNextIteration() { /** * 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. + * Unlike a path condition, the refinement of an instance is not dropped when the variable is assigned. The instance + * records them as inferred at {@code point} of the loop. */ - private void addToLastInstances(List facts) { + private void addToLastInstances(List facts, Point point) { for (String variable : variables) { Optional last = checker.getContext().getLastVariableInstance(variable); if (last.isEmpty()) continue; Predicate refinement = declared.computeIfAbsent(last.get(), RefinedVariable::getRefinement); + List added = new ArrayList<>(); for (Predicate fact : facts) - if (fact.getVariableNames().contains(variable)) - refinement = Predicate.createConjunction(refinement, onLastInstances(fact)); + if (fact.getVariableNames().contains(variable)) { + Predicate onLast = onLastInstances(fact); + refinement = Predicate.createConjunction(refinement, onLast); + added.addAll(VCSimplificationUtils.factsOf(onLast.getExpression())); + } last.get().setRefinement(refinement); + last.get().setInferredFacts( + added.isEmpty() ? null : new InferredFacts(last.get().getName(), added, loop.getPosition(), point)); } } /** Whether a fact on variable names holds for their last instances, from what is known here */ private boolean proved(Predicate fact) { + return holds(new Predicate(), onLastInstances(fact)); + } + + /** Whether {@code assumed} implies a fact, from what is known here */ + private boolean holds(Predicate assumed, Predicate fact) { try { - return checker.checkStateSMT(new Predicate(), onLastInstances(fact), loop.getPosition(), true); + return checker.checkStateSMT(assumed, fact, loop.getPosition(), true); } catch (LJError e) { return false; } 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 f09d17d4..1aedb6ea 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 @@ -17,6 +17,7 @@ import liquidjava.diagnostics.Diagnostics; import liquidjava.diagnostics.errors.LJError; +import liquidjava.diagnostics.errors.RefinementError; import liquidjava.processor.context.*; import liquidjava.processor.refinement_checker.general_checkers.MethodsFunctionsChecker; import liquidjava.processor.refinement_checker.general_checkers.OperationsChecker; @@ -1061,8 +1062,12 @@ private void checkUntilFixpoint(LoopTypestates states, LoopInvariants loopInvari states.recordNextIteration(); loopInvariants.recordNextIteration(); } catch (LJError e) { - if (!loopInvariants.checkAgainAfterError(statement -> canSkip(statement, states))) + if (!loopInvariants.checkAgainAfterError(statement -> canSkip(statement, states))) { + if (e instanceof RefinementError error) + LoopInvariantHint.addTo(error, + loops.stream().map(loop -> invariants.get(loop.loop())).toList()); throw e; + } diagnostics.getErrors().retainAll(errors); forgetInferredNestedIn(states.loop()); continue; diff --git a/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/VCChecker.java b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/VCChecker.java index e83f075a..189b5db9 100644 --- a/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/VCChecker.java +++ b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/VCChecker.java @@ -11,6 +11,7 @@ import liquidjava.diagnostics.errors.*; import liquidjava.diagnostics.DebugLog; +import liquidjava.diagnostics.InferredFacts; import liquidjava.diagnostics.SourceReference; import liquidjava.diagnostics.TranslationTable; import liquidjava.diagnostics.categories.ErrorCategory; @@ -27,6 +28,7 @@ import liquidjava.rj_language.opt.VCRelevantFacts; import liquidjava.rj_language.opt.VCSimplification; import liquidjava.rj_language.opt.VCSimplificationResult; +import liquidjava.rj_language.opt.VCSimplificationUtils; import liquidjava.smt.Counterexample; import liquidjava.smt.SMTEvaluator; import liquidjava.smt.SMTResult; @@ -92,6 +94,7 @@ public void processSubtyping(Predicate expectedType, List list, CtEl RefinementError error = new RefinementError(element.getPosition(), declarationPosition, expectedType, implBeforeChange.simplify(NeededVariables.forRefinementError(expectedType)), map, result.getCounterexample(), customMessage, context.getAliases()); + error.setInferredFacts(inferredFactsOf(error.getFound())); OriginNotes.unrefinedParameters(error, element, context).forEach(error::addMessageNote); OriginNotes.returnedValues(error, context).forEach(error::addMessageNote); throw error; @@ -469,9 +472,27 @@ protected void throwRefinementError(SourcePosition position, SourcePosition decl Predicate found, Counterexample counterexample, String customMessage) throws RefinementError { TranslationTable map = new TranslationTable(); VCImplication premises = buildPremiseChain(map, expected, found); - throw new RefinementError(position, declarationPosition, expected, + RefinementError error = new RefinementError(position, declarationPosition, expected, premises.simplify(NeededVariables.forRefinementError(expected)), map, counterexample, customMessage, context.getAliases()); + error.setInferredFacts(inferredFactsOf(error.getFound())); + throw error; + } + + /** The facts that loop invariant inference gave the values of the chain found was simplified from */ + private List inferredFactsOf(VCSimplificationResult found) { + List inferred = new ArrayList<>(); + for (VCImplication link = found.getOriginal().getImplication(); link != null; link = link.getNext()) { + if (!link.hasBinder() || !(context.getVariableByName(link.getName())instanceof VariableInstance instance) + || instance.getInferredFacts().isEmpty()) + continue; + InferredFacts facts = instance.getInferredFacts().get(); + List shown = VCSimplificationUtils.factsOf(link.getRefinement().getExpression()); + List kept = facts.facts().stream().filter(shown::contains).toList(); + if (!kept.isEmpty()) + inferred.add(new InferredFacts(facts.variable(), kept, facts.loop(), facts.point())); + } + return inferred; } /** What a state refinement error shows as found: what is known about the variables of both predicates */ diff --git a/liquidjava-verifier/src/test/java/liquidjava/api/tests/TestLoopInvariantDiagnostics.java b/liquidjava-verifier/src/test/java/liquidjava/api/tests/TestLoopInvariantDiagnostics.java new file mode 100644 index 00000000..742abcc6 --- /dev/null +++ b/liquidjava-verifier/src/test/java/liquidjava/api/tests/TestLoopInvariantDiagnostics.java @@ -0,0 +1,73 @@ +package liquidjava.api.tests; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.List; + +import org.junit.jupiter.api.Test; + +import liquidjava.api.CommandLineLauncher; +import liquidjava.diagnostics.Diagnostics; +import liquidjava.diagnostics.InferredFacts; +import liquidjava.diagnostics.InferredFacts.Point; +import liquidjava.diagnostics.SourceReference; +import liquidjava.diagnostics.errors.RefinementError; +import liquidjava.diagnostics.hints.Hint; +import liquidjava.rj_language.ast.formatter.ExpressionFormatter; + +class TestLoopInvariantDiagnostics { + + private static final String TEST_SUITE = "../liquidjava-example/src/main/java/testSuite/"; + + @Test + void factsInferredAtTheLoopHeadAreMarkedWithTheLoop() { + RefinementError error = errorAt("ErrorLoopInvariants.java", 48); + assertEquals("found `i@46#1 >= 0 && i@46#1 < 10 && i == i@46#1 + 3` but expected `i <= 10`", + error.getMessage()); + InferredFacts inferred = error.getInferredFacts().get(0); + assertEquals(1, error.getInferredFacts().size()); + assertEquals("i@46#1", error.getDisplayNames().get(inferred.variable())); + assertEquals(List.of("i@46#1 >= i@45"), shown(error, inferred)); + assertEquals(46, inferred.loop().getLine()); + assertEquals(Point.ITERATION_START, inferred.point()); + } + + @Test + void factsKnownAfterTheLoopAreMarkedWithTheLoop() { + RefinementError error = errorAt("ErrorLoopExitFacts.java", 45); + InferredFacts inferred = error.getInferredFacts().get(0); + assertEquals(1, error.getInferredFacts().size()); + assertEquals(List.of("i >= i@41", "!(i < 10)"), shown(error, inferred)); + assertEquals(42, inferred.loop().getLine()); + assertEquals(Point.AFTER_LOOP, inferred.point()); + } + + @Test + void hintSuggestsStatingExpectedOnTheDeclarationOfTheVariableTheLoopChanges() { + RefinementError error = errorAt("ErrorLoopInvariants.java", 25); + Hint hint = error.getHints().get(0); + assertEquals(1, error.getHints().size()); + assertEquals("`i` changes in the loop at line 24, and LiquidJava only keeps what holds for it on every " + + "iteration. If `i >= 0` should hold on every iteration, state it on the declaration: " + + "`@Refinement(\"_ >= 0\") int i = 0;`", hint.message()); + SourceReference reference = hint.reference(); + assertEquals("line 24", reference.text()); + assertEquals(24, reference.line()); + } + + @Test + void noHintWhenExpectedFailsOnTheFirstIterationToo() { + assertEquals(List.of(), errorAt("ErrorLoopUnprovedInvariant.java", 19).getHints()); + } + + private static List shown(RefinementError error, InferredFacts inferred) { + return inferred.facts().stream().map(fact -> ExpressionFormatter.format(fact, error.getDisplayNames())) + .toList(); + } + + private static RefinementError errorAt(String test, int line) { + CommandLineLauncher.launch(TEST_SUITE + test); + return Diagnostics.getInstance().getErrors().stream().filter(e -> e.getPosition().getLine() == line) + .map(RefinementError.class::cast).findFirst().orElseThrow(); + } +} From b22325df4b3277964b6e97bd71624b3231454e9d Mon Sep 17 00:00:00 2001 From: Catarina Gamboa Date: Tue, 24 Nov 2026 13:13:19 +0000 Subject: [PATCH 2/2] Mark only the inferred facts of values expected depends on Co-Authored-By: Claude Opus 5.5 --- .../refinement_checker/LoopInvariantHint.java | 21 ++++++++++++------- .../refinement_checker/VCChecker.java | 20 ++++++++++++------ .../tests/TestLoopInvariantDiagnostics.java | 5 +++++ 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariantHint.java b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariantHint.java index bd17149a..ef9c4574 100644 --- a/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariantHint.java +++ b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/LoopInvariantHint.java @@ -51,7 +51,7 @@ static void addTo(RefinementError error, List loops) { if (loop.isPresent()) { Optional> declaration = declaration(variable, loop.get().loop()); boolean aboutVariable = error.getExpected().getVariableNames().stream() - .anyMatch(name -> VariableFormatter.withoutInstance(name).equals(variable)); + .anyMatch(name -> isValueOf(name, variable)); if (declaration.isPresent() && !isRefined(declaration.get()) && aboutVariable && loop.get().holdsOnFirstIteration(error.getExpected())) hint(error, declaration.get(), loop.get()).ifPresent(error::addHint); @@ -88,10 +88,9 @@ private static Optional hint(RefinementError error, CtLocalVariable dec */ private static Optional refinementFor(String variable, Predicate expected, CtLoop loop) { List names = expected.getVariableNames().stream().distinct().toList(); - List values = names.stream().filter(name -> VariableFormatter.withoutInstance(name).equals(variable)) - .toList(); - Set written = loop.getElements(new TypeFilter>(CtVariableWrite.class)).stream() - .map(write -> write.getVariable().getSimpleName()).collect(Collectors.toSet()); + List values = names.stream().filter(name -> isValueOf(name, variable)).toList(); + Set written = writes(loop).stream().map(write -> write.getVariable().getSimpleName()) + .collect(Collectors.toSet()); boolean othersNamed = names.stream().filter(name -> !values.contains(name)) .allMatch(name -> !name.contains("#") && !written.contains(name)); if (values.size() != 1 || !othersNamed) @@ -99,6 +98,15 @@ private static Optional refinementFor(String variable, Predicate expe return Optional.of(expected.substituteVariable(values.get(0), Keys.WILDCARD)); } + /** Whether a name in a predicate is the variable or one of its instances */ + private static boolean isValueOf(String name, String variable) { + return VariableFormatter.withoutInstance(name).equals(variable); + } + + private static List> writes(CtLoop loop) { + return loop.getElements(new TypeFilter>(CtVariableWrite.class)); + } + private static boolean isRefined(CtLocalVariable declaration) { return declaration.getAnnotations().stream().anyMatch(annotation -> annotation.getAnnotationType() .getQualifiedName().equals("liquidjava.specification.Refinement")); @@ -106,8 +114,7 @@ private static boolean isRefined(CtLocalVariable declaration) { /** The declaration of a local variable the loop writes */ private static Optional> declaration(String variable, CtLoop loop) { - return loop.getElements(new TypeFilter>(CtVariableWrite.class)).stream() - .filter(write -> write.getVariable().getSimpleName().equals(variable)) + return writes(loop).stream().filter(write -> write.getVariable().getSimpleName().equals(variable)) .map(write -> write.getVariable().getDeclaration()) .filter(declaration -> declaration instanceof CtLocalVariable) .> map(declaration -> (CtLocalVariable) declaration).findFirst(); diff --git a/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/VCChecker.java b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/VCChecker.java index 189b5db9..3ad57260 100644 --- a/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/VCChecker.java +++ b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/VCChecker.java @@ -94,7 +94,7 @@ public void processSubtyping(Predicate expectedType, List list, CtEl RefinementError error = new RefinementError(element.getPosition(), declarationPosition, expectedType, implBeforeChange.simplify(NeededVariables.forRefinementError(expectedType)), map, result.getCounterexample(), customMessage, context.getAliases()); - error.setInferredFacts(inferredFactsOf(error.getFound())); + error.setInferredFacts(inferredFactsOf(error.getFound(), error.getExpected())); OriginNotes.unrefinedParameters(error, element, context).forEach(error::addMessageNote); OriginNotes.returnedValues(error, context).forEach(error::addMessageNote); throw error; @@ -475,15 +475,23 @@ protected void throwRefinementError(SourcePosition position, SourcePosition decl RefinementError error = new RefinementError(position, declarationPosition, expected, premises.simplify(NeededVariables.forRefinementError(expected)), map, counterexample, customMessage, context.getAliases()); - error.setInferredFacts(inferredFactsOf(error.getFound())); + error.setInferredFacts(inferredFactsOf(error.getFound(), error.getExpected())); throw error; } - /** The facts that loop invariant inference gave the values of the chain found was simplified from */ - private List inferredFactsOf(VCSimplificationResult found) { + /** + * The facts that loop invariant inference gave the values of the chain found was simplified from, those linked to + * the terms of expected + */ + private List inferredFactsOf(VCSimplificationResult found, Predicate expected) { + VCImplication chain = found.getOriginal().getImplication(); + List expectedTerms = VCSimplificationUtils.termsOf(expected.getExpression()); + Set linked = VCSimplificationUtils + .linkedTerms(VCSimplificationUtils.factsOf(chain.toPredicate().getExpression()), expectedTerms); List inferred = new ArrayList<>(); - for (VCImplication link = found.getOriginal().getImplication(); link != null; link = link.getNext()) { - if (!link.hasBinder() || !(context.getVariableByName(link.getName())instanceof VariableInstance instance) + for (VCImplication link = chain; link != null; link = link.getNext()) { + if (!link.hasBinder() || !(expectedTerms.isEmpty() || linked.contains(link.getName())) + || !(context.getVariableByName(link.getName())instanceof VariableInstance instance) || instance.getInferredFacts().isEmpty()) continue; InferredFacts facts = instance.getInferredFacts().get(); diff --git a/liquidjava-verifier/src/test/java/liquidjava/api/tests/TestLoopInvariantDiagnostics.java b/liquidjava-verifier/src/test/java/liquidjava/api/tests/TestLoopInvariantDiagnostics.java index 742abcc6..87eb9967 100644 --- a/liquidjava-verifier/src/test/java/liquidjava/api/tests/TestLoopInvariantDiagnostics.java +++ b/liquidjava-verifier/src/test/java/liquidjava/api/tests/TestLoopInvariantDiagnostics.java @@ -42,6 +42,11 @@ void factsKnownAfterTheLoopAreMarkedWithTheLoop() { assertEquals(Point.AFTER_LOOP, inferred.point()); } + @Test + void factsInferredForValuesExpectedDoesNotDependOnAreNotMarked() { + assertEquals(List.of(), errorAt("ErrorLoopUnprovedInvariant.java", 19).getInferredFacts()); + } + @Test void hintSuggestsStatingExpectedOnTheDeclarationOfTheVariableTheLoopChanges() { RefinementError error = errorAt("ErrorLoopInvariants.java", 25);