packages feed

hsmt-0.1.0.0: bench/Main.hs

-- | Runs the SMT-LIB benchmarks in @bench/smtlib@ with hsmt and, when it
-- is available (through @HSMT_Z3@ or the @PATH@), with Z3, and prints the
-- answers and times of both.
--
-- > cabal bench --benchmark-options='--timeout=30 QF_BV'
--
-- Options: @--timeout=SECS@ (per check for hsmt, per file for Z3; default
-- 10) and substrings that select files. hsmt runs in this process and Z3
-- as a separate one, so Z3 times include starting it (a few
-- milliseconds). The program fails when hsmt gives an answer that
-- contradicts the @:status@ annotation of a file.
module Main (main) where

import Control.Exception (SomeException, evaluate, try)
import Data.IORef
import Data.List (isInfixOf, isPrefixOf, stripPrefix)
import Data.Maybe (fromMaybe, mapMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import GHC.Clock (getMonotonicTime)
import System.Directory (findExecutable)
import System.Environment (getArgs, lookupEnv)
import System.Exit (exitFailure)
import System.FilePath ((</>))
import System.IO (BufferMode (..), hSetBuffering, stdout)
import System.Process (readProcessWithExitCode)
import System.Timeout (timeout)
import Text.Printf (printf)
import Text.Read (readMaybe)

import HSMT.Benchmarks
import HSMT.SMT.Engine (CheckOptions (..), defaultCheckOptions)
import HSMT.SMTLib.Run

data Run = Run
  { runAnswers :: [Text]
  , runSeconds :: Double
  }

main :: IO ()
main = do
  hSetBuffering stdout LineBuffering
  args <- getArgs
  let secs = fromMaybe 10 (mapMaybe (\a -> stripPrefix "--timeout=" a >>= readMaybe) args `at` 0)
      filters = filter (not . ("--" `isPrefixOf`)) args
  files <- filter (\f -> null filters || any (`isInfixOf` f) filters) <$> benchmarkFiles
  z3 <- lookupEnv "HSMT_Z3" >>= maybe (findExecutable "z3") (pure . Just)
  printf "%-42s %-24s %-24s %8s   %-24s %8s\n" ("benchmark" :: String) ("expected" :: String) ("hsmt" :: String) ("" :: String) (maybe "z3 (absent)" (const "z3") z3 :: String) ("" :: String)
  rows <- mapM (bench secs z3) files
  let checks = concat [zip e (runAnswers h) | (e, h, _) <- rows]
      wrong = length [() | (e, a) <- checks, a `elem` ["sat", "unsat"], e `elem` ["sat", "unsat"], a /= e]
      solved = length [() | (e, a) <- checks, a == e]
      z3Solved = length [() | (e, _, Just z) <- rows, (x, a) <- zip e (runAnswers z), x == a]
      total f = sum [runSeconds (f r) | r <- rows]
  printf "\n%d files, %d checks\n" (length rows) (length checks)
  printf "hsmt: %d solved, %d wrong, %.2f s in total\n" solved wrong (total (\(_, h, _) -> h))
  case z3 of
    Just _ -> printf "z3:   %d solved, %.2f s in total\n" z3Solved (total (\(_, _, z) -> maybe (Run [] 0) id z))
    Nothing -> pure ()
  if wrong > 0 then exitFailure else pure ()
  where
    at xs i = if length xs > i then Just (xs !! i) else Nothing

bench :: Double -> Maybe FilePath -> FilePath -> IO ([Text], Run, Maybe Run)
bench secs z3 file = do
  txt <- T.readFile (benchmarkDir </> file)
  let expected = expectedStatuses txt
  h <- runHsmt secs txt
  z <- traverse (\exe -> runZ3 secs exe (benchmarkDir </> file)) z3
  let mark :: Run -> String
      mark r = if runAnswers r == expected then " " else "*"
  printf
    "%-42s %-24s %-24s %7.2fs%s  %-24s %s\n"
    file
    (T.unpack (T.unwords expected))
    (T.unpack (T.unwords (runAnswers h)))
    (runSeconds h)
    (mark h)
    (maybe "" (T.unpack . T.unwords . runAnswers) z)
    (maybe "" (\r -> printf "%7.2fs%s" (runSeconds r) (mark r)) z :: String)
  pure (expected, h, z)

runHsmt :: Double -> Text -> IO Run
runHsmt secs txt = do
  out <- newIORef []
  start <- getMonotonicTime
  let opts = defaultCheckOptions {coTimeout = Just secs}
      record = \case
        CheckResult r -> modifyIORef' out (answerText r :)
        CommandError e -> modifyIORef' out (("error: " <> e) :)
        _ -> pure ()
  r <- try (runScriptWith opts (\x -> record x >> evaluate ()) txt)
  end <- getMonotonicTime
  answers <- reverse <$> readIORef out
  pure $ case r of
    Left (e :: SomeException) -> Run (answers <> ["crash: " <> T.pack (show e)]) (end - start)
    Right () -> Run (map short answers) (end - start)
  where
    short a = if "error" `T.isPrefixOf` a then "error" else a

runZ3 :: Double -> FilePath -> FilePath -> IO Run
runZ3 secs exe file = do
  start <- getMonotonicTime
  r <- timeout (round ((secs + 5) * 1e6)) (readProcessWithExitCode exe ["-T:" <> show (ceiling secs :: Int), file] "")
  end <- getMonotonicTime
  let answers = case r of
        Nothing -> ["timeout"]
        Just (_, out, _) ->
          [ if "(error" `T.isPrefixOf` l then "error" else l
          | l <- T.lines (T.pack out)
          , any (`T.isPrefixOf` l) ["sat", "unsat", "unknown", "timeout", "(error"]
          ]
  pure (Run answers (end - start))