| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
 | 
module Solver.SMTLIB.Internal.Interaction where
import IO        (Handle, hClose, hFlush, hPutStr)
import IOExts    (execCmd)
import Text.Pretty
import           Language.SMTLIB.Files        (writeSMTDump)
import           Language.SMTLIB.Goodies      (comment, echo, isEcho, var)
import           Language.SMTLIB.Parser       (parseCmdRsps)
import           Language.SMTLIB.Pretty
import qualified Language.SMTLIB.Types as SMT
import Solver.SMTLIB.Internal.Utils
import Solver.SMTLIB.Types
data SMTSession = SMTSession
  { handles     :: (Handle, Handle, Handle)
  , buffer      :: [SMT.Command]
  , trace       :: [SMT.Command]
  , options     :: SMTOpts
  , fresh       :: Int
  , globalDecls :: [SMT.Command]
  }
data SMTSess a = SMTSess { runSMTSess :: SMTSession -> SMT (a, SMTSession) }
instance Monad SMTSess where
  return x = SMTSess $ \s -> return (x, s)
  m >>= f = SMTSess $ \s -> do
    (r, s') <- runSMTSess m s
    runSMTSess (f r) s'
getSess :: SMTSess SMTSession
getSess = SMTSess $ \s -> return (s, s)
putSess :: SMTSession -> SMTSess ()
putSess s = SMTSess $ \_ -> return ((), s)
evalSess :: SMTSess a -> SMT a
evalSess smtSess = do
  s <- get
  runSMTSess smtSess s >>= \(r, s') -> put s' >> return r
evalSessionsImpl :: SMTSolver -> SMTOpts -> SMTSess a -> IO a
evalSessionsImpl solver opts as = do
  s       <- startSession solver opts
  (r, s') <- runSMT (evalSess as >>= \res -> closeSession >> return res) s
  termSession s'
  whenM (tracing $ options s') (dumpSession s')
  return r
data SMT a = SMT { runSMT :: SMTSession -> IO (a, SMTSession) }
instance Monad SMT where
  return x = SMT $ \s -> return (x, s)
  m >>= f = SMT $ \s -> do
    (r, s') <- runSMT m s
    runSMT (f r) s'
evalSMT :: SMT a -> SMTSession -> IO a
evalSMT smt s = runSMT smt s >>= return . fst
execSMT :: SMT a -> SMTSession -> IO SMTSession
execSMT smt s =
  runSMT smt s >>= return . snd
gets :: (SMTSession -> a) -> SMT a
gets f = SMT $ \s -> return (f s, s)
get :: SMT SMTSession
get = gets id
put :: SMTSession -> SMT ()
put s = SMT $ \_ -> return ((), s)
getStdin :: SMT Handle
getStdin = gets ((\(x, _, _) -> x) . handles)
getStdout :: SMT Handle
getStdout = gets ((\(_, y, _) -> y) . handles)
takeBuffer :: SMT [SMT.Command]
takeBuffer = do
  buf <- gets buffer
  modify $ \s -> s { buffer = [] }
  return buf
getTrace :: SMT [SMT.Command]
getTrace = gets trace
getGlobalCmds :: SMT [SMT.Command]
getGlobalCmds = gets (globalCmds . options)
isIncremental :: SMT Bool
isIncremental = gets (incremental . options)
getGlobalDecls :: SMT [SMT.Command]
getGlobalDecls = gets globalDecls
modify :: (SMTSession -> SMTSession) -> SMT ()
modify f = SMT $ \s -> return ((), f s)
liftIOA :: IO a -> SMTSess a
liftIOA = liftSMT . liftIO2SMT
liftSMT :: SMT a -> SMTSess a
liftSMT smt = SMTSess $ \s -> smt >>= (\x -> return (x, s))
liftIO2SMT :: IO a -> SMT a
liftIO2SMT io = SMT $ \s -> io >>= (\x -> return (x, s))
evalSession :: SMT a -> SMTSess a
evalSession smt = do
  s         <- getSess
  (res, s') <- liftIOA $ runSMT smt s
  putSess s'
  return res
data SMTResult = Error  [SMTError]
            | Unsat
            | Unknown
            | Sat
            | Model  [SMT.ModelRsp]
            | Values [SMT.ValuationPair]
  deriving Show
instance Pretty SMTResult where
  pretty (Error msgs) = vsep $ map pretty msgs
  pretty Unsat        = text "unsat"
  pretty Unknown      = text "unknown"
  pretty Sat          = text "sat"
  pretty (Model   ms) = parent (map pretty ms)
  pretty (Values vps) = parent (map ppValPair vps)
rsp2Msg :: SMT.CmdResponse -> SMTError
rsp2Msg rsp = case rsp of
  SMT.ErrorRsp            msg -> SolverError  msg
  SMT.CheckSatRsp SMT.Unknown -> SolverError  "Unknown"
  SMT.UnsupportedRsp          -> SolverError  "Unsupported command"
  SMT.CheckSatRsp SMT.Unsat   -> SolverError  "Unsat"
  _                           -> OtherError $ "Unexpected response: " ++ show rsp
res2Msgs :: SMTResult -> [SMTError]
res2Msgs res = case res of
  Error msgs -> msgs
  Unsat      -> [SolverError "Unsat"]
  Unknown    -> [SolverError "Unknown"]
  _          -> [OtherError ("Unexpected result: " ++ show res)]
declareVars :: Int -> SMT.Sort -> SMT [SMT.Term]
declareVars n sort = do
  s <- get
  let v     = fresh s
      names = map (('x' :) . show) [v .. v + n - 1]
  put s { fresh       = v + n
        , globalDecls = globalDecls s ++ map (flip SMT.DeclareConst sort) names
        }
  return $ map var names
checkSat :: SMT SMTResult
checkSat = do
  errMsg <- getDelimited
  
  case parseCmdRsps errMsg of
    Left  msg                -> return $ Error [ParserError msg]
    Right rs | not (null rs) -> return $ Error (map rsp2Msg rs)
             | otherwise     -> do
      sendCmds [SMT.CheckSat]
      satMsg <- getDelimited
      
      case parseCmdRsps satMsg of
        Left  msg                           -> return $ Error [ParserError msg]
        Right [SMT.CheckSatRsp SMT.Unknown] -> return $ Unknown
        Right [SMT.CheckSatRsp SMT.Unsat]   -> return $ Unsat
        Right [SMT.CheckSatRsp SMT.Sat]     -> return $ Sat
        Right rsps                          -> return $ Error $ map rsp2Msg rsps
getModel :: SMT (Either [SMTError] [SMT.ModelRsp])
getModel = do
  sendCmds [SMT.GetModel]
  modelMsg <- getDelimited
  case parseCmdRsps modelMsg of
    Left  msg                 -> return $ Left  $ [ParserError msg]
    Right [SMT.GetModelRsp m] -> return $ Right $ m
    Right rsps                -> return $ Left  $ map rsp2Msg rsps
getValues :: [SMT.Term] -> SMT (Either [SMTError] [SMT.ValuationPair])
getValues ts = do
  sendCmds [SMT.GetValue ts]
  valMsg <- getDelimited
  case parseCmdRsps valMsg of
    Left  msg                 -> return $ Left  $ [ParserError msg]
    Right [SMT.GetValueRsp m] -> return $ Right $ m
    Right rsps                -> return $ Left  $ map rsp2Msg rsps
bufferGlobalDefs :: SMT ()
bufferGlobalDefs = do
  globals <- getGlobalDecls >>= \ds   ->
             getGlobalCmds  >>= \cmds -> return (ds ++ cmds)
  unlessM (null globals) $ do
    info "Asserting global definitions"
    bufferCmds $ (comment "----- BEGIN GLOBAL DEFINITIONS -----") : globals
      ++ [comment "----- END   GLOBAL DEFINITIONS -----"]
    isInc <- isIncremental
    whenM isInc $ modify $ \s -> s { options = (options s) { globalCmds = [] }
                                   , globalDecls = []
                                   }
resetSession :: SMT ()
resetSession = modify $ \s -> s { buffer = [SMT.Reset] }
optReset :: SMT ()
optReset = isIncremental >>= \isInc -> unlessM isInc $ do
  info "Resetting SMT solver stack"
  resetSession
optTracing :: [SMT.Command] -> SMT ()
optTracing buf = do
  s <- get
  whenM (tracing $ options s) (put s { trace = trace s ++ buf })
closeSession :: SMT ()
closeSession = sendCmds [SMT.Exit]
startSession :: SMTSolver -> SMTOpts -> IO SMTSession
startSession solver opts = do
  unlessM (quiet opts) $ putStrLn $ "Starting " ++ sname ++ " session."
  hs <- execCmd $ unwords $ sname : flags solver
  return $ SMTSession hs [] [] opts 1 []
 where sname = executable solver
termSession :: SMTSession -> IO ()
termSession (SMTSession (i, o, e) _ _ opts _ _) = do
  unlessM (quiet opts) $ putStrLn "Terminating session."
  hClose i
  hClose o
  hClose e
dumpSession :: SMTSession -> IO ()
dumpSession s = writeSMTDump "smtDump" (rmvEchos $ trace s)
bufferCmds :: [SMT.Command] -> SMT ()
bufferCmds cmds = modify $ \s -> s { buffer = buffer s ++ cmds }
sendCmds :: [SMT.Command] -> SMT ()
sendCmds cmds = do
  bufferCmds (cmds ++ [echo delim])
  sin <- getStdin
  buf <- takeBuffer
  liftIO2SMT $ hPutStr sin (showSMT buf) >> hFlush sin
  optTracing buf
getDelimited :: SMT String
getDelimited = getStdout >>= liftIO2SMT . flip hGetUntil delim
info :: String -> SMT ()
info msg = get >>= \s -> unlessM (quiet (options s)) $ liftIO2SMT $ putStrLn msg
rmvEchos :: [SMT.Command] -> [SMT.Command]
rmvEchos = filter (not . isEcho)
 |