Skip to content

Choose numeric conversions by sort, not by target type - #92

Merged
HowardvanRooijen merged 1 commit into
feature/anonymous-environmentsfrom
feature/numeric-conversions
Oct 28, 2026
Merged

HowardvanRooijen merged 1 commit into
feature/anonymous-environmentsfrom
feature/numeric-conversions

Conversation

@HowardvanRooijen

@HowardvanRooijen HowardvanRooijen commented Sep 1, 2026 •

Copy link
Copy Markdown
Member

Fixes #76.

The defect

A double symbol could not be compared against a float variable:

float f = 1.5f;
using var context = new Z3Context();
context.NewTheorem<Symbols<double, int>>().Where(t => t.X1 == f).Solve();
// System.InvalidCastException: Unable to cast object of type 'Microsoft.Z3.RatNum'
//                              to type 'Microsoft.Z3.IntExpr'

C# widens the float to double, so the tree carries a Convert(Single -> Double) node, and the
visitor chose the conversion from the node's target type alone: every conversion to double was
MkInt2Real, on the assumption that the operand must have been an integer. Here it was a real.

It is wider than the issue says. Measured before the change, sixteen shapes:

Constraint Before
double symbol == float variable - the issue InvalidCastException
double symbol == (double) of a float or decimal variable InvalidCastException
double symbol == float symbol InvalidCastException
double symbol == float symbol * 2 InvalidCastException
long symbol == int symbol NotImplementedException - no arm for long at all
decimal symbol == int symbol NotImplementedException - no arm for decimal
float symbol == int symbol NotImplementedException - no arm for float
float symbol == (float) of a double variable NotImplementedException
double symbol == int, long or short variable, or int symbol worked - the one widening the arm was written for
double symbol == float literal worked - folded to a double constant before the visitor sees it, which is why the issue needed a variable

The bold rows are two symbols of the library's own supported types that could not appear in the
same constraint. Nothing about Symbols<double, float> or Symbols<long, int> suggests its
members cannot be compared.

The change

A numeric conversion means one of three things in Z3, and which one depends on the sorts, not
the CLR types: nothing at all when both types map to the same sort, integer-to-real, or
real-to-integer. The visitor now asks for the target type's sort from the same mapping the
symbols are declared with - TryGetSymbolSort, which #64 made the single source for that
question and which becomes internal here - and decides from that and the operand's sort:

if (inner.Sort.Equals(targetSort))              return inner;
if (inner.IsInt  && targetSort is RealSort)     return context.MkInt2Real((IntExpr)inner);
if (inner.IsReal && targetSort is IntSort)      return context.MkReal2Int((RealExpr)inner);

That replaces the switch on the target type, including the when inner.IsInt arm #63 added for
short and enums - which was this rule for one row. The mutation matrix shows the #63 coverage
carrying over: dropping the same-sort branch fails every short and enum test #63 wrote.

A conversion to a type the mapping has no row for still falls through to the existing catch-all,
with its message unchanged.

One behaviour changed on purpose beyond the issue. The char arm passed an integer operand
through and threw for a real one; a real operand converted to char now goes through
MkReal2Int, as it does for int. No test exercised the char arm in either direction; it is
kept as an integer-sort target so the integer case is unchanged.

Measured after the change

All sixteen shapes round-trip: the issue's repro gives 1.5, double == float symbol gives
1.5 on both sides, double == float * 2 gives 3, long == int symbol gives 5,
decimal == int symbol gives 7, float == int symbol gives 3, and every shape that worked
before still gives the same value.

Tests

230 → 239. A new NumericConversionTests.cs for the shapes above, since they are a subject of
their own rather than a marshalling detail, and one pin repointed.

