packages feed

hsmt-0.1.0.0: test/HSMT/SMTLibSpec.hs

module HSMT.SMTLibSpec (tests) where

import Data.Bits (complement, rotateL, rotateR, xor, (.&.), (.|.))
import qualified Data.Text as T
import Data.Word (Word8)
import Test.QuickCheck hiding ((.&.))
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck (testProperty)

import qualified Data.Map.Strict as Map

import HSMT.Core.Eval
import HSMT.Core.Expr
import HSMT.Core.Op
import HSMT.Core.Sort
import HSMT.Core.Value
import HSMT.Gen.Expr
import HSMT.SMTLib.Parser
import HSMT.SMT.Engine (EngineResult (..))
import HSMT.SMTLib.Printer
import HSMT.SMTLib.Run
import HSMT.SMTLib.Syntax

tests :: TestTree
tests =
  testGroup
    "SMT-LIB"
    [ testCase "string escapes" $ do
        renderString "a\"b" @?= "\"a\"\"b\""
        renderString "\\" @?= "\"\\u{5c}\""
        renderString "é" @?= "\"\\u{e9}\""
    , testCase "symbol quoting" $ do
        renderSymbol "x!0" @?= "x!0"
        renderSymbol "a b" @?= "|a b|"
        renderSymbol "1x" @?= "|1x|"
    , testCase "negative literals and degenerate connectives" $ do
        renderExpr (constant (IntConst (-3))) @?= "(- 3)"
        renderExpr (App And []) @?= "true"
        renderExpr (App Or [constant (BoolConst True)]) @?= "true"
    , testCase "parse errors are reported" $ do
        assertLeft (parseScript "(assert x)")
        assertLeft (parseScript "(declare-const x Int) (assert x)")
        assertLeft (parseScript "(assert (and true)")
    , testCase "define-fun macros are expanded" $
        case parseScript "(define-fun f ((x Int)) Bool (> x 0)) (assert (f 3))" of
          Right [DefineFun {}, Assert e] -> evalExpr emptyInterpretation e @?= Right (VBool True)
          other -> assertFailure (show other)
    , testCase "string literal escapes are resolved" $
        case parseScript "(assert (= \"a\"\"\\u{5c}\\u00e9\" \"\"))" of
          Right [Assert (App Eq [App (StrConst s) [], _])] -> s @?= "a\"\\é"
          other -> assertFailure (show other)
    , testCase "let, define-const and define-sort" $
        case parseScript
          ( T.unlines
              [ "(define-sort Byte () (_ BitVec 8))"
              , "(define-const k Byte #x0f)"
              , "(declare-const x Int)"
              , "(assert (let ((x 2) (y x)) (let ((x (+ x 1))) (and (= x 3) (= y x) (= k (bvand k #xff))))))"
              ]
          ) of
          Right [DefineFun {}, DeclareFun _, Assert e] ->
            -- The inner y is the declared x, not a let-bound one.
            let x3 = Interpretation (Map.singleton (Symbol "x" [] IntSort) (constInterp (VInt 3))) z z Map.empty
                z = constInterp (VInt 0)
             in evalExpr x3 e @?= Right (VBool True)
          other -> assertFailure (show other)
    , testCase "declarations are scoped by push and pop" $ do
        assertRight (parseScript "(push 1) (declare-const x Int) (pop 1) (declare-const x Bool) (assert x)")
        assertLeft (parseScript "(push 1) (declare-const y Int) (pop 1) (assert (> y 0))")
        assertLeft (parseScript "(push 1) (pop 2)")
        assertRight (parseScript "(declare-const y Int) (reset) (declare-const y Bool)")
    , testProperty "derived bit-vector operators" prop_bvDerived
    , testCase "script responses" $ do
        rs <-
          runScriptResponses True $
            T.unlines
              [ "(set-option :print-success true)"
              , "(declare-fun f (Int) Int)"
              , "(declare-const x Int)"
              , "(assert (and (= (f x) 5) (= x 2)))"
              , "(get-model)"
              , "(check-sat)"
              , "(get-value ((f x) (+ x 1)))"
              , "(assert (> y 0))"
              , "(get-info :reason-unknown)"
              , "(get-info :error-behavior)"
              , "(get-info :no-such-key)"
              , "(get-assertions)"
              , "(echo \"ok\")"
              , "(exit)"
              , "(check-sat)"
              ]
        map renderResponse rs
          @?= [ "success"
              , "success"
              , "success"
              , "success"
              , "(error \"no model available\")"
              , "sat"
              , "(((f x) 5)\n ((+ x 1) 3))"
              , "(error \"unknown symbol: y in (assert (> y 0))\")"
              , "(error \"the last check did not answer unknown\")"
              , "(:error-behavior continued-execution)"
              , "unsupported"
              , "((and (= (f x) 5) (= x 2)))"
              , "\"ok\""
              , "success"
              ]
    , testCase "get-model answers a model that checks" $ do
        let decls =
              [ "(declare-sort U 0)"
              , "(declare-fun g (U) U)"
              , "(declare-const a U)"
              , "(declare-const s String)"
              , "(declare-const arr (Array Int Int))"
              ]
            constraints =
              [ "(assert (distinct a (g a) (g (g a))))"
              , "(assert (= (str.len s) (select arr 4)))"
              , "(assert (> (select arr 4) 2))"
              ]
        model <-
          runScriptResponses True (T.unlines (decls <> constraints <> ["(check-sat)", "(get-model)"])) >>= \case
            [CheckResult _, m@(Model _ _)] -> pure (renderResponse m)
            other -> assertFailure (show other)
        -- The model, read as definitions, satisfies the constraints.
        let defs = T.unlines (drop 1 (init (T.lines model)))
            check = T.unlines ["(declare-sort U 0)", defs] <> T.unlines constraints <> "(check-sat)"
        runScriptText True check >>= \case
          Right [r] -> show r `seq` assertBool (T.unpack check) (isSat r)
          other -> assertFailure (T.unpack check <> show other)
    , testProperty "print/parse round trip" prop_roundTrip
    ]
  where
    assertLeft = either (const (pure ())) (assertFailure . ("expected an error, got " <>) . show)
    assertRight = either (assertFailure . T.unpack) (const (pure ()))
    isSat = \case
      ESat _ -> True
      _ -> False

