packages feed

hsmt-0.1.0.0: src/HSMT/API/Sort.hs

{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}

-- | Type-level sorts of the typed API and their Haskell value types.
module HSMT.API.Sort
  ( -- * Sorts
    Sort (..)
  , KnownSort (..)
  , KnownSorts (..)
  , KnownFields (..)
  , sortOfProxy
    -- * Records
  , FieldSort
  , UniqueFields
  , NotMember
    -- * Values
  , Value
  , BitVector (..)
  , ArrayValue (..)
  , RecordValue (..)
  , Uninterp (..)
    -- * Floating point
  , FloatingPoint (..)
  , RoundingMode (..)
  , Float16S
  , Float32S
  , Float64S
  , floatValue
  , floatFromValue
  , toFloat
  , fromFloat
  , toDouble
  , fromDouble
  ) where

import Data.Kind (Constraint, Type)
import qualified Data.Map.Strict as Map
import Data.Proxy (Proxy (..))
import Data.Text (Text)
import qualified Data.Text as T
import GHC.TypeLits
  ( ErrorMessage (..)
  , KnownNat
  , KnownSymbol
  , Nat
  , Symbol
  , TypeError
  , natVal
  , symbolVal
  , type (<=)
  )

import GHC.Float (castDoubleToWord64, castFloatToWord32, castWord32ToFloat, castWord64ToDouble)

import HSMT.Core.Float (RoundingMode (..))
import qualified HSMT.Core.Float as F
import qualified HSMT.Core.Sort as C
import qualified HSMT.Core.Value as C

-- | Sorts, promoted to the kind level with @DataKinds@.
data Sort
  = BoolS
  | IntS
  | StringS
  | BVS Nat
    -- ^ Bit-vectors of the given (positive) width.
  | ArrayS Sort Sort
    -- ^ Arrays from the first sort to the second.
  | RecordS [(Symbol, Sort)]
    -- ^ Records with named fields.
  | UninterpS Symbol
    -- ^ Uninterpreted sort with the given name.
  | FPS Nat Nat
    -- ^ Floating-point numbers with the given exponent and significand
    -- widths (the significand width counts the hidden bit; both at
    -- least 2).
  | RoundingModeS
  | RegLanS
    -- ^ Regular languages over strings. Expressions of this sort must be
    -- ground (built from string literals), so there are no constants or
    -- model values of it.

-- | IEEE half precision (binary16).
type Float16S = 'FPS 5 11

-- | IEEE single precision (binary32), the format of 'Float'.
type Float32S = 'FPS 8 24

-- | IEEE double precision (binary64), the format of 'Double'.
type Float64S = 'FPS 11 53

