Skip to content

Support uint and ulong as bit-vector symbols - #101

Merged
HowardvanRooijen merged 1 commit into
feature/expression-visitor-instancefrom
feature/bit-vector-symbols
Oct 28, 2026
Merged

HowardvanRooijen merged 1 commit into
feature/expression-visitor-instancefrom
feature/bit-vector-symbols

Conversation

@HowardvanRooijen

@HowardvanRooijen HowardvanRooijen commented Sep 1, 2026 •

Copy link
Copy Markdown
Member

The second follow-up #99 listed. #99 diagnosed integer bitwise (&/|/^), ~ and shifts as
unsupported, because Z3's integer sort has no bit operations - they need a fixed-width
BitVec. This adds the bit-vector: uint maps to a 32-bit bit-vector and ulong to 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/ulong join the one CLR-type-to-sort mapping (TryGetSymbolSort) as
MkBitVecSort(32|64), alongside a BitVectorWidth helper. The read paths gain arms that read a
BitVecNum back to uint/ulong; constants translate through MkBV.

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 for
bit-vectors, and are refused with a clear message on plain integers. So:

Shape (all measured) Result
t.X1 == 7u, round-trip incl. uint.MaxValue exact
(t.X1 & 6u) == 4u, (t.X1 | 1u) == 7u, (t.X1 ^ 5u) == 0u bitwise works
(~t.X1) == 0xFFFFFFF0u complement works (C# emits Not for ~; now sort-aware)
(t.X1 << 2) == 8u, (t.X1 >> 1) == 5u shifts work; the int shift amount is widened to the value's width
t.X1 + 1u == 0u wraps to uint.MaxValue - the defining bit-vector behaviour
t.X1 > 0xFFFFFFF0u unsigned comparison
ulong beyond uint, uint[] elements, Optimize all work

Comparisons are unsigned, matching uint/ulong; shifts are logical (MkBVLSHR). The #87
range bounds do not apply - a bit-vector is bounded by its width, and AssertBounds only touches
IntExpr symbols, 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 byte and ushort cannot
carry the feature
: C# promotes them to int in every expression - byte & 0x0F is computed in
int space - so a byte symbol would produce a byte->int Convert and then fail, because
int has no bitwise. uint/ulong are not promoted, which is why they work. Mapping byte/
ushort to a bit-vector sort would be a trap: the symbol would carry a sort every constraint then
fails to use. So they stay unsupported (rejected cleanly at environment build, as before), and
BitVectorWidth documents why. The pin that asserted uint was unsupported is repointed at
byte.

Limitation

A bit-vector symbol mixed with an int that forces promotion (an int variable, or a literal
too big for uint) is not supported - the resulting uint<->int conversion has no meaning the
library 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 on
BitVectorSymbolTests.

Tests

290 -> 305, in a new BitVectorSymbolTests, plus one repointed pin. Where a constraint does not
pin a unique value, the assertion checks the constraint holds on the result rather than a specific
model.

Test Covers
Solve_UIntSymbol_RoundTripsTheValue round-trip incl. uint.MaxValue
Solve_UIntBitwiseAnd/Or/Xor, Solve_UIntOnesComplement the bitwise operators and ~
Solve_UIntLeftShift, Solve_UIntRightShift shifts, with the int-amount conversion
Solve_UIntArithmeticWraps_PinsMaxValue wrapping - unsatisfiable for an int symbol
Solve_UIntComparison_IsUnsigned a band across the signed boundary, UNSAT under signed order
Solve_UIntSymbolMaximised, Solve_ULong*, Solve_UIntCollectionElement optimiser, 64-bit, collections
Solve_ByteProperty_ThrowsNotSupportedException (repointed from uint) byte/ushort stay unsupported

Mutation results

Mutation Failures Which
uint/ulong not mapped to a sort 15 every bit-vector test
Bitwise arm throws instead of the BV op 5 the four bitwise tests and the ulong one
All comparisons signed (MkBVU* -> MkBVS*) 2 the unsigned-comparison band and the maximise test
Shift amount not widened to the value's sort 2 both shift tests
Complement arm dead (~ no longer MkBVNot) 1 the ones-complement test

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, TreatWarningsAsErrors and
    documentation generation on
  • 305/305 locally
  • ./build.ps1 -Configuration Release - 46 tasks, 0 errors, 0 warnings
  • Coverage 89.3% -> 89.0% line (894 of 1004), 76.0% -> 77.2% branch (592 of 766)

Release note

Releases remain on hold under #60 until Microsoft.Z3 5.x reaches nuget.org, so this reaches main
but not consumers. The public surface gains uint/ulong symbol support; nothing is removed.

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>
@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown

Test Results

  1 files  ± 0    1 suites  ±0   11s ⏱️ -6s
294 tests +15  294 ✅ +15  0 💤 ±0  0 ❌ ±0 
305 runs  +15  305 ✅ +15  0 💤 ±0  0 ❌ ±0 

Results for commit 106735e. ± Comparison against base commit 81c8b1d.

@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

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

Comment on lines +244 to +246
return left is BitVecExpr bvLeft
? bv(this.context, bvLeft, (BitVecExpr)right)
: arith(this.context, (ArithExpr)left, (ArithExpr)right);

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. 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);

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. 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),

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. 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.

@HowardvanRooijen HowardvanRooijen added no_release Suppresses auto_release functionality and removed pending_release labels Oct 27, 2026
@HowardvanRooijen
HowardvanRooijen merged commit 2ed9e9e into main Oct 28, 2026
12 checks passed
@HowardvanRooijen
HowardvanRooijen deleted the feature/bit-vector-symbols 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.

3 participants