Skip to content

Commit 6572019

Browse files
Read a state value only against the sets that apply to the argument's type
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent cee54dc commit 6572019

5 files changed

Lines changed: 103 additions & 36 deletions

File tree

‎liquidjava-example/src/main/java/testSuite/ErrorStateValues.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,7 @@ class ErrorStateValuesSharedState {}
1717

1818
@StateSet({"state1", "open"}) // Expect: Error
1919
class ErrorStateValuesGeneratedSetName {}
20+
21+
// an unrelated set named door that has a state locked does not make locked a state of the door above
22+
@StateSet(name = "door", value = {"locked", "free"})
23+
class ErrorStateValuesOtherDoor {}

‎liquidjava-verifier/src/main/java/liquidjava/processor/context/AliasWrapper.java‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,13 @@ public AliasWrapper(AliasDTO a, Factory factory, String klass, String path, Sour
2929
this.position = position;
3030
varTypes = new ArrayList<>();
3131
varNames = a.getVarNames();
32-
for (String s : a.getVarTypes()) {
33-
CtTypeReference<?> r = Utils.getType(s.equals(klass) ? path : s, factory);
34-
varTypes.add(r);
35-
}
32+
for (String s : a.getVarTypes())
33+
varTypes.add(parameterType(s, factory, klass, path));
34+
}
35+
36+
/** The type of an alias parameter written {@code type}, in an alias declared on class {@code klass} at path */
37+
public static CtTypeReference<?> parameterType(String type, Factory factory, String klass, String path) {
38+
return Utils.getType(type.equals(klass) ? path : type, factory);
3639
}
3740

3841
public String getName() {

‎liquidjava-verifier/src/main/java/liquidjava/processor/facade/AliasDTO.java‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import java.util.stream.Collectors;
55

66
import liquidjava.diagnostics.errors.LJError;
7-
import liquidjava.processor.context.GhostState;
87
import liquidjava.rj_language.Predicate;
98
import liquidjava.rj_language.StateValues;
109
import liquidjava.rj_language.ast.Expression;
@@ -52,11 +51,12 @@ public void resolveStaticFinalConstants(CtElement context, SourcePosition positi
5251
}
5352
}
5453

