Repository navigation
Support uint and ulong as bit-vector symbols - #101
HowardvanRooijen merged 1 commit into
Conversation
The second #99 follow-up: give integer-like symbols the operators an unbounded integer cannot carry - bitwise & | ^ ~, shifts, and wrapping arithmetic with unsigned comparison - by mapping uint and ulong to Z3 bit-vectors of their width (32 and 64). Purely additive: those types were rejected before. The operator dispatch now chooses by the operands' sort - a bit-vector gets the BV form, an int or real the arithmetic form, a bool the logical one - so & | ^ and ~ work on bit-vectors, are refused clearly on plain integers (Z3's integer sort has no bitwise ops), and still do Boolean logic on bools. Shifts convert their int amount to the value's width; comparisons are unsigned, matching uint/ulong. byte and ushort are deliberately left unsupported: C# promotes them to int in every expression, so such a symbol could never keep its bit-vector sort through a constraint - mapping them would be a trap, not a feature. Measured while building this; documented on BitVectorWidth. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
Unsigned expression translation still has semantic gaps that can produce invalid models or reject valid constraints.
3 open issues
What changed in this PR
Adds uint and ulong symbol support to the expression-to-Z3 translation layer, enabling fixed-width operations unavailable on integer sorts.
Changes:
- Maps unsigned symbols and constants to 32-bit or 64-bit bit-vectors and reads model values back.
- Adds sort-aware arithmetic, unsigned comparisons, bitwise operations, and logical shifts.
- Adds unsigned-symbol tests and updates the unsupported-type test to use
byte.
| File | Description |
|---|---|
| solutions/Z3.Linq/Theorem.cs | Adds bit-vector sort mapping, width helpers, and unsigned value marshalling. |
| solutions/Z3.Linq/ExpressionVisitor.cs | Translates unsigned constants and dispatches operators by sort. |
| solutions/Z3.Linq.Tests/UnsupportedExpressionTests.cs | Replaces the unsupported uint case with byte and updates explanatory comments. |
| solutions/Z3.Linq.Tests/BitVectorSymbolTests.cs | Tests unsigned round-trips, operators, optimization, and collections. |
Review effort: Balanced
| return left is BitVecExpr bvLeft | ||
| ? bv(this.context, bvLeft, (BitVecExpr)right) | ||
| : arith(this.context, (ArithExpr)left, (ArithExpr)right); |
There was a problem hiding this comment.
Correct. checked(t.X1 + 1u) == 0u returned uint.MaxValue. Fixed in 0bd8d81 (#116). AddChecked, SubtractChecked and MultiplyChecked on bit-vector operands now throw a NotSupportedException that says overflow checking is not translated. Checked arithmetic on int and real symbols is unchanged. The test covers all three operators across uint and ulong.
|
|
||
| throw new NotSupportedException( | ||
| $"The '{op}' operator is supported only on Boolean operands. A bitwise operation on integer symbols is not supported, because it would need a bit-vector representation the library does not expose."); | ||
| BitVecExpr bvAmount = amount as BitVecExpr ?? this.context.MkInt2BV(bvValue.SortSize, (IntExpr)amount); |
There was a problem hiding this comment.
Correct. Fixed in 0bd8d81 (#116). The count is now ANDed with the width minus one before the shift. The int-to-bit-vector conversion is modulo 2^width, so a negative count reaches the mask in two's complement and matches C# too. The tests use a symbolic count of 1, the width, the width plus one, and -1, for both uint and ulong, and the expected value is computed in C# from the returned symbols.
| TypeCode.Int16 or TypeCode.Int32 or TypeCode.Int64 or TypeCode.DateTime => context.IntSort, | ||
| TypeCode.Boolean => context.BoolSort, | ||
| TypeCode.Single or TypeCode.Decimal or TypeCode.Double => context.RealSort, | ||
| TypeCode.UInt32 or TypeCode.UInt64 => context.MkBitVecSort(BitVectorWidth(typeCode)!.Value), |
There was a problem hiding this comment.
Correct. NewTheorem<Symbols<uint, ulong>>().Where(t => t.X1 == t.X2) threw. Fixed in 0bd8d81 (#116). 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. The tests include uint.MaxValue, the value that tells zero-extension from sign-extension.
* 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>


The second follow-up #99 listed. #99 diagnosed integer bitwise (
&/|/^),~and shifts asunsupported, because Z3's integer sort has no bit operations - they need a fixed-width
BitVec. This adds the bit-vector:uintmaps to a 32-bit bit-vector andulongto a 64-bit one,so those symbols carry the operators an unbounded integer cannot. Purely additive - both types
were rejected before.
The change
Sort.
uint/ulongjoin the one CLR-type-to-sort mapping (TryGetSymbolSort) asMkBitVecSort(32|64), alongside aBitVectorWidthhelper. The read paths gain arms that read aBitVecNumback touint/ulong; constants translate throughMkBV.Operators, chosen by sort. The visitor's dispatch became sort-aware: each arithmetic and
relational operator picks the bit-vector form for bit-vector operands and the arithmetic form for
integer/real ones;
&/|/^and~pick the Boolean form for bools, the bitwise form forbit-vectors, and are refused with a clear message on plain integers. So:
t.X1 == 7u, round-trip incl.uint.MaxValue(t.X1 & 6u) == 4u,(t.X1 | 1u) == 7u,(t.X1 ^ 5u) == 0u(~t.X1) == 0xFFFFFFF0uNotfor~; now sort-aware)(t.X1 << 2) == 8u,(t.X1 >> 1) == 5uintshift amount is widened to the value's widtht.X1 + 1u == 0uuint.MaxValue- the defining bit-vector behaviourt.X1 > 0xFFFFFFF0uulongbeyonduint,uint[]elements,OptimizeComparisons are unsigned, matching
uint/ulong; shifts are logical (MkBVLSHR). The #87range bounds do not apply - a bit-vector is bounded by its width, and
AssertBoundsonly touchesIntExprsymbols, so bit-vectors are skipped naturally.byte and ushort, measured and deliberately excluded
The opt-in was "unsigned/fixed types," but building it surfaced that
byteandushortcannotcarry the feature: C# promotes them to
intin every expression -byte & 0x0Fis computed inintspace - so abytesymbol would produce abyte->intConvertand then fail, becauseinthas no bitwise.uint/ulongare not promoted, which is why they work. Mappingbyte/ushortto a bit-vector sort would be a trap: the symbol would carry a sort every constraint thenfails to use. So they stay unsupported (rejected cleanly at environment build, as before), and
BitVectorWidthdocuments why. The pin that asserteduintwas unsupported is repointed atbyte.Limitation
A bit-vector symbol mixed with an
intthat forces promotion (anintvariable, or a literaltoo big for
uint) is not supported - the resultinguint<->intconversion has no meaning thelibrary commits to, and falls through to the existing conversion catch-all. Unsigned literals
(
6u,6UL) and int literals that fit keep the expression in bit-vector space. Documented onBitVectorSymbolTests.Tests
290 -> 305, in a new
BitVectorSymbolTests, plus one repointed pin. Where a constraint does notpin a unique value, the assertion checks the constraint holds on the result rather than a specific
model.
Solve_UIntSymbol_RoundTripsTheValueuint.MaxValueSolve_UIntBitwiseAnd/Or/Xor,Solve_UIntOnesComplement~Solve_UIntLeftShift,Solve_UIntRightShiftSolve_UIntArithmeticWraps_PinsMaxValueintsymbolSolve_UIntComparison_IsUnsignedSolve_UIntSymbolMaximised,Solve_ULong*,Solve_UIntCollectionElementSolve_ByteProperty_ThrowsNotSupportedException(repointed fromuint)Mutation results
uint/ulongnot mapped to a sortMkBVU*->MkBVS*)~no longerMkBVNot)The unsigned-comparison test needed strengthening first: a value that satisfied the constraint
under signed order coincidentally satisfied the unsigned assertion, so the mutation slipped
through until the constraint was made a band that is unsatisfiable under signed order.
Verification
dotnet build solutions/Z3.Linq.slnx -c Release- clean,TreatWarningsAsErrorsanddocumentation generation on
./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. The public surface gains
uint/ulongsymbol support; nothing is removed.