Skip to content
Merged
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,41 @@
package testSuite;

import liquidjava.specification.Refinement;

// A guard on a variable still describes its old value after the variable is assigned (#538)
@SuppressWarnings("unused")
public class CorrectGuardedAssignment {
static int read() {
return 1;
}

static void use(@Refinement("_ >= 5") int x) {}

static void guarded() {
@Refinement("_ <= 10")
int t = 0;
int n = read();
if (n <= 10 - t) {
t = t + n;
}
}

static void earlyExit() {
@Refinement("_ <= 10")
int t = 0;
int n = read();
if (n > 10 - t)
return;
t = t + n;
}

// the else branch starts from the value the condition was checked on
static void elseAfterAssignment() {
int t = read();
if (t < 5) {
t = 100;
} else {
use(t);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package testSuite;

import liquidjava.specification.Refinement;

// A guard on a variable must not be applied to the value assigned to it afterwards (#538)
@SuppressWarnings("unused")
public class ErrorGuardedAssignment {
static int read() {
return 1;
}

static void lessThanFive(@Refinement("_ < 5") int x) {}

static void negative(@Refinement("_ < 0") int x) {}

static void assigned() {
int t = read();
if (t < 5) {
t = t + 10;
lessThanFive(t); // Expect: Refinement Error
}
}

static void incremented() {
int t = read();
if (t < 5) {
t++;
lessThanFive(t); // Expect: Refinement Error
}
}

// after the if, t is the value assigned in the only branch that continues, which the condition was not checked on
static void assignedInOnlyBranchThatContinues() {
int t = read();
if (t < 5) {
t = 100;
} else {
return;
}
negative(1); // Expect: Refinement Error
}

// x was given the value of y on entry, not the value assigned to y afterwards
static void parameterWrittenAfterCopy(int y) {
int x = y;
if (x > 0) {
y = -1;
negative(1); // Expect: Refinement Error
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public static void ifAssignment1() {
public static void ifAssignment2() {
@Refinement("_ < 10")
int a = 5;
if (a < 0)
if (a > 0)
a = 100; // Expect: Refinement Error
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package testSuite;

import liquidjava.specification.Refinement;

// What an if nested in a branch establishes holds only on that branch's paths
@SuppressWarnings("unused")
public class ErrorNestedIfPathCondition {
static void nonPositive(@Refinement("_ <= 0") int x) {}

static void otherBranch(boolean c, int t) {
if (c) {
if (t > 0)
return;
} else {
nonPositive(t); // Expect: Refinement Error
}
}

static void afterBothBranches(boolean c, int t) {
if (c) {
if (t > 0)
return;
}
nonPositive(t); // Expect: Refinement Error
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ public <T> void visitCtConstructor(CtConstructor<T> constructor) {
context.enterContext();
context.restoreInstanceVariables();
mfc.loadFunctionInfo(constructor);
snapshotWrittenParameters(constructor);
try {
super.visitCtConstructor(constructor);
} catch (LJError e) {
Expand All @@ -164,6 +165,7 @@ public <R> void visitCtMethod(CtMethod<R> method) {
context.restoreInstanceVariables();
if (!method.getSignature().equals("main(java.lang.String[])")) {
mfc.loadFunctionInfo(method);
snapshotWrittenParameters(method);
}
try {
super.visitCtMethod(method);
Expand All @@ -175,6 +177,27 @@ public <R> void visitCtMethod(CtMethod<R> method) {
vcChecker.clearPathVariables();
}

/**
* Gives each parameter that the executable writes an instance for its value on entry. What is known about that
* value (e.g. {@code x == y} after {@code int x = y}) then names the instance, and still holds after {@code y} is
* written: a variable's name stands for its last instance.
*/
private void snapshotWrittenParameters(CtExecutable<?> executable) {
Set<CtVariable<?>> written = new HashSet<>();
for (CtVariableWrite<?> write : executable
.getElements(new TypeFilter<CtVariableWrite<?>>(CtVariableWrite.class)))
written.add(write.getVariable().getDeclaration());
for (CtParameter<?> parameter : executable.getParameters()) {
String name = parameter.getSimpleName();
if (!written.contains(parameter) || !(context.getVariableByName(name)instanceof Variable variable))
continue;
String instanceName = String.format(Formats.INSTANCE, name, context.getCounter());
context.addInstanceToContext(instanceName, variable.getType(),
variable.getMainRefinement().substituteVariable(name, instanceName), parameter);
context.addRefinementInstanceToVariable(name, instanceName);
}
}

@Override
public <T> void visitCtLocalVariable(CtLocalVariable<T> localVariable) {
super.visitCtLocalVariable(localVariable);
Expand Down Expand Up @@ -551,6 +574,10 @@ public void visitCtIf(CtIf ifElement) {
context.variablesSetBeforeIf();
context.enterContext();

// each branch starts from the path conditions before the if; the conditions it adds or drops (see
// keepPathVariablesOnCurrentValue for the ones assignments rename) hold only on its own paths
List<RefinedVariable> pathBefore = vcChecker.getPathVariables();

// VISIT THEN
context.enterContext();
visitCtBlock(ifElement.getThenStatement());
Expand All @@ -560,13 +587,14 @@ public void visitCtIf(CtIf ifElement) {
}
contextHistory.saveContext(ifElement.getThenStatement(), context);
context.exitContext();
List<RefinedVariable> pathAfterThen = vcChecker.getPathVariables();
Predicate thenRefsAtEnd = freshRV.getRefinement();

// VISIT ELSE
boolean elseCompletes = true;
vcChecker.replacePathVariables(pathBefore);
context.newRefinementToVariableInContext(pathVarName, elseRefs);
if (ifElement.getElseStatement() != null) {
context.getVariableByName(pathVarName);
context.newRefinementToVariableInContext(pathVarName, elseRefs);

context.enterContext();
visitCtBlock(ifElement.getElseStatement());
elseCompletes = canCompleteNormally(ifElement.getElseStatement());
Expand All @@ -578,13 +606,18 @@ public void visitCtIf(CtIf ifElement) {
}
// end
if (thenCompletes == elseCompletes) {
// only the conditions from before the if that both branches kept hold after it
List<RefinedVariable> pathAfterElse = vcChecker.getPathVariables();
vcChecker.replacePathVariables(pathBefore.stream()
.filter(rv -> pathAfterThen.contains(rv) && pathAfterElse.contains(rv)).toList());
// Reset the path variable's refinement to the original condition after the if,
// so branch-local truth assertions (and any typestate they imply) don't leak past the join.
context.newRefinementToVariableInContext(pathVarName, lastExpRefs);
vcChecker.removePathVariable(freshRV);
} else {
// Keep the refinement of the only branch that reaches the code after the if.
context.newRefinementToVariableInContext(pathVarName, thenCompletes ? thenRefs : elseRefs);
} else if (thenCompletes) {
// the path conditions are those of the only branch that reaches the code after the if
vcChecker.replacePathVariables(pathAfterThen);
context.newRefinementToVariableInContext(pathVarName, thenRefsAtEnd);
}
context.exitContext();
context.variablesCombineFromIf(joinGuard);
Expand Down Expand Up @@ -1097,7 +1130,7 @@ private void havocChangedIn(CtLoop loop, Set<String> tracked) {
void forgetChanges(String name, Predicate known, CtElement element) {
if (!(context.getVariableByName(name)instanceof Variable variable))
return;
vcChecker.removePathVariableThatIncludes(name);
vcChecker.keepPathVariablesOnCurrentValue(name);
String instanceName = String.format(Formats.INSTANCE, name, context.getCounter());
Predicate declared = variable.getMainRefinement().substituteVariable(name, instanceName);
context.addInstanceToContext(instanceName, variable.getType(),
Expand Down Expand Up @@ -1159,7 +1192,7 @@ private boolean mayChangeState(CtInvocation<?> invocation) {

/**
* Assumes the loop condition in the body, as a path condition on the values it was evaluated on (same encoding as
* the condition of an if, see visitCtIf). Re-assigning a variable in the body drops the conditions on it.
* the condition of an if, see visitCtIf). Re-assigning a variable in the body keeps the condition on its old value.
*/
private void assumeLoopCondition(CtExpression<Boolean> condition) {
assumeCondition(condition, true, GeneratedNames.LOOP_CONDITION);
Expand Down Expand Up @@ -1247,11 +1280,6 @@ private void checkAssignment(String name, CtTypeReference<?> type, CtExpression<
refinementFound = new Predicate();
}
}
Optional<VariableInstance> r = context.getLastVariableInstance(name);
// AQUI!!
r.ifPresent(variableInstance -> vcChecker.removePathVariableThatIncludes(variableInstance.getName()));

vcChecker.removePathVariableThatIncludes(name); // AQUI!!
checkVariableRefinements(refinementFound, name, type, parentElem, varDecl);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,7 @@ public void checkVariableRefinements(Predicate refinementFound, String simpleNam
RefinedVariable rv = context.addInstanceToContext(newName, type, correctNewRefinement, usage);
for (CtTypeReference<?> t : mainRV.getSuperTypes())
rv.addSuperType(t);
vcChecker.keepPathVariablesOnCurrentValue(simpleName);
context.addRefinementInstanceToVariable(simpleName, newName);
String customMessage = getMessageFromAnnotation(variable).orElse(mainRV != null ? mainRV.getMessage() : null);
checkSMT(cEt, usage, declarationPosition, customMessage);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,25 @@ void removePathVariableThatIncludes(String otherVar) {
.forEach(pathVariables::remove);
}

/**
* Keeps the path conditions true when variable {@code name} is about to get a new instance. A variable's name
* stands for its last instance, so a condition on the name would then describe the new value: the name is replaced
* by the last instance, which holds the value the condition was checked on and never changes. A condition on the
* name is dropped when the variable has no instance yet to name that value, or is not of a primitive type: an
* object also gets new instances when its state changes, which leave the conditions on its name behind.
*/
void keepPathVariablesOnCurrentValue(String name) {
RefinedVariable variable = context.getVariableByName(name);
Optional<VariableInstance> current = context.getLastVariableInstance(name);
if (current.isEmpty() || variable.getType() == null || !variable.getType().isPrimitive()) {
removePathVariableThatIncludes(name);
return;
}
for (RefinedVariable rv : pathVariables)
if (rv.getRefinement().getVariableNames().contains(name))
rv.setRefinement(rv.getRefinement().substituteVariable(name, current.get().getName()));
}

private boolean hasDependencyCycle(RefinedVariable rv, String var, List<RefinedVariable> vars, Set<String> seen) {
if (!seen.add(rv.getName()))
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ void multipleParametersAndGeneratedReturnFollowBinderOrder() {
@Test
void variableUpdateIncludesNegativeInputAndGeneratedReturn() {
RefinementError error = verify("ErrorAssignmentBeforeReturn.java");
assertAssignments(error, assignment("#ret", "0"), assignment("x", "-1"));
assertAssignments(error, assignment("#ret", "0"), assignment("#x", "-1"));
}

@Test
Expand Down
Loading