Skip to content

Give a conditional expression the value of its condition, not its refinement - #561

Open
CatarinaGamboa wants to merge 3 commits into
mainfrom
fix/558-array-ternary
Open

CatarinaGamboa wants to merge 3 commits into
mainfrom
fix/558-array-ternary

Conversation

@CatarinaGamboa

@CatarinaGamboa CatarinaGamboa commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #558

Root causes

Crash (Sorts (Array Int Int) and Bool are incompatible). visitCtConditional built the refinement of c ? x : y as ite(refinement(c), refinement(x), refinement(y)). The refinement of c constrains the condition through the wildcard (_ == b for a read of b), but in the conditional's refinement the wildcard is the result. So int[] a = b ? new int[1] : new int[1] gave a == b ? ... : ..., comparing an array with a boolean. This is not specific to arrays: on main every ternary whose condition is a variable, a literal, a call or another ternary crashes (Sorts Int and Bool, Sorts Box and Bool, ...). Only comparison conditions like (a == 2) worked, because their refinement has no wildcard.

Variable 'args' could not be found. This is a separate cause, and the ternary is not needed to trigger it. main(String[]) was skipped both when its contract was collected and when its body was entered, so args was never in the context. Any verification condition that reached args failed, for example boolean b = args.length > 0; if (b) { @Refinement("_ > 0") int n = args.length; }. The array ternary only exposed it because its condition pulled b, and so args, into the VC.

Fix

  • The condition's value is kept in a fresh boolean ##ternary_condition_N. A refinement with the wildcard (or of a call) constrains it, and a refinement without one is its value. Like the switch selector, it names the instances the condition read, so later writes do not change which branch was taken. Conditions with side effects or no information leave it unconstrained, as assumeCondition does. The result then gets x's facts when the condition holds and y's when it does not.
  • x += c ? 1 : 2 goes through OperationsChecker, which had the same problem when c's refinement was not _ == e (e.g. a nested ternary). It now uses a fresh value there too.
  • main is loaded like any other method.
  • The condition's value is taken before the branches are checked. The guard snapshot (snapshotMutableParameters → snapshotMutableVariables) now also covers fields the method writes, so f ? (f = false) : true does not read the written f. This helper also guards if and switch, so if (f > 0) { f = 0; x = -1; } else { x = 1; } pos(x); (accepted on main) is now rejected.

Tests

CorrectTernaryExpression gets an array ternary under its condition (args-based), and a compound assignment with a nested-ternary condition. ErrorTernaryExpression gets b ? new int[1] : new int[2] against length(_) == 1, and a field condition written in a branch. Each added line fails on main.

Cases tried (one class each; all now pass or are rejected as expected):

  • arrays: equal and different lengths; under if (b) / if (!b); as an argument, a return value and an assignment (a = b ? new int[2] : a); nested ternaries in a branch and in the condition; literal and call conditions (with and without a return refinement); condition variable or parameter written after the ternary; variable lengths; an array parameter as a branch.
  • ints and booleans: returned, passed, assigned, nested; boolean branches (b ? y > 0 : true must not assume y > 0); compound assignments.
  • non-array references (same cause): typestate objects (Box z = b ? x : y; z.peek()) and ghost refinements on parameters.

Test suite: 364 tests, 0 failures. Study task check: 55/55 variants with identical verdicts and messages.

Known pre-existing issues, not fixed here (see the review comments): calls on a ternary receiver ((b ? x : y).m()) are never state-checked; an int field read in an operand and written later (int y = f; f = 5;) changes what y means; a conditional used as an if condition carries no information; and an assignment used as a value has no refinement.

🤖 Generated with Claude Code

…inement

The refinement of `c ? x : y` used the refinement of `c` as the condition
of its if-then-else. That refinement constrains the condition through the
wildcard, which in the conditional's refinement is the result, so a
condition like `b` became `result == b` and Z3 rejected the sorts
(Int, Bool, arrays or objects). The condition is now kept in a fresh
boolean, on the values it was evaluated on, as the switch selector is.
Compound assignments with a conditional get their condition's value the
same way.

The `args` of `main` were never added to the context, so any verification
condition that reached them failed with a Not Found error. `main` is now
loaded as any other method.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 1

Codex ran about 40 small programs against this branch and a build of origin/main. Its final summary was cut off by a content filter, so the results below are from its run log. I re-ran each one myself.

Should be rejected, and are rejected: ternaries between arrays, ints and booleans; nested ternaries in a branch and in the condition; ternaries returned, passed as arguments, assigned and compound-assigned (x = 1 + (b ? 1 : -2)); call conditions (flip() ? ...); the condition written after the ternary; if (b ? true : false) guards; typestate objects assigned from a ternary (Box x = b ? a : c; x.send(), on main a Sorts ... and Bool crash).

