Skip to content

Commit fbc5e9f

Browse files
Add a Relevant to Expected step to state errors (#495)
Fixes #297 A state error's Found now ends with a step called **Relevant to Expected**. This step keeps only the facts that the expected state depends on. The full Found is still the step before it. This is a display change only: the VC sent to the solver, the verdict, the hints and the category are all unchanged. #### When a fact is left out (established independence) Each fact (a conjunct of a Found row) is reduced to the solver terms it constrains: - a ghost function applied to an object, `f(x)`. A state stands for its state set function, so `open(x)` and `state1(x) == state1(y)` both constrain `state1(x)`. - a variable whose own value the fact constrains, such as `mode`, `#canRedo_result`, or `x` in `x == y`. A fact is kept if it shares a term with Expected, either directly or through other kept facts. All other facts are left out. Different ghost functions, or the same function over different objects, are different solver terms, so a fact that shares no term with this group is independent of Expected. To keep this safe, an object is never split into its ghost functions when any fact constrains it as a value (`x == y`) or passes it to an alias or an unknown function. In that case, all of its facts stay together. Conditions are not split either: facts under the same `c ? … : …` share `c` and stay together. No step is added when every fact or no fact is relevant. The pass works on expressions and ghost declarations, not on rendered names. #### Before / after (CLI message, which uses the last step) | Example | Before | After | |---|---|---| | E_A3_07 scanner (the issue example) | `startTiling(preview@53) && state2(preview@53) == state2(preview@52) && compressionSet(preview) && state1(preview) == state1(preview@53)` | `startTiling(preview@53) && state1(preview) == state1(preview@53)` | | Study A1_01 SlideRecoder | `tilingNotExplicit(wParam) && compressionNotExplicit(wParam)` | `compressionNotExplicit(wParam)` | | A3_05 ScaledImageGenerator | `startCompression(iwparam) && state1(iwparam) == 0` | `startCompression(iwparam)` | | `ErrorTrafficLightRGB` | `green(tl@48) && red(tl) && r(tl) == r(tl@48) && g(tl) == g(tl@48) && b(tl) == b(tl@48)` | `red(tl)` | | `ErrorArgumentPicksTheStateEarlier` | `tilingOff(param@24) && uncompressed(param@24) && tilingOff(param@25) && state2(param@25) == state2(param@24) && compressed(param) && state1(param) == state1(param@25)` | `tilingOff(param@25) && state1(param) == state1(param@25)` | Expected is unchanged in every row. Across the 98 state-error cases in `testSuite`, 15 messages in 10 cases change. Only the Found text changes; other examples are `resultset_forward_error`, `ErrorIteratorReturnHasNext`, `ErrorStateHintJoins` and `ErrorStateHintMultipleSets`. The CLI output of the other 88 cases is byte-identical. **The six study exercises** (proposal D): all report the same verdicts and lines. A1_01 gets the step, as shown above. A1_38 (`open(buffered) && unmarked(buffered)`, where both state sets are in Expected), A1_09 (one conditional fact), and A1_56 (no Found, "could not prove it") have nothing safe to remove, so they get no step. A2_04 and A2_10 are refinement errors and are unaffected. In the A1_56 partial-fix variant (only `redo()` guarded), every fact sits under the shared `#canRedo_result` condition, so it also gets no step. Much of that noise comes from switch cases not being modelled (see the comment on #297). #### Webview The server already sends the whole history, so the extra step reaches the panel without any server change, and the back arrow returns to the full Found. However, `vc-implications.ts` labels the newest step "Simplified" and never shows its pass name. For the label "Relevant to Expected" to appear, vscode-liquidjava needs a one-line change: use `simplification` for index 0 when it is set. That change is not part of this PR. #### Tests - `TestStateErrorContext#foundEndsWithTheFactsRelevantToTheExpectedStateSet`: the message, the step name, and that stepping back shows the compression state set (existing fixture). - `VCSimplificationTest`: two conservative cases where nothing may be left out: an object compared as a value, and an object passed to an unknown function. Each one fails if its rule is removed. Full suite: 715 tests pass locally. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 8a03a74 commit fbc5e9f

4 files changed

Lines changed: 192 additions & 4 deletions

File tree

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

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
import liquidjava.rj_language.ast.Ite;
2222
import liquidjava.rj_language.ast.Var;
2323
import liquidjava.rj_language.opt.NeededVariables;
24+
import liquidjava.rj_language.opt.VCRelevantFacts;
25+
import liquidjava.rj_language.opt.VCSimplification;
26+
import liquidjava.rj_language.opt.VCSimplificationResult;
2427
import liquidjava.smt.Counterexample;
2528
import liquidjava.smt.SMTEvaluator;
2629
import liquidjava.smt.SMTResult;
@@ -459,9 +462,23 @@ protected void throwStateRefinementError(SourcePosition position, SourcePosition
459462
StateErrorContext context) throws StateRefinementError {
460463
TranslationTable map = new TranslationTable();
461464
VCImplication foundState = buildPremiseChain(map, expected, found);
462-
throw new StateRefinementError(position, declarationPosition, expected,
463-
foundState.simplify(NeededVariables.forStateError(expected)), map, customMessage, hints, category,
464-
context);
465+
VCSimplificationResult simplified = foundState.simplify(NeededVariables.forStateError(expected));
466+
VCSimplificationResult shown = VCSimplification.simplifyOnce(simplified,
467+
new VCRelevantFacts(expected.getExpression(), this::ghostFunctionsOf));
468+
throw new StateRefinementError(position, declarationPosition, expected, shown, map, customMessage, hints,
469+
category, context);
470+
}
471+
472+
/** The ghost functions an invocation name stands for: a state's state set function, or the ghost itself */
473+
private Set<String> ghostFunctionsOf(String name) {
474+
Set<String> functions = new HashSet<>();
475+
for (GhostState state : context.getGhostStates())
476+
if (state.matches(name))
477+
functions.add(state.getParent() != null ? state.getParent().getName() : state.getName());
478+
for (GhostFunction ghost : context.getGhosts())
479+
if (ghost.matches(name))
480+
functions.add(ghost.getName());
481+
return functions;
465482
}
466483

467484
protected void throwStateConflictError(SourcePosition position, Predicate expected) throws StateConflictError {
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
package liquidjava.rj_language.opt;
2+
3+
import static liquidjava.rj_language.opt.VCSimplificationUtils.copyWithRefinement;
4+
import static liquidjava.rj_language.opt.VCSimplificationUtils.factsOf;
5+
import static liquidjava.rj_language.opt.VCSimplificationUtils.variablesOf;
6+
7+
import java.util.ArrayList;
8+
import java.util.HashMap;
9+
import java.util.HashSet;
10+
import java.util.Iterator;
11+
import java.util.List;
12+
import java.util.Map;
13+
import java.util.Set;
14+
import java.util.function.Function;
15+
16+
import liquidjava.processor.VCImplication;
17+
import liquidjava.rj_language.Predicate;
18+
import liquidjava.rj_language.ast.BinaryExpression;
19+
import liquidjava.rj_language.ast.Expression;
20+
import liquidjava.rj_language.ast.FunctionInvocation;
21+
import liquidjava.rj_language.ast.Var;
22+
23+
/**
24+
* Keeps in a state error's Found only the facts the expected state depends on, for display: the solver's VC is not
25+
* changed. Each fact is split into the symbols it constrains: a ghost function applied to an object, such as the state
26+
* set {@code state1(x)} that both {@code open(x)} and {@code state1(x) == state1(y)} constrain, or a variable whose own
27+
* value it constrains. Different ghost functions, or the same one over different objects, are different solver terms,
28+
* so facts that share no symbol with expected, directly or through other facts, are independent of it and are left out.
29+
* An object whose value a fact constrains, such as {@code x == y}, or that an alias or unknown function takes, is one
30+
* symbol with all its ghost functions, so its facts are never split. Nothing changes when every fact or none is
31+
* relevant
32+
*/
33+
public class VCRelevantFacts implements VCSimplificationPass {
34+
35+
private final Expression expected;
36+
private final Function<String, Set<String>> ghostFunctionsOf;
37+
38+
/**
39+
* @param ghostFunctionsOf
40+
* the ghost functions an invocation name stands for: a state's state set function, or the ghost itself;
41+
* none for any other name
42+
*/
43+
public VCRelevantFacts(Expression expected, Function<String, Set<String>> ghostFunctionsOf) {
44+
this.expected = expected;
45+
this.ghostFunctionsOf = ghostFunctionsOf;
46+
}
47+
48+
@Override
49+
public String getName() {
50+
return "Relevant to Expected";
51+
}
52+
53+
@Override
54+
public VCImplication apply(VCImplication implication) {
55+
List<List<Expression>> rowFacts = new ArrayList<>();
56+
for (VCImplication row = implication; row != null; row = row.getNext())
57+
rowFacts.add(factsOf(row.getRefinement().getExpression()));
58+
List<Expression> allFacts = rowFacts.stream().flatMap(List::stream).toList();
59+
Set<String> values = new HashSet<>();
60+
addSymbols(expected, new HashMap<>(), values);
61+
allFacts.forEach(fact -> addSymbols(fact, new HashMap<>(), values));
62+
63+
Set<String> linked = symbolsOf(expected, values);
64+
List<Set<String>> unlinked = new ArrayList<>(allFacts.stream().map(fact -> symbolsOf(fact, values)).toList());
65+
boolean changed = true;
66+
while (changed) {
67+
changed = false;
68+
for (Iterator<Set<String>> it = unlinked.iterator(); it.hasNext();) {
69+
Set<String> symbols = it.next();
70+
if (symbols.stream().anyMatch(linked::contains)) {
71+
linked.addAll(symbols);
72+
it.remove();
73+
changed = true;
74+
}
75+
}
76+
}
77+
78+
List<List<Expression>> kept = rowFacts.stream().map(facts -> facts.stream()
79+
.filter(fact -> symbolsOf(fact, values).stream().anyMatch(linked::contains)).toList()).toList();
80+
int relevant = kept.stream().mapToInt(List::size).sum();
81+
if (relevant == 0 || relevant == allFacts.size())
82+
return implication;
83+
return rebuild(implication, rowFacts.iterator(), kept.iterator());
84+
}
85+
86+
// The rows with their relevant facts, leaving out those that keep none
87+
private VCImplication rebuild(VCImplication row, Iterator<List<Expression>> all, Iterator<List<Expression>> kept) {
88+
if (row == null)
89+
return null;
90+
List<Expression> rowAll = all.next(), rowKept = kept.next();
91+
VCImplication next = rebuild(row.getNext(), all, kept);
92+
if (rowKept.isEmpty())
93+
return next;
94+
Expression refinement = rowKept.size() == rowAll.size() ? row.getRefinement().getExpression().clone()
95+
: rowKept.stream().map(Expression::clone)
96+
.reduce((first, second) -> new BinaryExpression(first, "&&", second)).get();
97+
VCImplication result = copyWithRefinement(row, new Predicate(refinement));
98+
result.setNext(next);
99+
return result;
100+
}
101+
102+
// The symbols an expression constrains: f(x) for a ghost function over an object, or the object itself when values
103+
// has it, and the variables whose value it constrains
104+
private Set<String> symbolsOf(Expression expression, Set<String> values) {
105+
Map<String, String> applications = new HashMap<>();
106+
Set<String> symbols = new HashSet<>();
107+
addSymbols(expression, applications, symbols);
108+
applications.forEach((application, object) -> symbols.add(values.contains(object) ? object : application));
109+
return symbols;
110+
}
111+
112+
// Adds each ghost function applied to a variable, as f(x) mapped to x, to applications, and the variables whose
113+
// value the expression constrains, or that an unknown function takes, to values
114+
private void addSymbols(Expression expression, Map<String, String> applications, Set<String> values) {
115+
if (expression instanceof FunctionInvocation invocation) {
116+
Set<String> functions = ghostFunctionsOf.apply(invocation.getName());
117+
if (!functions.isEmpty() && invocation.getArgs().size() == 1
118+
&& invocation.getArgs().get(0)instanceof Var object)
119+
functions.forEach(
120+
function -> applications.put(function + "(" + object.getName() + ")", object.getName()));
121+
else
122+
values.addAll(variablesOf(invocation));
123+
return;
124+
}
125+
if (expression instanceof Var var)
126+
values.add(var.getName());
127+
for (Expression child : expression.getChildren())
128+
addSymbols(child, applications, values);
129+
}
130+
}

‎liquidjava-verifier/src/test/java/liquidjava/api/tests/TestStateErrorContext.java‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import liquidjava.diagnostics.errors.LJError;
1212
import liquidjava.diagnostics.errors.StateErrorContext;
1313
import liquidjava.diagnostics.errors.StateRefinementError;
14+
import liquidjava.rj_language.opt.VCSimplificationResult;
1415

1516
class TestStateErrorContext {
1617

@@ -50,10 +51,25 @@ void classWithoutStateSetHasNoContext() {
5051
assertNull(contextOf("ErrorUnconstrainedStateRefinement.java"));
5152
}
5253

54+
@Test
55+
void foundEndsWithTheFactsRelevantToTheExpectedStateSet() {
56+
StateRefinementError error = errorOf("ErrorArgumentPicksTheStateEarlier.java");
57+
assertEquals("found tilingOff(param@25) && state1(param) == state1(param@25) but expected tilingOn(param)",
58+
error.getMessage());
59+
VCSimplificationResult found = error.getFoundSimplification();
60+
assertEquals("Relevant to Expected", found.getSimplification());
61+
// stepping back shows the compression state set again
62+
assertTrue(found.getOrigin().getImplication().toString().contains("compressed"));
63+
}
64+
5365
private static StateErrorContext contextOf(String test) {
66+
return errorOf(test).getContext();
67+
}
68+
69+
private static StateRefinementError errorOf(String test) {
5470
CommandLineLauncher.launch(TEST_SUITE + test);
5571
List<LJError> errors = Diagnostics.getInstance().getErrors().stream().toList();
5672
assertEquals(1, errors.size(), "Expected exactly one error from " + test);
57-
return assertInstanceOf(StateRefinementError.class, errors.get(0)).getContext();
73+
return assertInstanceOf(StateRefinementError.class, errors.get(0));
5874
}
5975
}

‎liquidjava-verifier/src/test/java/liquidjava/rj_language/opt/VCSimplificationTest.java‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,14 @@
33
import static liquidjava.utils.VCTestUtils.*;
44
import static org.junit.jupiter.api.Assertions.assertNull;
55

6+
import java.util.Map;
7+
import java.util.Set;
8+
69
import org.junit.jupiter.api.AfterEach;
710
import org.junit.jupiter.api.Test;
811

912
import liquidjava.processor.context.Context;
13+
import liquidjava.rj_language.parsing.RefinementsParser;
1014
import liquidjava.utils.TestUtils;
1115

1216
class VCSimplificationTest {
@@ -180,4 +184,25 @@ void simplifyEliminatesRemovableConstraintImpliedByEarlierAntecedent() {
180184
assertSimplificationSteps(vc("∀x:int. x > 1", "∀cond:boolean. x > 0", "∀y:int. y == x + 1", "y < 0"),
181185
step("x > 1", "x > 0", "x + 1 < 0"), step("x > 1", "x + 1 < 0"));
182186
}
187+
188+
// tiling states and state1 are one state set, compression states and state2 another
189+
private static VCRelevantFacts relevantTo(String expected) {
190+
Map<String, String> stateSets = Map.of("startTiling", "state1", "tilingSet", "state1", "state1", "state1",
191+
"compressionSet", "state2", "state2", "state2");
192+
return new VCRelevantFacts(RefinementsParser.createAST(expected, ""),
193+
name -> stateSets.containsKey(name) ? Set.of(stateSets.get(name)) : Set.of());
194+
}
195+
196+
@Test
197+
void relevantStepKeepsEveryStateSetOfAnObjectComparedAsAValue() {
198+
assertSimplificationSteps(relevantTo("tilingSet(p)"),
199+
vc("∀q:Object. compressionSet(q) && startTiling(p)", "p == q"),
200+
step("compressionSet(q) && startTiling(p)", "p == q"));
201+
}
202+
203+
@Test
204+
void relevantStepKeepsFactsAnUnknownFunctionTakesTheObjectOf() {
205+
assertSimplificationSteps(relevantTo("tilingSet(p)"), vc("compressionSet(p) && ready(p)", "startTiling(p)"),
206+
step("compressionSet(p) && ready(p)", "startTiling(p)"));
207+
}
183208
}

0 commit comments

Comments
 (0)