hsmt-0.1.0.0: src/HSMT/API/Monad.hs
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
-- | The t'SMT' monad: declaring symbols, asserting formulas and checking
-- satisfiability.
module HSMT.API.Monad
( SMT
, runSMT
, Config (..)
, defaultConfig
, Backend (..)
, ExternalSolver (..)
, Dialect (..)
, z3Backend
, SMTError (..)
, Result (..)
, Core
, coreAssertions
, coreAssumptions
, declare
, declareFun
, fresh
, assert
, push
, pop
, scoped
, checkSat
, checkSatAssuming
, assertions
) where
import Control.Exception (Exception, bracket, throwIO)
import Control.Monad.IO.Class (MonadIO (..))
import Control.Monad.Reader (ReaderT (..), ask)
import Data.IORef
import qualified Data.IntSet as IntSet
import Data.Kind (Type)
import Data.Proxy (Proxy (..))
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Text (Text)
import qualified Data.Text as T
import HSMT.API.Expr
import HSMT.API.Model
import HSMT.API.Sort
import qualified HSMT.Core.Expr as C
import HSMT.Core.Op (Op (..), Symbol (..))
import HSMT.Backend
import HSMT.SMT.Engine
-- | Solver configuration.
data Config = Config
{ cfgValidateModels :: Bool
-- ^ Check every model against the assertions before returning it.
, cfgTimeout :: Maybe Int
-- ^ Time limit of each check, in milliseconds; a check that reaches it
-- answers @Unknown "timeout"@.
, cfgConflictLimit :: Maybe Int
-- ^ Limit on the conflicts of the SAT solver in each check; a check
-- that reaches it answers @Unknown "resource limit reached"@.
, cfgMinimizeCores :: Bool
-- ^ Make unsatisfiable cores minimal: removing any formula of the core
-- makes the others satisfiable. Each formula of the core costs one more
-- check. Without it, cores are usually small but not minimal.
, cfgBackend :: Backend
-- ^ The solver that decides the formulas: the Haskell engine
-- ('Native') or an external process such as @'External' 'z3Backend'@.
-- The API is the same for both; with an external solver, results that
-- SMT-LIB leaves unspecified (division by zero, @fp.min@ of zeros of
-- different signs, out-of-range @fp.to_ubv@) agree with the solver on
-- the terms of the checked formulas and take the evaluator's defaults
-- elsewhere.
}
deriving (Show)
-- | The Haskell engine, validated models, no limits, cores without
-- minimization.
defaultConfig :: Config
defaultConfig =
Config
{ cfgValidateModels = True
, cfgTimeout = Nothing
, cfgConflictLimit = Nothing
, cfgMinimizeCores = False
, cfgBackend = Native
}
-- | Misuses of the solver, thrown as exceptions by 'runSMT'.
data SMTError
= DuplicateDeclaration Text
-- ^ A name was declared twice.
| PopWithoutPush
-- ^ 'pop' without a matching 'push'.
deriving (Show)
instance Exception SMTError
data SolverState = SolverState
{ stConfig :: Config
, stDecls :: Map Text Symbol
, stScopes :: [[C.Expr]]
-- ^ Assertion scopes, innermost first; each scope is in reverse order.
, stFresh :: Int
, stSession :: BackendSession
-- ^ The solver's incremental state, shared by all checks.
}
-- | Computations over one solver instance. The phantom parameter @ctx@
-- prevents expressions and models from leaking into other instances.
newtype SMT (ctx :: Type) a = SMT (ReaderT (IORef SolverState) IO a)
deriving newtype (Functor, Applicative, Monad, MonadIO)
-- | Run a solver instance. An external solver process is stopped when the
-- computation ends.
runSMT :: Config -> (forall ctx. SMT ctx a) -> IO a
runSMT cfg (SMT m) =
bracket (newBackendSession (cfgBackend cfg)) closeBackendSession $ \sess -> do
ref <- newIORef (SolverState cfg Map.empty [[]] 0 sess)
runReaderT m ref
getState :: SMT ctx SolverState
getState = SMT (ask >>= liftIO . readIORef)
modifyState :: (SolverState -> SolverState) -> SMT ctx ()
modifyState f = SMT (ask >>= \r -> liftIO (modifyIORef' r f))
-- | The answer of a check.
data Result ctx
= Sat (Model ctx)
-- ^ Satisfiable, with a model of the assertions (and assumptions).
| Unsat (Core ctx)
-- ^ Unsatisfiable, with a subset of the assertions and assumptions
-- that is unsatisfiable on its own.
| Unknown Text
-- ^ The solver gave up; the text explains why.
deriving (Show)
-- | An unsatisfiable core: active assertions and assumptions whose
-- conjunction is unsatisfiable.
data Core ctx = Core [C.Expr] [C.Expr]
deriving (Show)
-- | The assertions of the core, in assertion order.
coreAssertions :: Core ctx -> [Expr ctx 'BoolS]
coreAssertions (Core as _) = map Expr as
-- | The assumptions of the core (see 'checkSatAssuming'), in the given
-- order.
coreAssumptions :: Core ctx -> [Expr ctx 'BoolS]
coreAssumptions (Core _ as) = map Expr as
declareSymbol :: Text -> Symbol -> SMT ctx ()
declareSymbol name sym = do
st <- getState
case Map.lookup name (stDecls st) of
Just _ -> liftIO (throwIO (DuplicateDeclaration name))
Nothing -> modifyState (\s -> s {stDecls = Map.insert name sym (stDecls s)})
-- | Declare a constant: @x <- declare \@IntS "x"@.
declare :: forall s ctx. KnownSort s => Text -> SMT ctx (Expr ctx s)
declare name = do
let sym = Symbol name [] (sortRep @s)
declareSymbol name sym
pure (Expr (C.App (Uninterpreted sym) []))
-- | Declare an uninterpreted function:
--
-- > f <- declareFun @'[IntS, IntS] @BoolS "f"
-- > assert (f x y)
declareFun
:: forall args r ctx
. (KnownSorts args, KnownSort r, CurryFn args)
=> Text
-> SMT ctx (Fn ctx args r)
declareFun name = do
let sym = Symbol name (sortReps @args) (sortRep @r)
declareSymbol name sym
pure (curryFn @args (Proxy @ctx) (Proxy @r) (C.App (Uninterpreted sym)))
-- | Declare a constant with a unique name derived from the prefix.
fresh :: forall s ctx. KnownSort s => Text -> SMT ctx (Expr ctx s)
fresh prefix = do
st <- getState
let n = stFresh st
name = prefix <> "!" <> T.pack (show n)
modifyState (\s -> s {stFresh = n + 1})
if Map.member name (stDecls st) then fresh prefix else declare @s name
-- | Add an assertion to the innermost scope.
assert :: Expr ctx 'BoolS -> SMT ctx ()
assert (Expr e) = modifyState $ \s -> case stScopes s of
(sc : rest) -> s {stScopes = (e : sc) : rest}
[] -> s {stScopes = [[e]]}
-- | Open a new assertion scope.
push :: SMT ctx ()
push = modifyState (\s -> s {stScopes = [] : stScopes s})
-- | Discard the assertions of the innermost scope. Declarations are global
-- and survive 'pop'.
pop :: SMT ctx ()
pop = do
st <- getState
case stScopes st of
(_ : rest@(_ : _)) -> modifyState (\s -> s {stScopes = rest})
_ -> liftIO (throwIO PopWithoutPush)
-- | Run an action inside a fresh scope.
scoped :: SMT ctx a -> SMT ctx a
scoped m = push *> m <* pop
-- | All active assertions, in assertion order.
assertions :: SMT ctx [C.Expr]
assertions = concatMap reverse . reverse . stScopes <$> getState
-- | Decide the conjunction of the active assertions.
checkSat :: SMT ctx (Result ctx)
checkSat = checkSatAssuming []
-- | Decide the conjunction of the active assertions and of the given
-- formulas, which are assumed for this check only. Checks reuse the work of
-- earlier ones (see t'HSMT.SMT.Engine.Session'); an external solver keeps
-- the assertion scopes as its own assertion levels.
checkSatAssuming :: [Expr ctx 'BoolS] -> SMT ctx (Result ctx)
checkSatAssuming assumed = do
st <- getState
let levels = map reverse (reverse (stScopes st))
as = concat levels
cfg = stConfig st
extra = map unExpr assumed
opts =
CheckOptions
{ coValidate = cfgValidateModels cfg
, coTimeout = (\ms -> fromIntegral ms / 1000) <$> cfgTimeout cfg
, coConflictLimit = cfgConflictLimit cfg
, coMinimizeCore = cfgMinimizeCores cfg
, coNeedCore = True
}
n = length as
r <- liftIO (checkBackend (stSession st) opts levels extra)
pure $ case r of
ESat interp -> Sat (Model interp)
EUnsat idx ->
let picked = IntSet.fromList idx
keep off es = [e | (i, e) <- zip [off ..] es, IntSet.member i picked]
in Unsat (Core (keep 0 as) (keep n extra))
EUnknown why -> Unknown why