hsmt-0.1.0.0: src/HSMT/Backend/External.hs
{-# LANGUAGE MultiWayIf #-}
-- | An external SMT solver (Z3 by default) driven through textual SMT-LIB
-- over a pipe, behind the same check interface as the Haskell engine
-- ('HSMT.SMT.Engine.checkSession').
--
-- One solver process serves all checks of a session. Formulas that only
-- grow are sent once; a check that drops formulas resets the solver,
-- unless 'solverIncremental' asks for one @push@ level per assertion
-- scope. Declarations of sorts and symbols are emitted on demand, at the
-- level of the first formula that needs them.
-- Unsatisfiable cores come from a separate tracked check (see
-- 'checkExternal'), whose indicator constants are named @hsmt!s!k@; the
-- prefix @hsmt!@ is reserved.
--
-- Models are read from @get-model@ (constants, @ite@ tables of functions,
-- @store@ chains, @as-array@ and @lambda@ arrays, elements of
-- uninterpreted sorts) and completed with @get-value@ at the applications
-- of uninterpreted functions, divisions by zero and unspecified
-- floating-point operations occurring in the formulas, so the model
-- agrees with the solver on every term the formulas mention. Elsewhere,
-- unspecified results take the evaluator's defaults.
--
-- The responses are read with the SMT-LIB parser of hsmt. The library
-- @simple-smt@ was considered, but its reader splits string literals at
-- spaces and parentheses, which corrupts string models and desynchronizes
-- the responses.
module HSMT.Backend.External
( -- * Solvers
ExternalSolver (..)
, Dialect (..)
, z3Backend
, solverFromCommand
-- * Sessions
, ExternalSession
, newExternalSession
, closeExternalSession
, checkExternal
) where
import Control.Concurrent (forkIO)
import Control.Exception (Exception, IOException, SomeException, catch, throwIO, try)
import Control.Monad (foldM, forM, forM_, unless, void, when)
import Data.Char (isDigit)
import Data.Containers.ListUtils (nubOrd)
import Data.IORef
import Data.List (isPrefixOf)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe, mapMaybe)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import System.Environment (lookupEnv)
import System.FilePath (takeFileName)
import System.IO
import System.Process
import System.Timeout (timeout)
import GHC.Clock (getMonotonicTime)
import HSMT.Core.Eval
import HSMT.Core.Expr
import HSMT.Core.Op
import HSMT.Core.Sort
import HSMT.Core.Value
import HSMT.SMT.Engine (CheckOptions (..), EngineResult (..))
import HSMT.SMTLib.Parser
import HSMT.SMTLib.Printer
import HSMT.SMTLib.Syntax
-------------------------------------------------------------------------------
-- Solvers
-- | How to run an external solver.
data ExternalSolver = ExternalSolver
{ solverPath :: FilePath
-- ^ The executable. For @"z3"@, the environment variable @HSMT_Z3@
-- takes precedence when set.
, solverArgs :: [String]
-- ^ Arguments that make the solver read SMT-LIB from the standard
-- input interactively (@-in -smt2@ for Z3, @--incremental@ for CVC5).
, solverDialect :: Dialect
-- ^ Which options the solver understands.
, solverLogic :: Text
-- ^ The argument of @set-logic@.
, solverIncremental :: Bool
-- ^ Keep the assertion scopes as @push@ levels of the solver, so each
-- check only sends what changed. Otherwise a check that drops formulas
-- starts over with @(reset)@ and asserts the current ones again. Any
-- @push@ puts Z3 in its incremental mode, which skips most
-- preprocessing: a chain of 30 equality diamonds takes 10 ms without
-- it and more than a minute with it. Hence the default is 'False'.
}
deriving (Eq, Show)
-- | The options an external solver understands beyond standard SMT-LIB.
data Dialect
= Z3Dialect
-- ^ Z3: @:timeout@ limits each check, @:sat.max_conflicts@ and
-- @:smt.max_conflicts@ limit conflicts, and @:smt.core.minimize@
-- minimizes cores.
| StandardDialect
-- ^ Only standard options: time limits are enforced by killing the
-- process, conflict limits are ignored, and cores are minimized by
-- removal, with one check per formula of the core.
deriving (Eq, Show)
-- | Z3, found through @HSMT_Z3@ or the @PATH@, with logic @ALL@.
z3Backend :: ExternalSolver
z3Backend = ExternalSolver "z3" ["-in", "-smt2"] Z3Dialect "ALL" False
-- | A solver from a command line (executable and arguments). The dialect
-- is 'Z3Dialect' when the executable is named @z3@, and the command @z3@
-- alone gets Z3's interactive arguments.
solverFromCommand :: [String] -> Maybe ExternalSolver
solverFromCommand = \case
[] -> Nothing
[path] | isZ3 path -> Just z3Backend {solverPath = path}
path : args ->
Just (ExternalSolver path args (if isZ3 path then Z3Dialect else StandardDialect) "ALL" False)
where
isZ3 p = "z3" `isPrefixOf` takeFileName p
-------------------------------------------------------------------------------
-- Sessions
-- | A connection to an external solver, started on the first check and
-- restarted after a failure.
data ExternalSession = ExternalSession ExternalSolver (IORef (Maybe Proc))
-- | A session that has not started the solver yet.
newExternalSession :: ExternalSolver -> IO ExternalSession
newExternalSession s = ExternalSession s <$> newIORef Nothing
-- | Stop the solver process, if any.
closeExternalSession :: ExternalSession -> IO ()
closeExternalSession (ExternalSession _ ref) = do
readIORef ref >>= mapM_ (\p -> void (try @SomeException (send p "(exit)")) >> kill p)
writeIORef ref Nothing
data Proc = Proc
{ prIn :: Handle
, prOut :: Handle
, prHandle :: ProcessHandle
, prStderr :: IORef [Text]
-- ^ The last lines the solver wrote to its standard error, newest first.
, prIncremental :: Bool
-- ^ See 'solverIncremental'.
, prLevels :: IORef [Level]
-- ^ The assertion levels pushed in the solver, innermost first. Without
-- 'solverIncremental', a single level that is not pushed.
, prKnown :: IORef Bool
-- ^ Whether the solver holds exactly the formulas of 'prLevels' (and
-- not, for instance, those of a core computation).
, prCounter :: IORef Int
, prOptions :: IORef (Maybe Int, Maybe Int)
-- ^ Timeout (ms) and conflict limit in effect.
}
-- | One @push@ of the solver.
data Level = Level
{ lvFormulas :: [Expr]
-- ^ Assertions, newest first.
, lvDecls :: Set.Set Text
-- ^ Declarations made at this level, as rendered.
}
emptyLevel :: Level
emptyLevel = Level [] Set.empty
-- | A failure of the solver process: an error response, an unexpected
-- answer, or the process ending.
newtype Failure = Failure Text
deriving (Show)
instance Exception Failure
-- | The answer of the main check of 'checkExternal'.
data Outcome
= OSat Interpretation
| OUnsat
| OUnknown Text
-- | Decide the conjunction of the formulas, given as assertion levels
-- (outermost first, each in assertion order) and assumptions. An 'EUnsat'
-- answer carries positions in the levels followed by the assumptions, as
-- for 'HSMT.SMT.Engine.checkSession'.
--
-- The check itself tracks nothing: assertions are plain, and assumptions
-- are asserted in a level of their own. Tracking (named assertions or
-- @check-sat-assuming@) turns off much of Z3's preprocessing, which makes
-- some easy problems hard (a chain of 30 equality diamonds takes 10 ms
-- untracked and more than a minute tracked). A core is computed only after
-- an @unsat@ answer, by a tracked check limited to five times the duration
-- of the first one (at least one second, at most the timeout); when it
-- fails, the core is every formula.
checkExternal :: ExternalSession -> CheckOptions -> [[Expr]] -> [Expr] -> IO EngineResult
checkExternal sess@(ExternalSession solver _) opts levels0 assumed = do
let levels = if null levels0 then [[]] else levels0
formulas = concat levels <> assumed
everything = [0 .. length formulas - 1]
t0 <- getMonotonicTime
main <- guarded sess (hardLimit (coTimeout opts)) (\p -> mainCheck solver p opts levels assumed)
case main of
Left why -> pure (EUnknown why)
Right (OUnknown why) -> pure (EUnknown why)
Right (OSat interp) ->
pure $ case [e | e <- formulas, evalExpr interp e /= Right (VBool True)] of
e : _
| coValidate opts ->
EUnknown ("the model of the external solver does not satisfy " <> renderExpr e)
_ -> ESat interp
Right OUnsat -> do
elapsed <- subtract t0 <$> getMonotonicTime
let budget = maybe id min (coTimeout opts) (max 1 (5 * elapsed))
tracked <-
if coNeedCore opts
then guarded sess (Just (budget + 1)) (\p -> trackedCore solver p budget formulas)
else pure (Left "no core wanted")
let core = either (const everything) id tracked
EUnsat <$> if coMinimizeCore opts then minimizeCore sess opts formulas core else pure core
-- | The hard limit for a check with the given timeout: the solver's own
-- timeout plus a margin.
hardLimit :: Maybe Double -> Maybe Double
hardLimit = fmap (\s -> s + max 0.5 (s / 2) + 1)
-- | Run an action on the solver process (started if needed) within a time
-- limit in seconds. A failure or the limit restarts the process on the
-- next use and is returned as 'Left'.
guarded :: ExternalSession -> Maybe Double -> (Proc -> IO a) -> IO (Either Text a)
guarded sess@(ExternalSession _ ref) limit act = do
let run = ensureStarted sess >>= act
r <- try (try (maybe (Just <$> run) (\s -> timeout (ceiling (s * 1e6)) run) limit))
case r of
Right (Right (Just x)) -> pure (Right x)
Right (Right Nothing) -> restart >> pure (Left "timeout")
Right (Left (Failure why)) -> restart >> pure (Left why)
Left (e :: IOException) -> do
err <- readIORef ref >>= maybe (pure []) (readIORef . prStderr)
restart
pure (Left ("external solver failed: " <> T.pack (show e) <> stderrNote err))
where
restart = do
readIORef ref >>= mapM_ kill
writeIORef ref Nothing
stderrNote = \case
[] -> ""
ls -> " (" <> T.intercalate "; " (reverse ls) <> ")"
ensureStarted :: ExternalSession -> IO Proc
ensureStarted (ExternalSession solver ref) =
readIORef ref >>= \case
Just p -> pure p
Nothing -> do
p <- start solver
writeIORef ref (Just p)
pure p
start :: ExternalSolver -> IO Proc
start solver = do
path <-
if solverPath solver == "z3"
then fromMaybe "z3" . mfilter' (not . null) <$> lookupEnv "HSMT_Z3"
else pure (solverPath solver)
(Just hin, Just hout, Just herr, ph) <-
createProcess
(proc path (solverArgs solver))
{ std_in = CreatePipe
, std_out = CreatePipe
, std_err = CreatePipe
}
forM_ [hin, hout, herr] (`hSetEncoding` utf8)
errRef <- newIORef []
let drain = do
l <- T.hGetLine herr
modifyIORef' errRef (take 20 . (l :))
drain
_ <- forkIO (drain `catch` \(_ :: IOException) -> pure ())
p <-
Proc hin hout ph errRef (solverIncremental solver)
<$> newIORef []
<*> newIORef True
<*> newIORef 0
<*> newIORef (Nothing, Nothing)
initialize solver p
pure p
where
mfilter' f = \case
Just x | f x -> Just x
_ -> Nothing
-- | Set the options and the logic of a solver that has just started or
-- been reset.
initialize :: ExternalSolver -> Proc -> IO ()
initialize solver p = do
ack p "(set-option :print-success true)"
ack p "(set-option :produce-models true)"
ack p "(set-option :produce-unsat-cores true)"
ack p ("(set-logic " <> solverLogic solver <> ")")
writeIORef (prOptions p) (Nothing, Nothing)
writeIORef (prLevels p) (if prIncremental p then [] else [emptyLevel])
writeIORef (prKnown p) True
-- | Drop every assertion and declaration: pop all levels, or reset the
-- solver.
clear :: ExternalSolver -> Proc -> IO ()
clear solver p
| prIncremental p = popAll p >> writeIORef (prKnown p) True
| otherwise = ack p "(reset)" >> initialize solver p
-- | Run an action in a temporary context holding only what the action
-- asserts. Incremental solvers keep their levels below it; the others are
-- reset before the next check.
isolated :: ExternalSolver -> Proc -> IO a -> IO a
isolated solver p act
| prIncremental p = do
popAll p
pushLevel p
r <- act
popLevels p 1
pure r
| otherwise = do
clear solver p
writeIORef (prKnown p) False
act
kill :: Proc -> IO ()
kill p = do
terminateProcess (prHandle p) `catch` \(_ :: SomeException) -> pure ()
forM_ [prIn p, prOut p] $ \h -> hClose h `catch` \(_ :: SomeException) -> pure ()
void (forkIO (void (waitForProcess (prHandle p)) `catch` \(_ :: SomeException) -> pure ()))
-------------------------------------------------------------------------------
-- Communication
send :: Proc -> Text -> IO ()
send p t = T.hPutStrLn (prIn p) t >> hFlush (prIn p)
-- | Read one response: lines until a complete S-expression.
recv :: Proc -> IO SExpr
recv p = go [] (0, Normal)
where
go acc st = do
l <- T.hGetLine (prOut p)
let acc' = l : acc
st'@(depth, mode) = scanLine st l
if depth <= 0 && mode == Normal
then case parseSExprs (T.unlines (reverse acc')) of
Right (e : _) -> pure e
Right [] -> go [] (0, Normal)
Left err -> throwIO (Failure ("unreadable solver output: " <> err))
else go acc' st'
data Mode = Normal | InString | InQuoted
deriving (Eq)
-- | Parenthesis depth after a line, outside strings, quoted symbols and
-- comments.
scanLine :: (Int, Mode) -> Text -> (Int, Mode)
scanLine st0 = go st0 . T.unpack
where
go st [] = st
go (d, Normal) (c : cs) = case c of
'(' -> go (d + 1, Normal) cs
')' -> go (d - 1, Normal) cs
'"' -> go (d, InString) cs
'|' -> go (d, InQuoted) cs
';' -> (d, Normal)
_ -> go (d, Normal) cs
go (d, InString) (c : cs)
| c == '"' = case cs of
'"' : cs' -> go (d, InString) cs'
_ -> go (d, Normal) cs
| otherwise = go (d, InString) cs
go (d, InQuoted) (c : cs)
| c == '|' = go (d, Normal) cs
| otherwise = go (d, InQuoted) cs
-- | Send a command and read its response; error responses are failures.
ask :: Proc -> Text -> IO SExpr
ask p cmd = do
send p cmd
recv p >>= \case
SList [SSym "error", SStr msg] -> throwIO (Failure ("external solver error: " <> msg))
r -> pure r
-- | Send a command that answers @success@.
ack :: Proc -> Text -> IO ()
ack p cmd =
ask p cmd >>= \case
SSym "success" -> pure ()
r -> throwIO (Failure ("unexpected answer to " <> cmd <> ": " <> showS r))
-------------------------------------------------------------------------------
-- Levels
freshName :: Proc -> Text -> IO Text
freshName p prefix = do
n <- readIORef (prCounter p)
writeIORef (prCounter p) (n + 1)
pure ("hsmt!" <> prefix <> "!" <> T.pack (show n))
pushLevel :: Proc -> IO ()
pushLevel p = do
ack p "(push 1)"
modifyIORef' (prLevels p) (emptyLevel :)
popLevels :: Proc -> Int -> IO ()
popLevels p n = when (n > 0) $ do
ack p ("(pop " <> T.pack (show n) <> ")")
modifyIORef' (prLevels p) (drop n)
popAll :: Proc -> IO ()
popAll p = readIORef (prLevels p) >>= popLevels p . length
modifyTop :: Proc -> (Level -> Level) -> IO ()
modifyTop p f =
modifyIORef' (prLevels p) $ \case
l : rest -> f l : rest
[] -> [f emptyLevel]
-- | Emit the declarations the expressions need that are not in scope.
declareFor :: Proc -> [Expr] -> IO ()
declareFor p es = do
scope <- foldMap lvDecls <$> readIORef (prLevels p)
let new = filter (`Set.notMember` scope) (nubOrd (map renderCommand (declarationsFor es)))
forM_ new (ack p)
modifyTop p (\l -> l {lvDecls = Set.union (Set.fromList new) (lvDecls l)})
assertPlain :: Proc -> Expr -> IO ()
assertPlain p e = do
declareFor p [e]
ack p (renderCommand (Assert e))
modifyTop p (\l -> l {lvFormulas = e : lvFormulas l})
-- | Make the solver hold exactly the given levels, then the assumptions.
-- Incremental solvers pop only the levels that differ and get the
-- assumptions in a level of their own (see 'retract'); the others start
-- over unless the formulas only grow.
prepare :: ExternalSolver -> Proc -> [[Expr]] -> [Expr] -> IO ()
prepare solver p levels assumed
| prIncremental p = do
syncLevels p levels
unless (null assumed) $ pushLevel p >> mapM_ (assertPlain p) assumed
| otherwise = do
known <- readIORef (prKnown p)
held <- reverse . concatMap lvFormulas <$> readIORef (prLevels p)
let target = concat levels <> assumed
if known && held `isPrefixOf` target
then mapM_ (assertPlain p) (drop (length held) target)
else clear solver p >> mapM_ (assertPlain p) target
-- | Undo the level of assumptions made by @prepare@.
retract :: Proc -> [Expr] -> IO ()
retract p assumed = when (prIncremental p && not (null assumed)) (popLevels p 1)
-- | Make the solver's levels hold exactly the given formulas, popping only
-- the levels that differ.
syncLevels :: Proc -> [[Expr]] -> IO ()
syncLevels p target = do
current <- reverse <$> readIORef (prLevels p)
let held = map (reverse . lvFormulas) current
same = length (takeWhile id (zipWith (==) held target))
case (drop same held, drop same target) of
(h : restH, t : restT) | h `isPrefixOf` t -> do
popLevels p (length restH)
mapM_ (assertPlain p) (drop (length h) t)
fresh restT
(hs, ts) -> do
popLevels p (length hs)
fresh ts
where
fresh = mapM_ (\fs -> pushLevel p >> mapM_ (assertPlain p) fs)
-------------------------------------------------------------------------------
-- Checks
-- | Set the time (seconds) and conflict limits of the next checks, for
-- solvers that understand them.
setLimits :: ExternalSolver -> Proc -> Maybe Double -> Maybe Int -> IO ()
setLimits solver p secs c = when (solverDialect solver == Z3Dialect) $ do
(t0, c0) <- readIORef (prOptions p)
let t = (\s -> max 1 (ceiling (s * 1000))) <$> secs
when (t /= t0) $ ack p ("(set-option :timeout " <> T.pack (show (fromMaybe 0 t)) <> ")")
when (c /= c0) $
forM_ ["sat", "smt"] $ \k ->
ack p ("(set-option :" <> k <> ".max_conflicts " <> T.pack (show (fromMaybe 4294967295 c)) <> ")")
writeIORef (prOptions p) (t, c)
-- | The check proper, with the assumptions in a level of their own.
mainCheck :: ExternalSolver -> Proc -> CheckOptions -> [[Expr]] -> [Expr] -> IO Outcome
mainCheck solver p opts levels assumed = do
setLimits solver p (coTimeout opts) (coConflictLimit opts)
prepare solver p levels assumed
r <-
checkCommand p [] >>= \case
"sat" -> OSat <$> readModel p (concat levels <> assumed)
"unsat" -> pure OUnsat
_ -> OUnknown <$> reasonUnknown p
retract p assumed
pure r
-- | Positions of an unsatisfiable subset of the formulas, from a check
-- that tracks each formula with an indicator constant, in an 'isolated'
-- context.
trackedCore :: ExternalSolver -> Proc -> Double -> [Expr] -> IO [Int]
trackedCore solver p budget formulas = isolated solver p $ do
setLimits solver p (Just budget) Nothing
inds <- forM formulas $ \e -> do
declareFor p [e]
name <- freshName p "s"
let sym = Symbol name [] BoolSort
ack p (renderCommand (DeclareFun sym))
ack p (renderCommand (Assert (App Implies [App (Uninterpreted sym) [], e])))
pure name
answer <- checkCommand p inds
unless (answer == "unsat") $ throwIO (Failure "no core")
core <-
ask p "(get-unsat-core)" >>= \case
SList xs -> pure [s | SSym s <- xs]
r -> throwIO (Failure ("unexpected unsatisfiable core: " <> showS r))
let position = Map.fromList (zip inds [0 ..])
pure (Set.toList (Set.fromList (mapMaybe (`Map.lookup` position) core)))
-- | Run @check-sat@ or @check-sat-assuming@ and return the answer.
checkCommand :: Proc -> [Text] -> IO Text
checkCommand p inds =
ask p (if null inds then "(check-sat)" else "(check-sat-assuming (" <> T.unwords inds <> "))") >>= \case
SSym a | a `elem` ["sat", "unsat", "unknown"] -> pure a
SSym "timeout" -> pure "unknown"
r -> throwIO (Failure ("unexpected answer to check-sat: " <> showS r))
reasonUnknown :: Proc -> IO Text
reasonUnknown p = do
r <- ask p "(get-info :reason-unknown)"
let why = case r of
SList [SKey _, SStr s] -> s
SList [SKey _, SSym s] -> s
_ -> showS r
lower = T.toLower why
pure $
if
| any (`T.isInfixOf` lower) ["timeout", "canceled"] -> "timeout"
| any (`T.isInfixOf` lower) ["conflict", "resource", "rlimit"] -> "resource limit reached"
| T.null why -> "unknown"
| otherwise -> why
-- | Shrink a core by removal: drop every formula whose removal keeps the
-- rest unsatisfiable, with untracked checks. A check that does not answer
-- @unsat@ (including a timeout) keeps the formula.
minimizeCore :: ExternalSession -> CheckOptions -> [Expr] -> [Int] -> IO [Int]
minimizeCore sess@(ExternalSession solver _) opts formulas core0 = foldM step core0 core0
where
fs = Map.fromList (zip [0 :: Int ..] formulas)
step core i = do
let rest = filter (/= i) core
r <- guarded sess (hardLimit (coTimeout opts)) $ \p -> isolated solver p $ do
setLimits solver p (coTimeout opts) (coConflictLimit opts)
mapM_ (assertPlain p) [fs Map.! j | j <- rest]
checkCommand p []
pure (if r == Right "unsat" then rest else core)
-------------------------------------------------------------------------------
-- Models
-- | A function or constant definition of @get-model@: parameters, result
-- sort and body.
data Definition = Definition [(Text, SExpr)] SExpr SExpr
-- | Read the model of the last satisfiable check for the symbols of the
-- formulas.
readModel :: Proc -> [Expr] -> IO Interpretation
readModel p formulas = do
ps0 <- either (throwIO . Failure) pure (declarationsState formulas)
items <-
ask p "(get-model)" >>= \case
SList (SSym "model" : xs) -> pure xs
SList xs -> pure xs
r -> throwIO (Failure ("unexpected model: " <> showS r))
let defs =
Map.fromList
[ (n, Definition [(x, s) | SList [SSym x, s] <- ps] res body)
| SList [SSym "define-fun", SSym n, SList ps, res, body] <- items
]
elems <-
either (throwIO . Failure) pure $
elements ps0 [(n, s) | SList [SSym "declare-fun", SSym n, SList [], s] <- items]
let ctx = ModelCtx (declareConstants (map fst elems) ps0) (elemInterp elems) defs
syms = Set.toList (foldMap symbols formulas)
base <- forM syms $ \sym -> do
fi <- case Map.lookup (symName sym) defs of
Nothing -> pure (Right (constInterp (defaultValue (symResult sym))))
Just (Definition params _ body) -> pure $ do
sorts <- traverse (parseSort ps0 . snd) params
tableOf ctx (zip (map fst params) sorts) body
case fi of
Right f -> pure (sym, f)
Left err
| null (symArgs sym) -> do
-- Fall back on the value the solver gives for the constant.
v <- valuesOf p ctx [App (Uninterpreted sym) []]
case Map.elems v of
[x] -> pure (sym, constInterp x)
_ -> throwIO (Failure ("cannot read the model of " <> symName sym <> ": " <> err))
| otherwise -> pure (sym, constInterp (defaultValue (symResult sym)))
let pts = nubOrd (concatMap points formulas)
terms = nubOrd (concat [args <> [t] | t@(App _ args) <- pts])
vals <- if null terms then pure Map.empty else valuesOf p ctx terms
let value e = Map.lookup e vals
interp0 = emptyInterpretation {interpSymbols = Map.fromList base}
pure (foldl (addPoint value) interp0 pts)
where
addPoint value interp t@(App op args) = fromMaybe interp $ do
v <- value t
vs <- traverse value args
pure $ case op of
Uninterpreted sym ->
let fi = Map.findWithDefault (constInterp (defaultValue (symResult sym))) sym (interpSymbols interp)
in interp {interpSymbols = Map.insert sym fi {fiTable = Map.insert vs v (fiTable fi)} (interpSymbols interp)}
IntDiv | [a, VInt 0] <- vs -> interp {interpDivByZero = extend (interpDivByZero interp) [a] v}
IntMod | [a, VInt 0] <- vs -> interp {interpModByZero = extend (interpModByZero interp) [a] v}
IntDiv -> interp
IntMod -> interp
_ -> interp {interpUnspecified = Map.insert (op, vs) v (interpUnspecified interp)}
extend fi k v = fi {fiTable = Map.insert k v (fiTable fi)}
-- | Applications whose value the model must take from the solver:
-- uninterpreted functions, division and remainder by a non-literal, and
-- floating-point operations with unspecified results.
points :: Expr -> [Expr]
points t@(App op args) = concatMap points args <> [t | wanted]
where
wanted = case (op, args) of
(Uninterpreted _, _ : _) -> True
(IntDiv, [_, App (IntConst n) []]) -> n == 0
(IntMod, [_, App (IntConst n) []]) -> n == 0
(IntDiv, _) -> True
(IntMod, _) -> True
(FPMin, _) -> True
(FPMax, _) -> True
(FPToUBV _, _) -> True
(FPToSBV _, _) -> True
_ -> False
-- | The parse state with the declarations of the formulas.
declarationsState :: [Expr] -> Either Text ParseState
declarationsState formulas = do
ses <- parseSExprs (renderScript (declarationsFor formulas))
foldM (\ps se -> fst <$> parseCommand ps se) initialParseState ses
-- | Elements of uninterpreted sorts, named as the solver names them
-- (@U!val!3@ is the element 3 of @U@).
elements :: ParseState -> [(Text, SExpr)] -> Either Text [(Symbol, Value)]
elements ps decls = do
sorted <- forM decls $ \(n, s) -> (,) n <$> parseSort ps s
let numbered = zipWith (\k (n, s) -> (Symbol n [] s, VUninterp s (fromMaybe k (number n)))) [1000000 ..] sorted
pure numbered
where
number n =
let digits = T.takeWhileEnd isDigit n
in if not (T.null digits) && "!val!" `T.isSuffixOf` T.dropEnd (T.length digits) n
then Just (read (T.unpack digits))
else Nothing
elemInterp :: [(Symbol, Value)] -> Map Symbol FunInterp
elemInterp es = Map.fromList [(s, constInterp v) | (s, v) <- es]
data ModelCtx = ModelCtx
{ mcState :: ParseState
-- ^ Declarations of the formulas and the elements of uninterpreted
-- sorts.
, mcElems :: Map Symbol FunInterp
, mcDefs :: Map Text Definition
}
-- | Ask the solver for the values of terms.
valuesOf :: Proc -> ModelCtx -> [Expr] -> IO (Map Expr Value)
valuesOf p ctx terms = do
r <- ask p (renderCommand (GetValue terms))
pairs <- case r of
SList xs | length xs == length terms -> pure [v | SList [_, v] <- xs]
_ -> throwIO (Failure ("unexpected answer to get-value: " <> showS r))
vs <- either (throwIO . Failure) pure (traverse (valueOf ctx) pairs)
pure (Map.fromList (zip terms vs))
-- | The value denoted by a ground term of a model.
valueOf :: ModelCtx -> SExpr -> Either Text Value
valueOf ctx se = do
(se', extra) <- replaceSpecial ctx se
let ps = declareConstants (map fst extra) (mcState ctx)
interp =
emptyInterpretation
{ interpSymbols = Map.union (Map.fromList [(s, constInterp v) | (s, v) <- extra]) (mcElems ctx)
}
(e, _) <- parseTerm ps se'
either (\err -> Left ("cannot evaluate a model value: " <> eeMessage err)) Right (evalExpr interp e)
-- | Replace the array values given as functions (@as-array@ and @lambda@)
-- by fresh constants with their values.
replaceSpecial :: ModelCtx -> SExpr -> Either Text (SExpr, [(Symbol, Value)])
replaceSpecial ctx se = case se of
SList [SSym "_", SSym "as-array", SSym g] -> case Map.lookup g (mcDefs ctx) of
Just (Definition [(x, s)] res body) -> array [(x, s)] res body
_ -> Left ("unsupported array value: " <> showS se)
SList [SSym "lambda", SList [SList [SSym x, s]], body] -> do
idx <- parseSort (mcState ctx) s
fi <- tableOf ctx [(x, idx)] body
constantFor (arrayOf idx fi)
SList xs -> do
rs <- traverse (replaceSpecial ctx) xs
pure (SList (map fst rs), concatMap snd rs)
-- Z3 names the elements of uninterpreted sorts S!val!k, and does not
-- always declare them in the model.
SSym n
| (prefix, digits) <- T.breakOnEnd "!val!" n
, Just sortName <- T.stripSuffix "!val!" prefix
, not (T.null digits) && T.all isDigit digits
, Right s@(UninterpretedSort _) <- parseSort (mcState ctx) (SSym sortName) ->
constantFor (VUninterp s (read (T.unpack digits)))
_ -> pure (se, [])
where
array params res body = do
sorts <- traverse (parseSort (mcState ctx) . snd) params
_ <- parseSort (mcState ctx) res
fi <- tableOf ctx (zip (map fst params) sorts) body
case sorts of
[idx] -> constantFor (arrayOf idx fi)
_ -> Left "array function of several arguments"
arrayOf idx fi = mkArray idx (Map.fromList [(k, v) | ([k], v) <- Map.toList (fiTable fi)]) (fiDefault fi)
-- Equal subterms denote equal values, so the name can be the term.
constantFor v = do
let sym = Symbol ("hsmt!v!" <> showS se) [] (valueSort v)
pure (SSym (symName sym), [(sym, v)])
-- | The interpretation of a function from its body: an @ite@ chain whose
-- conditions fix every parameter, ending in a value.
tableOf :: ModelCtx -> [(Text, Sort)] -> SExpr -> Either Text FunInterp
tableOf ctx params = go
where
names = map fst params
mentions = \case
SSym s -> s `elem` names
SList xs -> any mentions xs
_ -> False
go = \case
SList [SSym "ite", c, v, rest] | mentions c && not (mentions v) -> do
keys <- condition c
val <- valueOf ctx v
FunInterp tbl def <- go rest
pure (FunInterp (foldr (`Map.insert` val) tbl keys) def)
body
| not (mentions body) -> constInterp <$> valueOf ctx body
| otherwise -> Left ("unsupported function interpretation: " <> showS body)
condition = \case
SList (SSym "or" : cs) -> concat <$> traverse condition cs
SList (SSym "and" : cs) -> traverse literal cs >>= assemble
c -> literal c >>= assemble . pure
literal = \case
SList [SSym "=", SSym x, v] | x `elem` names, not (mentions v) -> (,) x <$> valueOf ctx v
SList [SSym "=", v, SSym x] | x `elem` names, not (mentions v) -> (,) x <$> valueOf ctx v
SSym x | x `elem` names -> Right (x, VBool True)
SList [SSym "not", SSym x] | x `elem` names -> Right (x, VBool False)
c -> Left ("unsupported condition in a function interpretation: " <> showS c)
assemble lits
| length lits == length names
, Just key <- traverse (`lookup` lits) names =
Right [key]
| otherwise = Left "a condition does not fix every parameter"