packages feed

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

-- | Reference evaluator for the core language.
--
-- This module defines the semantics of every operator, following the
-- SMT-LIB 2.6 standard. It is used to evaluate expressions under a model
-- and serves as the oracle that decision procedures are tested against.
module HSMT.Core.Eval
  ( Interpretation (..)
  , FunInterp (..)
  , emptyInterpretation
  , constInterp
  , evalExpr
  , applyOp
  , EvalError (..)
  ) where

import Data.Bits (complement, shiftL, shiftR, testBit, xor, (.&.), (.|.))
import Data.Char (isDigit)
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.Expr
import qualified HSMT.Core.Float as F
import qualified HSMT.Core.Regex as R
import HSMT.Core.Op
import HSMT.Core.Value

-- | Finite interpretation of a function: an explicit table plus a default
-- result for every other argument tuple.
data FunInterp = FunInterp
  { fiTable :: !(Map [Value] Value)
  , fiDefault :: !Value
  }
  deriving (Eq, Show)

-- | The interpretation that returns the given value for every argument tuple.
constInterp :: Value -> FunInterp
constInterp = FunInterp Map.empty

-- | An interpretation of uninterpreted symbols.
--
-- SMT-LIB leaves integer division and remainder by zero unspecified: they
-- behave as uninterpreted functions of the dividend. Their interpretation is
-- therefore part of a model as well. The same holds for the floating-point
-- results SMT-LIB leaves unspecified ('interpUnspecified').
data Interpretation = Interpretation
  { interpSymbols :: !(Map Symbol FunInterp)
  , interpDivByZero :: !FunInterp
  , interpModByZero :: !FunInterp
  , interpUnspecified :: !(Map (Op, [Value]) Value)
    -- ^ Results of @fp.min@ and @fp.max@ of zeros of different signs, and
    -- of @fp.to_ubv@ and @fp.to_sbv@ of NaN, infinities and values out of
    -- range, by operator and arguments. Missing entries are the first
    -- argument (for @fp.min@ and @fp.max@) and zero.
  }
  deriving (Eq, Show)

-- | The interpretation with no symbols, where division and remainder by zero
-- return @0@ and unspecified floating-point results take their defaults.
emptyInterpretation :: Interpretation
emptyInterpretation =
  Interpretation Map.empty (constInterp (VInt 0)) (constInterp (VInt 0)) Map.empty

-- | An evaluation failure: an operator applied to arguments it does not
-- accept (ill-sorted or otherwise invalid).
data EvalError = EvalError
  { eeOp :: Op
  -- ^ The operator being applied.
  , eeArgs :: [Value]
  -- ^ The argument values it received.
  , eeMessage :: Text
  -- ^ A human-readable description of the problem.
  }
  deriving (Eq, Show)

-- | Evaluate an expression. Symbols missing from the interpretation take the
-- default value of their sort.
evalExpr :: Interpretation -> Expr -> Either EvalError Value
evalExpr interp = go
  where
    go (App Ite [c, t, e]) =
      go c >>= \case
        VBool True -> go t
        VBool False -> go e
        v -> Left (EvalError Ite [v] "condition is not Boolean")
    go (App op args) = traverse go args >>= applyOp interp op

