packages feed

hsmt-0.1.0.0: src/HSMT/SMTLib/Run.hs

-- | Execution of SMT-LIB scripts with the hsmt engine or an external
-- solver ("HSMT.Backend").
--
-- All checks of a script run in one incremental session
-- (t'HSMT.SMT.Engine.Session', or one external solver process). Models
-- of external solvers are read back, so @get-model@ and @get-value@ are
-- answered by hsmt in both cases. Scripts are elaborated and executed command
-- by command: a command with an error answers @(error ...)@ and the script
-- goes on, as the @:error-behavior@ @continued-execution@ of SMT-LIB 2.6
-- describes.
--
-- Besides the standard options (@:print-success@, @:produce-models@ and the
-- like, which are accepted), the options @:timeout@ (milliseconds per check)
-- and @:smt.core.minimize@ (as in Z3) are honored. With an external
-- solver, @get-unsat-core@ gives a small core only under
-- @:produce-unsat-cores true@ (as SMT-LIB requires); otherwise it names
-- every assertion.
module HSMT.SMTLib.Run
  ( -- * Responses
    Response (..)
  , renderResponse
    -- * Running scripts
  , runScriptWith
  , runScriptWithBackend
  , runScriptResponses
  , runScriptResponsesWith
  , runScriptText
    -- * Running elaborated commands
  , runResponses
  , runCommands
  ) where