Test What it covers
Solve_DoubleSymbolComparedToAFloatVariable_RoundTripsTheValue the issue's repro
Solve_DoubleSymbolComparedToAFloatSymbol_RelatesTheTwo / ..InArithmeticWithAFloatSymbol.. two symbols of different real types, directly and under a multiplication
Solve_DoubleSymbolComparedToAnIntSymbol_RelatesTheTwo the widening the old arm handled - so the fix cannot be a regression in disguise
Solve_DecimalSymbolComparedToAnIntSymbol_RelatesTheTwo / ..Float.. the two real targets that had no arm
Solve_LongSymbolComparedToAnIntSymbol_RelatesTheTwo the integer target that had no arm - the former "unsupported cast" pin, now positive
Solve_DoubleSymbolComparedToAWidenedDecimalVariable.. / Solve_FloatSymbolComparedToANarrowedDoubleVariable.. explicit casts between real types, widening and narrowing, both no-ops in Z3
Solve_CastToAnUnmappedType_ThrowsNotImplementedException (in UnsupportedExpressionTests) the catch-all, repointed from (long) - which now works - to (byte), which the mapping has no row for

The real-to-integer direction already has its test from #63,
Solve_DoubleSymbolCastToInt_ConvertsRatherThanPassingThrough, which stays where it is.

Mutation results

Mutation Failures Which
Drop the same-sort no-op branch 20 the six new no-op cases, every short and enum test from #63, the short collection tests from #64, and the anonymous every-scalar test from #75
Drop the integer-to-real branch 3 double, decimal and float symbols against an int symbol - and nothing else in the suite, which is why the regression guard is there
Drop the real-to-integer branch 1 the #63 cast test alone

The first row is the useful one: four earlier fixes in this stack all ran through the arm this
change replaces, and all of them still fail when it is wrong.

Verification

  • dotnet build solutions/Z3.Linq.slnx -c Release - clean, TreatWarningsAsErrors on
  • 239/239 locally
  • ./build.ps1 -Configuration Release - 46 tasks, 0 errors, 0 warnings
  • Coverage 88.1% -> 88.5% line (689 of 778), 76.5% -> 77.2% branch (451 of 584)

Release note

Releases remain on hold under #60 until Microsoft.Z3 5.x reaches nuget.org, so this reaches main
but not consumers. Nothing about the hold changes.

A double symbol could not be compared against a float variable. C#
widens the float, and the visitor read the Convert node's target type as
telling it what the operand was: every conversion to double was
integer-to-real, so a real operand was cast to IntExpr and failed. The
same assumption meant two symbols of different real types could not be
related at all, and long, float and decimal had no arm whatever - a long
symbol could not be compared to an int one.

A numeric conversion is one of three things in Z3, decided by the sorts:
nothing when both types map to the same sort, integer-to-real, or
real-to-integer. The visitor now asks TryGetSymbolSort - the one mapping
the symbols are declared with, internal from here - for the target sort
and decides from that and the operand. The arm #63 added for short and
enums was this rule for one row and is subsumed; its tests still fail
when the rule is wrong.

The pin that recorded (long)t.X1 as unsupported is repointed at (byte),
which the mapping genuinely has no row for, so the catch-all stays
covered.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown

Test Results

  1 files  ±0    1 suites  ±0   5s ⏱️ ±0s
228 tests +9  228 ✅ +9  0 💤 ±0  0 ❌ ±0 
239 runs  +9  239 ✅ +9  0 💤 ±0  0 ❌ ±0 

Results for commit 1a7f5ec. ± Comparison against base commit c8c015d.

@HowardvanRooijen
HowardvanRooijen marked this pull request as ready for review October 27, 2026 07:53
Copilot AI balanced review requested due to automatic review settings October 27, 2026 07:53

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

User-defined conversion operators can be silently ignored, allowing returned solutions to violate the original constraints.

1 open issue
What changed in this PR

This PR addresses #76 by choosing numeric conversions from Z3 sorts rather than CLR target types, enabling mixed-type constraints within the library’s existing numeric model.

