Skip to content

Commit 4631bc2

Browse files
Ask the solver only about the state sets a refinement names (#475)
Follow-up to #474, stacked on it: **review and merge #474 first**. The diff here is only the last commit. ## What State hints asked Z3 about every state set, even the ones a refinement never names. This PR stops asking about those sets and changes no hint. The verifier already keeps the state of every set a refinement's `to` does not name (`AuxStateHandler.addOldStates` adds `stateK(this) == stateK(old(this))`). Different state sets are different ghost functions. So: - **Entry.** Whether a `from` holds depends only on the sets it names, so it is asked once for each state of those sets, not once for each of the 12 combined states. This is done both when building the state machine (`StateMachineBuilder.transitionsOf`) and for hint variants (`SolverEffects.entry`). - **States after.** The only candidates are those that keep the sets `to` does not name. Where the call leads in the sets it does name depends only on the state before in the sets it names for `old(this)`, so that answer is reused across states (`statesAfter`, `SolverEffects.computeAfter`). - **Guards.** If the receiver can be in any combination of states, a guard whose state or return refinements name no state of the sets the failing call checks cannot change them. It is skipped before any query. An alias is assumed to name every set, because its body is not expanded at this point. ## Numbers: the study's UndoManager (A1_56 fixture, 12 states in 3 sets) | | #474 | this PR | |---|---|---| | Solver queries (whole file) | 1419 | 258 | | Machine build (entry + states after) | 951 | 187 | | Hint queries | 432 | 35 | | Wall time, whole run (3 runs) | 10.0–10.2 s | 5.0–6.1 s | ## Checks - **Same output.** On every test-suite path and every fixture project under `liquidjava-dev/fixtures`, errors and hints are identical to #474. - **Sweep time.** The test suite went from 1m25s to 1m07s and the fixtures from 25 s to 17 s. - **Full suite.** Passes locally: 685 tests, 0 failures. - **New unit tests** in `StateMachineTest` for `namedSets`, `namedSetsBefore` (only `old(this)` mentions count), the alias case and `keeping`. - **A bug the sweep caught.** Query guards such as `hasNext()` with `_ == hasMore(this)` keep their state in the return refinement, so the guard filter now looks there too. Before this fix, it dropped the `hasNext()`, `canUndo()` and `!isDisplayable()` guards. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 9e4b5e6 commit 4631bc2

5 files changed

Lines changed: 219 additions & 19 deletions

File tree

‎liquidjava-verifier/src/main/java/liquidjava/diagnostics/hints/StateHints.java‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import liquidjava.processor.state_machine.DecidingArgument;
1919
import liquidjava.processor.state_machine.State;
2020
import liquidjava.processor.state_machine.StateMachine;
21+
import liquidjava.rj_language.Predicate;
2122
import liquidjava.utils.Utils;
2223
import liquidjava.utils.constants.Keys;
2324
import spoon.reflect.reference.CtExecutableReference;
@@ -143,7 +144,10 @@ private List<Hint> howToReach(Set<State> current, RefinedFunction call, String f
143144
*/
144145
private List<Hint> guard(Set<State> current, RefinedFunction call) {
145146
List<CallVariant> guards = new ArrayList<>();
147+
boolean anyCombination = anyCombination(current);
146148
for (CallVariant guard : machine.guards()) {
149+
if (anyCombination && !namesCheckedState(guard.method()))
150+
continue;
147151
if (!machine.allows(current, guard))
148152
continue;
149153
Set<State> reached = machine.after(current, guard);
@@ -162,6 +166,33 @@ private List<Hint> guard(Set<State> current, RefinedFunction call) {
162166
return List.of(new Hint(Kind.GUARD, message));
163167
}
164168

169+
/**
170+
* Whether the receiver can be in any combination of the states {@code current} has in each state set. Then a call
171+
* that names no state of the sets the failing call checks leaves them as they were, whatever it returns, so the
172+
* failing call stays disallowed after it
173+
*/
174+
private boolean anyCombination(Set<State> current) {
175+
long combinations = 1;
176+
for (int set = 0; set < current.iterator().next().names().size(); set++) {
177+
int index = set;
178+
combinations *= current.stream().map(s -> s.names().get(index)).distinct().count();
179+
}
180+
return combinations == current.size();
181+
}
182+
183+
/**
184+
* Whether a state refinement or the return refinement of {@code method} names a state of a set the failing call
185+
* checks, or an alias
186+
*/
187+
private boolean namesCheckedState(RefinedFunction method) {
188+
Set<String> checked = machine.states().stream().flatMap(s -> checkedSets.stream().map(s.names()::get))
189+
.collect(Collectors.toSet());
190+
Stream<Predicate> refinements = Stream.concat(
191+
method.getAllStates().stream().flatMap(o -> Stream.of(o.getFrom(), o.getTo())),
192+
Stream.ofNullable(method.getRefReturn()));
193+
return refinements.anyMatch(p -> StateMachine.mayName(p, checked));
194+
}
195+
165196
private Hint callSequence(Set<State> current, List<CallVariant> sequence, String from) {
166197
Set<State> reached = current;
167198
for (CallVariant step : sequence)

‎liquidjava-verifier/src/main/java/liquidjava/processor/state_machine/SolverEffects.java‎

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import java.util.ArrayList;
44
import java.util.HashMap;
5+
import java.util.HashSet;
6+
import java.util.LinkedHashSet;
57
import java.util.List;
68
import java.util.Map;
79
import java.util.Optional;
@@ -56,8 +58,14 @@ record Scope(TypeChecker tc, StateSolver solver, List<State> states, List<List<S
5658
/** The effects with any arguments, whose entries a condition on the result does not change, or null */
5759
private final CallVariant.Effects any;
5860

59-
private final Map<Integer, Map<State, CallVariant.Entry>> entries = new HashMap<>();
61+
/** By state refinement, then by the states before the call in the state sets its {@code from} names */
62+
private final Map<Integer, Map<List<String>, CallVariant.Entry>> entries = new HashMap<>();
6063
private final Map<Integer, Map<State, Optional<Set<State>>>> afters = new HashMap<>();
64+
/**
65+
* By state refinement, then by the states before the call in the sets its {@code to} names for {@code old(this)}:
66+
* the states it can lead to in the sets it names
67+
*/
68+
private final Map<Integer, Map<List<String>, Set<List<String>>>> reachedBefore = new HashMap<>();
6169

6270
/**
6371
* @param changes
@@ -99,13 +107,17 @@ public CallVariant.Entry entry(int index, State state) {
99107
return CallVariant.Entry.HOLDS; // no state refinement: allowed in every state
100108
if (onResult && any != null)
101109
return any.entry(index, state); // the result is not known before the call
102-
return entries.computeIfAbsent(index, i -> new HashMap<>()).computeIfAbsent(state, s -> {
110+
// the states of the other sets are about other ghost functions, so they cannot change the answer
111+
Predicate from = changes.get(index).getFrom();
112+
List<String> named = namedSets(from).stream().map(state.names()::get).toList();
113+
return entries.computeIfAbsent(index, i -> new HashMap<>()).computeIfAbsent(named, n -> {
103114
Optional<CallVariant.Entry> entry = withScope(() -> {
104-
Predicate before = before(s);
105-
Predicate from = changes.get(index).getFrom().substituteVariable(Keys.THIS, BEFORE);
106-
if (scope.solver().implies(before, from))
115+
Predicate before = before(state);
116+
Predicate fromBefore = from.substituteVariable(Keys.THIS, BEFORE);
117+
if (scope.solver().implies(before, fromBefore))
107118
return CallVariant.Entry.HOLDS;
108-
return scope.solver().compatible(before, from) ? CallVariant.Entry.UNDECIDED : CallVariant.Entry.FAILS;
119+
return scope.solver().compatible(before, fromBefore) ? CallVariant.Entry.UNDECIDED
120+
: CallVariant.Entry.FAILS;
109121
});
110122
return entry.orElse(CallVariant.Entry.UNDECIDED);
111123
});
@@ -132,11 +144,23 @@ private Optional<Set<State>> computeAfter(int index, State state, Set<State> can
132144
ObjectState change = changes.get(index);
133145
if (!change.hasTo())
134146
return Set.of(state);
135-
Predicate to = change.getTo().substituteVariable(Keys.THIS, AFTER).changeOldMentions(BEFORE, AFTER);
136-
Predicate known = Predicate.createConjunction(before(state), to);
137-
if (onResult)
138-
known = Predicate.createConjunction(known, condition);
139-
Set<State> next = possibleStates(candidates, known, AFTER);
147+
List<Integer> named = namedSets(change.getTo()).stream().sorted().toList();
148+
Set<State> kept = Set.copyOf(StateMachine.keeping(candidates, state, Set.copyOf(named)));
149+
// where it leads in the sets it names depends only on the state before in those it names for old(this)
150+
List<String> before = StateMachine.namedSetsBefore(change.getTo(), scope.stateSets()).stream().sorted()
151+
.map(state.names()::get).toList();
152+
Map<List<String>, Set<List<String>>> reached = reachedBefore.computeIfAbsent(index, i -> new HashMap<>());
153+
if (!reached.containsKey(before)) {
154+
Predicate to = change.getTo().substituteVariable(Keys.THIS, AFTER).changeOldMentions(BEFORE, AFTER);
155+
Predicate known = Predicate.createConjunction(before(state), to);
156+
if (onResult)
157+
known = Predicate.createConjunction(known, condition);
158+
reached.put(before, possibleStates(kept, known, AFTER).stream()
159+
.map(c -> named.stream().map(c.names()::get).toList()).collect(Collectors.toSet()));
160+
}
161+
Set<State> next = scope.states().stream().filter(kept::contains)
162+
.filter(c -> reached.get(before).contains(named.stream().map(c.names()::get).toList()))
163+
.collect(Collectors.toCollection(LinkedHashSet::new));
140164
// no state at all: the condition contradicts the refinement here, so nothing can be claimed
141165
return next.isEmpty() && !onResult ? null : next;
142166
});
@@ -170,6 +194,13 @@ private Set<State> possibleStates(Set<State> candidates, Predicate known, String
170194
return scope.solver().possibleStates(combined, known, variable);
171195
}
172196

197+
/** The state sets that {@code predicate} or this variant's condition may name a state of */
198+
private Set<Integer> namedSets(Predicate predicate) {
199+
Set<Integer> named = new HashSet<>(StateMachine.namedSets(predicate, scope.stateSets()));
200+
named.addAll(StateMachine.namedSets(condition, scope.stateSets()));
201+
return named;
202+
}
203+
173204
/** What is known before the call in {@code state} */
174205
private Predicate before(State state) {
175206
Predicate before = state.predicate().substituteVariable(Keys.THIS, BEFORE);

‎liquidjava-verifier/src/main/java/liquidjava/processor/state_machine/StateMachine.java‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,16 @@
1212
import java.util.Optional;
1313
import java.util.Set;
1414
import java.util.stream.Collectors;
15+
import java.util.stream.IntStream;
1516

1617
import liquidjava.processor.context.ObjectState;
1718
import liquidjava.processor.context.RefinedFunction;
1819
import liquidjava.rj_language.Predicate;
20+
import liquidjava.rj_language.ast.AliasInvocation;
21+
import liquidjava.rj_language.ast.Expression;
22+
import liquidjava.rj_language.ast.FunctionInvocation;
23+
import liquidjava.utils.Utils;
24+
import liquidjava.utils.constants.Keys;
1925

2026
/**
2127
* The typestate of a class as a finite state machine, built by {@link StateMachineBuilder}
@@ -258,6 +264,60 @@ public Set<State> ordered(Collection<State> subset) {
258264
return states.stream().filter(subset::contains).collect(Collectors.toCollection(LinkedHashSet::new));
259265
}
260266

267+
/**
268+
* Whether {@code predicate} names one of {@code states}, by its simple name, or calls an alias, which may name one
269+
* that cannot be seen without expanding it
270+
*/
271+
public static boolean mayName(Predicate predicate, Set<String> states) {
272+
return mayName(predicate.getExpression(), states, false);
273+
}
274+
275+
/**
276+
* The state sets, as indexes into {@link State#names()}, that {@code predicate} {@link #mayName may name} a state
277+
* of
278+
*
279+
* @param stateSets
280+
* the states of each state set on its own, in the order the sets are declared
281+
*/
282+
static Set<Integer> namedSets(Predicate predicate, List<List<State>> stateSets) {
283+
return namedSets(predicate, stateSets, false);
284+
}
285+
286+
/** Like {@link #namedSets}, but only the sets it may name a state of for {@code old(this)} */
287+
static Set<Integer> namedSetsBefore(Predicate predicate, List<List<State>> stateSets) {
288+
return namedSets(predicate, stateSets, true);
289+
}
290+
291+
private static Set<Integer> namedSets(Predicate predicate, List<List<State>> stateSets, boolean onOld) {
292+
return IntStream.range(0, stateSets.size())
293+
.filter(k -> mayName(predicate.getExpression(),
294+
stateSets.get(k).stream().map(s -> s.names().get(0)).collect(Collectors.toSet()), onOld))
295+
.boxed().collect(Collectors.toSet());
296+
}
297+
298+
/**
299+
* The {@code candidates} in the same state as {@code before} in every state set but those in {@code changed}: the
300+
* verifier keeps the state of a set that a state refinement's {@code to} does not name
301+
*/
302+
static List<State> keeping(Collection<State> candidates, State before, Set<Integer> changed) {
303+
return candidates.stream().filter(c -> IntStream.range(0, before.names().size())
304+
.allMatch(k -> changed.contains(k) || c.names().get(k).equals(before.names().get(k)))).toList();
305+
}
306+
307+
private static boolean mayName(Expression expression, Set<String> states, boolean onOld) {
308+
if (expression instanceof AliasInvocation)
309+
return true;
310+
if (expression instanceof FunctionInvocation f && states.contains(Utils.getSimpleName(f.getName()))
311+
&& (!onOld || invokesOld(f)))
312+
return true;
313+
return expression.getChildren().stream().anyMatch(e -> mayName(e, states, onOld));
314+
}
315+
316+
private static boolean invokesOld(Expression expression) {
317+
return expression instanceof FunctionInvocation f && Keys.OLD.equals(f.getName())
318+
|| expression.getChildren().stream().anyMatch(StateMachine::invokesOld);
319+
}
320+
261321
private Optional<Transition> transition(State from, RefinedFunction method) {
262322
return transitions.stream().filter(t -> t.from().equals(from) && t.method().equals(method)).findFirst();
263323
}

‎liquidjava-verifier/src/main/java/liquidjava/processor/state_machine/StateMachineBuilder.java‎

Lines changed: 46 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
import java.util.ArrayDeque;
44
import java.util.ArrayList;
55
import java.util.Deque;
6+
import java.util.HashMap;
67
import java.util.HashSet;
78
import java.util.LinkedHashMap;
9+
import java.util.LinkedHashSet;
810
import java.util.List;
911
import java.util.Map;
1012
import java.util.Objects;
@@ -509,32 +511,68 @@ private Optional<List<Transition>> transitionsOf(RefinedFunction method) throws
509511
if (!canModel(method))
510512
return Optional.empty();
511513
List<Transition> transitions = new ArrayList<>();
514+
List<List<State>> sets = stateSets();
515+
List<ObjectState> changes = method.getAllStates();
516+
// whether a from holds depends only on the state sets it names: the others are other ghost functions
517+
List<Map<List<String>, CallVariant.Entry>> entries = changes.stream()
518+
.map(c -> new HashMap<List<String>, CallVariant.Entry>()).collect(Collectors.toList());
519+
List<Map<List<String>, Set<List<String>>>> afters = changes.stream()
520+
.map(c -> new HashMap<List<String>, Set<List<String>>>()).collect(Collectors.toList());
512521
for (State state : states) {
513522
Predicate current = state.predicate().substituteVariable(Keys.THIS, BEFORE);
514-
for (ObjectState change : method.getAllStates()) {
523+
for (int i = 0; i < changes.size(); i++) {
524+
ObjectState change = changes.get(i);
515525
if (!change.hasFrom())
516526
continue;
517-
Predicate from = change.getFrom().substituteVariable(Keys.THIS, BEFORE);
518-
if (solver.implies(current, from)) {
527+
List<String> named = StateMachine.namedSets(change.getFrom(), sets).stream().map(state.names()::get)
528+
.toList();
529+
CallVariant.Entry entry = entries.get(i).get(named);
530+
if (entry == null) {
531+
entry = entry(current, change.getFrom().substituteVariable(Keys.THIS, BEFORE));
532+
entries.get(i).put(named, entry);
533+
}
534+
if (entry == CallVariant.Entry.HOLDS) {
519535
// like the verifier, the first state change whose precondition holds is the one applied
520-
Set<State> next = statesAfter(change, state, current);
536+
Set<State> next = statesAfter(change, state, current, sets, afters.get(i));
521537
if (next.isEmpty())
522538
return Optional.empty();
523539
transitions.add(new Transition(state, method, change, next));
524540
break;
525541
}
526-
if (solver.compatible(current, from))
542+
if (entry == CallVariant.Entry.UNDECIDED)
527543
return Optional.empty(); // allowed only sometimes in this state
528544
}
529545
}
530546
return Optional.of(transitions);
531547
}
532548

533-
private Set<State> statesAfter(ObjectState change, State state, Predicate current) throws LJError {
549+
private CallVariant.Entry entry(Predicate current, Predicate from) throws LJError {
550+
if (solver.implies(current, from))
551+
return CallVariant.Entry.HOLDS;
552+
return solver.compatible(current, from) ? CallVariant.Entry.UNDECIDED : CallVariant.Entry.FAILS;
553+
}
554+
555+
/**
556+
* The states {@code change} can lead to from {@code state}. The verifier keeps the state of the sets its {@code to}
557+
* does not name, and the states it can lead to in the others depend only on the state before in the sets it names
558+
* for {@code old(this)}, so they are asked once for each and kept in {@code known}
559+
*/
560+
private Set<State> statesAfter(ObjectState change, State state, Predicate current, List<List<State>> sets,
561+
Map<List<String>, Set<List<String>>> known) throws LJError {
534562
if (!change.hasTo())
535563
return Set.of(state);
536-
Predicate to = change.getTo().substituteVariable(Keys.THIS, AFTER).changeOldMentions(BEFORE, AFTER);
537-
return solver.possibleStates(states, Predicate.createConjunction(current, to), AFTER);
564+
List<Integer> named = StateMachine.namedSets(change.getTo(), sets).stream().sorted().toList();
565+
List<State> candidates = StateMachine.keeping(states, state, Set.copyOf(named));
566+
List<String> before = StateMachine.namedSetsBefore(change.getTo(), sets).stream().sorted()
567+
.map(state.names()::get).toList();
568+
if (!known.containsKey(before)) {
569+
Predicate to = change.getTo().substituteVariable(Keys.THIS, AFTER).changeOldMentions(BEFORE, AFTER);
570+
known.put(before, solver.possibleStates(candidates, Predicate.createConjunction(current, to), AFTER)
571+
.stream().map(s -> named.stream().map(s.names()::get).toList()).collect(Collectors.toSet()));
572+
}
573+
Set<List<String>> after = known.get(before);
574+
return candidates.stream().filter(c -> after.contains(named.stream().map(c.names()::get).toList()))
575+
.collect(Collectors.toCollection(LinkedHashSet::new));
538576
}
539577

540578
/** The states {@code constructor} can create the object in, or nothing if they depend on its arguments */

‎liquidjava-verifier/src/test/java/liquidjava/processor/state_machine/StateMachineTest.java‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515

1616
import liquidjava.processor.context.RefinedFunction;
1717
import liquidjava.rj_language.Predicate;
18+
import liquidjava.rj_language.ast.AliasInvocation;
19+
import liquidjava.utils.constants.Keys;
1820

1921
class StateMachineTest {
2022

@@ -23,6 +25,9 @@ class StateMachineTest {
2325
private static final State OPEN_UNLOCKED = state("open", "unlocked");
2426
private static final State CLOSED_LOCKED = state("closed", "locked");
2527
private static final State CLOSED_UNLOCKED = state("closed", "unlocked");
28+
private static final List<List<State>> SETS = List.of(List.of(state("open"), state("closed")),
29+
List.of(state("locked"), state("unlocked")));
30+
private static final Predicate THIS = Predicate.createVar(Keys.THIS);
2631
private static final StateMachine MACHINE = machine(
2732
List.of(OPEN_LOCKED, OPEN_UNLOCKED, CLOSED_LOCKED, CLOSED_UNLOCKED));
2833

@@ -139,6 +144,41 @@ void callWhoseStatesAfterAreUnknownIsNotAllowed() {
139144
assertFalse(machine(ABC, call).allows(Set.of(A), call));
140145
}
141146

147+
@Test
148+
void setsNamedAreThoseWithAStateInThePredicate() {
149+
Predicate openAndPositive = Predicate.createConjunction(inState("open", THIS),
150+
Predicate.createInvocation("size", THIS));
151+
assertEquals(Set.of(0), StateMachine.namedSets(openAndPositive, SETS));
152+
assertEquals(Set.of(), StateMachine.namedSets(new Predicate(), SETS));
153+
}
154+
155+
@Test
156+
void aliasMayNameEverySet() {
157+
Predicate alias = new Predicate(new AliasInvocation("Ready", List.of(THIS.getExpression())));
158+
assertEquals(Set.of(0, 1), StateMachine.namedSets(alias, SETS));
159+
assertEquals(Set.of(0, 1), StateMachine.namedSetsBefore(alias, SETS));
160+
}
161+
162+
@Test
163+
void setsNamedBeforeAreThoseNamedForOld() {
164+
// locked(this) && open(old(this))
165+
Predicate to = Predicate.createConjunction(inState("locked", THIS),
166+
inState("open", Predicate.createInvocation(Keys.OLD, THIS)));
167+
assertEquals(Set.of(0, 1), StateMachine.namedSets(to, SETS));
168+
assertEquals(Set.of(0), StateMachine.namedSetsBefore(to, SETS));
169+
}
170+
171+
@Test
172+
void candidatesKeepTheStateOfSetsNotChanged() {
173+
assertEquals(List.of(OPEN_LOCKED, OPEN_UNLOCKED),
174+
StateMachine.keeping(MACHINE.states(), OPEN_LOCKED, Set.of(1)));
175+
assertEquals(List.of(OPEN_LOCKED), StateMachine.keeping(MACHINE.states(), OPEN_LOCKED, Set.of()));
176+
}
177+
178+
private static Predicate inState(String state, Predicate object) {
179+
return Predicate.createInvocation(state, object);
180+
}
181+
142182
/** Effects given by hand: the states where each refinement's from holds, and the states after the call from each */
143183
private record Effects(boolean changesState, Map<State, Set<State>> after, Set<State> undecided) {
144184
Effects(boolean changesState, Map<State, Set<State>> after) {

0 commit comments

Comments
 (0)