-- | The operators the parser defines through others agree with
-- "Data.Bits".
prop_bvDerived :: Word8 -> Word8 -> Int -> Property
prop_bvDerived a b k0 =
  conjoin
    [ check ("((_ rotate_left " <> show k <> ") " <> lit a <> ")") (rotateL a k)
    , check ("((_ rotate_right " <> show k <> ") " <> lit a <> ")") (rotateR a k)
    , check ("(bvnand " <> lit a <> " " <> lit b <> ")") (complement (a .&. b))
    , check ("(bvnor " <> lit a <> " " <> lit b <> ")") (complement (a .|. b))
    , check ("(bvxnor " <> lit a <> " " <> lit b <> ")") (complement (a `xor` b))
    , value ("(bvcomp " <> lit a <> " " <> lit b <> ")") === Right (VBV 1 (if a == b then 1 else 0))
    , value ("((_ repeat 2) " <> lit a <> ")") === Right (VBV 16 (toInteger a * 257))
    ]
  where
    k = k0 `mod` 20
    lit x = "(_ bv" <> show x <> " 8)"
    check t r = counterexample t (value t === Right (VBV 8 (toInteger r)))
    value t = case parseScript (T.pack ("(define-const v (_ BitVec " <> width t <> ") " <> t <> ")")) of
      Right [DefineFun _ _ e] -> either (Left . show) Right (evalExpr emptyInterpretation e)
      other -> Left (show other)
    width t
      | "(bvcomp" `isPrefix` t = "1"
      | "((_ repeat" `isPrefix` t = "16"
      | otherwise = "8"
    isPrefix p t = take (length p) t == p

-- | Printing a problem and parsing it back gives the same assertions, up to
-- the expansions the printer performs.
prop_roundTrip :: Property
prop_roundTrip =
  forAllShrink (genProblem allTheoriesConfig) shrinkProblem $ \as ->
    let txt = renderScript (problemScript as)
     in counterexample (show txt) $ case parseScript txt of
          Left err -> counterexample (show err) False
          Right cmds -> [e | Assert e <- cmds] === map normalize as

-- | The printer expands record updates and degenerate connectives, and the
-- parser reads the negation of a numeral as a negative literal.
normalize :: Expr -> Expr
normalize (App Neg [App (IntConst n) []]) | n >= 0 = constant (IntConst (negate n))
normalize (App op args) = case (op, map normalize args) of
  (And, []) -> constant (BoolConst True)
  (And, [a]) -> a
  (Or, []) -> constant (BoolConst False)
  (Or, [a]) -> a
  (RecordSet f, [r, v]) | RecordSort fs <- sortOfExpr r ->
    App (RecordMk (map fst fs)) [if g == f then v else App (RecordGet g) [r] | (g, _) <- fs]
  (_, args') -> App op args'