Changes:

  • Reuses the shared symbol-sort mapping to select no-op, integer-to-real, or real-to-integer conversions.
  • Adds nine regression tests for mixed numeric comparisons and explicit casts.
  • Changes the unsupported-cast test from long to unmapped byte.
File Description
solutions/​Z3.Linq/​Theorem.cs Exposes and documents the shared sort mapping for conversion handling.
solutions/​Z3.Linq/​ExpressionVisitor.cs Replaces target-type conversion dispatch with sort-based handling.
solutions/​Z3.Linq.Tests/​UnsupportedExpressionTests.cs Preserves catch-all coverage using a cast to byte.
solutions/​Z3.Linq.Tests/​NumericConversionTests.cs Adds coverage for mixed numeric types and explicit conversions.

Review effort: Balanced

? context.IntSort
: Theorem.TryGetSymbolSort(context, Type.GetTypeCode(expression.Type));

if (targetSort is not null)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. A conversion with a Method was translated from the sorts alone. Fixed in 38ef8f2 (#116). A conversion that calls an operator method is now refused with a NotSupportedException naming the operator, unless the method is declared on decimal, because decimal's built-in conversions are operator methods too. The check applies only where the conversion would otherwise have been translated, so a cast to a type with no sort (such as IntPtr) still throws NotImplementedException as before. The regression test is your example: a type mapped to float whose explicit operator doubles its value.

@HowardvanRooijen HowardvanRooijen added no_release Suppresses auto_release functionality and removed pending_release labels Oct 27, 2026
@HowardvanRooijen
HowardvanRooijen merged commit a328370 into main Oct 28, 2026
12 checks passed
@HowardvanRooijen
HowardvanRooijen deleted the feature/numeric-conversions branch October 28, 2026 07:38
HowardvanRooijen added a commit that referenced this pull request Oct 28, 2026
* Pin the true arm in the false-branch ternary test

The test pinned X1 to -1 and asserted `(X1 > 0 ? X2 : 9) == 9`, leaving
X2 free. A translation that always took the true arm would still find a
model - X2 = 9 - so the test could not tell the two arms apart, and it
was the only ternary test exercising the false arm. X2 is now pinned to
0, which makes the true arm unsatisfiable.

Checked by mutation: with the ternary translated as its true arm alone,
this test now fails and the other three ternary tests still pass.

Found by Copilot review on #99.

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

* Build the Optimize benchmark's objective once

Optimize takes an expression tree, so the inline `t => t.X1` built a new
tree on every measured invocation and charged its construction and
allocation to the solve. Every other benchmark builds its expressions in
Setup; the objective is now a field built once, so the Optimize figures
measure the same thing as the rest.

Found by Copilot review on #104.

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

* Say what the template's collections are for

"whose collections give the solution's their length" lost its noun. The
template's collections set the lengths of the solution's collections;
both GetSolution overloads now say so.

Found by Copilot review on #94.

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

* Tell the demos README to populate the Z3 feed first

The Microsoft.Z3 version the library needs is not on nuget.org, so
restore finds it only in the local _z3-feed folder, which the build
script fills. `dotnet run demos/<file>.cs` does not run the build
script, so on a clean clone the first demo run fails with NU1102. The
README now says to run scripts/Install-Z3Package.ps1 first.

Reproduced with an empty _z3-feed and an empty NUGET_PACKAGES folder:
restoring demos/sudoku.cs fails with "NU1102: Unable to find package
Microsoft.Z3 with version (>= 5.3.2)".

Found by Copilot review on #110.

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

* Read a template member only where its value is used

The marshaller read every member of the template passed to NewTheorem,
scalars included, and handed the value down - but only a collection
(for its length) and a nested environment (for its own collections)
use it. A scalar getter that threw failed a solve that only needed the
setter, and a getter with side effects ran for nothing.

ConvertZ3Expression now takes the template instance and reads the
member from it in the collection and nested-object branches only. The
type is normalised through its TheoremVariableTypeMapping before the
branch is chosen, so a mapped scalar is skipped too.

The new test counts reads of a scalar getter on the template: one before
the change, none after.

Found by Copilot review on #93.

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

* Fix three bit-vector translations that disagreed with C#

All three were introduced with the uint/ulong bit-vector symbols.

Shift counts were not masked. C# uses only the low five bits of the
count for a uint and the low six for a ulong, so `1u << 32` is 1; Z3
shifts by the whole count and gives 0. The count is now ANDed with the
width minus one before the shift. A negative count reaches the mask in
two's complement, since the int-to-bit-vector conversion is modulo
2^width, so it matches C# too.

A uint beside a ulong threw NotImplementedException. C# widens the uint
implicitly, so `t.X1 == t.X2` over Symbols<uint, ulong> was unusable.
VisitConvert now zero-extends from 32 to 64 bits, and an explicit
`(uint)` cast on a ulong keeps the low 32 bits, as an unchecked cast
does.

Checked arithmetic wrapped. AddChecked, SubtractChecked and
MultiplyChecked shared the wrapping bit-vector form, so
`checked(t.X1 + 1u) == 0u` returned uint.MaxValue, a value for which the
C# predicate throws OverflowException. These are now refused with a
NotSupportedException that says so; overflow checking is not translated.
Checked arithmetic on int and real symbols is unchanged.

The shift tests take the count as a symbol, so the solver cannot fold
it, and compute the expected value with C# from the returned symbols.

Found by Copilot review on #101.

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

* Wrap narrowing integer casts, and refuse conversion operators

Two ways VisitConvert returned a model the C# predicate rejects, both
because it chose the translation from the sorts alone.

A narrowing cast between integer types was a no-op. Every integer type
but uint and ulong is an unbounded integer in Z3, so `(int)t.X1` on a
long symbol kept the long value: `(int)4294967295L` came out as
4294967295 where C# gives -1, and against a bounded int symbol the
theorem was reported unsatisfiable. The cast now wraps into the target
range, ((x - low) mod n) + low, which is the unchecked C# result for
signed and unsigned targets and negative operands alike. A widening
cast, and any cast to long, is still a no-op. A checked cast is a
ConvertChecked node, which is not translated.

A user-defined conversion operator was dropped. For a type mapped to
float whose explicit operator to float doubles its value,
`(float)t.X1 == 6f` returned a symbol holding 6, which the operator
turns into 12. A conversion that calls an operator method is now
refused with a NotSupportedException naming the operator, except
decimal's built-in conversions, which are operator methods on decimal.
A cast to a type with no sort still throws NotImplementedException, as
before.

The wrap reuses Theorem.GetBounds, which becomes internal, so a
conversion and a symbol agree about a type's range.

Found by Copilot review on #88 (narrowing) and #92 (operators).

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

* Let a collectible environment type unload

The per-type reflection caches - type mappings, public properties and
public fields - were static ConcurrentDictionary instances keyed on
Type, so they held every environment type they had seen for the life
of the library. A host loading environments from a collectible assembly
(a plugin it reloads, a script it compiles) could never unload one.

They are now ConditionalWeakTable instances, which drop an entry when
nothing else holds the type. A cached PropertyInfo or FieldInfo refers
back to its declaring type, which a weak table tolerates without
keeping the key alive. A weak table's value cannot be null, so an
absent mapping is cached as an entry holding null.

The new test emits an environment type into a RunAndCollect assembly,
solves with it, drops its references and checks that the type is
collected. It fails with the dictionaries and passes with the weak
tables, so nothing else in the solve path keeps the type alive.

Measured with the benchmark suite (--job short), before and after:
allocations are identical in every shape (3.3 KB to 6.2 KB per solve),
and the differences in mean time are inside the run-to-run noise of a
roughly 15 ms solve that Z3 dominates.

Found by Copilot review on #105.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

no_release Suppresses auto_release functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

float variables cannot be compared against real symbols: the widening Convert is read as int-to-real

3 participants