hsmt-0.1.0.0: test-diff/Differential/Z3.hs
-- | Running Z3 as an external process.
module Differential.Z3
( Z3 (..)
, findZ3
, runZ3
) where
import Control.Exception (IOException, try)
import qualified Data.Text as T
import System.Directory (findExecutable)
import System.Environment (lookupEnv)
import System.Exit (ExitCode (..))
import System.Process (proc, readCreateProcessWithExitCode)
import System.Timeout (timeout)
import HSMT.SMTLib.Syntax
data Z3 = Z3
{ z3Path :: FilePath
, z3TimeoutSecs :: Int
, z3Options :: [String]
-- ^ Extra @param=value@ settings.
}
-- | Locate Z3 through @HSMT_Z3@ or the @PATH@.
findZ3 :: IO (Maybe FilePath)
findZ3 =
lookupEnv "HSMT_Z3" >>= \case
Just p | not (null p) -> pure (Just p)
_ -> findExecutable "z3"
-- | Run a script and return the answers of its @check-sat@ commands. Z3
-- errors (including rejected input) are reported as 'Left'; a timeout
-- yields 'AnsUnknown' answers.
runZ3 :: Z3 -> T.Text -> IO (Either T.Text [Answer])
runZ3 z3 script = do
let args = ["-in", "-smt2", "-T:" <> show (z3TimeoutSecs z3)] <> z3Options z3
run = readCreateProcessWithExitCode (proc (z3Path z3) args) (T.unpack script)
r <- timeout ((z3TimeoutSecs z3 + 5) * 1000000) (try run)
pure $ case r of
Nothing -> Right [AnsUnknown]
Just (Left (e :: IOException)) -> Left ("cannot run z3: " <> T.pack (show e))
Just (Right (code, out, err)) -> do
let ls = filter (not . T.null) (map T.strip (T.lines (T.pack out)))
errors = filter ("(error" `T.isPrefixOf`) ls
case (errors, code) of
(e : _, _) -> Left e
([], ExitFailure _) | not (null err) -> Left (T.pack err)
_ -> traverse answer ls
where
answer = \case
"sat" -> Right AnsSat
"unsat" -> Right AnsUnsat
"unknown" -> Right AnsUnknown
"timeout" -> Right AnsUnknown
other -> Left ("unexpected z3 output: " <> other)