packages feed

hsmt-0.1.0.0: src/HSMT/Core/Value.hs

-- | Concrete values of the core language, used in models.
module HSMT.Core.Value
  ( Value (..)
  , mkArray
  , arraySelect
  , arrayStore
  , defaultValue
  , valueSortMatches
  , prettyValue
    -- * Bit-vector helpers
  , bvMask
  , bvNormalize
  , bvToSigned
  , bvFromSigned
  ) where

import Data.Bits (shiftL)
import Data.List (sortOn)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Text (Text)
import qualified Data.Text as T

import HSMT.Core.Float (FP (..), RoundingMode, canonicalNaN, decode, isNaNBits, rmName)
import HSMT.Core.Regex (Regex, prettyRegex)
import qualified HSMT.Core.Regex as R
import HSMT.Core.Sort

-- | A concrete value.
--
-- Array values are kept in a canonical form (see 'mkArray'), so the derived
-- 'Eq' instance coincides with extensional equality.
data Value
  = VBool !Bool
  | VInt !Integer
  | VString !Text
  | VBV !Int !Integer
    -- ^ Width and unsigned value.
  | VArray !Sort !(Map Value Value) !Value
    -- ^ Index sort, explicit entries and default element.
  | VRecord ![(Text, Value)]
  | VUninterp !Sort !Int
    -- ^ The @n@-th abstract element of an uninterpreted sort.
  | VFP !Int !Int !Integer
    -- ^ Format and bit pattern; NaN is always the canonical pattern.
  | VRM !RoundingMode
  | VRegLan !Regex
    -- ^ A regular language. 'Eq' compares expressions, not languages (see
    -- 'HSMT.Core.Regex.equivalent').
  deriving (Eq, Ord, Show)

-- | Build an array value in canonical form.
--
-- For infinite index sorts the default is observable, so the canonical form
-- simply drops entries equal to the default. For finite index sorts every
-- entry may be overridden; in that case the default is chosen as the least
-- element of the array's image, making the representation unique.
mkArray :: Sort -> Map Value Value -> Value -> Value
mkArray idx entries def =
  case finiteCardinality idx of
    Nothing -> canon def entries
    Just card
      | fromIntegral (Map.size entries) >= card ->
          canon (minimum (Map.elems entries)) entries
      | Just keys <- enumerateSort idx ->
          let full = Map.union entries (Map.fromList [(k, def) | k <- keys])
           in canon (minimum (Map.elems full)) full
      -- Domains too large to enumerate cannot have every key overridden in
      -- practice, so the default is observable and already canonical.
      | otherwise -> canon def entries
  where
    canon d es = VArray idx (Map.filter (/= d) es) d

