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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
|
module Main where
import Control.Monad ( unless, when )
import Data.IORef
import Data.List ( (\\), elemIndex, find, maximum, minimum
, partition, union )
import Data.Maybe ( catMaybes )
import System.Environment ( getArgs )
import Analysis.ProgInfo
import Analysis.TotallyDefined ( siblingCons )
import Analysis.Types
import CASS.Server ( analyzeGeneric, analyzePublic )
import Contract.Names
import Contract.Usage ( checkContractUsage )
import Control.Monad.Trans.Class ( lift )
import Control.Monad.Trans.State ( StateT, get, put, evalStateT )
import Debug.Profile
import FlatCurry.TypeAnnotated.TypeSubst ( substRule )
import FlatCurry.Files ( readFlatCurryInt )
import FlatCurry.Types
import FlatCurry.Annotated.Goodies
import FlatCurry.ShowIntMod ( showCurryModule )
import RW.Base ( ReadWrite )
import System.FilePath ( (</>) )
import System.IOExts ( evalCmd )
import System.Path ( fileInPath )
import System.Process ( exitWith )
import ESMT
import Curry2SMT
import FlatCurry.Typed.Read
import FlatCurry.Typed.Goodies
import FlatCurry.Typed.Names
import FlatCurry.Typed.Types
import PackageConfig ( packagePath )
import ToolOptions
import VerifierState
test :: Int -> String -> IO ()
test v = verifyNonFailingMod defaultOptions { optVerb = v }
testv :: String -> IO ()
testv = test 3
testcv :: String -> IO ()
testcv = verifyNonFailingMod defaultOptions { optVerb = 3, optContract = True }
banner :: String
banner = unlines [bannerLine,bannerText,bannerLine]
where
bannerText = "Fail-Free Verification Tool for Curry (Version of 28/09/24)"
bannerLine = take (length bannerText) (repeat '=')
main :: IO ()
main = do
args <- getArgs
(opts,progs) <- processOptions banner args
let optname = optName opts
if not (null optname)
then putStrLn $ "Non-failure condition for '" ++ optname ++ "':\n" ++
encodeContractName (optname ++ "'nonfail")
else do
z3exists <- fileInPath "z3"
if z3exists
then do
when (optVerb opts > 0) $ putStrLn banner
verifyNonFailingModules opts [] progs
else do
putStrLn "NON-FAILING ANALYSIS SKIPPED:"
putStrLn "The SMT solver Z3 is required for the verifier to work"
putStrLn "but the program 'z3' is not found on the PATH!"
exitWith 1
verifyNonFailingModules :: Options -> [String] -> [String] -> IO ()
verifyNonFailingModules _ _ [] = return ()
verifyNonFailingModules opts verifiedmods (mod:mods)
| mod `elem` verifiedmods
= verifyNonFailingModules opts verifiedmods mods
| optRec opts
= do (Prog _ imps _ _ _) <- readFlatCurryInt mod
let newimps = filter (`notElem` verifiedmods) imps
if null newimps
then do printWhenStatus opts ""
verifyNonFailingMod opts mod
verifyNonFailingModules opts (mod:verifiedmods) mods
else verifyNonFailingModules opts verifiedmods
(newimps ++ mod : (mods \\ newimps))
| otherwise
= do verifyNonFailingMod opts mod
verifyNonFailingModules opts (mod:verifiedmods) mods
verifyNonFailingMod :: Options -> String -> IO ()
verifyNonFailingMod opts modname = do
printWhenStatus opts $ "Analyzing module '" ++ modname ++ "':"
prog <- readSimpTypedFlatCurryWithSpec opts modname
let errs = checkContractUsage (progName prog)
(map (\fd -> (snd (funcName fd), funcType fd)) (progFuncs prog))
unless (null errs) $ do
putStr $ unlines (map showOpError errs)
exitWith 1
impprogs <- mapM (readSimpTypedFlatCurryWithSpec opts) (progImports prog)
let allprogs = prog : impprogs
vinfo = foldr addFunsToVerifyInfo (initVerifyInfo opts)
(map progFuncs allprogs)
vstate = foldr addProgToState (initVState vinfo) allprogs
siblingconsinfo <- loadAnalysisWithImports siblingCons prog
pi1 <- getProcessInfos
printWhenAll opts $ unlines $
["ORIGINAL PROGRAM:", line, showCurryModule (unAnnProg prog), line]
vstref <- newIORef vstate
proveNonFailingFuncs opts siblingconsinfo vstref (progFuncs prog)
stats <- readIORef vstref
pi2 <- getProcessInfos
let tdiff = maybe 0 id (lookup ElapsedTime pi2) -
maybe 0 id (lookup ElapsedTime pi1)
when (optTime opts) $ putStrLn $
"TOTAL VERIFICATION TIME : " ++ show tdiff ++ " msec"
when (optVerb opts > 0 || not (isVerified stats)) $
putStr (showStats stats)
where
line = take 78 (repeat '-')
showOpError (qf,err) =
snd qf ++ " (module " ++ fst qf ++ "): " ++ err
loadAnalysisWithImports ::
(Read a, Show a, ReadWrite a, Eq a) => Analysis a -> TAProg -> IO (ProgInfo a)
loadAnalysisWithImports analysis prog = do
maininfo <- analyzeGeneric analysis (progName prog)
>>= return . either id error
impinfos <- mapM (\m -> analyzePublic analysis m >>=
return . either id error)
(progImports prog)
return $ foldr combineProgInfo maininfo impinfos
data TransState = TransState
{ cAssertion :: Term
, freshVar :: Int
, varTypes :: [(Int,TypeExpr)]
}
makeTransState :: Int -> [(Int,TypeExpr)] -> TransState
makeTransState = TransState tTrue
emptyTransState :: TransState
emptyTransState = makeTransState 0 []
type TransStateM a = StateT TransState IO a
getFreshVarIndex :: TransStateM Int
getFreshVarIndex = get >>= return . freshVar
setFreshVarIndex :: Int -> TransStateM ()
setFreshVarIndex fvi = do
st <- get
put $ st { freshVar = fvi }
getFreshVar :: TransStateM Int
getFreshVar = do
st <- get
put $ st { freshVar = freshVar st + 1 }
return $ freshVar st
incFreshVarIndex :: TransState -> TransState
incFreshVarIndex st = st { freshVar = freshVar st + 1 }
getVarTypes :: TransStateM [(Int,TypeExpr)]
getVarTypes = get >>= return . varTypes
addVarTypes :: [(Int,TypeExpr)] -> TransStateM ()
addVarTypes vts = do
st <- get
put $ st { varTypes = vts ++ varTypes st }
getAssertion :: TransStateM Term
getAssertion = get >>= return . cAssertion
setAssertion :: Term -> TransStateM ()
setAssertion formula = do
st <- get
put $ st { cAssertion = formula }
addToAssertion :: Term -> TransStateM ()
addToAssertion formula = do
st <- get
put $ st { cAssertion = tConj [cAssertion st, formula] }
proveNonFailingFuncs :: Options -> ProgInfo [(QName,Int)] -> IORef VState
-> [TAFuncDecl] -> IO ()
proveNonFailingFuncs opts siblingconsinfo vstref =
mapM_ (proveNonFailingFunc opts siblingconsinfo vstref)
proveNonFailingFunc :: Options -> ProgInfo [(QName,Int)] -> IORef VState
-> TAFuncDecl -> IO ()
proveNonFailingFunc opts siblingconsinfo vstref fdecl =
unless (isContractOp (funcName fdecl) || isProperty fdecl) $ do
printWhenIntermediate opts $
"Operation to be analyzed: " ++ snd (funcName fdecl)
modifyIORef vstref incNumAllInStats
let efdecl = etaExpandFuncDecl fdecl
proveNonFailingRule opts siblingconsinfo vstref
(funcName efdecl) (funcType efdecl)
(funcRule efdecl)
proveNonFailingRule :: Options -> ProgInfo [(QName,Int)] -> IORef VState
-> QName -> TypeExpr -> TARule -> IO ()
proveNonFailingRule _ _ vstref qn ftype (AExternal _ _) = do
ti <- readVerifyInfoRef vstref
let atypes = argTypes ftype
args = zip [1 .. length atypes] atypes
nfcond <- evalStateT (nonfailPreCondExpOf ti qn ftype args) emptyTransState
unless (nfcond == tTrue) $ modifyIORef vstref incNumNFCInStats
proveNonFailingRule opts siblingconsinfo vstref qn@(_,fn) ftype
(ARule _ rargs rhs) = do
ti <- readVerifyInfoRef vstref
let st = makeTransState (maximum (0 : map fst rargs ++ allVars rhs) + 1) rargs
(flip evalStateT) st $ do
precondformula <- nonfailPreCondExpOf ti qn ftype rargs
setAssertion precondformula
unless (precondformula == tTrue) $ lift $
modifyIORef vstref incNumNFCInStats
unless (precondformula == tFalse) $ proveNonFailExp ti rhs
where
proveNonFailExp ti exp = case simpExpr exp of
AComb _ ct (qf,qfty) args -> do
mapM_ (proveNonFailExp ti) args
when (isCombTypeFuncPartCall ct) $
let qnnonfail = toNonFailQName qf
in maybe
(return ())
(\_ -> lift $ do
let reason = "due to call '" ++ ppTAExpr exp ++ "'"
modifyIORef vstref (addFailedFuncToStats fn reason)
printWhenIntermediate opts $
fn ++ ": POSSIBLY FAILING CALL OF '" ++ snd qf ++ "'")
(find (\fd -> funcName fd == qnnonfail) (nfConds ti))
when (ct==FuncCall) $ do
lift $ printWhenIntermediate opts $ "Analyzing call to " ++ snd qf
precond <- getAssertion
(bs,_) <- normalizeArgs args
bindexps <- mapM (binding2SMT True ti) bs
let callargs = zip (map fst bs) (map annExpr args)
nfcondcall <- nonfailPreCondExpOf ti qf qfty callargs
vartypes <- getVarTypes
valid <- if nfcondcall == tTrue
then return (Just True)
else lift $ do
modifyIORef vstref incFailTestInStats
let title = "SMT script to verify non-failing call of '" ++
snd qf ++ "' in function '" ++ fn ++ "'"
checkImplicationWithSMT opts vstref title vartypes
precond (tConj bindexps) nfcondcall
if valid == Just True
then lift $ printWhenIntermediate opts $
fn ++ ": NON-FAILING CALL OF '" ++ snd qf ++ "'"
else lift $ do
let reason = if valid == Nothing
then "due to SMT error"
else "due to call '" ++ ppTAExpr exp ++ "'"
modifyIORef vstref (addFailedFuncToStats fn reason)
printWhenIntermediate opts $
fn ++ ": POSSIBLY FAILING CALL OF '" ++ snd qf ++ "'"
ACase _ _ e brs -> do
proveNonFailExp ti e
maybe
(do
freshvar <- getFreshVar
let freshtypedvar = (freshvar, annExpr e)
be <- binding2SMT True ti (freshvar,e)
addToAssertion be
addVarTypes [freshtypedvar]
let misscons = missingConsInBranch siblingconsinfo brs
st <- get
mapM_ (verifyMissingCons freshtypedvar exp) misscons
put st
mapM_ (proveNonFailBranch ti freshtypedvar) brs
)
(\ (fe,te) -> do
be <- pred2SMT e
st <- get
addToAssertion (tNot be)
proveNonFailExp ti fe
put st
addToAssertion be
proveNonFailExp ti te
)
(testBoolCase brs)
AOr _ e1 e2 -> do st <- get
proveNonFailExp ti e1
put st
proveNonFailExp ti e2
ALet _ bs e -> do (rbs,re) <- renameLetVars bs e
mapM_ (proveNonFailExp ti) (map snd rbs)
proveNonFailExp ti re
AFree _ fvs e -> do (_,re) <- renameFreeVars fvs e
proveNonFailExp ti re
ATyped _ e _ -> proveNonFailExp ti e
AVar _ _ -> return ()
ALit _ _ -> return ()
verifyMissingCons (var,vartype) exp (cons,_) = do
let title = "check missing constructor case '" ++ snd cons ++
"' in function '" ++ fn ++ "'"
lift $ printWhenIntermediate opts $
title ++ "\nVAR: " ++ show (var,vartype) ++ "\nCASE:: " ++
show (unAnnExpr (simpExpr exp))
lift $ modifyIORef vstref incPatTestInStats
vartypes <- getVarTypes
precond <- getAssertion
valid <- lift $ checkImplicationWithSMT opts vstref
("SMT script to " ++ title) vartypes precond tTrue
(tNot (constructorTest False cons (TSVar var) vartype))
unless (valid == Just True) $ lift $ do
let reason = if valid == Nothing
then "due to SMT error"
else "maybe not defined on constructor '" ++
showQName cons ++ "'"
modifyIORef vstref (addFailedFuncToStats fn reason)
printWhenIntermediate opts $
"POSSIBLY FAILING BRANCH in function '" ++ fn ++
"' with constructor " ++ snd cons
proveNonFailBranch ti (var,vartype) branch = do
ABranch p e <- renamePatternVars branch
let bpat = pat2SMT (setAnnPattern vartype p)
addToAssertion (tEquVar var bpat)
proveNonFailExp ti e
missingConsInBranch :: ProgInfo [(QName,Int)] -> [TABranchExpr] -> [(QName,Int)]
missingConsInBranch _ [] =
error "missingConsInBranch: case with empty branches!"
missingConsInBranch _ (ABranch (ALPattern _ _) _ : _) =
error "TODO: case with literal pattern"
missingConsInBranch siblingconsinfo
(ABranch (APattern _ (cons,_) _) _ : brs) =
let othercons = maybe (error $ "Sibling constructors of " ++
showQName cons ++ " not found!")
id
(lookupProgInfo cons siblingconsinfo)
branchcons = map (patCons . branchPattern) brs
in filter ((`notElem` branchcons) . fst) othercons
simpExpr :: TAExpr -> TAExpr
simpExpr exp = case exp of
AComb ty FuncCall (qf,_) args ->
if qf == pre "?"
then AOr ty (args!!0) (args!!1)
else if qf == pre "ord" || qf == pre "id"
then head args
else exp
_ -> exp
binding2SMT :: Bool -> VerifyInfo -> (Int,TAExpr) -> TransStateM Term
binding2SMT demanded ti (resvar,exp) =
case simpExpr exp of
AVar _ i -> return $ if resvar==i then tTrue
else tEquVar resvar (TSVar i)
ALit _ l -> return (tEquVar resvar (lit2SMT l))
AComb rtype ct (qf,_) args -> do
(bs,nargs) <- normalizeArgs args
bindexps <- mapM (binding2SMT (isPrimOp qf || optStrict (toolOpts ti)) ti)
bs
comb2bool qf rtype ct nargs bs bindexps
ALet _ bs e -> do
bindexps <- mapM (binding2SMT False ti)
(map (\ ((i,_),ae) -> (i,ae)) bs)
bexp <- binding2SMT demanded ti (resvar,e)
return (tConj (bindexps ++ [bexp]))
AOr _ e1 e2 -> do
bexp1 <- binding2SMT demanded ti (resvar,e1)
bexp2 <- binding2SMT demanded ti (resvar,e2)
return (tDisj [bexp1, bexp2])
ACase _ _ e brs -> do
freshvar <- getFreshVar
addVarTypes [(freshvar, annExpr e)]
argbexp <- binding2SMT demanded ti (freshvar,e)
bbrs <- mapM branch2bool (map (\b->(freshvar,b)) brs)
return (tConj [argbexp, tDisj bbrs])
ATyped _ e _ -> binding2SMT demanded ti (resvar,e)
AFree _ _ _ -> error "Free variables not yet supported!"
where
comb2bool qf rtype ct nargs bs bindexps
| qf == pre "otherwise"
= return (tEquVar resvar tTrue)
| ct == ConsCall
= return (tConj (bindexps ++
[tEquVar resvar
(TComb (cons2SMT (null nargs) False qf rtype)
(map arg2bool nargs))]))
| qf == pre "apply"
=
return tTrue
| isPrimOp qf
= return (tConj (bindexps ++
[tEquVar resvar
(TComb (cons2SMT True False qf rtype)
(map arg2bool nargs))]))
| otherwise
= do let targs = zip (map fst bs) (map annExpr nargs)
precond <- preCondExpOf ti qf targs
postcond <- postCondExpOf ti qf (targs ++ [(resvar,rtype)])
return (tConj (bindexps ++
if demanded && optContract (toolOpts ti)
then [precond,postcond]
else []))
branch2bool (cvar, ABranch p e) = do
branchbexp <- binding2SMT demanded ti (resvar,e)
addVarTypes patvars
return (tConj [ tEquVar cvar (pat2SMT p), branchbexp])
where
patvars = if isConsPattern p
then patArgs p
else []
arg2bool e = case e of AVar _ i -> TSVar i
ALit _ l -> lit2SMT l
_ -> error $ "Not normalized: " ++ show e
nonfailPreCondExpOf :: VerifyInfo -> QName -> TypeExpr -> [(Int,TypeExpr)]
-> TransStateM Term
nonfailPreCondExpOf ti qf ftype args =
if optContract (toolOpts ti)
then do
(fvars,nfcond) <- nonfailCondExpOf ti qf ftype args
precond <- preCondExpOf ti qf (args ++ fvars)
return (simpTerm (tConj [nfcond,precond]))
else do
(_,rt) <- nonfailCondExpOf ti qf ftype args
return rt
nonfailCondExpOf :: VerifyInfo -> QName -> TypeExpr -> [(Int,TypeExpr)]
-> TransStateM ([(Int,TypeExpr)], Term)
nonfailCondExpOf ti qf ftype args =
maybe
(predefs qf)
(\fd -> let moreargs = funcArity fd - length args in
if moreargs > 0
then do
let etatypes = argTypes (dropArgTypes (length args) ftype)
fvars <- getFreshVarsForTypes (take moreargs etatypes)
rt <- applyFunc fd (args ++ fvars) >>= pred2SMT
return (fvars,rt)
else if moreargs < 0
then error $ "Operation '" ++ snd qf ++
"': nonfail condition has too few arguments!"
else do rt <- applyFunc fd args >>= pred2SMT
return ([],rt) )
(find (\fd -> decodeContractQName (funcName fd) == toNonFailQName qf)
(nfConds ti))
where
predefs qn | qn `elem` [pre "failed", pre "=:="] ||
(qn == pre "error" && optError (toolOpts ti))
= return ([], tFalse)
| otherwise
= return ([], tTrue)
preCondExpOf :: VerifyInfo -> QName -> [(Int,TypeExpr)] -> TransStateM Term
preCondExpOf ti qf args =
maybe (return tTrue)
(\fd -> applyFunc fd args >>= pred2SMT)
(find (\fd -> funcName fd == toPreCondQName qf) (preConds ti))
postCondExpOf :: VerifyInfo -> QName -> [(Int,TypeExpr)] -> TransStateM Term
postCondExpOf ti qf args =
maybe (return tTrue)
(\fd -> applyFunc fd args >>= pred2SMT)
(find (\fd -> funcName fd == toPostCondQName qf) (postConds ti))
applyFunc :: TAFuncDecl -> [(Int,TypeExpr)] -> TransStateM TAExpr
applyFunc fdecl targs = do
fv <- getFreshVarIndex
let tsub = maybe (error $ "applyFunc: types\n" ++
show (argTypes (funcType fdecl)) ++ "\n" ++
show (map snd targs) ++ "\ndo not match!")
id
(matchTypes (argTypes (funcType fdecl)) (map snd targs))
(ARule _ orgargs orgexp) = substRule tsub (funcRule fdecl)
exp = rnmAllVars (renameRuleVar fv orgargs) orgexp
setFreshVarIndex (max fv (maximum (0 : args ++ allVars exp) + 1))
return $ simpExpr $ applyArgs exp (drop (length orgargs) args)
where
args = map fst targs
renameRuleVar fv orgargs r = maybe (r + fv)
(args!!)
(elemIndex r (map fst orgargs))
applyArgs e [] = e
applyArgs e (v:vs) =
let e_v = AComb failed FuncCall
(pre "apply", failed) [e, AVar failed v]
in applyArgs e_v vs
pred2SMT :: TAExpr -> TransStateM Term
pred2SMT exp = case simpExpr exp of
AVar _ i -> return (TSVar i)
ALit _ l -> return (lit2SMT l)
AComb _ ct (qf,ftype) args -> comb2bool qf ftype ct (length args) args
_ -> return (tComb (show exp) [])
where
comb2bool qf ftype ct ar args
| qf == pre "[]" && ar == 0
= return (sortedConst "nil" (polytype2sort (annExpr exp)))
| qf == pre "not" && ar == 1
= do barg <- pred2SMT (head args)
return (tNot barg)
| qf == pre "null" && ar == 1
= do let arg = head args
barg <- pred2SMT arg
vartype <- typeOfVar arg
return (tEqu barg (sortedConst "nil" (polytype2sort vartype)))
| qf == pre "apply"
= do
fvar <- getFreshVar
addVarTypes [(fvar,annExpr exp)]
return (TSVar fvar)
| qf == pre "/="
= do be <- comb2bool (pre "==") ftype ct ar args
return (tNot be)
| otherwise
= do bargs <- mapM pred2SMT args
return (TComb (cons2SMT (ct /= ConsCall || not (null bargs))
False qf ftype)
bargs)
typeOfVar e = do
vartypes <- getVarTypes
case e of
AVar _ i -> maybe
(error $ "pred2SMT: variable " ++ show i ++ " not found")
return
(lookup i vartypes)
_ -> return $ annExpr e
normalizeArgs :: [TAExpr] -> TransStateM ([(Int,TAExpr)],[TAExpr])
normalizeArgs [] = return ([],[])
normalizeArgs (e:es) = case e of
AVar _ i -> do (bs,nes) <- normalizeArgs es
return ((i,e):bs, e:nes)
_ -> do fvar <- getFreshVar
addVarTypes [(fvar,annExpr e)]
(bs,nes) <- normalizeArgs es
return ((fvar,e):bs, AVar (annExpr e) fvar : nes)
getFreshVarsForTypes :: [TypeExpr] -> TransStateM [(VarIndex, TypeExpr)]
getFreshVarsForTypes types = do
fv <- getFreshVarIndex
let n = length types
vars = take n [fv ..]
tvars = zip vars types
setFreshVarIndex (fv + n)
addVarTypes tvars
return tvars
renameLetVars :: [((VarIndex, TypeExpr), TAExpr)] -> TAExpr
-> TransStateM ([((VarIndex, TypeExpr), TAExpr)], TAExpr)
renameLetVars bindings exp = do
fv <- getFreshVarIndex
let args = map (fst . fst) bindings
minarg = minimum (0 : args)
maxarg = maximum (0 : args)
rnm i = if i `elem` args then i - minarg + fv else i
nargs = map (\ ((v,t),_) -> (rnm v,t)) bindings
setFreshVarIndex (fv + maxarg - minarg + 1)
addVarTypes nargs
return (map (\ ((v,t),be) -> ((rnm v,t), rnmAllVars rnm be)) bindings,
rnmAllVars rnm exp)
renameFreeVars :: [(VarIndex, TypeExpr)] -> TAExpr
-> TransStateM ([(VarIndex, TypeExpr)], TAExpr)
renameFreeVars freevars exp = do
fv <- getFreshVarIndex
let args = map fst freevars
minarg = minimum (0 : args)
maxarg = maximum (0 : args)
rnm i = if i `elem` args then i - minarg + fv else i
nargs = map (\ (v,t) -> (rnm v,t)) freevars
setFreshVarIndex (fv + maxarg - minarg + 1)
addVarTypes nargs
return (map (\ (v,t) -> (rnm v,t)) freevars, rnmAllVars rnm exp)
renamePatternVars :: TABranchExpr -> TransStateM TABranchExpr
renamePatternVars (ABranch p e) = do
if isConsPattern p
then do fv <- getFreshVarIndex
let args = map fst (patArgs p)
minarg = minimum (0 : args)
maxarg = maximum (0 : args)
rnm i = if i `elem` args then i - minarg + fv else i
nargs = map (\ (v,t) -> (rnm v,t)) (patArgs p)
setFreshVarIndex (fv + maxarg - minarg + 1)
addVarTypes nargs
return $ ABranch (updPatArgs (map (\ (v,t) -> (rnm v,t))) p)
(rnmAllVars rnm e)
else return $ ABranch p e
checkImplicationWithSMT :: Options -> IORef VState -> String -> [(Int,TypeExpr)]
-> Term -> Term -> Term -> IO (Maybe Bool)
checkImplicationWithSMT opts vstref scripttitle vartypes
assertion impbindings imp = do
let (pretypes,usertypes) =
partition ((== "Prelude") . fst)
(foldr union [] (map (tconsOfTypeExpr . snd) vartypes))
vst <- readIORef vstref
let allsyms = catMaybes
(map (\n -> maybe Nothing Just (untransOpName n))
(map qidName
(allQIdsOfTerm (tConj [assertion, impbindings, imp]))))
unless (null allsyms) $ printWhenIntermediate opts $
"Translating operations into SMT: " ++
unwords (map showQName allsyms)
smtfuncs <- funcs2SMT vstref allsyms
let decls = map (maybe (error "Internal error: some datatype not found!") id)
(map (tdeclOf vst) usertypes)
smt = concatMap preludeType2SMT (map snd pretypes) ++
[ EmptyLine ] ++
(if null decls
then []
else [ Comment "User-defined datatypes:" ] ++
map tdecl2SMT decls) ++
[ EmptyLine, smtfuncs, EmptyLine
, Comment "Free variables:" ] ++
map typedVar2SMT vartypes ++
[ EmptyLine
, Comment "Boolean formula of assertion (known properties):"
, sAssert assertion, EmptyLine
, Comment "Bindings of implication:"
, sAssert impbindings, EmptyLine
, Comment "Assert negated implication:"
, sAssert (tNot imp), EmptyLine
, Comment "check satisfiability:"
, CheckSat
, Comment "if unsat, the implication is valid"
]
smtprelude <- readFile (packagePath </> "include" </> "Prelude.smt")
let smtinput = "; " ++ scripttitle ++ "\n\n" ++ smtprelude ++ showSMT smt
printWhenAll opts $ "SMT SCRIPT:\n" ++ showWithLineNums smtinput
printWhenAll opts $ "CALLING Z3 (with options: -smt2 -T:5)..."
(ecode,out,err) <- evalCmd "z3" ["-smt2", "-in", "-T:5"] smtinput
when (ecode>0) $ do printWhenAll opts $ "EXIT CODE: " ++ show ecode
writeFile "error.smt" smtinput
printWhenAll opts $ "RESULT:\n" ++ out
unless (null err) $ printWhenAll opts $ "ERROR:\n" ++ err
let pcvalid = let ls = lines out in not (null ls) && head ls == "unsat"
return (if ecode>0 then Nothing else Just pcvalid)
axiomatizedOps :: [String]
axiomatizedOps = ["Prelude_null","Prelude_take","Prelude_length"]
typedVar2SMT :: (Int,TypeExpr) -> Command
typedVar2SMT (i,te) = DeclareVar (SV i (polytype2sort te))
tconsOfTypeExpr :: TypeExpr -> [QName]
tconsOfTypeExpr (TVar _) = []
tconsOfTypeExpr (FuncType a b) = union (tconsOfTypeExpr a) (tconsOfTypeExpr b)
tconsOfTypeExpr (TCons qName texps) =
foldr union [qName] (map tconsOfTypeExpr texps)
tconsOfTypeExpr (ForallType _ te) = tconsOfTypeExpr te
testBoolCase :: [TABranchExpr] -> Maybe (TAExpr,TAExpr)
testBoolCase brs =
if length brs /= 2 then Nothing
else case (brs!!0, brs!!1) of
(ABranch (APattern _ (c1,_) _) e1, ABranch (APattern _ (c2,_) _) e2) ->
if c1 == pre "False" && c2 == pre "True" then Just (e1,e2) else
if c1 == pre "True" && c2 == pre "False" then Just (e2,e1) else Nothing
_ -> Nothing
showWithLineNums :: String -> String
showWithLineNums txt =
let txtlines = lines txt
maxlog = ilog (length txtlines + 1)
showNum n = (take (maxlog - ilog n) (repeat ' ')) ++ show n ++ ": "
in unlines . map (uncurry (++)) . zip (map showNum [1..]) $ txtlines
ilog :: Int -> Int
ilog n | n>0 = if n<10 then 0 else 1 + ilog (n `div` 10)
|