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 @@ -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() {
Expand All @@ -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) {
Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Expression> 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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -48,6 +49,7 @@ public class RefinementError extends LJError {
private final List<AliasExpansion> foundAliases;
private final List<AliasExpansion> expectedAliases;
private final List<String> aliasDeclarations;
private List<InferredFacts> inferredFacts = List.of();

public RefinementError(SourcePosition position, SourcePosition declarationPosition, Predicate expected,
VCSimplificationResult found, TranslationTable translationTable, Counterexample counterexample,
Expand Down Expand Up @@ -117,6 +119,15 @@ public List<AliasExpansion> getExpectedAliases() {
return expectedAliases;
}

/** The facts of found that loop invariant inference gave the values it is about */
public List<InferredFacts> getInferredFacts() {
return inferredFacts;
}

public void setInferredFacts(List<InferredFacts> inferredFacts) {
this.inferredFacts = List.copyOf(inferredFacts);
}

/** A where line declaring each alias the message uses, then the other notes */
@Override
public List<String> getMessageNotes() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -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);
Expand Down Expand Up @@ -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<InferredFacts> getInferredFacts() {
return Optional.ofNullable(inferredFacts);
}

public void setInferredFacts(InferredFacts inferredFacts) {
this.inferredFacts = inferredFacts;
}

public Optional<Variable> getParent() {
return parent == null ? Optional.empty() : Optional.of(parent);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
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<LoopInvariants> loops) {
if (error.getHints().stream().anyMatch(hint -> hint.kind() == Hint.Kind.LOOP_INVARIANT))
return;
for (Pair<String, String> assignment : error.getCounterexample().assignments()) {
String variable = VariableFormatter.withoutInstance(assignment.first());
Optional<LoopInvariants> loop = loops.stream()
.filter(invariants -> invariants.variables().contains(variable)).findFirst();
if (loop.isPresent()) {
Optional<CtLocalVariable<?>> declaration = declaration(variable, loop.get().loop());
boolean aboutVariable = error.getExpected().getVariableNames().stream()
.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);
return;
}
}
}

private static Optional<Hint> 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<Predicate> 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<Predicate> refinementFor(String variable, Predicate expected, CtLoop loop) {
List<String> names = expected.getVariableNames().stream().distinct().toList();
List<String> values = names.stream().filter(name -> isValueOf(name, variable)).toList();
Set<String> 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)
return Optional.empty();
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<CtVariableWrite<?>> writes(CtLoop loop) {
return loop.getElements(new TypeFilter<CtVariableWrite<?>>(CtVariableWrite.class));
}

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<CtLocalVariable<?>> declaration(String variable, CtLoop loop) {
return writes(loop).stream().filter(write -> write.getVariable().getSimpleName().equals(variable))
.map(write -> write.getVariable().getDeclaration())
.filter(declaration -> declaration instanceof CtLocalVariable<?>)
.<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();
}
}
Loading
Loading