import Control.Exception (bracket)
import Data.IORef
import Data.Maybe (mapMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Version (showVersion)
import Text.Read (readMaybe)

import HSMT.Backend
import HSMT.Core.Eval
import HSMT.Core.Expr
import HSMT.Core.Op (Symbol)
import HSMT.SMT.Engine
import HSMT.SMTLib.Parser
import HSMT.SMTLib.Printer
import HSMT.SMTLib.Syntax
import qualified Paths_hsmt as Paths

-- | The output of a command.
data Response
  = CheckResult EngineResult
    -- ^ Answer of @check-sat@ or @check-sat-assuming@.
  | UnsatCore [Text]
    -- ^ Answer of @get-unsat-core@: the names of the named assertions and
    -- the assumptions (rendered) of the last core.
  | Model Interpretation [Symbol]
    -- ^ Answer of @get-model@: the model and the symbols in scope.
  | Values [(Expr, Expr)]
    -- ^ Answer of @get-value@: each term with its value, as a term.
  | Assertions [Text]
    -- ^ Answer of @get-assertions@, rendered.
  | Info Text Text
    -- ^ Answer of @get-info@ or @get-option@: the keyword and its value.
  | Success
    -- ^ The answer of a command without output under @:print-success@.
  | Unsupported
    -- ^ An unknown keyword of @get-info@ or @get-option@.
  | Echoed Text
  | CommandError Text
    -- ^ A command that cannot be executed, such as @get-unsat-core@ after
    -- a satisfiable check or an ill-sorted term. The script goes on.
  deriving (Show)

-- | The text a solver prints for a response, without the final newline.
renderResponse :: Response -> Text
renderResponse = \case
  CheckResult (ESat _) -> "sat"
  CheckResult (EUnsat _) -> "unsat"
  CheckResult (EUnknown _) -> "unknown"
  UnsatCore names -> "(" <> T.unwords names <> ")"
  Model interp syms -> case modelResponse interp syms of
    [] -> "(\n)"
    cs -> "(\n" <> T.unlines (map (("  " <>) . renderCommand) cs) <> ")"
  Values vs -> "(" <> T.intercalate "\n " ["(" <> renderExpr t <> " " <> renderExpr v <> ")" | (t, v) <- vs] <> ")"
  Assertions as -> "(" <> T.intercalate "\n " as <> ")"
  Info k v -> "(:" <> k <> " " <> v <> ")"
  Success -> "success"
  Unsupported -> "unsupported"
  Echoed t -> renderString t
  CommandError why -> "(error " <> renderString why <> ")"

-- | An entry of an assertion level.
data Entry
  = EAssert (Maybe Text) Expr
  | EDeclare Symbol

data RunState = RunState
  { rsBackend :: Backend
  , rsSession :: BackendSession
  , rsLevels :: [[Entry]]
    -- ^ Assertion levels, innermost first; each in reverse order.
  , rsOptions :: CheckOptions
  , rsInitialOptions :: CheckOptions
    -- ^ The options @reset@ restores.
  , rsPrintSuccess :: Bool
  , rsLast :: Maybe (EngineResult, [Maybe Text])
    -- ^ The last check result and the labels of its formulas, while no
    -- assertion level changed since.
  , rsReason :: Maybe Text
    -- ^ Why the last check answered unknown.
  }

newState :: Backend -> CheckOptions -> IO RunState
newState backend opts = do
  sess <- newBackendSession backend
  -- Scripts that want cores say so with :produce-unsat-cores.
  let opts' = opts {coNeedCore = False}
  pure (RunState backend sess [[]] opts' opts' False Nothing Nothing)

-- | Execute one command, giving its responses and whether the script goes
-- on.
execute :: RunState -> Command -> IO (RunState, [Response], Bool)
execute st = \case
  Assert e -> quiet (change (addEntry (EAssert Nothing e) st))
  AssertNamed n e -> quiet (change (addEntry (EAssert (Just n) e) st))
  DeclareFun sym -> quiet (addEntry (EDeclare sym) st)
  Push n -> quiet (change st {rsLevels = replicate n [] <> rsLevels st})
  Pop n
    | n < length (rsLevels st) -> quiet (change st {rsLevels = drop n (rsLevels st)})
    | otherwise -> out st [CommandError "pop: not enough assertion levels"]
  CheckSat -> check []
  CheckSatAssuming es -> check es
  GetModel -> withModel $ \interp -> [Model interp (declared st)]
  GetValue es -> withModel $ \interp ->
    case traverse (evalExpr interp) es of
      Right vs -> [Values (zip es (map valueExpr vs))]
      Left err -> [CommandError ("cannot evaluate: " <> eeMessage err)]
  GetAssertions -> out st [Assertions [render n e | EAssert n e <- reverse (concat (rsLevels st))]]
  GetUnsatCore -> out st $ case rsLast st of
    Just (EUnsat idx, labels) -> [UnsatCore (mapMaybe (labels !!) idx)]
    _ -> [CommandError "no unsatisfiable core available"]
  GetInfo k -> out st [info k]
  GetOption k -> out st [option k]
  SetOption o v -> quiet (setOption o v st)
  Echo t -> out st [Echoed t]
  Reset -> do
    closeBackendSession (rsSession st)
    newState (rsBackend st) (rsInitialOptions st) >>= quiet
  ResetAssertions -> do
    closeBackendSession (rsSession st)
    sess <- newBackendSession (rsBackend st)
    quiet st {rsSession = sess, rsLevels = [[]], rsLast = Nothing}
  Exit -> pure (st, [Success | rsPrintSuccess st], False)
  _ -> quiet st
  where
    out st' rs = pure (st', rs, True)
    quiet st' = out st' [Success | rsPrintSuccess st']
    change st' = st' {rsLast = Nothing}

    addEntry e st' = case rsLevels st' of
      (l : rest) -> st' {rsLevels = (e : l) : rest}
      [] -> st' {rsLevels = [[e]]}

    render n e = maybe (renderExpr e) (\name -> "(! " <> renderExpr e <> " :named " <> renderSymbol name <> ")") n

    check assumed = do
      let levels = [[(n, e) | EAssert n e <- reverse l] | l <- reverse (rsLevels st)]
          labels = map fst (concat levels) <> map (Just . renderExpr) assumed
      r <- checkBackend (rsSession st) (rsOptions st) (map (map snd) levels) assumed
      let reason = case r of
            EUnknown why -> Just why
            _ -> Nothing
      out st {rsLast = Just (r, labels), rsReason = reason} [CheckResult r]

    withModel k = out st $ case rsLast st of
      Just (ESat interp, _) -> k interp
      _ -> [CommandError "no model available"]

    declared st' = reverse [sym | EDeclare sym <- concat (rsLevels st')]

    info = \case
      "name" -> Info "name" "\"hsmt\""
      "version" -> Info "version" (renderString (T.pack (showVersion Paths.version)))
      "authors" -> Info "authors" "\"rodrigogribeiro\""
      "error-behavior" -> Info "error-behavior" "continued-execution"
      "assertion-stack-levels" -> Info "assertion-stack-levels" (T.pack (show (length (rsLevels st) - 1)))
      "all-statistics" -> Info "all-statistics" "()"
      "reason-unknown" -> case rsReason st of
        Just "timeout" -> Info "reason-unknown" "timeout"
        Just why -> Info "reason-unknown" (renderString why)
        Nothing -> CommandError "the last check did not answer unknown"
      _ -> Unsupported

    option = \case
      "print-success" -> Info "print-success" (bool (rsPrintSuccess st))
      "produce-models" -> Info "produce-models" "true"
      "produce-unsat-cores" -> Info "produce-unsat-cores" (bool (coNeedCore (rsOptions st)))
      "smt.core.minimize" -> Info "smt.core.minimize" (bool (coMinimizeCore (rsOptions st)))
      "timeout" -> Info "timeout" (maybe "0" (\t -> T.pack (show (round (t * 1000) :: Integer))) (coTimeout (rsOptions st)))
      _ -> Unsupported

    bool b = if b then "true" else "false"

    setOption o v st' = case o of
      "print-success" -> st' {rsPrintSuccess = v == "true"}
      "timeout" | Just ms <- readMaybe (T.unpack v) ->
        let t = if ms <= 0 then Nothing else Just (fromInteger ms / 1000)
         in st' {rsOptions = (rsOptions st') {coTimeout = t}}
      "smt.core.minimize" -> st' {rsOptions = (rsOptions st') {coMinimizeCore = v == "true"}}
      "produce-unsat-cores" -> st' {rsOptions = (rsOptions st') {coNeedCore = v == "true"}}
      _ -> st'

