packages feed

hsmt-0.1.0.0: test/HSMT/EUFSpec.hs

{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ExplicitNamespaces #-}
module HSMT.EUFSpec (tests) where

import Control.Monad (forM_)
import Data.List (nub, zip4)
import qualified Data.Text as T
import qualified Data.Map.Strict as Map
import Test.QuickCheck.Monadic (monadicIO, run)
import qualified Test.QuickCheck.Monadic as QC
import Test.Tasty
import Test.Tasty.HUnit hiding (assert)
import Test.Tasty.QuickCheck

import GHC.TypeLits (KnownNat, type (<=))

import HSMT

type U = 'UninterpS "U"

isSat, isUnsat :: Result ctx -> Bool
isSat = \case Sat _ -> True; _ -> False
isUnsat = \case Unsat _ -> True; _ -> False

checkUnsat :: (forall ctx. SMT ctx ()) -> Assertion
checkUnsat setup = do
  r <- runSMT defaultConfig (setup >> checkSat >>= pure . describe)
  r @?= "unsat"

checkSatisfiable :: (forall ctx. SMT ctx ()) -> Assertion
checkSatisfiable setup = do
  r <- runSMT defaultConfig (setup >> checkSat >>= pure . describe)
  r @?= "sat"

describe :: Result ctx -> String
describe = \case
  Sat _ -> "sat"
  Unsat _ -> "unsat"
  Unknown why -> "unknown: " <> show why

-------------------------------------------------------------------------------
-- Random ground formulas with a brute-force oracle

-- | Terms over constants a, b, c, the literals 0 and 1, and a unary f.
data T = A | B | C | Lit Integer | F T
  deriving (Eq, Ord, Show)

data Fm = EqT T T | NotF Fm | AndF Fm Fm | OrF Fm Fm
  deriving (Show)

genT :: Bool -> Gen T
genT withLits = sized (\n -> go (min 3 n))
  where
    leaves = [A, B, C] ++ (if withLits then [Lit 0, Lit 1] else [])
    go 0 = elements leaves
    go d = frequency [(3, elements leaves), (2, F <$> go (d - 1))]

-- | A conjunction of small clauses over equalities and disequalities, which
-- yields a good mix of satisfiable and unsatisfiable problems.
genFm :: Bool -> Gen Fm
genFm withLits = do
  n <- chooseInt (2, 7)
  clauses <- vectorOf n clause
  pure (foldr1 AndF clauses)
  where
    atom = do
      e <- EqT <$> genT withLits <*> genT withLits
      positive <- frequency [(2, pure True), (1, pure False)]
      pure (if positive then e else NotF e)
    clause = do
      k <- frequency [(3, pure 1), (2, pure 2)]
      foldr1 OrF <$> vectorOf k atom

-- | Formulas with few distinct terms, so that enumerating partitions (Bell
-- numbers) stays cheap.
smallFm :: Bool -> Gen Fm
smallFm withLits = genFm withLits `suchThat` ((<= 8) . length . termsOf)

subtermsOf :: T -> [T]
subtermsOf t = t : case t of
  F u -> subtermsOf u
  _ -> []

termsOf :: Fm -> [T]
termsOf = nub . concatMap subtermsOf . go
  where
    go = \case
      EqT a b -> [a, b]
      NotF f -> go f
      AndF f g -> go f ++ go g
      OrF f g -> go f ++ go g

-- | All partitions of a list, as maps from element to block index.
partitions :: [T] -> [Map.Map T Int]
partitions = go Map.empty 0
  where
    go acc _ [] = [acc]
    go acc nBlocks (x : xs) =
      concat [go (Map.insert x b acc) (max nBlocks (b + 1)) xs | b <- [0 .. nBlocks]]

-- | A partition is a model when it respects congruence and literals, and
-- does not need more values than the sort has.
consistent :: Maybe Int -> [T] -> Map.Map T Int -> Bool
consistent card ts p = congruent && literalsDistinct && fits
  where
    fits = maybe True (\k -> length (nub (Map.elems p)) <= k) card
    same x y = p Map.! x == p Map.! y
    congruent = and [same (F x) (F y) | F x <- ts, F y <- ts, same x y]
    literalsDistinct = and [not (same x y) | x@(Lit i) <- ts, y@(Lit j) <- ts, i /= j]

holds :: Map.Map T Int -> Fm -> Bool
holds p = \case
  EqT a b -> p Map.! a == p Map.! b
  NotF f -> not (holds p f)
  AndF f g -> holds p f && holds p g
  OrF f g -> holds p f || holds p g

bruteForceSat :: Maybe Int -> Fm -> Bool
bruteForceSat card f =
  let ts = termsOf f
   in any (\p -> consistent card ts p && holds p f) (partitions ts)

prop_eufAgreesWithBruteForce :: Property
prop_eufAgreesWithBruteForce = forAll (smallFm False) $ \fm -> monadicIO $ do
  r <- run (solveU fm)
  let expected = bruteForceSat Nothing fm
  QC.monitor (cover 20 expected "sat" . cover 10 (not expected) "unsat")
  QC.monitor (cover 20 (length (termsOf fm) >= 5) "at least 5 terms")
  QC.assert (r == if expected then "sat" else "unsat")
  where
    solveU fm = runSMT defaultConfig $ do
      a <- declare @U "a"
      b <- declare @U "b"
      c <- declare @U "c"
      f <- declareFun @'[U] @U "f"
      let term = \case
            A -> a
            B -> b
            C -> c
            F t -> f (term t)
            Lit _ -> error "no literals in U"
      assert (toFormula term fm)
      describe <$> checkSat

prop_eufWithLiterals :: Property
prop_eufWithLiterals = forAll (smallFm True) $ \fm -> monadicIO $ do
  r <- run (solveInt fm)
  let expected = bruteForceSat Nothing fm
  QC.monitor (cover 20 expected "sat" . cover 10 (not expected) "unsat")
  QC.monitor (cover 20 (length (termsOf fm) >= 5) "at least 5 terms")
  QC.assert (r == if expected then "sat" else "unsat")
  where
    solveInt fm = runSMT defaultConfig $ do
      a <- declare @'IntS "a"
      b <- declare @'IntS "b"
      c <- declare @'IntS "c"
      f <- declareFun @'[ 'IntS] @'IntS "f"
      let term = \case
            A -> a
            B -> b
            C -> c
            Lit n -> int n
            F t -> f (term t)
      assert (toFormula term fm)
      describe <$> checkSat