-- | Sort of a field in a record field list, with a readable error when the
-- field does not exist.
type family FieldSort (l :: Symbol) (fs :: [(Symbol, Sort)]) :: Sort where
  FieldSort l '[] = TypeError ('Text "Record has no field " ':<>: 'ShowType l)
  FieldSort l ('(l, s) ': _) = s
  FieldSort l (_ ': fs) = FieldSort l fs

-- | Rejects records with repeated field names.
type family UniqueFields (fs :: [(Symbol, Sort)]) :: Constraint where
  UniqueFields '[] = ()
  UniqueFields ('(l, _) ': fs) = (NotMember l fs, UniqueFields fs)

-- | Rejects a field name that occurs in the rest of the field list.
type family NotMember (l :: Symbol) (fs :: [(Symbol, Sort)]) :: Constraint where
  NotMember _ '[] = ()
  NotMember l ('(l, _) ': _) = TypeError ('Text "Duplicated record field " ':<>: 'ShowType l)
  NotMember l (_ ': fs) = NotMember l fs

-- | Haskell representation of values of each sort, as returned by models.
type family Value (s :: Sort) :: Type where
  Value 'BoolS = Bool
  Value 'IntS = Integer
  Value 'StringS = Text
  Value ('BVS n) = BitVector n
  Value ('ArrayS i e) = ArrayValue (Value i) (Value e)
  Value ('RecordS fs) = RecordValue fs
  Value ('UninterpS n) = Uninterp n
  Value ('FPS eb sb) = FloatingPoint eb sb
  Value 'RoundingModeS = RoundingMode

-- | An unsigned bit-vector value of width @n@.
newtype BitVector (n :: Nat) = BitVector {bitVectorValue :: Integer}
  deriving (Eq, Ord, Show)

-- | A finite array value: explicit entries plus the value at every other
-- index.
data ArrayValue i e = ArrayValue
  { arrayEntries :: [(i, e)]
  , arrayDefault :: e
  }
  deriving (Eq, Show)

-- | A record value. Fields are read with 'HSMT.API.Model.field'.
newtype RecordValue (fs :: [(Symbol, Sort)]) = RecordValue [(Text, C.Value)]
  deriving (Eq)

instance Show (RecordValue fs) where
  show (RecordValue fs) =
    "{" <> T.unpack (T.intercalate ", " [f <> " = " <> C.prettyValue v | (f, v) <- fs]) <> "}"

-- | An abstract element of an uninterpreted sort.
newtype Uninterp (n :: Symbol) = Uninterp Int
  deriving (Eq, Ord, Show)

-- | A floating-point value: its IEEE bit pattern (sign, biased exponent and
-- trailing significand, from the most significant bit). There is a single
-- NaN, with the pattern 'HSMT.Core.Float.canonicalNaN'.
newtype FloatingPoint (eb :: Nat) (sb :: Nat) = FloatingPoint {floatingPointBits :: Integer}
  deriving (Eq, Ord)

instance (KnownNat eb, KnownNat sb) => Show (FloatingPoint eb sb) where
  show x = show (floatValue x)

formatOf :: forall eb sb. (KnownNat eb, KnownNat sb) => (Int, Int)
formatOf = (fromIntegral (natVal (Proxy @eb)), fromIntegral (natVal (Proxy @sb)))

-- | The value of a pattern: NaN, an infinity, a zero or a finite number
-- (with its sign and exact magnitude).
floatValue :: forall eb sb. (KnownNat eb, KnownNat sb) => FloatingPoint eb sb -> F.FP
floatValue (FloatingPoint x) = let (eb, sb) = formatOf @eb @sb in F.decode eb sb x

-- | The pattern of a value, rounding finite numbers to nearest (ties to
-- even).
floatFromValue :: forall eb sb. (KnownNat eb, KnownNat sb) => F.FP -> FloatingPoint eb sb
floatFromValue v =
  let (eb, sb) = formatOf @eb @sb
   in FloatingPoint . F.encode eb sb $ case v of
        F.Finite neg m -> F.roundRational RNE eb sb neg m
        other -> other

-- | The 'Float' with the same bit pattern (NaN for the NaN).
toFloat :: FloatingPoint 8 24 -> Float
toFloat (FloatingPoint x) = castWord32ToFloat (fromInteger x)

-- | The value of a 'Float'; every NaN becomes the single NaN of SMT-LIB.
fromFloat :: Float -> FloatingPoint 8 24
fromFloat = FloatingPoint . F.canonicalize 8 24 . toInteger . castFloatToWord32

-- | The 'Double' with the same bit pattern (NaN for the NaN).
toDouble :: FloatingPoint 11 53 -> Double
toDouble (FloatingPoint x) = castWord64ToDouble (fromInteger x)

-- | The value of a 'Double'; every NaN becomes the single NaN of SMT-LIB.
fromDouble :: Double -> FloatingPoint 11 53
fromDouble = FloatingPoint . F.canonicalize 11 53 . toInteger . castDoubleToWord64

-- | Sorts with a run-time representation.
class KnownSort (s :: Sort) where
  sortRep :: C.Sort
  decodeValue :: C.Value -> Maybe (Value s)

-- | The run-time representation of the sort of a proxy.
sortOfProxy :: forall s proxy. KnownSort s => proxy s -> C.Sort
sortOfProxy _ = sortRep @s

instance KnownSort 'BoolS where
  sortRep = C.BoolSort
  decodeValue = \case C.VBool b -> Just b; _ -> Nothing

instance KnownSort 'IntS where
  sortRep = C.IntSort
  decodeValue = \case C.VInt n -> Just n; _ -> Nothing

instance KnownSort 'StringS where
  sortRep = C.StringSort
  decodeValue = \case C.VString s -> Just s; _ -> Nothing

instance (KnownNat n, 1 <= n) => KnownSort ('BVS n) where
  sortRep = C.BVSort (fromIntegral (natVal (Proxy @n)))
  decodeValue = \case C.VBV _ x -> Just (BitVector x); _ -> Nothing

instance (KnownSort i, KnownSort e) => KnownSort ('ArrayS i e) where
  sortRep = C.ArraySort (sortRep @i) (sortRep @e)
  decodeValue = \case
    C.VArray _ entries def ->
      ArrayValue
        <$> traverse
          (\(k, v) -> (,) <$> decodeValue @i k <*> decodeValue @e v)
          (Map.toList entries)
        <*> decodeValue @e def
    _ -> Nothing

instance (KnownFields fs, UniqueFields fs) => KnownSort ('RecordS fs) where
  sortRep = C.RecordSort (fieldReps @fs)
  decodeValue = \case
    C.VRecord fs -> Just (RecordValue fs)
    _ -> Nothing

instance KnownSymbol n => KnownSort ('UninterpS n) where
  sortRep = C.UninterpretedSort (T.pack (symbolVal (Proxy @n)))
  decodeValue = \case C.VUninterp _ k -> Just (Uninterp k); _ -> Nothing

instance (KnownNat eb, KnownNat sb, 2 <= eb, 2 <= sb) => KnownSort ('FPS eb sb) where
  sortRep = let (eb, sb) = formatOf @eb @sb in C.FPSort eb sb
  decodeValue = \case C.VFP _ _ x -> Just (FloatingPoint x); _ -> Nothing

instance KnownSort 'RoundingModeS where
  sortRep = C.RoundingModeSort
  decodeValue = \case C.VRM r -> Just r; _ -> Nothing

-- | Record field lists with a run-time representation.
class KnownFields (fs :: [(Symbol, Sort)]) where
  fieldReps :: [(Text, C.Sort)]

instance KnownFields '[] where
  fieldReps = []

instance (KnownSymbol l, KnownSort s, KnownFields fs) => KnownFields ('(l, s) ': fs) where
  fieldReps = (T.pack (symbolVal (Proxy @l)), sortRep @s) : fieldReps @fs

-- | Lists of sorts, used for the domains of uninterpreted functions.
class KnownSorts (ss :: [Sort]) where
  sortReps :: [C.Sort]

instance KnownSorts '[] where
  sortReps = []

instance (KnownSort s, KnownSorts ss) => KnownSorts (s ': ss) where
  sortReps = sortRep @s : sortReps @ss