-- | Apply an operator to argument values.
applyOp :: Interpretation -> Op -> [Value] -> Either EvalError Value
applyOp interp op vs = case (op, vs) of
  (Uninterpreted sym, _) ->
    pure $ case Map.lookup sym (interpSymbols interp) of
      Just fi -> Map.findWithDefault (fiDefault fi) vs (fiTable fi)
      Nothing -> defaultValue (symResult sym)
  -- Booleans
  (BoolConst b, []) -> bool b
  (Not, [VBool a]) -> bool (not a)
  (And, _) -> VBool . and <$> traverse asBool vs
  (Or, _) -> VBool . or <$> traverse asBool vs
  (Xor, _) -> VBool . foldl' (/=) False <$> traverse asBool vs
  (Implies, _ : _) -> do
    bs <- traverse asBool vs
    -- Right associative: a => b => c is a => (b => c).
    pure (VBool (foldr1 (\a b -> not a || b) bs))
  (Ite, [VBool c, t, e]) -> pure (if c then t else e)
  -- Regular languages are equal when they have the same strings.
  (Eq, VRegLan r : rest) -> VBool . and <$> traverse (sameLanguage r) rest
  (Distinct, VRegLan _ : _) ->
    VBool . not . or
      <$> sequence [sameLanguage a (VRegLan b) | (i, VRegLan a) <- zip [0 :: Int ..] vs, VRegLan b <- drop (i + 1) vs]
  (Eq, x : rest) -> bool (all (== x) rest)
  (Distinct, _) -> bool (allDistinct vs)
  -- Integers
  (IntConst n, []) -> int n
  (Add, _) -> VInt . sum <$> traverse asInt vs
  (Mul, _) -> VInt . product <$> traverse asInt vs
  (Sub, _) -> traverse asInt vs >>= \case
    (x : xs) -> int (foldl' (-) x xs)
    [] -> bad "no arguments"
  (Neg, [VInt a]) -> int (negate a)
  (IntDiv, [VInt a, VInt b])
    | b == 0 -> pure (applyFun (interpDivByZero interp) [VInt a])
    | otherwise -> int (fst (euclidean a b))
  (IntMod, [VInt a, VInt b])
    | b == 0 -> pure (applyFun (interpModByZero interp) [VInt a])
    | otherwise -> int (snd (euclidean a b))
  (Abs, [VInt a]) -> int (abs a)
  (Le, _) -> chain (<=) =<< traverse asInt vs
  (Lt, _) -> chain (<) =<< traverse asInt vs
  (Ge, _) -> chain (>=) =<< traverse asInt vs
  (Gt, _) -> chain (>) =<< traverse asInt vs
  -- Bit-vectors
  (BVConst w x, []) -> pure (VBV w x)
  (BVNot, [VBV w a]) -> bv w (complement a)
  (BVNeg, [VBV w a]) -> bv w (negate a)
  (BVAnd, VBV w _ : _) -> bv w . foldr1 (.&.) =<< traverse asBV vs
  (BVOr, VBV w _ : _) -> bv w . foldr1 (.|.) =<< traverse asBV vs
  (BVXor, VBV w _ : _) -> bv w . foldr1 xor =<< traverse asBV vs
  (BVAdd, VBV w _ : _) -> bv w . sum =<< traverse asBV vs
  (BVMul, VBV w _ : _) -> bv w . product =<< traverse asBV vs
  (BVSub, [VBV w a, VBV _ b]) -> bv w (a - b)
  (BVUDiv, [VBV w a, VBV _ b]) -> bv w (udiv w a b)
  (BVURem, [VBV w a, VBV _ b]) -> bv w (urem a b)
  (BVSDiv, [VBV w a, VBV _ b]) -> bv w (sdiv w a b)
  (BVSRem, [VBV w a, VBV _ b]) -> bv w (srem w a b)
  (BVSMod, [VBV w a, VBV _ b]) -> bv w (smod w a b)
  (BVShl, [VBV w a, VBV _ b]) -> bv w (if b >= fromIntegral w then 0 else a `shiftL` fromIntegral b)
  (BVLShr, [VBV w a, VBV _ b]) -> bv w (if b >= fromIntegral w then 0 else a `shiftR` fromIntegral b)
  (BVAShr, [VBV w a, VBV _ b]) ->
    let sa = bvToSigned w a
        sh = if b >= fromIntegral w then w else fromIntegral b
     in bv w (sa `shiftR` sh)
  (BVConcat, _) -> do
    parts <- traverse (\case VBV w x -> Right (w, x); v -> badArg v) vs
    let w = sum (map fst parts)
        x = foldl' (\acc (wi, xi) -> (acc `shiftL` wi) .|. xi) 0 parts
    pure (VBV w x)
  (BVExtract h l, [VBV _ a]) -> pure (VBV (h - l + 1) ((a `shiftR` l) .&. bvMask (h - l + 1)))
  (BVZeroExtend k, [VBV w a]) -> pure (VBV (w + k) a)
  (BVSignExtend k, [VBV w a]) -> bv (w + k) (bvToSigned w a)
  (BVULt, [VBV _ a, VBV _ b]) -> bool (a < b)
  (BVULe, [VBV _ a, VBV _ b]) -> bool (a <= b)
  (BVUGt, [VBV _ a, VBV _ b]) -> bool (a > b)
  (BVUGe, [VBV _ a, VBV _ b]) -> bool (a >= b)
  (BVSLt, [VBV w a, VBV _ b]) -> bool (bvToSigned w a < bvToSigned w b)
  (BVSLe, [VBV w a, VBV _ b]) -> bool (bvToSigned w a <= bvToSigned w b)
  (BVSGt, [VBV w a, VBV _ b]) -> bool (bvToSigned w a > bvToSigned w b)
  (BVSGe, [VBV w a, VBV _ b]) -> bool (bvToSigned w a >= bvToSigned w b)
  -- Arrays
  (Select, [a@VArray {}, i]) -> pure (arraySelect a i)
  (Store, [a@VArray {}, i, e]) -> pure (arrayStore a i e)
  (ConstArray idx, [e]) -> pure (mkArray idx Map.empty e)
  -- Strings
  (StrConst s, []) -> str s
  (StrConcat, _) -> VString . T.concat <$> traverse asStr vs
  (StrLen, [VString s]) -> int (fromIntegral (T.length s))
  (StrAt, [VString s, VInt i]) -> str (substr s i 1)
  (StrSubstr, [VString s, VInt i, VInt n]) -> str (substr s i n)
  (StrContains, [VString s, VString t]) -> bool (t `T.isInfixOf` s)
  (StrPrefixOf, [VString s, VString t]) -> bool (s `T.isPrefixOf` t)
  (StrSuffixOf, [VString s, VString t]) -> bool (s `T.isSuffixOf` t)
  (StrIndexOf, [VString s, VString t, VInt i]) -> int (indexOf s t i)
  (StrReplace, [VString s, VString t, VString t']) -> str (replaceFirst s t t')
  (StrToInt, [VString s])
    | not (T.null s) && T.all isDigit s -> int (read (T.unpack s))
    | otherwise -> int (-1)
  (StrFromInt, [VInt n])
    | n >= 0 -> str (T.pack (show n))
    | otherwise -> str ""
  (StrLt, [VString s, VString t]) -> bool (s < t)
  (StrLe, [VString s, VString t]) -> bool (s <= t)
  -- Regular expressions
  (StrToRe, [VString s]) -> re (R.literal s)
  (StrInRe, [VString s, VRegLan r]) -> bool (R.matches r s)
  (ReNone, []) -> re R.none
  (ReAll, []) -> re R.everything
  (ReAllChar, []) -> re R.allChar
  (ReConcat, _) -> VRegLan . foldr1 R.cat <$> traverse asRe vs
  (ReUnion, _) -> VRegLan . R.union <$> traverse asRe vs
  (ReInter, _) -> VRegLan . R.inter <$> traverse asRe vs
  (ReStar, [VRegLan r]) -> re (R.star r)
  (RePlus, [VRegLan r]) -> re (R.plus r)
  (ReOpt, [VRegLan r]) -> re (R.opt r)
  (ReRange, [VString a, VString b]) -> re (R.range a b)
  (ReComp, [VRegLan r]) -> re (R.complement r)
  (ReDiff, VRegLan r : rest) -> VRegLan . foldl R.difference r <$> traverse asRe rest
  (ReLoop i j, [VRegLan r]) -> re (R.loop i j r)
  (RePower n, [VRegLan r]) -> re (R.power n r)
  -- Records
  (RecordMk names, _) -> pure (VRecord (zip names vs))
  (RecordGet f, [VRecord fs]) -> case lookup f fs of
    Just v -> pure v
    Nothing -> bad ("missing field " <> f)
  (RecordSet f, [VRecord fs, v]) ->
    pure (VRecord [(g, if g == f then v else u) | (g, u) <- fs])
  -- Floating point
  (FPConst eb sb x, []) -> pure (VFP eb sb x)
  (RMConst rm, []) -> pure (VRM rm)
  (FPFromFields, [VBV 1 sg, VBV eb e, VBV f m]) -> pure (VFP eb (f + 1) (F.fpFromFields eb (f + 1) sg e m))
  (FPAbs, [VFP eb sb x]) -> fp eb sb (F.fpAbs eb sb x)
  (FPNeg, [VFP eb sb x]) -> fp eb sb (F.fpNeg eb sb x)
  (FPAdd, [VRM rm, VFP eb sb x, VFP _ _ y]) -> fp eb sb (F.fpAdd rm eb sb x y)
  (FPSub, [VRM rm, VFP eb sb x, VFP _ _ y]) -> fp eb sb (F.fpSub rm eb sb x y)
  (FPMul, [VRM rm, VFP eb sb x, VFP _ _ y]) -> fp eb sb (F.fpMul rm eb sb x y)
  (FPDiv, [VRM rm, VFP eb sb x, VFP _ _ y]) -> fp eb sb (F.fpDiv rm eb sb x y)
  (FPFma, [VRM rm, VFP eb sb x, VFP _ _ y, VFP _ _ z]) -> fp eb sb (F.fpFma rm eb sb x y z)
  (FPSqrt, [VRM rm, VFP eb sb x]) -> fp eb sb (F.fpSqrt rm eb sb x)
  (FPRem, [VFP eb sb x, VFP _ _ y]) -> fp eb sb (F.fpRem F.RNE eb sb x y)
  (FPRoundToIntegral, [VRM rm, VFP eb sb x]) -> fp eb sb (F.fpRoundToIntegral rm eb sb x)
  (FPMin, [VFP eb sb x, VFP _ _ y]) -> unspecified (VFP eb sb x) (VFP eb sb <$> F.fpMin eb sb x y)
  (FPMax, [VFP eb sb x, VFP _ _ y]) -> unspecified (VFP eb sb x) (VFP eb sb <$> F.fpMax eb sb x y)
  (FPLeq, VFP eb sb _ : _) -> fpChain (F.fpLeq eb sb)
  (FPLt, VFP eb sb _ : _) -> fpChain (F.fpLt eb sb)
  (FPGeq, VFP eb sb _ : _) -> fpChain (flip (F.fpLeq eb sb))
  (FPGt, VFP eb sb _ : _) -> fpChain (flip (F.fpLt eb sb))
  (FPEq, VFP eb sb _ : _) -> fpChain (F.fpEq eb sb)
  (FPIsNormal, [VFP eb sb x]) -> bool (F.fpIsNormal eb sb x)
  (FPIsSubnormal, [VFP eb sb x]) -> bool (F.fpIsSubnormal eb sb x)
  (FPIsZero, [VFP eb sb x]) -> bool (case F.decode eb sb x of F.Zero _ -> True; _ -> False)
  (FPIsInfinite, [VFP eb sb x]) -> bool (case F.decode eb sb x of F.Inf _ -> True; _ -> False)
  (FPIsNaN, [VFP eb sb x]) -> bool (F.decode eb sb x == F.NaN)
  (FPIsNegative, [VFP eb sb x]) -> bool (fpSign eb sb x == Just True)
  (FPIsPositive, [VFP eb sb x]) -> bool (fpSign eb sb x == Just False)
  (ToFP eb sb, [VBV _ x]) -> pure (VFP eb sb (F.canonicalize eb sb x))
  (ToFP eb sb, [VRM rm, VFP eb' sb' x]) -> fp eb sb (F.fpConvert rm (eb', sb') (eb, sb) x)
  (ToFP eb sb, [VRM rm, VBV w x]) -> fp eb sb (F.fpFromInteger rm eb sb (bvToSigned w x))
  (ToFPUnsigned eb sb, [VRM rm, VBV _ x]) -> fp eb sb (F.fpFromInteger rm eb sb x)
  (FPToUBV w, [VRM rm, VFP eb sb x]) ->
    unspecified (VBV w 0) (VBV w <$> F.fpToInteger rm eb sb (0, bvMask w) x)
  (FPToSBV w, [VRM rm, VFP eb sb x]) ->
    unspecified (VBV w 0) (VBV w . bvNormalize w <$> F.fpToInteger rm eb sb (negate (2 ^ (w - 1)), 2 ^ (w - 1) - 1) x)
  _ -> bad "ill-sorted application"
  where
    fp eb sb x = pure (VFP eb sb x)
    unspecified def = \case
      Just v -> pure v
      Nothing -> pure (Map.findWithDefault def (op, vs) (interpUnspecified interp))
    fpChain rel = do
      xs <- traverse (\case VFP _ _ x -> Right x; v -> badArg v) vs
      bool (and (zipWith rel xs (drop 1 xs)))
    fpSign eb sb x = case F.decode eb sb x of
      F.NaN -> Nothing
      F.Inf neg -> Just neg
      F.Zero neg -> Just neg
      F.Finite neg _ -> Just neg
    bad msg = Left (EvalError op vs msg)
    re = pure . VRegLan
    asRe = \case
      VRegLan r -> pure r
      _ -> bad "expected a regular language"
    sameLanguage r = \case
      VRegLan r' -> case R.equivalent r r' of
        Just b -> pure b
        Nothing -> bad "regular expressions too large to compare"
      _ -> bad "expected a regular language"
    badArg v = Left (EvalError op vs ("unexpected argument " <> prettyValue v))
    bool = pure . VBool
    int = pure . VInt
    str = pure . VString
    bv w x = pure (VBV w (bvNormalize w x))

    asBool = \case VBool b -> Right b; v -> badArg v
    asInt = \case VInt n -> Right n; v -> badArg v
    asStr = \case VString s -> Right s; v -> badArg v
    asBV = \case VBV _ x -> Right x; v -> badArg v

    chain rel xs = bool (and (zipWith rel xs (drop 1 xs)))

    allDistinct [] = True
    allDistinct (x : xs) = notElem x xs && allDistinct xs

applyFun :: FunInterp -> [Value] -> Value
applyFun fi args = Map.findWithDefault (fiDefault fi) args (fiTable fi)

-- | Euclidean division: @a = b * q + r@ with @0 <= r < |b|@.
euclidean :: Integer -> Integer -> (Integer, Integer)
euclidean a b =
  let r = a `mod` abs b
   in ((a - r) `div` b, r)

udiv :: Int -> Integer -> Integer -> Integer
udiv w a b
  | b == 0 = bvMask w
  | otherwise = a `div` b

urem :: Integer -> Integer -> Integer
urem a b
  | b == 0 = a
  | otherwise = a `mod` b

msb :: Int -> Integer -> Bool
msb w x = testBit x (w - 1)

bvNegate :: Int -> Integer -> Integer
bvNegate w x = bvNormalize w (negate x)

sdiv :: Int -> Integer -> Integer -> Integer
sdiv w s t = case (msb w s, msb w t) of
  (False, False) -> udiv w s t
  (True, False) -> bvNegate w (udiv w (bvNegate w s) t)
  (False, True) -> bvNegate w (udiv w s (bvNegate w t))
  (True, True) -> udiv w (bvNegate w s) (bvNegate w t)

srem :: Int -> Integer -> Integer -> Integer
srem w s t = case (msb w s, msb w t) of
  (False, False) -> urem s t
  (True, False) -> bvNegate w (urem (bvNegate w s) t)
  (False, True) -> urem s (bvNegate w t)
  (True, True) -> bvNegate w (urem (bvNegate w s) (bvNegate w t))

smod :: Int -> Integer -> Integer -> Integer
smod w s t =
  let absS = if msb w s then bvNegate w s else s
      absT = if msb w t then bvNegate w t else t
      u = urem absS absT
   in if u == 0
        then u
        else case (msb w s, msb w t) of
          (False, False) -> u
          (True, False) -> bvNormalize w (bvNegate w u + t)
          (False, True) -> bvNormalize w (u + t)
          (True, True) -> bvNegate w u

-- | SMT-LIB @str.substr@: empty unless the offset is within bounds and the
-- length is positive.
substr :: Text -> Integer -> Integer -> Text
substr s i n
  | i < 0 || n <= 0 || i >= len = ""
  | otherwise = T.take (fromIntegral (min n (len - i))) (T.drop (fromIntegral i) s)
  where
    len = fromIntegral (T.length s)

-- | SMT-LIB @str.indexof@.
indexOf :: Text -> Text -> Integer -> Integer
indexOf s t i
  | i < 0 || i > len = -1
  | T.null t = i
  | otherwise =
      -- Note: 'T.breakOn' rejects an empty pattern, handled above.
      case T.breakOn t (T.drop (fromIntegral i) s) of
        (before, after)
          | T.null after -> -1
          | otherwise -> i + fromIntegral (T.length before)
  where
    len = fromIntegral (T.length s)

-- | SMT-LIB @str.replace@: replaces the first occurrence; an empty pattern
-- prepends the replacement.
replaceFirst :: Text -> Text -> Text -> Text
replaceFirst s t t'
  | T.null t = t' <> s
  | otherwise = case T.breakOn t s of
      (before, after)
        | T.null after -> s
        | otherwise -> before <> t' <> T.drop (T.length t) after