Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package testSuite;

import liquidjava.specification.Refinement;

// After a loop that only exits through its condition, the invariants hold and the condition is false
@SuppressWarnings("unused")
public class CorrectLoopExitFacts {
static boolean next() {
return true;
}

static void atLeast(int i, @Refinement("_ <= i") int n) {}

static void ten(@Refinement("_ == 10") int x) {}

static void countUp(int n) {
int i = 0;
while (i < n) {
i++;
}
atLeast(i, n);
}

static void countUpWithContinue() {
int i = 0;
for (; i < 10; i++) {
if (next())
continue;
}
ten(i);
}

// the catch block may start from any value i had in the loop
static void loopInTry(boolean fail) {
int i = 0;
try {
while (i < 10) {
if (fail)
throw new RuntimeException();
i++;
}
} catch (RuntimeException e) {
}
if (i != 10)
return;
ten(i);
}
}
44 changes: 44 additions & 0 deletions liquidjava-example/src/main/java/testSuite/ErrorLoopExitFacts.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package testSuite;

import liquidjava.specification.Refinement;

// After a loop that may exit elsewhere than at its condition, the condition is not known to be false
@SuppressWarnings("unused")
public class ErrorLoopExitFacts {
static boolean next() {
return true;
}

static void atLeast(int i, @Refinement("_ <= i") int n) {}

static void atMostThree(@Refinement("_ <= 3") int x) {}

static void ten(@Refinement("_ == 10") int x) {}

static void exitByBreak(int n) {
int i = 0;
while (i < n) {
if (next())
break;
i++;
}
atLeast(i, n); // Expect: Refinement Error
}

// i <= 3 holds at the start of each iteration, but the loop exits after the body, with i == 5
static void doWhile() {
int i = 0;
do {
i = i + 5;
} while (i < 3);
atMostThree(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;
while (i++ < 10) {
}
ten(i); // Expect: Refinement Error
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,36 @@ private static String nonStrict(BinaryOperatorKind kind) {
};
}

/**
* The predicate a loop condition stands for, if it is built of {@code &&}, {@code ||}, {@code !} and comparisons of
* the terms a candidate may mention
*/
static Optional<Predicate> condition(CtExpression<?> condition) {
if (condition instanceof CtUnaryOperator<?> operator && operator.getKind() == UnaryOperatorKind.NOT)
return condition(operator.getOperand()).map(Predicate::negate);
if (!(condition instanceof CtBinaryOperator<?> operator))
return Optional.empty();
String op = switch (operator.getKind()) {
case AND -> Ops.AND;
case OR -> Ops.OR;
case LT -> Ops.LT;
case LE -> Ops.LE;
case GT -> Ops.GT;
case GE -> Ops.GE;
case EQ -> Ops.EQ;
case NE -> Ops.NEQ;
default -> null;
};
boolean logical = operator.getKind() == BinaryOperatorKind.AND || operator.getKind() == BinaryOperatorKind.OR;
Optional<Predicate> left = logical ? condition(operator.getLeftHandOperand())
: term(operator.getLeftHandOperand());
Optional<Predicate> right = logical ? condition(operator.getRightHandOperand())
: term(operator.getRightHandOperand());
if (op == null || left.isEmpty() || right.isEmpty())
return Optional.empty();
return Optional.of(Predicate.createOperation(left.get(), op, right.get()));
}

/** The integer term an expression stands for, if it is built only of what a candidate may mention */
private static Optional<Predicate> term(CtExpression<?> expression) {
if (expression instanceof CtLiteral<?> literal && literal.getValue()instanceof Integer value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,16 @@ boolean reachedFixpoint() {
return !dropped;
}

/**
* After a loop that only exits through its condition, once what it changes is forgotten: the variables satisfy the
* invariants, and the condition is false, as at the loop head where it exited
*/
void afterLoop() {
List<Predicate> facts = new ArrayList<>(candidates);
InvariantCandidates.condition(condition(loop)).ifPresent(condition -> facts.add(condition.negate()));
addToLastInstances(facts);
}

/** The candidates, and that each variable grew or shrank since the loop head, that are proved here */
private List<Predicate> provedForNextIteration() {
List<Predicate> facts = new ArrayList<>(candidates);
Expand Down Expand Up @@ -180,7 +190,8 @@ private Predicate onLastInstances(Predicate fact) {
return result;
}

private static CtExpression<Boolean> condition(CtLoop loop) {
/** The condition of a loop, or null if it has none */
static CtExpression<Boolean> condition(CtLoop loop) {
if (loop instanceof CtWhile whileLoop)
return whileLoop.getLoopingExpression();
if (loop instanceof CtDo doLoop)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1015,6 +1015,8 @@ private void visitLoop(CtLoop loop, Consumer<LoopTypestates> iteration) {
}
vcChecker.restorePathVariables(pathVariables);
havocChangedIn(loop, states.tracked());
if (exitsAtHeadThroughCondition(loop))
loopInvariants.afterLoop();
states.finishLoop();
}

Expand Down Expand Up @@ -1109,6 +1111,18 @@ private void scanBody(CtLoop loop, LoopTypestates states) {
loopInvariants.endBody(completes);
}

/**
* Whether the code after a loop is only reached from its head, where the condition is false: the loop is not a
* do-while, which exits after its body, no break leaves it, and its condition writes no variable
*/
private static boolean exitsAtHeadThroughCondition(CtLoop loop) {
CtExpression<Boolean> condition = LoopInvariants.condition(loop);
return !(loop instanceof CtDo)
&& loop.getElements(new TypeFilter<>(CtBreak.class)).stream()
.noneMatch(jump -> jumpTarget(jump) == loop)
&& (condition == null || condition.getElements(new TypeFilter<>(CtVariableWrite.class)).isEmpty());
}

/** The loop being checked that {@code jump} leaves, if any */
private Optional<LoopTypestates> loopLeftBy(CtLabelledFlowBreak jump) {
CtElement target = jumpTarget(jump);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,10 @@ private void addAnyOfInstances(Map<Variable, VariableInstance> before,
for (VariableInstance vi : instances)
anyOf = Predicate.createDisjunction(anyOf, vi.getRenamedRefinements(name));
}
// a recorded instance may refer to values of a block that ended (e.g. a loop body checked again), which
// are no longer known: the variable is then unknown
if (anyOf.getVariableNames().stream().anyMatch(n -> !n.equals(name) && !context.hasVariable(n)))
anyOf = new Predicate();
context.addInstanceToContext(name, v.getType(), anyOf, element);
context.addRefinementInstanceToVariable(v.getName(), name);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,15 @@ void atMostAFixedNumberPerVariable() {
.size());
}

@Test
void translatesConditionsOverTheSameTerms() {
// printed without parentheses
assertEquals("!i < n || i == 0 && i != n", InvariantCandidates
.condition(condition("!(i < n) || i == 0 && i != n")).map(Predicate::toString).orElseThrow());
assertEquals(Optional.empty(), InvariantCandidates.condition(condition("i < n && i < size()")));
assertEquals(Optional.empty(), InvariantCandidates.condition(condition("true")));
}

private static List<String> candidates(String variable, String before, String condition) {
return InvariantCandidates.of(variable, Optional.ofNullable(before), condition(condition)).stream()
.map(Predicate::toString).toList();
Expand Down
Loading