Skip to content

Give integer / and % Java's semantics for negative operands - #566

Open
CatarinaGamboa wants to merge 3 commits into
mainfrom
fix/564-java-division
Open

CatarinaGamboa wants to merge 3 commits into
mainfrom
fix/564-java-division

Conversation

@CatarinaGamboa

@CatarinaGamboa CatarinaGamboa commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #564

Z3's integer div and mod are Euclidean: the remainder is never negative. Java's / rounds toward zero and % has the sign of the dividend, so the solver thought -7 / 2 == -4 and -7 % 2 == 1, and wrong programs passed, e.g. a parity check x % 2 refined as _ == 0 || _ == 1.

Change

TranslatorToZ3.makeDiv/makeMod (used both for refinements and for code) now build Java's result from Z3's. The two only differ when the dividend is negative and the division is not exact:

q = ite(a >= 0 || a mod b == 0, a div b, a div b + (b > 0 ? 1 : -1))
r = ite(a >= 0 || a mod b == 0, a mod b, b > 0 ? a mod b - b : a mod b + b)

Division by zero is unchanged: a div 0 stays unconstrained, so a / 0 and a % 0 are still any value.

long values are reals in the solver, and / on them was real division (7L / 2L == 3.5, so @Refinement("_ * 2 == 7") long q = 7L / 2L; passed). Long / is now the real quotient rounded toward zero, and a % b is a - b * (a / b). This is Java's result for the integral values longs take, and keeps the quotient's sign when the solver picks non-integral values for longs (converting the operands to integers first turned a divisor of 1/2 into 0).

Constant folding (VCFolding, StaticConstants.foldIntegral) already used Java's operators, so messages showed Java's value even when the solver disagreed (on main, @Refinement("_ == -3") int n = -7 / 2; reported "found n == -3 but expected n == -3").

How it was checked

  • Z3 proves, for all integers a and b != 0, that the encoded q, r satisfy a == b*q + r, |r| < |b|, r is 0 or has the sign of a, and |b*q| <= |a|, which define Java's results. The same property is satisfiable (fails) for Z3's plain div/mod, so the check is not vacuous.
  • makeDiv/makeMod on literals match Java's / and % for all |a|, |b| <= 20, b != 0, for int and long (6560 checks).
  • For long, Z3 proves the same definition for every divisor in -20..20 and every integral dividend (a symbolic divisor makes the query nonlinear).
  • Programs with negative dividends, divisors and both; /= and %=; _ == a / b and _ == a % b contracts called with negative arguments; x % 2 == 1 parity on negative x; x % y >= 0 with y > 0; longs. Wrong ones are now rejected with counterexamples such as x == -1 && #ret == -1; right ones (like _ % 2 == 1 implies _ > 0, or x > -2 implies x / 2 >= 0) now pass.

Limitation: long is still a real

The solver can still pick non-integral values for long variables, so a few valid long programs are rejected, e.g. x / 1L == x, x % 1L == 0 and x * 2 / 2 == x (main accepted these, but it rejected others, such as x > -2 implies x / 2 >= 0, and accepted wrong ones). See the comparison in the Codex round 2 comment. Modelling long as an Int is the full fix and is left for a separate issue.

Tests

Extended CorrectArithmeticBinaryOperations (negative /, % and long /) and ErrorSpecificArithmetic (parity). Both fail on main.

🤖 Generated with Claude Code

CatarinaGamboa and others added 2 commits November 30, 2026 20:23
Z3's integer div and mod are Euclidean: the remainder is never negative.
Java rounds the quotient toward zero and gives the remainder the sign of
the dividend, so -7 / 2 was -4 and -7 % 2 was 1 in the solver. Build
Java's result from Z3's, which only differs when the dividend is negative
and the division is not exact. Longs, which are reals in the solver, now
use the same integer division instead of real division.

Fixes #564

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Longs are reals in the solver, which may pick non-integral values for
them. Converting the operands to integers first could turn a positive
divisor into zero and lose the quotient's sign, so x / y with x < 0 and
y > 0 was no longer known to be at most zero. Move the parity check to a
fixture no other test counts errors in.

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

CatarinaGamboa commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator Author

Codex review, round 1

PR regression — valid long division contract is rejected.

@Refinement("_ <= 0")
static long divide(@Refinement("_ < 0") long x,
                   @Refinement("_ > 0") long y) {
    return x / y;
}