-- | Finite sorts: bit-vectors of width 1 and 2, with literals 0 and 1.
prop_eufFiniteSort :: Int -> Property
prop_eufFiniteSort width = forAll (smallFm True) $ \fm -> monadicIO $ do
  r <- run (if width == 1 then solveBV @1 fm else solveBV @2 fm)
  let expected = bruteForceSat (Just (2 ^ width)) fm
  QC.monitor (cover 20 expected "sat" . cover 10 (not expected) "unsat")
  QC.assert (r == if expected then "sat" else "unsat")

solveBV :: forall w. (KnownNat w, 1 <= w) => Fm -> IO String
solveBV fm = runSMT defaultConfig $ do
  a <- declare @('BVS w) "a"
  b <- declare @('BVS w) "b"
  c <- declare @('BVS w) "c"
  f <- declareFun @'[ 'BVS w] @('BVS w) "f"
  let term = \case
        A -> a
        B -> b
        C -> c
        Lit n -> fromInteger n
        F t -> f (term t)
  assert (toFormula term fm)
  describe <$> checkSat

toFormula :: (T -> Expr ctx s) -> Fm -> Expr ctx 'BoolS
toFormula term = go
  where
    go = \case
      EqT x y -> term x .== term y
      NotF g -> notB (go g)
      AndF g h -> go g .&& go h
      OrF g h -> go g .|| go h

-- | x0 = x1 = ... = xn through either branch of each diamond, and x0 /= xn.
diamonds :: Int -> SMT ctx ()
diamonds n = do
  let v p i = declare @U (T.pack (p <> show i))
  xs <- mapM (v "x") [0 .. n]
  ys <- mapM (v "y") [0 .. n - 1]
  zs <- mapM (v "z") [0 .. n - 1]
  forM_ (zip4 xs (drop 1 xs) ys zs) $ \(xi, xj, yi, zi) ->
    assert ((xi .== yi .&& yi .== xj) .|| (xi .== zi .&& zi .== xj))
  case (xs, reverse xs) of
    (x0 : _, xn : _) -> assert (x0 ./= xn)
    _ -> pure ()

-------------------------------------------------------------------------------

tests :: TestTree
tests =
  testGroup
    "EUF"
    [ testCase "congruence" $ checkUnsat $ do
        x <- declare @U "x"
        y <- declare @U "y"
        f <- declareFun @'[U] @U "f"
        assert (x .== y)
        assert (f x ./= f y)
    , testCase "transitivity" $ checkUnsat $ do
        x <- declare @U "x"
        y <- declare @U "y"
        z <- declare @U "z"
        assert (x .== y .&& y .== z .&& x ./= z)
    , testCase "f^3(a) = a and f^5(a) = a imply f(a) = a" $ checkUnsat $ do
        a <- declare @U "a"
        f <- declareFun @'[U] @U "f"
        let iter n = foldr (const f) a [1 .. n :: Int]
        assert (iter 3 .== a)
        assert (iter 5 .== a)
        assert (f a ./= a)
    , testCase "binary functions" $ checkUnsat $ do
        a <- declare @U "a"
        b <- declare @U "b"
        g <- declareFun @'[U, U] @U "g"
        assert (g a b .== a)
        assert (g (g a b) b ./= a)
    , testCase "distinct literals" $ checkUnsat $ do
        x <- declare @'IntS "x"
        assert (x .== 1 .&& x .== 2)
    , testCase "functions over literals" $ checkUnsat $ do
        x <- declare @'IntS "x"
        f <- declareFun @'[ 'IntS] @'IntS "f"
        assert (x .== 1 .&& f x .== 2 .&& f 1 .== 3)
    , testCase "string and bit-vector literals" $ do
        checkUnsat $ do
          s <- declare @'StringS "s"
          assert (s .== "a" .&& s .== "b")
        checkUnsat $ do
          v <- declare @('BVS 8) "v"
          assert (v .== 3 .&& v .== 4)
    , testCase "ite over terms" $ checkUnsat $ do
        p <- declare @'BoolS "p"
        a <- declare @U "a"
        b <- declare @U "b"
        y <- declare @U "y"
        assert (y .== ite p a b)
        assert (y ./= a .&& y ./= b)
    , testCase "Boolean-valued functions" $ checkUnsat $ do
        x <- declare @U "x"
        y <- declare @U "y"
        p <- declareFun @'[U] @'BoolS "p"
        assert (p x .&& notB (p y) .&& x .== y)
    , testCase "Boolean arguments" $ checkUnsat $ do
        q <- declare @'BoolS "q"
        g <- declareFun @'[ 'BoolS] @U "g"
        assert (q .&& g true ./= g q)
    , testCase "distinct is satisfiable over an infinite sort" $ checkSatisfiable $ do
        xs <- mapM (\n -> declare @U n) ["a", "b", "c", "d"]
        assert (distinct xs)
    , testCase "a sat model is usable" $ do
        r <- runSMT defaultConfig $ do
          x <- declare @'IntS "x"
          y <- declare @'IntS "y"
          f <- declareFun @'[ 'IntS] @'IntS "f"
          assert (f x .== 7 .&& f y ./= 7 .&& x ./= 5)
          checkSat >>= \case
            Sat m -> pure (Just (eval m (f x), eval m x /= eval m y))
            _ -> pure Nothing
        r @?= Just (7, True)
    , testCase "bit-vector domains are finite" $ do
        checkUnsat $ do
          xs <- mapM (\n -> declare @('BVS 1) n) ["a", "b", "c"]
          assert (distinct xs)
        checkSatisfiable $ do
          xs <- mapM (\n -> declare @('BVS 1) n) ["a", "b"]
          assert (distinct xs)
        -- Pigeonhole through congruence: f maps 2 values to 3 distinct ones.
        checkUnsat $ do
          xs <- mapM (\n -> declare @('BVS 1) n) ["a", "b", "c"]
          f <- declareFun @'[ 'BVS 1] @U "f"
          assert (distinct (map f xs))
    , testCase "the only value left is chosen" $ do
        r <- runSMT defaultConfig $ do
          x <- declare @('BVS 2) "x"
          assert (distinct [x, 0, 1, 2])
          checkSat >>= \case
            Sat m -> pure (Just (eval m x))
            _ -> pure Nothing
        r @?= Just (BitVector 3)
    , testCase "incremental use" $ do
        r <- runSMT defaultConfig $ do
          x <- declare @U "x"
          y <- declare @U "y"
          f <- declareFun @'[U] @U "f"
          assert (f x ./= f y)
          r1 <- isSat <$> checkSat
          r2 <- scoped (assert (x .== y) >> isUnsat <$> checkSat)
          r3 <- isSat <$> checkSat
          pure (r1, r2, r3)
        r @?= (True, True, True)
    , localOption (mkTimeout 30000000) $
        testCase "chains of diamonds (need transitivity lemmas)" $
          -- 110 used to hang when only one branch of a diamond could derive
          -- the shortcut equality.
          mapM_ (\n -> checkUnsat (diamonds n)) [20, 60, 110, 150]
    , testProperty "agrees with brute force (uninterpreted sort)" (checkCoverage (withMaxSuccess 1500 prop_eufAgreesWithBruteForce))
    , testProperty "agrees with brute force (1-bit vectors)" (checkCoverage (withMaxSuccess 1500 (prop_eufFiniteSort 1)))
    , testProperty "agrees with brute force (2-bit vectors)" (checkCoverage (withMaxSuccess 1500 (prop_eufFiniteSort 2)))
    , testProperty "agrees with brute force (integers with literals)" (checkCoverage (withMaxSuccess 1500 prop_eufWithLiterals))
    ]