55-
// Read the states written as values of their sets, phase(x) == open, as the shorthand open(x); only the alias's
56-
// parameters are variables, so a variable where the alias is used cannot take the place of a state
57-
public void readStateValues(List<GhostState> states) throws LJError {
54+
// Read the states written as values of their sets, phase(x) == open, as the shorthand open(x), with only the
55+
// alias's
56+
// parameters as variables, so a variable where the alias is used cannot take the place of a state
57+
public void readStateValues(StateValues values) throws LJError {
5858
if (expression != null) {
59-
this.expression = StateValues.toShorthand(expression, states, varNames::contains);
59+
this.expression = values.toShorthand(expression);
6060
}
6161
}
6262

‎liquidjava-verifier/src/main/java/liquidjava/processor/refinement_checker/TypeChecker.java‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@
2525
import liquidjava.processor.state_machine.StateSolver;
2626
import liquidjava.rj_language.Predicate;
2727
import liquidjava.rj_language.StateValues;
28+
import liquidjava.rj_language.ast.Expression;
29+
import liquidjava.rj_language.ast.FunctionInvocation;
30+
import liquidjava.rj_language.ast.Var;
2831
import liquidjava.rj_language.ast.formatter.FieldDisplayNames;
2932
import liquidjava.rj_language.parsing.RefinementsParser;
3033
import liquidjava.smt.SMTEvaluator;
@@ -43,6 +46,7 @@
4346
import spoon.reflect.declaration.CtExecutable;
4447
import spoon.reflect.declaration.CtInterface;
4548
import spoon.reflect.declaration.CtMethod;
49+
import spoon.reflect.declaration.CtParameter;
4650
import spoon.reflect.declaration.CtTypedElement;
4751
import spoon.reflect.declaration.CtVariable;
4852
import spoon.reflect.declaration.CtType;
@@ -389,9 +393,10 @@ protected void getGhostFunction(String value, CtElement element, SourcePosition
389393
* {@code open(x)}, in the scope of {@code element}, whose variables keep their meaning
390394
*/
391395
public Predicate readStateValues(Predicate p, CtElement element, SourcePosition position) throws LJError {
396+
StateValues values = new StateValues(context.getGhostStates(), name -> isVariableIn(element, name),
397+
(argument, set) -> typeIn(element, argument).map(type -> isOfType(type, set.getPrefix())).orElse(true));
392398
try {
393-
return new Predicate(StateValues.toShorthand(p.getExpression(), context.getGhostStates(),
394-
name -> isVariableIn(element, name)));
399+
return new Predicate(values.toShorthand(p.getExpression()));
395400
} catch (LJError e) {
396401
if (e.getPosition() == null)
397402
e.setPosition(position);
@@ -409,6 +414,44 @@ private boolean isVariableIn(CtElement element, String name) {
409414
return executable != null && executable.getParameters().stream().anyMatch(p -> p.getSimpleName().equals(name));
410415
}
411416

417+
/** The type of a state's argument where {@code element} is: this, _, a parameter, a variable, or old of one */
418+
private Optional<CtTypeReference<?>> typeIn(CtElement element, Expression argument) {
419+
if (argument instanceof FunctionInvocation old && old.getName().equals(Keys.OLD) && old.getArgs().size() == 1)
420+
return typeIn(element, old.getArgs().get(0));
421+
if (!(argument instanceof Var var))
422+
return Optional.empty();
423+
String name = var.getName();
424+
if (name.equals(Keys.THIS))
425+
return Optional.ofNullable(getQualifiedClassName(element)).map(c -> factory.Type().createReference(c));
426+
if (name.equals(Keys.WILDCARD))
427+
return element instanceof CtTypedElement<?> typed ? Optional.ofNullable(typed.getType()) : Optional.empty();
428+
CtExecutable<?> executable = element instanceof CtExecutable<?> e ? e : element.getParent(CtExecutable.class);
429+
if (executable != null)
430+
for (CtParameter<?> parameter : executable.getParameters())
431+
if (parameter.getSimpleName().equals(name))
432+
return Optional.ofNullable(parameter.getType());
433+
return context.hasVariable(name) ? Optional.ofNullable(context.getVariableByName(name).getType())
434+
: Optional.empty();
435+
}
436+
437+
/**
438+
* Reads the states written as values of their sets in the body of {@code alias}, declared on class {@code klass} at
439+
* {@code path}: only its parameters are variables, typed as they are declared
440+
*/
441+
private StateValues aliasStateValues(AliasDTO alias, String klass, String path) {
442+
return new StateValues(context.getGhostStates(), alias.getVarNames()::contains, (argument, set) -> {
443+
int parameter = argument instanceof Var var ? alias.getVarNames().indexOf(var.getName()) : -1;
444+
return parameter < 0
445+
|| isOfType(AliasWrapper.parameterType(alias.getVarTypes().get(parameter), factory, klass, path),
446+
set.getPrefix());
447+
});
448+
}
449+
450+
/** Whether {@code type} is the class {@code className} or one of its subtypes */
451+
private boolean isOfType(CtTypeReference<?> type, String className) {
452+
return type.getQualifiedName().equals(className) || type.isSubtypeOf(factory.Type().createReference(className));
453+
}
454+
412455
protected void handleAlias(String ref, CtElement element, SourcePosition position) throws LJError {
413456
try {
414457
AliasDTO a = RefinementsParser.parseAliasDefinition(ref);
@@ -424,7 +467,7 @@ protected void handleAlias(String ref, CtElement element, SourcePosition positio
424467
if (klass != null && path != null) {
425468
a.parse(path);
426469
a.resolveStaticFinalConstants(element, position);
427-
a.readStateValues(context.getGhostStates());
470+
a.readStateValues(aliasStateValues(a, klass, path));
428471
if (a.getExpression() != null && !a.getExpression().isBooleanExpression()) {
429472
throw new InvalidRefinementError(position, "Refinement alias must return a boolean expression",
430473
ref);

‎liquidjava-verifier/src/main/java/liquidjava/rj_language/StateValues.java‎

Lines changed: 41 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import java.util.List;
44
import java.util.Objects;
55
import java.util.Optional;
6+
import java.util.function.BiPredicate;
67
import java.util.function.Predicate;
78
import java.util.stream.Collectors;
89

@@ -22,59 +23,75 @@
2223
*/
2324
public final class StateValues {
2425

25-
private StateValues() {
26+
private final List<GhostState> states;
27+
private final Predicate<String> isVariable;
28+
private final BiPredicate<Expression, GhostFunction> appliesTo;
29+
30+
/**
31+
* @param isVariable
32+
* whether a name is a variable where the spec is written; a variable keeps its meaning
33+
* @param appliesTo
34+
* whether a state set can be applied to an argument, by the argument's type; true when it is not known
35+
*/
36+
public StateValues(List<GhostState> states, Predicate<String> isVariable,
37+
BiPredicate<Expression, GhostFunction> appliesTo) {
38+
this.states = states;
39+
this.isVariable = isVariable;
40+
this.appliesTo = appliesTo;
2641
}
2742

2843
/**
2944
* {@code expression} with each {@code set(e) == state} read as {@code state(e)} and each {@code set(e) != state} as
30-
* {@code !state(e)}. A name {@code isVariable} accepts keeps its meaning as a variable
45+
* {@code !state(e)}
3146
*
3247
* @throws CustomError
3348
* when the name is not a variable and is a state of another set of the same class
3449
*/
35-
public static Expression toShorthand(Expression expression, List<GhostState> states, Predicate<String> isVariable)
36-
throws LJError {
37-
return rewrite(expression.clone(), states, isVariable);
50+
public Expression toShorthand(Expression expression) throws LJError {
51+
return rewrite(expression.clone());
3852
}
3953

40-
private static Expression rewrite(Expression e, List<GhostState> states, Predicate<String> isVariable)
41-
throws LJError {
54+
private Expression rewrite(Expression e) throws LJError {
4255
if (e instanceof BinaryExpression b && (b.getOperator().equals("==") || b.getOperator().equals("!="))) {
43-
Optional<FunctionInvocation> state = stateOf(b.getFirstOperand(), b.getSecondOperand(), states, isVariable);
56+
Optional<FunctionInvocation> state = stateOf(b.getFirstOperand(), b.getSecondOperand());
4457
if (state.isEmpty())
45-
state = stateOf(b.getSecondOperand(), b.getFirstOperand(), states, isVariable);
58+
state = stateOf(b.getSecondOperand(), b.getFirstOperand());
4659
if (state.isPresent())
4760
return b.getOperator().equals("==") ? state.get() : new UnaryExpression("!", state.get());
4861
}
4962
for (int i = 0; i < e.getChildren().size(); i++)
50-
e.setChild(i, rewrite(e.getChildren().get(i), states, isVariable));
63+
e.setChild(i, rewrite(e.getChildren().get(i)));
5164
return e;
5265
}
5366

5467
/**
55-
* {@code state(e)} when {@code set} is a state set applied to {@code e} and {@code name} one of its states, named
56-
* as the shorthand written in the same place, so that it is resolved the same way, in a subclass too
68+
* {@code state(e)} when {@code set} is a state set applied to {@code e} and {@code name} a state of every set of
69+
* that name that applies to {@code e}. It is named as the shorthand written in the same place, so that it is
70+
* resolved the same way, in a subclass too. When only some of those sets have the state, nothing is read, and the
71+
* name stays an unknown variable
5772
*/
58-
private static Optional<FunctionInvocation> stateOf(Expression set, Expression name, List<GhostState> states,
59-
Predicate<String> isVariable) throws LJError {
73+
private Optional<FunctionInvocation> stateOf(Expression set, Expression name) throws LJError {
6074
if (!(set instanceof FunctionInvocation invocation && invocation.getArgs().size() == 1
6175
&& name instanceof Var var && !isVariable.test(var.getName())))
6276
return Optional.empty();
77+
Expression argument = invocation.getArgs().get(0);
6378
List<GhostFunction> sets = states.stream().map(GhostState::getParent).filter(Objects::nonNull).distinct()
64-
.filter(s -> s.matches(invocation.getName())).toList();
65-
if (sets.stream().anyMatch(s -> !statesOf(s, states, var.getName()).isEmpty()))
79+
.filter(s -> s.matches(invocation.getName()) && appliesTo.test(argument, s)).toList();
80+
long withState = sets.stream().filter(s -> !statesOf(s, var.getName()).isEmpty()).count();
81+
if (withState > 0 && withState == sets.size())
6682
return Optional.of(new FunctionInvocation(qualifiedLike(invocation.getName(), var.getName()),
67-
List.of(invocation.getArgs().get(0).clone())));
68-
for (GhostFunction s : sets)
69-
if (isStateOfAnotherSet(var.getName(), s, states))
70-
throw new CustomError(String.format("State '%s' is not a state of '%s' (its states are %s)",
71-
var.getName(), s.getName(),
72-
statesOf(s, states, null).stream().map(GhostState::getName).collect(Collectors.joining(", "))));
83+
List.of(argument.clone())));
84+
if (withState == 0)
85+
for (GhostFunction s : sets)
86+
if (isStateOfAnotherSet(var.getName(), s))
87+
throw new CustomError(String.format("State '%s' is not a state of '%s' (its states are %s)",
88+
var.getName(), s.getName(),
89+
statesOf(s, null).stream().map(GhostState::getName).collect(Collectors.joining(", "))));
7390
return Optional.empty();
7491
}
7592

7693
/** The states of {@code set}, or only those named {@code name} when it is not null */
77-
private static List<GhostState> statesOf(GhostFunction set, List<GhostState> states, String name) {
94+
private List<GhostState> statesOf(GhostFunction set, String name) {
7895
return states.stream().filter(s -> s.getParent() == set && (name == null || s.getName().equals(name))).toList();
7996
}
8097

@@ -84,7 +101,7 @@ private static String qualifiedLike(String setName, String state) {
84101
return dot < 0 ? state : setName.substring(0, dot + 1) + state;
85102
}
86103

87-
private static boolean isStateOfAnotherSet(String name, GhostFunction stateSet, List<GhostState> states) {
104+
private boolean isStateOfAnotherSet(String name, GhostFunction stateSet) {
88105
return states.stream().anyMatch(s -> s.getName().equals(name) && s.getParent() != null
89106
&& s.getParent() != stateSet && s.getParent().getPrefix().equals(stateSet.getPrefix()));
90107
}

0 commit comments

Comments
 (0)