Java always returns a nonpositive value here. The PR reports a refinement error with x == -1, y == 1/2, and return value 1; origin/main accepts the same program. In TranslatorToZ3.java, the new long division path converts solver Reals to integers. A fractional value admitted for y becomes zero, making the result unconstrained. This is a PR-caused false rejection, not an accepted incorrect program.

Pre-existing soundness bug — overflow is accepted as positive.

@Refinement("_ > 0")
static int badInt() { return Integer.MIN_VALUE / -1; }

@Refinement("_ > 0")
static long badLong() { return Long.MIN_VALUE / -1L; }

Java returns the negative minimum value in both cases, so both contracts should be rejected. Both the PR and origin/main accept them.

I also exercised negative operands, symbolic int and long parameters, mixed int/long operations, /= and %=, return and parameter refinements, method calls, aliases, ghost state, char, and short. Those cases matched expectations apart from the long division regression above. The working tree is clean.

Response

  • Long division regression: fixed in the next commit. Long / is now the real quotient rounded toward zero (a % b is a - b * (a / b)), so a non-integral divisor the solver picks no longer becomes 0. The reported program passes again. Z3 proves that, for every divisor in -20..20 and every integral dividend, the quotient and remainder meet Java's definition.
  • Overflow (Integer.MIN_VALUE / -1): pre-existing, the solver uses unbounded integers for every operator; out of scope here.
  • Also moved the new parity case from ErrorIntegerDivision to ErrorSpecificArithmetic, since two tests expect exactly one error from ErrorIntegerDivision.
@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 2

PR-caused regression: valid long contracts are rejected. Two minimal examples are:

@Refinement("_ == x")
static long divide(long x) { return x / 1L; }

@Refinement("_ == 0")
static long remainder(long x) { return x % 1L; }

Both must pass for every Java long. The current PR rejects divide with x = 1/2, result = 0 and remainder with x = -1/2, result = -1/2. Those counterexamples are impossible Java values. origin/main accepts both. The new rounding in TranslatorToZ3.java exposes the existing Real model’s lack of an integer constraint for long.

I found no false acceptance in the other tested cases, covering negative operands, int/long mixes, refined parameters, contracts, /=, %=, chained and nested expressions, calls, and a loop. The working tree is clean.

Response

Not changed in this PR; the cause is that longs are unconstrained reals, which no rounding encoding can fully hide. I compared the options on 9 valid and 7 invalid long programs (each method verified on its own):

Long encoding Valid ones accepted Invalid ones rejected
main (real /, to_int then Euclidean mod) 6/9 3/7 (accepts x % 2 in {0, 1}, 7L / 2L * 2 == 7, x / 2 * 2 == x, -7L % 2 == 1)
to_int the operands, then the int encoding (round 1) 4/9 7/7
real quotient rounded toward zero (this PR) 6/9 (rejects x / 1 == x, x % 1 == 0, x * 2 / 2 == x) 7/7
same, guarded by is_int on the operands 4/9, two of them time out 7/7
an is_int axiom for every long variable times out on x * 2 / 2 == x -
long as Int sort 9/9 7/7

The PR keeps the rounded real quotient: sound, and as complete as main on these programs. Modelling long as Int is the real fix, but it is a wider change: toFP reads integer numerals with getInt() and fails on long literals outside the int range ("Numeral is not an int"), TestQueryCache.typeOfAVariable relies on longs being reals, and the sort lines sit next to the ones PR #539 changes. I suggest a separate issue for it.

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

Copy link
Copy Markdown
Collaborator Author

Clean-code review

Audit of the diff (clean-code-principles):

  • TranslatorToZ3.java toInt - [core-yagni] no caller left once long / and % stopped converting their operands to integers. Removed.
  • TranslatorToZ3.java makeLongDiv - [name-meaningful] down / up did not say what they were (up was the magnitude of a negative quotient's rounding). Renamed to floor and ceiling, with the negation moved into ceiling.
  • TranslatorToZ3.java makeMod, long branch - [doc-why-not-what] a - b * (a / b) is Java's own definition of the remainder; added a one-line comment saying so.
  • makeJavaDiv / makeJavaMod - [core-dry] they share the condition under which Z3's result already is Java's; it is one helper (euclideanIsJava), as is isPositive. No change.
  • [solid-srp] The encodings stay private helpers of TranslatorToZ3, next to the other operator translations; a separate class would only move four small methods. No change.
  • Tests - lean: one Correct and one Error fixture extended, each failing on main. No change.

Re-checked after the changes: test suite green, the Z3 checks of the encoding still pass, and the error-message study tasks give identical verdicts and messages.

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

Labels

None yet

1 participant