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
Expand Up @@ -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());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -48,6 +49,8 @@ class LoopInvariants {
private final CtLoop loop;
private final List<String> variables;
private final List<Predicate> candidates = new ArrayList<>();
// the instance of each variable before the loop
private final Map<String, String> before = new LinkedHashMap<>();
// the instance of each variable at the loop head
private final Map<String, VariableInstance> head = new LinkedHashMap<>();
// the refinement of each instance before facts were added to it
Expand All @@ -71,18 +74,36 @@ 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<String> variables) {
LoopInvariants(RefinementTypeChecker checker, CtLoop loop, List<String> variables, Set<String> previous) {
this.checker = checker;
this.loop = loop;
this.variables = variables;
for (String variable : variables) {
Optional<String> 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<String> 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<String, String> 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 */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ public class RefinementTypeChecker extends TypeChecker {
private final Deque<LoopTypestates> loops = new ArrayDeque<>();
// the invariants inferred for the loops being checked
private final Map<CtLoop, LoopInvariants> 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<CtLoop, Set<String>> lastInferred = new IdentityHashMap<>();

public RefinementTypeChecker(Context context, Factory factory) {
super(context, factory);
Expand Down Expand Up @@ -1007,16 +1012,22 @@ private void visitLoop(CtLoop loop, Consumer<LoopTypestates> iteration) {
Set<String> 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<String> 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());
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1162,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<Predicate> joinedFacts = loopInvariants.atJoin(completes);
vcChecker.restorePathVariables(pathVariables);
Expand Down
Loading