Repository navigation
Choose numeric conversions by sort, not by target type - #92
Conversation
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>
There was a problem hiding this comment.
🟡 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
longto unmappedbyte.
| 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) |
There was a problem hiding this comment.
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.
* 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>

Fixes #76.
The defect
A
doublesymbol could not be compared against afloatvariable:C# widens the
floattodouble, so the tree carries aConvert(Single -> Double)node, and thevisitor chose the conversion from the node's target type alone: every conversion to
doublewasMkInt2Real, 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:
doublesymbol==floatvariable - the issueInvalidCastExceptiondoublesymbol==(double)of afloatordecimalvariableInvalidCastExceptiondoublesymbol==floatsymbolInvalidCastExceptiondoublesymbol==floatsymbol* 2InvalidCastExceptionlongsymbol==intsymbolNotImplementedException- no arm forlongat alldecimalsymbol==intsymbolNotImplementedException- no arm fordecimalfloatsymbol==intsymbolNotImplementedException- no arm forfloatfloatsymbol==(float)of adoublevariableNotImplementedExceptiondoublesymbol==int,longorshortvariable, orintsymboldoublesymbol==floatliteraldoubleconstant before the visitor sees it, which is why the issue needed a variableThe 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>orSymbols<long, int>suggests itsmembers 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 thatquestion and which becomes
internalhere - and decides from that and the operand's sort:That replaces the switch on the target type, including the
when inner.IsIntarm #63 added forshortand enums - which was this rule for one row. The mutation matrix shows the #63 coveragecarrying over: dropping the same-sort branch fails every
shortand 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
chararm passed an integer operandthrough and threw for a real one; a real operand converted to
charnow goes throughMkReal2Int, as it does forint. No test exercised thechararm in either direction; it iskept 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 == floatsymbol gives1.5on both sides,double == float * 2gives3,long == intsymbol gives5,decimal == intsymbol gives7,float == intsymbol gives3, and every shape that workedbefore still gives the same value.
Tests
230 → 239. A new
NumericConversionTests.csfor the shapes above, since they are a subject oftheir own rather than a marshalling detail, and one pin repointed.
Solve_DoubleSymbolComparedToAFloatVariable_RoundTripsTheValueSolve_DoubleSymbolComparedToAFloatSymbol_RelatesTheTwo/..InArithmeticWithAFloatSymbol..Solve_DoubleSymbolComparedToAnIntSymbol_RelatesTheTwoSolve_DecimalSymbolComparedToAnIntSymbol_RelatesTheTwo/..Float..Solve_LongSymbolComparedToAnIntSymbol_RelatesTheTwoSolve_DoubleSymbolComparedToAWidenedDecimalVariable../Solve_FloatSymbolComparedToANarrowedDoubleVariable..Solve_CastToAnUnmappedType_ThrowsNotImplementedException(inUnsupportedExpressionTests)(long)- which now works - to(byte), which the mapping has no row forThe real-to-integer direction already has its test from #63,
Solve_DoubleSymbolCastToInt_ConvertsRatherThanPassingThrough, which stays where it is.Mutation results
shortand enum test from #63, theshortcollection tests from #64, and the anonymous every-scalar test from #75double,decimalandfloatsymbols against anintsymbol - and nothing else in the suite, which is why the regression guard is thereThe 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,TreatWarningsAsErrorson./build.ps1 -Configuration Release- 46 tasks, 0 errors, 0 warningsRelease note
Releases remain on hold under #60 until Microsoft.Z3 5.x reaches nuget.org, so this reaches
mainbut not consumers. Nothing about the hold changes.