-- | Enumerate the elements of a small finite sort.
enumerateSort :: Sort -> Maybe [Value]
enumerateSort s = case finiteCardinality s of
  Just n | n <= 4096 -> go s
  _ -> Nothing
  where
    go = \case
      BoolSort -> Just [VBool False, VBool True]
      BVSort w -> Just [VBV w v | v <- [0 .. bvMask w]]
      FPSort eb sb ->
        Just
          [ VFP eb sb v
          | v <- [0 .. bvMask (eb + sb)]
          , not (isNaNBits eb sb v) || v == canonicalNaN eb sb
          ]
      RoundingModeSort -> Just (map VRM [minBound .. maxBound])
      RecordSort fs -> do
        vss <- traverse (go . snd) fs
        pure [VRecord (zip (map fst fs) vs) | vs <- sequence vss]
      ArraySort i e -> do
        is <- go i
        es <- go e
        case es of
          [] -> Nothing
          (e0 : _) -> pure [mkArray i (Map.fromList (zip is es')) e0 | es' <- mapM (const es) is]
      _ -> Nothing

-- | Read an array value at an index. The first argument must be a 'VArray'.
arraySelect :: Value -> Value -> Value
arraySelect (VArray _ entries def) i = Map.findWithDefault def i entries
arraySelect v _ = error ("arraySelect: not an array: " <> show v)

-- | Update an array value at an index, keeping the canonical form. The
-- first argument must be a 'VArray'.
arrayStore :: Value -> Value -> Value -> Value
arrayStore (VArray idx entries def) i e = mkArray idx (Map.insert i e entries) def
arrayStore v _ _ = error ("arrayStore: not an array: " <> show v)

-- | The value used to complete models for symbols the solver did not need to
-- constrain.
defaultValue :: Sort -> Value
defaultValue = \case
  BoolSort -> VBool False
  IntSort -> VInt 0
  StringSort -> VString ""
  BVSort w -> VBV w 0
  ArraySort i e -> mkArray i Map.empty (defaultValue e)
  RecordSort fs -> VRecord [(f, defaultValue s) | (f, s) <- fs]
  s@(UninterpretedSort _) -> VUninterp s 0
  FPSort eb sb -> VFP eb sb 0
  RoundingModeSort -> VRM minBound
  RegLanSort -> VRegLan R.none

-- | Check whether a value inhabits a sort.
valueSortMatches :: Sort -> Value -> Bool
valueSortMatches s v = case (s, v) of
  (BoolSort, VBool _) -> True
  (IntSort, VInt _) -> True
  (StringSort, VString _) -> True
  (BVSort w, VBV w' x) -> w == w' && 0 <= x && x <= bvMask w
  (ArraySort i e, VArray i' entries def) ->
    i == i'
      && valueSortMatches e def
      && all (valueSortMatches i) (Map.keys entries)
      && all (valueSortMatches e) (Map.elems entries)
  (RecordSort fs, VRecord vs) ->
    map fst fs == map fst vs && and (zipWith valueSortMatches (map snd fs) (map snd vs))
  (UninterpretedSort _, VUninterp s' _) -> s == s'
  (FPSort eb sb, VFP eb' sb' x) ->
    eb == eb' && sb == sb' && 0 <= x && x <= bvMask (eb + sb)
      && (not (isNaNBits eb sb x) || x == canonicalNaN eb sb)
  (RoundingModeSort, VRM _) -> True
  (RegLanSort, VRegLan _) -> True
  _ -> False

-- | Render a value as an SMT-LIB term.
prettyValue :: Value -> Text
prettyValue = \case
  VBool b -> if b then "true" else "false"
  VInt n
    | n < 0 -> "(- " <> tshow (negate n) <> ")"
    | otherwise -> tshow n
  VString s -> "\"" <> T.replace "\"" "\"\"" s <> "\""
  VBV w x -> "#b" <> T.pack [if odd (x `div` (2 ^ i)) then '1' else '0' | i <- [w - 1, w - 2 .. 0]]
  VArray idx entries def ->
    let base = "((as const (Array " <> prettySort idx <> " " <> "_)) " <> prettyValue def <> ")"
     in foldl
          (\acc (k, e) -> "(store " <> acc <> " " <> prettyValue k <> " " <> prettyValue e <> ")")
          base
          (sortOn fst (Map.toList entries))
  VRecord fs -> "(record " <> T.unwords [f <> "=" <> prettyValue v | (f, v) <- fs] <> ")"
  VUninterp s n -> "(as @" <> prettySort s <> "_" <> tshow n <> ")"
  VFP eb sb x -> case decode eb sb x of
    NaN -> "(_ NaN " <> tshow eb <> " " <> tshow sb <> ")"
    Inf neg -> "(_ " <> (if neg then "-" else "+") <> "oo " <> tshow eb <> " " <> tshow sb <> ")"
    Zero neg -> "(_ " <> (if neg then "-" else "+") <> "zero " <> tshow eb <> " " <> tshow sb <> ")"
    Finite {} ->
      "(fp " <> binary 1 (x `div` 2 ^ (eb + sb - 1)) <> " "
        <> binary eb ((x `div` 2 ^ (sb - 1)) `mod` 2 ^ eb) <> " "
        <> binary (sb - 1) (x `mod` 2 ^ (sb - 1)) <> ")"
  VRM rm -> rmName rm
  VRegLan r -> prettyRegex r
  where
    binary w v = prettyValue (VBV w v)
    tshow :: Show a => a -> Text
    tshow = T.pack . show

-- | Largest unsigned value of the given width.
bvMask :: Int -> Integer
bvMask w = (1 `shiftL` w) - 1

-- | Reduce an integer modulo @2^w@.
bvNormalize :: Int -> Integer -> Integer
bvNormalize w x = x `mod` (1 `shiftL` w)

-- | Two's complement interpretation of an unsigned value.
bvToSigned :: Int -> Integer -> Integer
bvToSigned w x
  | x >= 1 `shiftL` (w - 1) = x - (1 `shiftL` w)
  | otherwise = x

-- | Unsigned value of the given width representing a (two's complement)
-- signed integer; inverse of 'bvToSigned'.
bvFromSigned :: Int -> Integer -> Integer
bvFromSigned = bvNormalize