packages feed

hsmt-0.1.0.0: test/HSMT/TutorialSpec.hs

{-# LANGUAGE OverloadedLabels #-}

-- | The examples of "HSMT.Tutorial", with the answers it states.
module HSMT.TutorialSpec (tests) where

import Data.Char (isAsciiLower, isAsciiUpper, isDigit)
import Data.Text (Text)
import qualified Data.Text as T
import System.Directory (findExecutable)
import System.Environment (lookupEnv)
import Test.Tasty
import Test.Tasty.HUnit hiding (assert)

import HSMT

example :: IO (Maybe (Integer, Integer))
example = runSMT defaultConfig $ do
  x <- declare @IntS "x"
  y <- declare @IntS "y"
  assert (x + y .== 10)
  assert (x - y .== 4)
  checkSat >>= \case
    Sat m -> pure (Just (eval m x, eval m y))
    _ -> pure Nothing

multipleOfSix :: IO Bool
multipleOfSix = runSMT defaultConfig $ do
  n <- declare @IntS "n"
  assert (n .> 7 .&& n .< 9)
  assert (n `imod` 2 .== 0 .&& n `imod` 3 .== 0)
  checkSat >>= \case
    Unsat _ -> pure False
    _ -> pure True

powerOfTwo :: IO (Maybe (BitVector 16))
powerOfTwo = runSMT defaultConfig $ do
  x <- declare @(BVS 16) "x"
  assert (bvAnd x (x - 1) .== 0)
  assert (bvUGt x 1000)
  assert (bvULt x 2000)
  checkSat >>= \case
    Sat m -> pure (Just (eval m x))
    _ -> pure Nothing

swapTwice :: IO Bool
swapTwice = runSMT defaultConfig $ do
  a <- declare @(ArrayS IntS IntS) "a"
  i <- declare @IntS "i"
  j <- declare @IntS "j"
  let swap b = store (store b i (select b j)) j (select b i)
  assert (swap (swap a) ./= a)
  checkSat >>= \case
    Unsat _ -> pure True
    _ -> pure False

greeting :: IO (Maybe Text)
greeting = runSMT defaultConfig $ do
  name <- declare @StringS "name"
  let s = "hello, " <+> name
  assert (strLen s .== 10)
  assert (suffixOf "!" name .&& contains name "b")
  checkSat >>= \case
    Sat m -> pure (Just (eval m s))
    _ -> pure Nothing

identifier :: IO (Maybe Text)
identifier = runSMT defaultConfig $ do
  s <- declare @StringS "s"
  let letter = reUnion [reRange 'a' 'z', reRange 'A' 'Z']
      ident = reConcat [letter, reStar (reUnion [letter, reRange '0' '9'])]
  assert (inRe s (reInter [ident, reLoop 3 5 reAllChar]))
  assert (notB (inRe s (reUnion ["else", "then"])))
  assert (contains s "9")
  checkSat >>= \case
    Sat m -> pure (Just (eval m s))
    _ -> pure Nothing

congruence :: IO Bool
congruence = runSMT defaultConfig $ do
  f <- declareFun @'[UninterpS "U"] @(UninterpS "U") "f"
  a <- declare @(UninterpS "U") "a"
  assert (f (f (f a)) .== a)
  assert (f (f (f (f (f a)))) .== a)
  assert (f a ./= a)
  checkSat >>= \case
    Unsat _ -> pure True
    _ -> pure False

type Point = RecordS '[ '("x", IntS), '("y", IntS)]

reflection :: IO (Maybe (Integer, Integer))
reflection = runSMT defaultConfig $ do
  p <- declare @Point "p"
  let q = record (#x := p ! #y :& #y := p ! #x :& FNil)
  assert (q .== setField #x 3 p)
  assert (p ! #x .> 0)
  checkSat >>= \case
    Sat m -> pure (Just (field #x (eval m p), field #y (eval m p)))
    _ -> pure Nothing

notReflexive :: IO (Maybe Bool)
notReflexive = runSMT defaultConfig $ do
  x <- declare @Float32S "x"
  assert (notB (fpEq x x))
  checkSat >>= \case
    Sat m -> pure (Just (isNaN (toFloat (eval m x))))
    _ -> pure Nothing

conflicting :: IO [Int]
conflicting = runSMT defaultConfig {cfgMinimizeCores = True} $ do
  x <- declare @IntS "x"
  labels <- mapM (\i -> declare @BoolS ("c" <> T.pack (show i))) [0 .. 3 :: Int]
  let constraints = [x .> 10, x .< 20, x .== 5, x .> 0]
  sequence_ [assert (l .=> c) | (l, c) <- zip labels constraints]
  checkSatAssuming labels >>= \case
    Unsat core -> pure [i | (i, l) <- zip [0 ..] labels, l `elem` coreAssumptions core]
    _ -> pure []

viaZ3 :: IO (Maybe (Integer, Integer))
viaZ3 = runSMT defaultConfig {cfgBackend = External z3Backend} $ do
  x <- declare @IntS "x"
  y <- declare @IntS "y"
  assert (x * y .== 12 .&& x .> y .&& y .> 1)
  checkSat >>= \case
    Sat m -> pure (Just (eval m x, eval m y))
    _ -> pure Nothing

-- | Whether Z3 can be found as 'z3Backend' finds it.
haveZ3 :: IO Bool
haveZ3 =
  lookupEnv "HSMT_Z3" >>= \case
    Just p | not (null p) -> pure True
    _ -> (/= Nothing) <$> findExecutable "z3"

isAsciiLetter :: Char -> Bool
isAsciiLetter c = isAsciiLower c || isAsciiUpper c

tests :: TestTree
tests =
  testGroup
    "tutorial"
    [ testCase "getting started" $ example >>= (@?= Just (7, 3))
    , testCase "integers" $ multipleOfSix >>= (@?= False)
    , testCase "bit-vectors" $ powerOfTwo >>= (@?= Just (BitVector 1024))
    , testCase "arrays" $ swapTwice >>= (@?= True)
    , testCase "strings" $
        greeting >>= \case
          Just s -> do
            T.length s @?= 10
            assertBool (show s) ("hello, " `T.isPrefixOf` s && "!" `T.isSuffixOf` s && T.isInfixOf "b" (T.drop 7 s))
          Nothing -> assertFailure "no model"
    , testCase "regular expressions" $
        identifier >>= \case
          Just s -> assertBool (show s) $
            T.length s >= 3 && T.length s <= 5 && T.any (== '9') s
              && isAsciiLetter (T.head s) && T.all (\c -> isAsciiLetter c || isDigit c) s
          Nothing -> assertFailure "no model"
    , testCase "uninterpreted functions" $ congruence >>= (@?= True)
    , testCase "records" $ reflection >>= (@?= Just (3, 3))
    , testCase "floating point" $ notReflexive >>= (@?= Just True)
    , testCase "unsatisfiable cores" $ conflicting >>= (@?= [0, 2])
    , testCase "external solvers (skipped without z3)" $ do
        z3 <- haveZ3
        if z3
          then viaZ3 >>= \r -> assertBool (show r) (r `elem` [Just (6, 2), Just (4, 3)])
          else pure ()
    ]