-------------------------------------------------------------------------------
-- Drivers

-- | Elaborate and execute a script command by command, passing each
-- response to the callback as soon as it is known. Errors (including a
-- syntax error, which ends the script) are responses.
runScriptWith :: CheckOptions -> (Response -> IO ()) -> Text -> IO ()
runScriptWith = runScriptWithBackend Native

-- | 'runScriptWith' with the given backend.
runScriptWithBackend :: Backend -> CheckOptions -> (Response -> IO ()) -> Text -> IO ()
runScriptWithBackend backend opts emit txt = do
  -- The session in use, stopped at the end even after an exception.
  current <- newIORef Nothing
  let (ses, syntaxError) = parseSExprsPartial txt
      go _ _ [] = mapM_ (emit . CommandError) syntaxError
      go ps st (se : rest) = case parseCommand ps se of
        Left err -> emit (CommandError err) >> go ps st rest
        Right (ps', cmds) -> steps ps' st cmds rest
      steps ps st [] rest = go ps st rest
      steps ps st (c : cs) rest = do
        (st', rs, continue) <- execute st c
        writeIORef current (Just (rsSession st'))
        mapM_ emit rs
        if continue then steps ps st' cs rest else pure ()
  bracket
    (newState backend opts)
    (\_ -> readIORef current >>= mapM_ closeBackendSession)
    (\st0 -> writeIORef current (Just (rsSession st0)) >> go initialParseState st0 ses)

-- | Elaborate and execute a script, returning every response in order.
-- When @validate@ holds, models are checked against the assertions.
runScriptResponses :: Bool -> Text -> IO [Response]
runScriptResponses = runScriptResponsesWith Native

-- | 'runScriptResponses' with the given backend.
runScriptResponsesWith :: Backend -> Bool -> Text -> IO [Response]
runScriptResponsesWith backend validate txt = do
  ref <- newIORef []
  runScriptWithBackend backend defaultCheckOptions {coValidate = validate} (\r -> modifyIORef' ref (r :)) txt
  reverse <$> readIORef ref

-- | Parse and run a script, returning the check results. Unlike
-- 'runScriptResponses', the first error in the script is returned as
-- 'Left' and nothing runs.
runScriptText :: Bool -> Text -> IO (Either Text [EngineResult])
runScriptText validate txt = case parseScript txt of
  Left err -> pure (Left err)
  Right cmds -> runCommands validate cmds

-- | Run elaborated commands and return the output of each, in order.
runResponses :: Bool -> [Command] -> IO [Response]
runResponses validate cmds0 = newState Native defaultCheckOptions {coValidate = validate} >>= go cmds0
  where
    go [] _ = pure []
    go (c : cs) st = do
      (st', rs, continue) <- execute st c
      (rs <>) <$> if continue then go cs st' else pure []

-- | Run elaborated commands and return the result of every @check-sat@
-- and @check-sat-assuming@, in order. An error is returned as 'Left'.
runCommands :: Bool -> [Command] -> IO (Either Text [EngineResult])
runCommands validate cmds = do
  rs <- runResponses validate cmds
  pure $ case [e | CommandError e <- rs] of
    e : _ -> Left e
    [] -> Right [r | CheckResult r <- rs]