Skip to content

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

Closed

Description

@HowardvanRooijen

Summary

Comparing a real symbol against a float variable throws:

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 for the comparison, so the expression tree carries a
Convert(Single -> Double) node. ExpressionVisitor.VisitUnary picks the conversion from the
node's target type alone (ExpressionVisitor.cs:129-130):

switch (Type.GetTypeCode(expression.Type))
{
    case TypeCode.Double:
        return context.MkInt2Real((IntExpr)inner);

That is right for the int -> double widening it was written for, and wrong for
float -> double: the operand has already been translated to a real, so the IntExpr cast
fails.

Why this is clearly a defect

float is one of the types GetEnvironment maps to a symbol, and a float-to-double
widening is something the C# compiler inserts on the user's behalf - the constraint above
contains no cast the caller wrote.

This is the same root cause as #63, one arm along. #63 is the TypeCode.Int32 arm
(ExpressionVisitor.cs:131-132), where a short or enum operand has been translated to an
integer and the code casts it to RealExpr. Both assume the operand's Z3 sort follows from the
conversion's target type.

Measured

Constraint against Symbols<double, int>.X1 Result
t.X1 == f where float f = 1.5f InvalidCastException
t.X1 == (double)f InvalidCastException
t.X1 == 1.5f (literal) works - the compiler folds the literal to a double constant, so no Convert node survives
t.X1 == i where int i = 2 works - the widening the arm was written for
(decimal)f against a decimal symbol NotImplementedException from the catch-all at ExpressionVisitor.cs:141

So the failure needs a float variable (or an explicit cast); a float literal is folded
away before the visitor sees it.

Suggested fix

Choose the conversion from the operand's translated sort rather than the target type - the
information is already to hand in inner:

case TypeCode.Double when inner is IntExpr intExpr:
    return context.MkInt2Real(intExpr);
case TypeCode.Double:
    return inner;   // already real-sorted; the widening is a no-op in Z3

Worth doing alongside #63, since the two arms fail for the same reason.

Note

Found while fixing #52. Line numbers are as of the branch for that fix
(feature/invariant-real-literals), which adds one using to the top of the file.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions