From ddbe7c3e7f84be9e98a9b39b0213f73aec3cade4 Mon Sep 17 00:00:00 2001 From: Catarina Gamboa Date: Mon, 23 Nov 2026 14:01:09 +0000 Subject: [PATCH] Add the candidate invariants of the int locals a loop changes For each int local variable a loop changes, the facts that may hold at the loop head on every iteration, as in Liquid Types' qualifiers: that it only grows or only shrinks from its value before the loop, and the comparisons of the loop condition that mention it, made non-strict. Terms are limited to integer literals, int locals and parameters, and +, - and *, with a cap per variable. Not used by the checker yet. Co-Authored-By: Claude Opus 5.5 --- .../InvariantCandidates.java | 128 ++++++++++++++++++ .../InvariantCandidatesTest.java | 83 ++++++++++++ 2 files changed, 211 insertions(+) create mode 100644 liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/InvariantCandidates.java create mode 100644 liquidjava-verifier/src/test/java/liquidjava/processor/refinement_checker/InvariantCandidatesTest.java diff --git a/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/InvariantCandidates.java b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/InvariantCandidates.java new file mode 100644 index 00000000..ba8b00dd --- /dev/null +++ b/liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/InvariantCandidates.java @@ -0,0 +1,128 @@ +package liquidjava.processor.refinement_checker; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import liquidjava.rj_language.Predicate; +import liquidjava.rj_language.ast.UnaryExpression; +import liquidjava.utils.constants.Ops; +import liquidjava.utils.constants.Types; +import spoon.reflect.code.BinaryOperatorKind; +import spoon.reflect.code.CtBinaryOperator; +import spoon.reflect.code.CtExpression; +import spoon.reflect.code.CtLiteral; +import spoon.reflect.code.CtLocalVariable; +import spoon.reflect.code.CtUnaryOperator; +import spoon.reflect.code.CtVariableRead; +import spoon.reflect.code.UnaryOperatorKind; +import spoon.reflect.declaration.CtParameter; +import spoon.reflect.declaration.CtVariable; + +/** + * The candidate invariants of an {@code int} local variable that a loop changes: facts that may hold at the loop head + * on every iteration, to be kept only if they are proved there. As the qualifiers of Liquid Types, they come from a + * fixed set of shapes: + * + * The comparisons are taken from the conjuncts of the condition, and only over integer literals, {@code int} local + * variables and parameters, and {@code +}, {@code -} and {@code *}; a field or a call may change out of sight of the + * loop. + */ +final class InvariantCandidates { + + /** The most candidates of a variable, so that a loop costs a bounded number of checks */ + static final int MAX_PER_VARIABLE = 6; + + private InvariantCandidates() { + } + + /** + * @param variable + * the name of an {@code int} local variable the loop changes + * @param before + * the name of its instance just before the loop, if it has one + * @param condition + * the loop condition, or null if it has none + * + * @return the candidates in a fixed order, without duplicates + */ + static List of(String variable, Optional before, CtExpression condition) { + Set candidates = new LinkedHashSet<>(); + before.ifPresent(instance -> { + candidates.add( + Predicate.createOperation(Predicate.createVar(variable), Ops.GE, Predicate.createVar(instance))); + candidates.add( + Predicate.createOperation(Predicate.createVar(variable), Ops.LE, Predicate.createVar(instance))); + }); + for (CtBinaryOperator comparison : comparisons(condition)) { + Optional left = term(comparison.getLeftHandOperand()); + Optional right = term(comparison.getRightHandOperand()); + if (left.isPresent() && right.isPresent() && (left.get().getVariableNames().contains(variable) + || right.get().getVariableNames().contains(variable))) + candidates.add(Predicate.createOperation(left.get(), nonStrict(comparison.getKind()), right.get())); + } + return candidates.stream().limit(MAX_PER_VARIABLE).toList(); + } + + /** The order comparisons ({@code <}, {@code <=}, {@code >}, {@code >=}) among the conjuncts of {@code condition} */ + private static List> comparisons(CtExpression condition) { + List> comparisons = new ArrayList<>(); + if (condition instanceof CtBinaryOperator operator) { + switch (operator.getKind()) { + case AND -> { + comparisons.addAll(comparisons(operator.getLeftHandOperand())); + comparisons.addAll(comparisons(operator.getRightHandOperand())); + } + case LT, LE, GT, GE -> comparisons.add(operator); + default -> { + } + } + } + return comparisons; + } + + private static String nonStrict(BinaryOperatorKind kind) { + return switch (kind) { + case LT, LE -> Ops.LE; + case GT, GE -> Ops.GE; + default -> throw new IllegalArgumentException("Not an order comparison: " + kind); + }; + } + + /** The integer term an expression stands for, if it is built only of what a candidate may mention */ + private static Optional term(CtExpression expression) { + if (expression instanceof CtLiteral literal && literal.getValue()instanceof Integer value) + return Optional.of(Predicate.createLit(value.toString(), Types.INT)); + if (expression instanceof CtVariableRead read && isIntLocal(read.getVariable().getDeclaration())) + return Optional.of(Predicate.createVar(read.getVariable().getSimpleName())); + if (expression instanceof CtUnaryOperator operator && operator.getKind() == UnaryOperatorKind.NEG) + return term(operator.getOperand()) + .map(operand -> new Predicate(new UnaryExpression(Ops.MINUS, operand.getExpression()))); + if (expression instanceof CtBinaryOperator operator) { + String op = switch (operator.getKind()) { + case PLUS -> Ops.PLUS; + case MINUS -> Ops.MINUS; + case MUL -> Ops.MUL; + default -> null; + }; + Optional left = term(operator.getLeftHandOperand()); + Optional right = term(operator.getRightHandOperand()); + if (op != null && left.isPresent() && right.isPresent()) + return Optional.of(Predicate.createOperation(left.get(), op, right.get())); + } + return Optional.empty(); + } + + /** Whether a variable is an {@code int} local variable or parameter */ + private static boolean isIntLocal(CtVariable variable) { + return (variable instanceof CtLocalVariable || variable instanceof CtParameter) + && variable.getType() != null && variable.getType().getQualifiedName().equals(Types.INT); + } +} diff --git a/liquidjava-verifier/src/test/java/liquidjava/processor/refinement_checker/InvariantCandidatesTest.java b/liquidjava-verifier/src/test/java/liquidjava/processor/refinement_checker/InvariantCandidatesTest.java new file mode 100644 index 00000000..152c7683 --- /dev/null +++ b/liquidjava-verifier/src/test/java/liquidjava/processor/refinement_checker/InvariantCandidatesTest.java @@ -0,0 +1,83 @@ +package liquidjava.processor.refinement_checker; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +import liquidjava.rj_language.Predicate; +import liquidjava.rj_language.ast.BinaryExpression; +import spoon.Launcher; +import spoon.reflect.code.CtExpression; +import spoon.reflect.code.CtWhile; +import spoon.reflect.visitor.filter.TypeFilter; + +class InvariantCandidatesTest { + + @Test + void growsOrShrinksFromItsValueBeforeTheLoop() { + assertEquals(List.of("i >= i0", "i <= i0"), candidates("i", "i0", "true")); + } + + @Test + void noBoundsFromBeforeWithoutAnInstance() { + assertEquals(List.of("i <= n"), candidates("i", null, "i < n")); + } + + @Test + void weakensTheComparisonsOfTheCondition() { + assertEquals(List.of("i >= i0", "i <= i0", "i <= n", "0 <= i", "i >= n - 1", "2 * i >= -n"), + candidates("i", "i0", "i < n && 0 <= i && i > n - 1 && 2 * i >= -n")); + } + + @Test + void keepsTheGroupingOfTerms() { + // printed without parentheses: the right-hand side is n - (n - 1), not n - n - 1 + Predicate candidate = InvariantCandidates.of("i", Optional.empty(), condition("i < n - (n - 1)")).get(0); + BinaryExpression bound = (BinaryExpression) candidate.getExpression().getChildren().get(1); + assertEquals("n - 1", bound.getSecondOperand().toString()); + } + + @Test + void onlyComparisonsThatMentionTheVariable() { + assertEquals(List.of("i <= 10"), candidates("i", null, "n > 0 && i < 10")); + } + + @Test + void onlyComparisonsTheConditionImplies() { + assertEquals(List.of(), candidates("i", null, "i < n || i > 10")); + assertEquals(List.of(), candidates("i", null, "!(i < n)")); + assertEquals(List.of(), candidates("i", null, "i != n")); + } + + @Test + void onlyTermsOverLiteralsAndIntLocals() { + assertEquals(List.of(), candidates("i", null, "i < field && i < size() && i < (int) d && i < n / 2")); + assertEquals(List.of(), candidates("i", null, "i < 10L")); + } + + @Test + void atMostAFixedNumberPerVariable() { + assertEquals(InvariantCandidates.MAX_PER_VARIABLE, + InvariantCandidates + .of("i", Optional.of("i0"), + condition("i < n && i < n + 1 && i < n + 2 && i < n + 3 && i < n + 4 && i < n + 5")) + .size()); + } + + private static List candidates(String variable, String before, String condition) { + return InvariantCandidates.of(variable, Optional.ofNullable(before), condition(condition)).stream() + .map(Predicate::toString).toList(); + } + + /** The condition of a loop in a method with int locals i and n, an int field, a double d and a size() method */ + @SuppressWarnings("unchecked") + private static CtExpression condition(String condition) { + var type = Launcher + .parseClass("class C { int field; int size() { return 0; } void f(int n, double d) { int i0 = 0;" + + " int i = 0; while (" + condition + ") { i++; } } }"); + return type.getElements(new TypeFilter<>(CtWhile.class)).get(0).getLoopingExpression(); + } +}