Skip to content

Commit 2bd898a

Browse files
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 <[email protected]>
1 parent 73c2c5f commit 2bd898a

2 files changed

Lines changed: 211 additions & 0 deletions

File tree

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
package liquidjava.processor.refinement_checker;
2+
3+
import java.util.ArrayList;
4+
import java.util.LinkedHashSet;
5+
import java.util.List;
6+
import java.util.Optional;
7+
import java.util.Set;
8+
9+
import liquidjava.rj_language.Predicate;
10+
import liquidjava.rj_language.ast.UnaryExpression;
11+
import liquidjava.utils.constants.Ops;
12+
import liquidjava.utils.constants.Types;
13+
import spoon.reflect.code.BinaryOperatorKind;
14+
import spoon.reflect.code.CtBinaryOperator;
15+
import spoon.reflect.code.CtExpression;
16+
import spoon.reflect.code.CtLiteral;
17+
import spoon.reflect.code.CtLocalVariable;
18+
import spoon.reflect.code.CtUnaryOperator;
19+
import spoon.reflect.code.CtVariableRead;
20+
import spoon.reflect.code.UnaryOperatorKind;
21+
import spoon.reflect.declaration.CtParameter;
22+
import spoon.reflect.declaration.CtVariable;
23+
24+
/**
25+
* The candidate invariants of an {@code int} local variable that a loop changes: facts that may hold at the loop head
26+
* on every iteration, to be kept only if they are proved there. As the qualifiers of Liquid Types, they come from a
27+
* fixed set of shapes:
28+
* <ul>
29+
* <li>{@code x >= x0} and {@code x <= x0}, with {@code x0} the instance of {@code x} before the loop: it only grows, or
30+
* only shrinks;</li>
31+
* <li>the comparisons of the loop condition that mention {@code x}, made non-strict so that the iteration that ends the
32+
* loop can keep them ({@code x < n} gives {@code x <= n}).</li>
33+
* </ul>
34+
* The comparisons are taken from the conjuncts of the condition, and only over integer literals, {@code int} local
35+
* variables and parameters, and {@code +}, {@code -} and {@code *}; a field or a call may change out of sight of the
36+
* loop.
37+
*/
38+
final class InvariantCandidates {
39+
40+
/** The most candidates of a variable, so that a loop costs a bounded number of checks */
41+
static final int MAX_PER_VARIABLE = 6;
42+
43+
private InvariantCandidates() {
44+
}
45+
46+
/**
47+
* @param variable
48+
* the name of an {@code int} local variable the loop changes
49+
* @param before
50+
* the name of its instance just before the loop, if it has one
51+
* @param condition
52+
* the loop condition, or null if it has none
53+
*
54+
* @return the candidates in a fixed order, without duplicates
55+
*/
56+
static List<Predicate> of(String variable, Optional<String> before, CtExpression<Boolean> condition) {
57+
Set<Predicate> candidates = new LinkedHashSet<>();
58+
before.ifPresent(instance -> {
59+
candidates.add(
60+
Predicate.createOperation(Predicate.createVar(variable), Ops.GE, Predicate.createVar(instance)));
61+
candidates.add(
62+
Predicate.createOperation(Predicate.createVar(variable), Ops.LE, Predicate.createVar(instance)));
63+
});
64+
for (CtBinaryOperator<?> comparison : comparisons(condition)) {
65+
Optional<Predicate> left = term(comparison.getLeftHandOperand());
66+
Optional<Predicate> right = term(comparison.getRightHandOperand());
67+
if (left.isPresent() && right.isPresent() && (left.get().getVariableNames().contains(variable)
68+
|| right.get().getVariableNames().contains(variable)))
69+
candidates.add(Predicate.createOperation(left.get(), nonStrict(comparison.getKind()), right.get()));
70+
}
71+
return candidates.stream().limit(MAX_PER_VARIABLE).toList();
72+
}
73+
74+
/** The order comparisons ({@code <}, {@code <=}, {@code >}, {@code >=}) among the conjuncts of {@code condition} */
75+
private static List<CtBinaryOperator<?>> comparisons(CtExpression<?> condition) {
76+
List<CtBinaryOperator<?>> comparisons = new ArrayList<>();
77+
if (condition instanceof CtBinaryOperator<?> operator) {
78+
switch (operator.getKind()) {
79+
case AND -> {
80+
comparisons.addAll(comparisons(operator.getLeftHandOperand()));
81+
comparisons.addAll(comparisons(operator.getRightHandOperand()));
82+
}
83+
case LT, LE, GT, GE -> comparisons.add(operator);
84+
default -> {
85+
}
86+
}
87+
}
88+
return comparisons;
89+
}
90+
91+
private static String nonStrict(BinaryOperatorKind kind) {
92+
return switch (kind) {
93+
case LT, LE -> Ops.LE;
94+
case GT, GE -> Ops.GE;
95+
default -> throw new IllegalArgumentException("Not an order comparison: " + kind);
96+
};
97+
}
98+
99+
/** The integer term an expression stands for, if it is built only of what a candidate may mention */
100+
private static Optional<Predicate> term(CtExpression<?> expression) {
101+
if (expression instanceof CtLiteral<?> literal && literal.getValue()instanceof Integer value)
102+
return Optional.of(Predicate.createLit(value.toString(), Types.INT));
103+
if (expression instanceof CtVariableRead<?> read && isIntLocal(read.getVariable().getDeclaration()))
104+
return Optional.of(Predicate.createVar(read.getVariable().getSimpleName()));
105+
if (expression instanceof CtUnaryOperator<?> operator && operator.getKind() == UnaryOperatorKind.NEG)
106+
return term(operator.getOperand())
107+
.map(operand -> new Predicate(new UnaryExpression(Ops.MINUS, operand.getExpression())));
108+
if (expression instanceof CtBinaryOperator<?> operator) {
109+
String op = switch (operator.getKind()) {
110+
case PLUS -> Ops.PLUS;
111+
case MINUS -> Ops.MINUS;
112+
case MUL -> Ops.MUL;
113+
default -> null;
114+
};
115+
Optional<Predicate> left = term(operator.getLeftHandOperand());
116+
Optional<Predicate> right = term(operator.getRightHandOperand());
117+
if (op != null && left.isPresent() && right.isPresent())
118+
return Optional.of(Predicate.createOperation(left.get(), op, right.get()));
119+
}
120+
return Optional.empty();
121+
}
122+
123+
/** Whether a variable is an {@code int} local variable or parameter */
124+
private static boolean isIntLocal(CtVariable<?> variable) {
125+
return (variable instanceof CtLocalVariable<?> || variable instanceof CtParameter<?>)
126+
&& variable.getType() != null && variable.getType().getQualifiedName().equals(Types.INT);
127+
}
128+
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package liquidjava.processor.refinement_checker;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.List;
6+
import java.util.Optional;
7+
8+
import org.junit.jupiter.api.Test;
9+
10+
import liquidjava.rj_language.Predicate;
11+
import liquidjava.rj_language.ast.BinaryExpression;
12+
import spoon.Launcher;
13+
import spoon.reflect.code.CtExpression;
14+
import spoon.reflect.code.CtWhile;
15+
import spoon.reflect.visitor.filter.TypeFilter;
16+
17+
class InvariantCandidatesTest {
18+
19+
@Test
20+
void growsOrShrinksFromItsValueBeforeTheLoop() {
21+
assertEquals(List.of("i >= i0", "i <= i0"), candidates("i", "i0", "true"));
22+
}
23+
24+
@Test
25+
void noBoundsFromBeforeWithoutAnInstance() {
26+
assertEquals(List.of("i <= n"), candidates("i", null, "i < n"));
27+
}
28+
29+
@Test
30+
void weakensTheComparisonsOfTheCondition() {
31+
assertEquals(List.of("i >= i0", "i <= i0", "i <= n", "0 <= i", "i >= n - 1", "2 * i >= -n"),
32+
candidates("i", "i0", "i < n && 0 <= i && i > n - 1 && 2 * i >= -n"));
33+
}
34+
35+
@Test
36+
void keepsTheGroupingOfTerms() {
37+
// printed without parentheses: the right-hand side is n - (n - 1), not n - n - 1
38+
Predicate candidate = InvariantCandidates.of("i", Optional.empty(), condition("i < n - (n - 1)")).get(0);
39+
BinaryExpression bound = (BinaryExpression) candidate.getExpression().getChildren().get(1);
40+
assertEquals("n - 1", bound.getSecondOperand().toString());
41+
}
42+
43+
@Test
44+
void onlyComparisonsThatMentionTheVariable() {
45+
assertEquals(List.of("i <= 10"), candidates("i", null, "n > 0 && i < 10"));
46+
}
47+
48+
@Test
49+
void onlyComparisonsTheConditionImplies() {
50+
assertEquals(List.of(), candidates("i", null, "i < n || i > 10"));
51+
assertEquals(List.of(), candidates("i", null, "!(i < n)"));
52+
assertEquals(List.of(), candidates("i", null, "i != n"));
53+
}
54+
55+
@Test
56+
void onlyTermsOverLiteralsAndIntLocals() {
57+
assertEquals(List.of(), candidates("i", null, "i < field && i < size() && i < (int) d && i < n / 2"));
58+
assertEquals(List.of(), candidates("i", null, "i < 10L"));
59+
}
60+
61+
@Test
62+
void atMostAFixedNumberPerVariable() {
63+
assertEquals(InvariantCandidates.MAX_PER_VARIABLE,
64+
InvariantCandidates
65+
.of("i", Optional.of("i0"),
66+
condition("i < n && i < n + 1 && i < n + 2 && i < n + 3 && i < n + 4 && i < n + 5"))
67+
.size());
68+
}
69+
70+
private static List<String> candidates(String variable, String before, String condition) {
71+
return InvariantCandidates.of(variable, Optional.ofNullable(before), condition(condition)).stream()
72+
.map(Predicate::toString).toList();
73+
}
74+
75+
/** The condition of a loop in a method with int locals i and n, an int field, a double d and a size() method */
76+
@SuppressWarnings("unchecked")
77+
private static CtExpression<Boolean> condition(String condition) {
78+
var type = Launcher
79+
.parseClass("class C { int field; int size() { return 0; } void f(int n, double d) { int i0 = 0;"
80+
+ " int i = 0; while (" + condition + ") { i++; } } }");
81+
return type.getElements(new TypeFilter<>(CtWhile.class)).get(0).getLoopingExpression();
82+
}
83+
}

0 commit comments

Comments
 (0)