Findings

  1. False accept, pre-existing (also on main): a call whose receiver is a ternary is never checked: (b ? open : closed).send(), nested ones too, and if (!b) (b ? a : c).send(). AuxStateHandler.prepareInvocationTarget has no case for a conditional target, so the call gets no target and no state check. This has a different cause from A ternary between arrays crashes: Sorts (Array Int Int) and Bool are incompatible #558. A sound fix also has to update the state of both branches after a state-changing call, so it is left for a follow-up issue.
  2. More rejections, by design: one((b = true) ? new int[1] : new int[2]) is now rejected. Conditions with side effects are not encoded, as in assumeCondition. On main the same shape with b = false is accepted, which is unsound, so this trades a false accept for a false reject.
  3. Imprecision, pre-existing: if (b ? false : true) one(b ? new int[2] : new int[1]) is rejected. getExpressionRefinements never visits a conditional used as an if condition, so the guard carries no information. This is sound (main crashes on it), so it goes to a follow-up.
  4. main(@Refinement("length(args) == 1") String[] args) now has its parameter refinement honoured. On main this was a Not Found error.
  5. choose(b).send(), where choose returns a ternary and has no return state, is accepted on main and on this branch. This is the existing treatment of calls on results with no state, not a ternary issue.

Nothing in this round needs a change in this PR.

…ten fields

A branch that writes a field the condition reads (f ? (f = false) : true)
made the condition name the written value. The condition's value is now
taken before the branches are checked, and a guard snapshots the fields
the method writes, as it already did for parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 2

This round covered what round 1 did not: fields, loops and loop conditions, switch, lambdas, long/double/char, null branches, boxed Integer, call branches with return refinements, and branches that write the condition's variable. Codex found no false accepts outside the field cases below.

Findings

  1. Regression, fixed in 4b2de48: boolean x = f ? (f = false) : true against _ == true, with an instance field or a static field f, was accepted. Main rejected it (through its broken encoding). Two problems combined. The condition's value was taken after the branches were scanned. Also, an unwritten field is read by its name (this#F.f) rather than an instance, so the write in the branch changed what the condition meant. Fix: the value is now taken right after the condition is scanned, and the guard snapshot (snapshotMutableParameters → snapshotMutableVariables) also covers fields the method writes, not only parameters. Test: ErrorTernaryExpression#clear. The same helper guards if and switch, so these also stop being accepted (they are accepted on main): if (f > 0) { f = 0; x = -1; } else { x = 1; } pos(x); and the equivalent switch (h). The study check is unchanged (55/55 variants identical).
  2. False accept, pre-existing (main too), not fixed here: int x = f > 0 ? (f = -1) : 1 against _ > 0 (int field). The comparison's operand gets a snapshot #f_N == this#F.f that still names the field, so the later write changes it. The same happens without a ternary: int y = f; f = 5; @Refinement("_ == 5") int z = y; is accepted on main. The proper fix is to give written fields an instance on method entry, as snapshotWrittenParameters does for parameters. That is a separate issue.
  3. Imprecision: f ? (f = true) : true against _ == true is now rejected. An assignment used as a value ((f = true)) has no refinement, so that branch says nothing. This is pre-existing and sound.

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 3

This round targeted 4b2de48, which snapshots written fields in if, switch and ternary conditions. Codex tried instance and static fields, fields of other objects, same-named fields in different classes, and writes in loops, constructors, lambdas and through method calls. It found no new false accepts, false rejects or crashes. Every finding below behaves the same on origin/main:

  • False accept: a field changed by a call inside the guarded code is not seen. In if (f) { clear(); @Refinement("_ == true") boolean x = f; } (and the switch equivalent), clear() sets f = false, yet the program is accepted. Calls do not invalidate the facts known about fields.
  • False reject: other.f = false on a distinct object makes this.f unknown. Fields are tracked per class, not per object.
  • Crash: for (int i = 0; i < 2; i++) f = !f; with a boolean field throws a NullPointerException.

None of these involve conditional expressions, so they are left for separate issues. Nothing relevant remains for this PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Clean-code review

clean-code-principles audit of git diff origin/main...HEAD:

  • RefinementTypeChecker.java (assumeCondition, conditionValue) - [core-dry] The side-effect test !condition.getElements(new TypeFilter<>(CtVariableWrite.class)).isEmpty() was written twice. Applied: it is now hasSideEffects(expression).
  • RefinementTypeChecker.java (conditionValue) vs OperationsChecker.getConditionRefinement - [core-dry] A condition's value is computed in two places: in a fresh ##ternary_condition boolean for the conditional's refinement, and in valueFromRefinement for compound assignments. Not applied: merging them would make OperationsChecker depend on the shape of the conditional's metadata. Each path is short, and both follow the same rule: a refinement with the wildcard constrains the value and is not the value.
  • RefinementTypeChecker.java (visitCtMethod) and MethodsFunctionsChecker.java - [name-searchable] The two "main(java.lang.String[])" magic strings are gone, since main is no longer special-cased.
  • snapshotMutableParameters → snapshotMutableVariables - [name-meaningful] The rename matches what the helper now covers (parameters and fields).
  • [solid-srp], [core-kiss] conditionValue does one thing (encode the condition once) and stays as small as assumeCondition next to it. Nothing to change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A ternary between arrays crashes: Sorts (Array Int Int) and Bool are incompatible

1 participant