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;

// #322: other.val is a different object's field, not this.val
// #322, #438: other.val is a different object's field, not this.val, but other may be this
public class ErrorFieldOfOtherObject {
@Refinement("val > 0")
int val;
Expand Down Expand Up @@ -31,6 +31,17 @@ void compound(ErrorFieldOfOtherObject other) {
int k = j; // Expect: Refinement Error
}

void write(ErrorFieldOfOtherObject other) {
other.val = 5;
@Refinement("_ == 5")
int k = val; // Expect: Refinement Error
}

void compoundWrite(ErrorFieldOfOtherObject other) {
val = 7;
other.val -= 5; // Expect: Refinement Error
}

void condition(ErrorFieldOfOtherObject other) {
val = 7;
if (other.val == 3) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package testSuite;

import liquidjava.specification.Refinement;

// #565: a value read from a field is the field's value when it is read, not its later values
public class ErrorFieldReadBeforeWrite {
int f;
boolean b;

void copy() {
int y = f;
f = 5;
@Refinement("_ == 5")
int k = y; // Expect: Refinement Error
}

void conditional() {
@Refinement("_ > 0")
int k = f > 0 ? (f = -1) : 1; // Expect: Refinement Error
}

void loop(int n) {
f = 0;
while (n > 0) {
@Refinement("_ == 0")
int k = f; // Expect: Refinement Error
f = 1;
n--;
}
}

void negate() {
b = true;
b = !b;
@Refinement("_ == true")
boolean k = b; // Expect: Refinement Error
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,11 @@ public static void main(String[] args) {
t.n = -1;
t.shouldFailIfFieldIsNegative(); // Expect: State Refinement Error
}

void writeThisAfterOther() {
ErrorFieldUpdate t = new ErrorFieldUpdate();
t.n = -1;
n = 1;
t.shouldFailIfFieldIsNegative(); // Expect: State Refinement Error
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import liquidjava.rj_language.BuiltinFunctionPredicate;
import liquidjava.rj_language.Predicate;
import liquidjava.rj_language.ast.Enum;
import liquidjava.rj_language.ast.formatter.FieldDisplayNames;
import liquidjava.utils.GeneratedNames;
import liquidjava.utils.StaticConstants;
import liquidjava.utils.Utils;
Expand Down Expand Up @@ -158,6 +159,7 @@ public <T> void visitCtConstructor(CtConstructor<T> constructor) {
context.restoreInstanceVariables();
mfc.loadFunctionInfo(constructor);
snapshotWrittenParameters(constructor);
snapshotFields(constructor);
try {
super.visitCtConstructor(constructor);
} catch (LJError e) {
Expand All @@ -174,6 +176,7 @@ public <R> void visitCtMethod(CtMethod<R> method) {
context.restoreInstanceVariables();
mfc.loadFunctionInfo(method);
snapshotWrittenParameters(method);
snapshotFields(method);
try {
super.visitCtMethod(method);
} catch (LJError e) {
Expand Down Expand Up @@ -205,6 +208,16 @@ private void snapshotWrittenParameters(CtExecutable<?> executable) {
}
}

/**
* Gives each field of this object that has no instance yet one for its value on entry, as for written parameters: a
* read of the field names its value at that point, which later writes, calls and loops do not change.
*/
private void snapshotFields(CtExecutable<?> executable) {
for (RefinedVariable rv : context.getCtxVars())
if (isField(rv.getName()) && rv instanceof Variable variable && variable.getLastInstance().isEmpty())
forgetChanges(rv.getName(), new Predicate(), executable);
}

@Override
public <T> void visitCtLocalVariable(CtLocalVariable<T> localVariable) {
super.visitCtLocalVariable(localVariable);
Expand Down Expand Up @@ -323,6 +336,7 @@ private <T, A extends T> void visitAssignment(CtAssignment<T, A> assignment) thr
CtFieldReference<?> cr = fw.getVariable();
CtField<?> f = fw.getVariable().getDeclaration();
String updatedVarName = Utils.qualifyFieldName(cr);
forgetFieldOfOtherObject(ex, assignment, true);
// a field declared outside the analyzed sources (e.g. a library field) has no declared refinement: the
// write stands in for its declaration
checkAssignment(updatedVarName, cr.getType(), ex, assignment.getAssignment(), assignment,
Expand All @@ -332,9 +346,26 @@ private <T, A extends T> void visitAssignment(CtAssignment<T, A> assignment) thr
if (f != null && fw.getVariable().getType().toString().equals("int")) {
AuxStateHandler.updateGhostField(fw, this);
}
forgetFieldOfOtherObject(ex, assignment, false);
}
}

/**
* Before and after a write to the field of another object ({@code other.f = v}, {@code other.f++}), forgets the
* value of the field of this object with the same name: the old value of {@code other.f} is not that of
* {@code this.f}, and {@code other} may be {@code this}, so after the write {@code this.f} may be either value
*/
private void forgetFieldOfOtherObject(CtExpression<?> written, CtElement element, boolean before) {
if (!(written instanceof CtFieldWrite<?> write) || Utils.accessesTrackedField(write))
return;
String name = Utils.qualifyFieldName(write.getVariable());
forgetChanges(name, new Predicate(), element);
// before the write, the value stands for the old value of the other object's field, and is named after it
if (before)
Utils.untrackedWriteReceiver(element).ifPresent(receiver -> context.getLastVariableInstance(name)
.ifPresent(old -> FieldDisplayNames.recordWriteReceiver(old.getName(), receiver)));
}

@Override
public <T> void visitCtArrayRead(CtArrayRead<T> arrayRead) {
super.visitCtArrayRead(arrayRead);
Expand Down Expand Up @@ -387,12 +418,11 @@ public <T> void visitCtField(CtField<T> f) {
public <T> void visitCtFieldRead(CtFieldRead<T> fieldRead) {
String fieldName = fieldRead.getVariable().getSimpleName();
// fields live in the context under their qualified name only: a variable with the field's simple name is an
// unrelated local, the tracked value is that of this object, not of another one
// unrelated local, the tracked value is that of this object, not of another one. The read names the current
// instance, as a read of a local does, so later writes to the field do not change the value read
if (Utils.accessesTrackedField(fieldRead)
&& context.hasVariable(Utils.qualifyFieldName(fieldRead.getVariable()))) {
String thisName = Utils.qualifyFieldName(fieldRead.getVariable());
fieldRead.putMetadata(Keys.REFINEMENT,
Predicate.createEquals(Predicate.createVar(Keys.WILDCARD), Predicate.createVar(thisName)));
getPutVariableMetadata(fieldRead, Utils.qualifyFieldName(fieldRead.getVariable()));

} else if (fieldRead.getVariable().getSimpleName().equals("length")) {
String targetName = fieldRead.getTarget().toString();
Expand Down Expand Up @@ -454,7 +484,9 @@ public <T> void visitCtBinaryOperator(CtBinaryOperator<T> operator) {
@Override
public <T> void visitCtUnaryOperator(CtUnaryOperator<T> operator) {
super.visitCtUnaryOperator(operator);
forgetFieldOfOtherObject(operator.getOperand(), operator, true);
otc.getUnaryOpRefinements(operator);
forgetFieldOfOtherObject(operator.getOperand(), operator, false);
}

public <R> void visitCtInvocation(CtInvocation<R> invocation) {
Expand Down Expand Up @@ -1298,8 +1330,8 @@ else if (inv.getTarget() != null && AuxStateHandler.isCurrentReceiver(inv.getTar
CtVariable<?> declaration = access.getVariable().getDeclaration();
if (declaration != null && declaration.hasParent(scope))
continue; // e.g. declared in a loop body: a new variable on each iteration
String name = access.getVariable().getSimpleName();
names.add(access instanceof CtFieldAccess<?> ? String.format(Formats.THIS, name) : name);
names.add(access instanceof CtFieldAccess<?> field ? Utils.qualifyFieldName(field.getVariable())
: access.getVariable().getSimpleName());
}
if (!calls.isEmpty())
context.getCtxVars().stream().map(RefinedVariable::getName).filter(RefinementTypeChecker::isField)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,12 @@ public <T> void getUnaryOpRefinements(CtUnaryOperator<T> operator) throws LJErro

} else if (ex instanceof CtVariableRead<T> var) {
name = var.getVariable().getSimpleName();
// If the variable is the same, the refinements need to be changed
// If the variable is the same, the refinements need to be changed; a field read already names the value
// of the field when it is read (see visitCtFieldRead), and the context has no variable by its simple name
try {
CtAssignment<?, ?> assign = operator.getParent(CtAssignment.class);
if (assign != null && assign.getAssigned() instanceof CtVariableWrite<?>) {
if (assign != null && !(var instanceof CtFieldRead<?>)
&& assign.getAssigned() instanceof CtVariableWrite<?>) {
CtVariableWrite<T> w = (CtVariableWrite<T>) assign.getAssigned();
String parentName = w.getVariable().getSimpleName();
if (name.equals(parentName)) {
Expand Down Expand Up @@ -495,6 +497,12 @@ private Predicate createFreshValue(CtExpression<?> element, CtTypeReference<?> t
*/
private <T> Predicate getRefinementUnaryVariableWrite(CtExpression<T> ex, CtUnaryOperator<T> operator,
CtVariableWrite<T> w, String name) throws LJError {
if (w instanceof CtFieldWrite<?> write && !Utils.accessesTrackedField(write)) {
// the old value of another object's field is the value given to the field before the write
String old = rtc.getContext().getLastVariableInstance(name).map(VariableInstance::getName).orElse(name);
Predicate c = getOperatorFromKind(operator.getKind(), ex).substituteVariable(Keys.WILDCARD, old);
return Predicate.createEquals(Predicate.createVar(Keys.WILDCARD), c);
}
String newName = String.format(Formats.INSTANCE, name, rtc.getContext().getCounter());

Predicate metadada = rtc.getContext().getVariableRefinements(name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,10 @@ public static void updateGhostField(CtFieldWrite<?> fw, TypeChecker tc) throws L
.substituteVariable(Keys.THIS, newInstanceName);

transitionedState = checkOldMentions(transitionedState, instanceName, newInstanceName);
// the ghost keeps the value written, which a later write to the field does not change
Optional<VariableInstance> written = tc.getContext().getLastVariableInstance(updatedVarName);
if (written.isPresent())
transitionedState = transitionedState.substituteVariable(updatedVarName, written.get().getName());
// update of stata of new instance of this#n#(whatever it was + 1)

VariableInstance vi2 = (VariableInstance) tc.getContext().addInstanceToContext(newInstanceName, vi.getType(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ void aliasedArgumentKeepsTheVariableItCopiesAfterIt() {
void fieldArgumentKeepsTheField() {
RefinementError error = verify("ErrorCounterexampleFieldArgument.java");
assertAssignments(error, assignment("#timeout", "-1"),
assignment("this#testSuite.ErrorCounterexampleFieldArgument.timeout", "-1"));
assignment("#this#testSuite.ErrorCounterexampleFieldArgument.timeout", "-1"));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ void steppingBackReachesTheOriginalWithTheDroppedRow() {
assertEquals(List.of("∀this.items true", "∀items items == this.items",
"∀items.size() items.size() == size(items) && items.size() >= 0"), shown.originalRows());
assertEquals(List.of("Substitution", "Binder"), shown.steps());
assertEquals(List.of("this#testSuite.classes.found_binders_error.Basket.items", "#items_", "#bound_"),
assertEquals(List.of("#this#testSuite.classes.found_binders_error.Basket.items_", "#items_", "#bound_"),
shown.originalBinders());
}

Expand Down Expand Up @@ -101,7 +101,7 @@ void variableOnlyExpectedNamesKeepsItsTrueRow() {
@Test
void writeToAnotherObjectsFieldIsNamedAfterThatObject() {
assertEquals("found `other.level == -1` but expected `other.level >= 0`", ERRORS.get(36).message());
assertEquals(List.of("∀this.level this.level >= 0", "∀other.level other.level == this.level - 1"),
assertEquals(List.of("∀other.level@48 other.level@48 >= 0", "∀other.level other.level == other.level@48 - 1"),
ERRORS.get(48).rows());
}

Expand Down
Loading