Skip to content

Commit 70edf72

Browse files
Drop true binders the error does not need and write fields as in code (#459)
## Problem When a method reads a field, Found shows a row for it under its internal name, and the row says only `true`. Issue reproducer (`ArrayList.size()` refined `_ == size(this) && _ >= 0`, `Random.nextInt(bound)` refined `bound > 0`): ``` ∀this#shop.Basket.items true → ∀bound⁶ bound⁶ == size(items) && bound⁶ >= 0 ``` In the IDE the first row wraps over several lines, above the row that matters. The message and the later row also write the field as `items`, so it reads like the local it was copied into. ![A2_10 in VS Code, before](https://raw.githubusercontent.com/liquid-java/liquidjava/pr-screenshots/issues/457/verification.png) ## Cause 1. `VCBinderSimplification` dropped a `true` binder only when no later row mentioned its variable. Here `size(this#shop.Basket.items)` mentions it. Every field, parameter, call result or local that is only passed along keeps its `true` row this way. The `∀getUndoManager⁸⁵⁶ true` and `∀#fresh… true` rows of #375 come from the same rule. 2. `VariableFormatter.format` left `this#<package>.<Class>.<field>` unchanged. The binder, the counterexample and the extension's context and translation-table keys therefore showed the internal name, while `ExpressionNameResolver` cut it down to the bare `items` inside expressions. ## Fix ### Which `true` rows stay A binder refined only by `true` states no fact. It stays in Found only when the error needs it: - **Linked to Expected.** Some fact of the chain constrains the binder's *value* and is linked to Expected, meaning it shares a term with Expected directly or through other linked facts. - Terms are variables and ghost or state applications such as `size(x)`. - Facts are the rows' conjuncts. A negated disjunction is split first: `!(p || q)` becomes `!p` and `!q`, so one combined guard does not link everything. - A variable of an **object** type that a fact names only as a ghost argument (`x` in `b == size(x)`) is not constrained by that fact. Its row would say nothing, so it goes. A primitive argument (`k` in `y == f(k)`) has a value of its own and is kept. - **Expected constrains its value, in a refinement error only.** The counterexample then shows that value; `filterCounterexample` lists only binders. A state error has no counterexample, so there this alone keeps nothing. The rule depends only on the chain and Expected, not on Z3's model, and it works the same way for both error kinds. A kept `true` binder that comes after a row using its variable is moved to just before that row. This is a separate `Binder` step. Examples: | Case | Rows (after) | |---|---| | issue reproducer | `∀bound⁶ bound⁶ == size(this.items) && bound⁶ >= 0` (field only inside `size(...)`) | | `if (port < 0) return; positive(t);` | `∀#fresh !(port < 0)`, `∀t true`: `port` dropped (unlinked guard), `t` kept (Expected, counterexample `t == 0`) | | `if (p \|\| q) return; positive(t);` | `∀#fresh !(p \|\| q)`, `∀t true`: `p` and `q` dropped | | `int y = x + 1` refined `_ > 0` | `∀x true`, `∀y y == x + 1`: `x` kept, linked through `y` | | `ErrorStateHintPathDependent` (state) | `∀ready true`, `∀f ready ? open(f) : created(f)`: `ready` kept | | state errors whose Found is otherwise `true` | unchanged from `main`: no `∀it true` / `∀this true` row is added | | `for (int i = start; i < served; i++) positive(i);` | `∀Basket.served true`, `∀i true`, `∀#fresh i < Basket.served`: `i` now before its first use | The linking is `VCSimplificationUtils.linkedConjuncts(conjuncts, termsOf, seed)`. It does what `linkedTerms` in `RefinementError` does on #460 (branch `fix/counterexample-expected-vars`, issue #453): the same closure over shared terms, with the term function passed in. Once both are merged, `linkedTerms` can call this helper with its `termsOf`, and `splitConjuncts` can replace `getConjuncts` there, so the counterexample and the rows are linked in the same way. I didn't touch `filterCounterexample`. ### Simplification history (the VS Code arrows) Dropping a `true` row is an ordinary simplification step of the `Binder` pass, one binder per step. It goes into `VCSimplificationResult`'s origin chain, which the extension's server sends whole (`VCSimplificationResultDTO.origin`). The panel steps back through that chain, and its last step is the untouched `Original` with every binder. What the panel shows for the issue reproducer: | Step | `main` (2 steps) | this branch (3 steps) | |---|---|---| | 1 Original | `∀this#shop.Basket.items true`<br>`∀items⁵ items⁵ == this#shop.Basket.items`<br>`∀bound⁶ bound⁶ == size(items⁵) && bound⁶ >= 0` | `∀this.items true`<br>`∀items⁵ items⁵ == this.items`<br>`∀bound⁶ bound⁶ == size(items⁵) && bound⁶ >= 0` | | 2 after Substitution | (Simplified) `∀this#shop.Basket.items true`<br>`∀bound⁶ bound⁶ == size(items) && bound⁶ >= 0` | `∀this.items true`<br>`∀bound⁶ bound⁶ == size(this.items) && bound⁶ >= 0` | | 3 after Binder | | (Simplified) `∀bound⁶ bound⁶ == size(this.items) && bound⁶ >= 0` | The field display name is applied at every step, including Original, because the server formats every step with `VariableFormatter.format`. The internal names are untouched in the history itself. `TestFoundBinders.steppingBackReachesTheOriginalWithTheDroppedRow` checks that the original's binders are `this#testSuite.classes.found_true_binders_error.Basket.items`, `#items_…`, `#bound_…`. Showing the Original raw would be a one-line change in `VCImplicationDTO` (skip `format` for the oldest step), but I left that for the PM to decide. ### Source-like field names `this#pkg.Class.field` is written `this.field` in the message, the Found rows, the counterexample and the extension's context and translation table. This holds for both `this.x` and bare `x`. A static field is written `Class.field`. Instance counters stay (`this.interrupts¹¹³`), nested classes and long package names reduce the same way, and the **internal SMT name is unchanged**. Static-ness is not in the name, so `Utils.qualifyFieldName` records static fields as it builds their names, and `CommandLineLauncher.launch` clears the record at the start of each run. Every error comes from code verified in that run, which also built the names of the fields it shows, so the record is complete for that run's errors. Verifying a static `total`, then an instance `total` of the same class, then the static one again in one JVM shows `C.total`, `this.total`, `C.total`. There is no incremental verification that skips classes. If one is added, the record would need to be filled from the field declarations instead. I removed the earlier class-based disambiguation (`Basket.this.count`). Real code could not reach it, it was not valid Java for inherited fields, and it was not applied to binder rows or translation-table keys. Two different fields with the same simple name in one expression (a shadowed field) now both read `this.x`. ### Writes to another object's field (display only) This PR does not change what the verifier accepts or rejects for any write. A write to another object's field (`other.level = …`, `other.level++`, `other.level--`, `other.level += …`) is still checked and tracked exactly as on `main`, against the current object's field variable. Only its label changes. When `TypeChecker.checkVariableRefinements` creates the new instance for a write that `Utils.accessesTrackedField` says is not to the current object, it records the receiver's variable name for that instance in `VariableFormatter` (a bare field name when the receiver is not a variable). The instance is then written `other.level¹` instead of `this.level¹`: ``` main: level¹ == -1 is not a subtype of level¹ >= 0 now: other.level¹ == -1 is not a subtype of other.level¹ >= 0 ``` Because tracking is unchanged, a decrement shows what the verifier actually uses as the old value: `other.level⁹ == this.level⁸ - 1`. Writes through another object leak into `this.level`, and aliasing with `this` is not handled. Both are left for their own issue. Parity with `main`, checked on the reviewers' reproducers and `ErrorOtherObjectFieldWrite.java`: - `other.level++`, `other.level += 1` and `other.level = other.level + 1` verify. - `other.level--` and `other.level = -1` are reported. - The write through `W other = this` and `maybeSelf(this)` are reported. - The `other.level = 5; int k = this.level` (`_ == 5`) case verifies as on `main`. ### #375 This covers part of #375, not all of it. The `true` rows go, and in the JabRef `EditAction` exercise all four are removed. The path conditions over now-undeclared fresh variables (`∀#fresh¹²² !#fresh¹²¹`) are not `true` rows and stay; they also tie in with #373. #375 stays open. ## Before / after (main vs this branch, every error) I ran the harness that dumps what the IDE gets (message, rows, counterexample, translation-table keys) over 321 test-suite errors and 117 errors from the 98 study exercises, with `main` and this branch on identical inputs: - The same errors are reported at the same lines on both sides (the harness requires it), so nothing that `main` accepts or rejects changes. - 58 test-suite errors and 57 exercise errors differ in what they show. - The differences are renames (`this#…` to `this.x` or `Class.x`), dropped `true` rows, the `Binder` reordering, and in refinement errors a kept `true` row for an Expected variable. In those refinement errors `main` showed only `true`; now the variable's counterexample value also shows, e.g. `port == 65536`. - `true` rows: 110 → 87 (test suite), 78 → 46 (exercises). Raw `this#` names: 30 → 0 and 72 → 0. - No state error gains a `true` row. - **Instance numbers do not move**: 0 of the 438 messages change their superscripts. I could not reproduce the `transactionCommitted²⁷→²⁸` shift (A1_50 shows `²⁸` on both). I think it came from different inputs between the two runs. **Several fields** (`pickAny`) ``` before: ∀this#testSuite.classes.found_true_binders_error.Basket.items³⁷ true ∀first³⁸ first³⁸ == size(items³⁷) && first³⁸ >= 0 ∀this#testSuite.classes.found_true_binders_error.Basket.extras⁴¹ true ∀second⁴² second⁴² == size(extras⁴¹) && second⁴² >= 0 ∀bound⁴⁵ bound⁴⁵ == first³⁸ + second⁴² after: ∀first³⁸ first³⁸ == size(this.items³⁷) && first³⁸ >= 0 ∀second⁴² second⁴² == size(this.extras⁴¹) && second⁴² >= 0 ∀bound⁴⁵ bound⁴⁵ == first³⁸ + second⁴² ``` **Static field, linked to Expected** (`serve`) ``` before: count⁵⁴ == served + 1 is not a subtype of count⁵⁴ > 0 ∀this#testSuite.classes.found_true_binders_error.Basket.served true ∀count⁵⁴ count⁵⁴ == served + 1 after: count⁵⁴ == Basket.served + 1 is not a subtype of count⁵⁴ > 0 ∀Basket.served true ∀count⁵⁴ count⁵⁴ == Basket.served + 1 Counterexample: Basket.served == -1 && count⁵⁴ == 0 ``` **Field holding a state kept, unrelated `true` parameter dropped** (`classes/found_field_state_error`, after Jpcsp's `IntrManager`) ``` before: ∀intrNumber true ∀#fresh¹⁶ !(intrNumber < 0 || intrNumber >= 67) ∀this#testSuite.classes.found_field_state_error.InterruptManager.interrupts¹³ empty(interrupts¹³) after: ∀#fresh¹⁶ !(intrNumber < 0 || intrNumber >= 67) ∀this.interrupts¹³ empty(this.interrupts¹³) ``` ## Tests - `TestFoundBinders` (19 tests) on the fixtures `classes/found_true_binders_error`, `classes/found_field_state_error`, `ErrorStateHintPathDependent.java` and the new `ErrorOtherObjectFieldWrite.java`: - dropped: the reproducer's field row; a `true` parameter, call result and local; several fields; `port` behind an unrelated guard; `p`/`q` behind one combined guard. - kept: `x` linked through `y == x + 1`; an Expected variable in a refinement error; `ready` in the path-dependent state error; the field row holding `empty(...)`. - row order for a loop variable. - names: static `Basket.served`; `this.amount` and bare `amount` written alike; an inner-class field; `other.level` for writes and decrements on another object, and `this.level` for an own write. - parity with `main` for writes: `other.level++` and `other.level += 1` verify; `other.level--` and the write through an alias of `this` are reported. - the original the panel steps back to keeps the dropped row and the raw binder names, and the history includes a `Binder` step. - `VCBinderSimplificationTest` (13 new, including a primitive ghost argument that is kept): - linked through one or several rows; - an unlinked guard; - a split negated disjunction; - an Expected binder in refinement vs state errors; - linking through a ghost while keeping only value variables; - an object named only inside a ghost; - moving a kept binder before its first use; - the `NeededVariables` factories. - `VCSimplificationUtilsTest` (4): splitting conjuncts and negated disjunctions; transitive linking. - `VariableFormatterTest` (6 new) and `ExpressionNameResolverTest` (2 new): instance, static, nested, long-package and other-object field names; clearing the static record between runs; a field next to a local of the same name; a field inside a ghost argument. Without the fix (`main` sources, the new tests kept), `TestFoundBinders` fails 15 of 19 and `ExpressionNameResolverTest` fails 2 of 5. The unit tests on the new API do not compile on `main`. `mvn test` (verifier): **583 tests, 0 failures** (`main`: 534). **Changed existing expectations** - `VCBinderSimplificationTest.keepsTrueBinderWhenVariableIsUsedDownstream` became `removesTrueBinderUsedDownstreamWhenNothingNeedsIt`: with nothing to link to, the binder goes. That is the rule change itself. - `VCBinderSimplificationTest.skipsInapplicableTrueBinderAndSimplifiesLaterBinder` now makes `x` an Expected variable, so its binder is still the inapplicable one the test is about. The expected steps are unchanged. - `VCTestUtils.parseImplication` splits a binder at the first `.` after the `:`, so binder names can contain dots. No `// Expect:` fixture, `TestCounterexamples` or `TestErrorCategories` expectation changed. ## Not in this PR - Raw names in the Original step (above). - `random.nextInt(items.size() + extras.size())` fails on `main` with `Sort mismatch … supplied sort is …Basket`, a separate translation bug. The fixture uses two locals instead. - The client's hover (`getOriginalVariableName`) strips only `this#`, so it does not match fields, before or after this change. Stripping a leading `this.` there would be a small follow-up in vscode-liquidjava. Fixes #457 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 48ef72d commit 70edf72

22 files changed

Lines changed: 758 additions & 27 deletions
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package testSuite.classes.found_binders_error;
2+
3+
import liquidjava.specification.ExternalRefinementsFor;
4+
import liquidjava.specification.Ghost;
5+
import liquidjava.specification.Refinement;
6+
7+
@ExternalRefinementsFor("java.util.ArrayList")
8+
@Ghost("int size")
9+
public interface ArrayListRefinements<E> {
10+
11+
public void ArrayList();
12+
13+
@Refinement("_ == size(this) && _ >= 0")
14+
public int size();
15+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package testSuite.classes.found_binders_error;
2+
3+
import java.util.ArrayList;
4+
import java.util.Random;
5+
6+
import liquidjava.specification.Refinement;
7+
8+
// Found drops the true rows the error does not need and writes fields as in code (#457)
9+
public class Basket {
10+
static int served;
11+
12+
@Refinement("_ >= 0")
13+
int level;
14+
15+
private final ArrayList<String> items;
16+
private final Random random = new Random();
17+
18+
Basket(ArrayList<String> items) {
19+
this.items = items;
20+
}
21+
22+
// the issue's reproducer: the field row only says true
23+
String pick() {
24+
ArrayList<String> items = this.items;
25+
return items.get(random.nextInt(items.size())); // Expect: Refinement Error
26+
}
27+
28+
// a static field
29+
void serve() {
30+
@Refinement("_ > 0")
31+
int count = served + 1; // Expect: Refinement Error
32+
}
33+
34+
// writes to another object's field are checked as on main, and named after that object
35+
void setOther(Basket other) {
36+
other.level = -1; // Expect: Refinement Error
37+
}
38+
39+
void incrementOther(Basket other) {
40+
other.level++;
41+
}
42+
43+
void addToOther(Basket other) {
44+
other.level += 1;
45+
}
46+
47+
void decrementOther(Basket other) {
48+
other.level--; // Expect: Refinement Error
49+
}
50+
51+
void writeThroughAlias() {
52+
level = 7;
53+
Basket other = this;
54+
other.level = 3;
55+
@Refinement("_ == 7")
56+
int k = level; // Expect: Refinement Error
57+
}
58+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package testSuite.classes.found_binders_error;
2+
3+
import liquidjava.specification.ExternalRefinementsFor;
4+
import liquidjava.specification.Refinement;
5+
6+
@ExternalRefinementsFor("java.util.Random")
7+
public interface RandomRefinements {
8+
9+
public void Random();
10+
11+
public int nextInt(@Refinement("bound > 0") int bound);
12+
}

‎liquidjava-verifier/src/main/java/liquidjava/api/CommandLineLauncher.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import liquidjava.diagnostics.warnings.CustomWarning;
1010
import liquidjava.processor.RefinementProcessor;
1111
import liquidjava.processor.context.ContextHistory;
12+
import liquidjava.rj_language.ast.formatter.FieldDisplayNames;
1213
import liquidjava.specification.Refinement;
1314
import picocli.CommandLine;
1415
import spoon.Launcher;
@@ -57,6 +58,7 @@ public static void launch(String... paths) {
5758

5859
diagnostics.clear();
5960
contextHistory.clearHistory();
61+
FieldDisplayNames.clear();
6062
Launcher launcher = new Launcher();
6163
for (String path : paths) {
6264
if (!new File(path).exists()) {

‎liquidjava-verifier/src/main/java/liquidjava/processor/VCImplication.java‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import java.util.Objects;
44

55
import liquidjava.rj_language.Predicate;
6+
import liquidjava.rj_language.opt.NeededVariables;
67
import liquidjava.rj_language.opt.VCSimplification;
78
import liquidjava.rj_language.opt.VCSimplificationResult;
89
import liquidjava.utils.Utils;
@@ -79,6 +80,10 @@ public VCSimplificationResult simplify() {
7980
return VCSimplification.simplifyToFixedPoint(this);
8081
}
8182

83+
public VCSimplificationResult simplify(NeededVariables needed) {
84+
return VCSimplification.simplifyToFixedPoint(this, needed);
85+
}
86+
8287
public Predicate toPredicate() {
8388
return hasBinder() || hasNext() ? toConjunctions() : refinement;
8489
}

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import liquidjava.processor.state_machine.StateMachineBuilder;
2424
import liquidjava.processor.state_machine.StateSolver;
2525
import liquidjava.rj_language.Predicate;
26+
import liquidjava.rj_language.ast.formatter.FieldDisplayNames;
2627
import liquidjava.rj_language.parsing.RefinementsParser;
2728
import liquidjava.smt.SMTEvaluator;
2829
import liquidjava.smt.SMTResult;
@@ -382,6 +383,8 @@ public void checkVariableRefinements(Predicate refinementFound, String simpleNam
382383
Predicate cet = cEt.substituteVariable(Keys.WILDCARD, simpleName);
383384

384385
String newName = String.format(Formats.INSTANCE, simpleName, context.getCounter());
386+
Utils.untrackedWriteReceiver(usage)
387+
.ifPresent(receiver -> FieldDisplayNames.recordWriteReceiver(newName, receiver));
385388
Predicate correctNewRefinement = refinementFound.substituteVariable(Keys.WILDCARD, newName);
386389
correctNewRefinement = correctNewRefinement.substituteVariable(Keys.THIS, newName);
387390
cEt = cEt.substituteVariable(simpleName, newName);

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

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import liquidjava.rj_language.ast.Expression;
2121
import liquidjava.rj_language.ast.Ite;
2222
import liquidjava.rj_language.ast.Var;
23+
import liquidjava.rj_language.opt.NeededVariables;
2324
import liquidjava.smt.Counterexample;
2425
import liquidjava.smt.SMTEvaluator;
2526
import liquidjava.smt.SMTResult;
@@ -83,7 +84,8 @@ public void processSubtyping(Predicate expectedType, List<GhostState> list, CtEl
8384
DebugLog.smtResult(result);
8485
if (result.isError()) {
8586
throw new RefinementError(element.getPosition(), declarationPosition, expectedType,
86-
implBeforeChange.simplify(), map, result.getCounterexample(), customMessage);
87+
implBeforeChange.simplify(NeededVariables.forRefinementError(expectedType)), map,
88+
result.getCounterexample(), customMessage);
8789
}
8890
}
8991

@@ -442,8 +444,8 @@ protected void throwRefinementError(SourcePosition position, SourcePosition decl
442444
Predicate found, Counterexample counterexample, String customMessage) throws RefinementError {
443445
TranslationTable map = new TranslationTable();
444446
VCImplication premises = buildPremiseChain(map, expected, found);
445-
throw new RefinementError(position, declarationPosition, expected, premises.simplify(), map, counterexample,
446-
customMessage);
447+
throw new RefinementError(position, declarationPosition, expected,
448+
premises.simplify(NeededVariables.forRefinementError(expected)), map, counterexample, customMessage);
447449
}
448450

449451
/** What a state refinement error shows as found: what is known about the variables of both predicates */
@@ -456,8 +458,9 @@ protected void throwStateRefinementError(SourcePosition position, SourcePosition
456458
StateErrorContext context) throws StateRefinementError {
457459
TranslationTable map = new TranslationTable();
458460
VCImplication foundState = buildPremiseChain(map, expected, found);
459-
throw new StateRefinementError(position, declarationPosition, expected, foundState.simplify(), map,
460-
customMessage, hints, category, context);
461+
throw new StateRefinementError(position, declarationPosition, expected,
462+
foundState.simplify(NeededVariables.forStateError(expected)), map, customMessage, hints, category,
463+
context);
461464
}
462465

463466
protected void throwStateConflictError(SourcePosition position, Predicate expected) throws StateConflictError {

‎liquidjava-verifier/src/main/java/liquidjava/rj_language/ast/formatter/ExpressionNameResolver.java‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ public static ExpressionNameResolver forExpression(Expression expression) {
2222

2323
public String resolveVariable(String name) {
2424
String formatted = VariableFormatter.format(name);
25+
// a field is always written as in code, as its binder and the counterexample write it
26+
if (VariableFormatter.isField(name))
27+
return formatted;
2528
return isAmbiguous(name, variables, ExpressionNameResolver::getVariableSimpleName) ? formatted
2629
: Utils.getSimpleName(formatted);
2730
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package liquidjava.rj_language.ast.formatter;
2+
3+
import java.util.Map;
4+
import java.util.Set;
5+
import java.util.concurrent.ConcurrentHashMap;
6+
7+
/**
8+
* What a verification learns about field names that their internal form does not say, so that {@link VariableFormatter}
9+
* can write them as in code: which fields are static, and which field instances were created by a write through another
10+
* object. Filled during a verification and cleared when the next one starts
11+
*/
12+
public final class FieldDisplayNames {
13+
private static final Set<String> STATIC_FIELDS = ConcurrentHashMap.newKeySet();
14+
private static final Map<String, String> WRITE_RECEIVERS = new ConcurrentHashMap<>();
15+
16+
private FieldDisplayNames() {
17+
}
18+
19+
/**
20+
* Records that a field name ({@code this#<declaring type>.<field>}) belongs to a static field, written
21+
* {@code Class.field}
22+
*/
23+
public static void recordStaticField(String name) {
24+
STATIC_FIELDS.add(name);
25+
}
26+
27+
/**
28+
* Records that a field instance ({@code #this#<declaring type>.<field>_<n>}) was created by a write through
29+
* {@code receiver} ({@code receiver.field = v}), written {@code receiver.field}; an empty receiver writes the bare
30+
* field name. Only the display changes
31+
*/
32+
public static void recordWriteReceiver(String instanceName, String receiver) {
33+
WRITE_RECEIVERS.put(instanceName, receiver);
34+
}
35+
36+
/**
37+
* Forgets what the previous verification recorded
38+
*/
39+
public static void clear() {
40+
STATIC_FIELDS.clear();
41+
WRITE_RECEIVERS.clear();
42+
}
43+
44+
static boolean isStaticField(String name) {
45+
return STATIC_FIELDS.contains(name);
46+
}
47+
48+
static String writeReceiver(String instanceName) {
49+
return WRITE_RECEIVERS.get(instanceName);
50+
}
51+
}

‎liquidjava-verifier/src/main/java/liquidjava/rj_language/ast/formatter/VariableFormatter.java‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
*/
99
public final class VariableFormatter {
1010
private static final Pattern INSTACE_VAR_PATTERN = Pattern.compile("^#(.+)_([0-9]+)$");
11+
// this#<declaring type>.<field>
12+
private static final Pattern FIELD_PATTERN = Pattern.compile("^this#([\\w.$]+)\\.([\\w$]+)$");
1113
private static final char[] SUPERSCRIPT_CHARS = { '⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹' };
1214

1315
public static String format(String name) {
@@ -19,19 +21,54 @@ public static String format(String name) {
1921

2022
Matcher matcher = INSTACE_VAR_PATTERN.matcher(name);
2123
if (!matcher.matches())
22-
return name;
24+
return formatField(name);
2325

2426
String baseName = matcher.group(1);
2527
String counter = matcher.group(2);
28+
String receiver = FieldDisplayNames.writeReceiver(name);
29+
if (receiver != null && isField(baseName))
30+
return (receiver.isEmpty() ? "" : receiver + ".") + fieldOf(baseName) + toSuperscript(counter);
2631
String prefix = isSpecialIdentifier(baseName) ? "#" : "";
27-
return prefix + baseName + toSuperscript(counter);
32+
return prefix + formatField(baseName) + toSuperscript(counter);
2833
}
2934

3035
public static String withoutInstance(String name) {
3136
Matcher matcher = INSTACE_VAR_PATTERN.matcher(name);
3237
return matcher.matches() ? matcher.group(1) : name;
3338
}
3439

40+
/**
41+
* Whether a name is that of a field, {@code this#<declaring type>.<field>}, possibly with an instance counter
42+
*/
43+
public static boolean isField(String name) {
44+
return FIELD_PATTERN.matcher(withoutInstance(name)).matches();
45+
}
46+
47+
/**
48+
* Writes a field name as it is written in code: {@code this.field} for an instance field and {@code Class.field}
49+
* for a static one, leaving any other name unchanged; the internal name keeps the declaring type to tell fields of
50+
* different classes apart
51+
*/
52+
private static String formatField(String name) {
53+
Matcher matcher = FIELD_PATTERN.matcher(name);
54+
if (!matcher.matches())
55+
return name;
56+
57+
if (FieldDisplayNames.isStaticField(name))
58+
return simpleTypeName(matcher.group(1)) + "." + matcher.group(2);
59+
return "this." + matcher.group(2);
60+
}
61+
62+
private static String fieldOf(String name) {
63+
Matcher matcher = FIELD_PATTERN.matcher(name);
64+
return matcher.matches() ? matcher.group(2) : name;
65+
}
66+
67+
private static String simpleTypeName(String qualifiedName) {
68+
int start = Math.max(qualifiedName.lastIndexOf('.'), qualifiedName.lastIndexOf('$'));
69+
return qualifiedName.substring(start + 1);
70+
}
71+
3572
private static String toSuperscript(String number) {
3673
StringBuilder sb = new StringBuilder(number.length());
3774
for (char c : number.toCharArray()) {

0 commit comments

Comments
 (0)