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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
|
module ContractProver where
import Control.Monad ( unless, when )
import Data.IORef
import Data.List ( elemIndex, find, init, isPrefixOf, last, maximum
, minimum, nub, partition, splitOn, union )
import Data.Maybe ( catMaybes, isJust, isNothing )
import System.Environment ( getArgs, getEnv )
import Contract.Names
import Contract.Usage ( checkContractUsage )
import Control.Monad.Trans.Class ( lift )
import Control.Monad.Trans.State ( StateT, get, put, evalStateT )
import System.FilePath ( (</>) )
import FlatCurry.Files
import FlatCurry.Types
import qualified FlatCurry.Goodies as FCG
import FlatCurry.Annotated.Goodies
import FlatCurry.Annotated.Types
import FlatCurry.TypeAnnotated.Files ( readTypeAnnotatedFlatCurry
, typeAnnotatedFlatCurryFileName
, writeTypeAnnotatedFlatCurryFile )
import FlatCurry.TypeAnnotated.TypeSubst ( substRule )
import FlatCurry.ShowIntMod ( showCurryModule )
import System.CurryPath ( runModuleActionQuiet )
import System.Directory ( doesFileExist )
import System.IOExts ( evalCmd )
import System.Process ( exitWith, system )
import ESMT
import Curry2SMT
import FlatCurry.Typed.Build
import FlatCurry.Typed.Read
import FlatCurry.Typed.Goodies
import FlatCurry.Typed.Names
import FlatCurry.Typed.Simplify ( simpProg, simpFuncDecl, simpExpr )
import FlatCurry.Typed.Types
import PackageConfig ( getPackagePath )
import ToolOptions
import VerifierState
banner :: String
banner = unlines [bannerLine, bannerText, bannerLine]
where
bannerText = "Contract Checking/Verification Tool (Version of 26/10/24)"
bannerLine = take (length bannerText) (repeat '=')
getContractCheckerModulePath :: IO String
getContractCheckerModulePath = getIncludePath "ContractChecker.curry"
main :: IO ()
main = do
args <- getArgs
(opts,progs) <- processOptions banner args
let optname = optName opts
if not (null optname)
then putStrLn $ "Precondition for '" ++ optname ++ "':\n" ++
encodeContractName (optname ++ "'pre") ++ "\n" ++
"Postcondition for '" ++ optname ++ "':\n" ++
encodeContractName (optname ++ "'post")
else do
when (optVerb opts > 0) $ putStrLn banner
z3exists <- fileInPath "z3"
unless (z3exists || not (optVerify opts)) $ putStrLn $ unlines $
[ "WARNING: CONTRACT VERIFICATION SKIPPED:"
, "The SMT solver Z3 is required for the verifier"
, "but the program 'z3' is not found in the PATH!"]
let opts' = if z3exists then opts else opts { optVerify = False }
mapM_ (proveContracts opts') progs
proveContracts :: Options -> String -> IO ()
proveContracts opts mainmodname = do
prog <- readTypedFlatCurryWithSpec opts mainmodname
let errs = checkContractUsage (progName prog)
(map (\fd -> (snd (funcName fd), funcType fd)) (progFuncs prog))
if null errs
then proveContractsInProg opts prog
else do putStr $ unlines (map showOpError errs)
exitWith 1
where
showOpError (qf,err) =
snd qf ++ " (module " ++ fst qf ++ "): " ++ err
proveContractsInProg :: Options -> TAProg -> IO ()
proveContractsInProg opts oprog = do
let sprog = simpProg oprog
printWhenAll opts $ unlines $
["ORIGINAL PROGRAM:", line, showCurryModule (unAnnProg oprog), line,
"SIMPLIFIED PROGRAM:", line, showCurryModule (unAnnProg sprog), line]
vstref <- newIORef (initVState (makeVerifyInfo opts (progFuncs sprog)))
modifyIORef vstref (addProgToState sprog)
prog1 <- verifyPostConditions opts oprog vstref
prog2 <- verifyPreConditions opts prog1 vstref
prog3 <- addPreConditions opts prog2 vstref
let unewprog = unAnnProg prog3
mname = progName prog3
printWhenAll opts $ unlines $
["TRANSFORMED PROGRAM WITH CONTRACT CHECKING:", line,
showCurryModule unewprog, line]
vst2 <- readIORef vstref
when (areContractsAdded vst2) $ do
when (optFCY opts) $
writeTransformedFCY opts (flatCurryFileName mname) unewprog
when (optTAFCY opts) $
writeTransformedTAFCY opts (typeAnnotatedFlatCurryFileName mname) prog3
printWhenStatus opts (showStats vst2)
where
line = take 78 (repeat '-')
writeTransformedFCY :: Options -> String -> Prog -> IO ()
writeTransformedFCY opts progfile prog = do
ccpath <- getContractCheckerModulePath
ccprog <- runModuleActionQuiet readFlatCurry ccpath
let rnmccprog = FCG.rnmProg (FCG.progName prog) ccprog
ccimps = FCG.progImports rnmccprog
ccfuncs = FCG.progFuncs rnmccprog
writeFCY progfile
(FCG.updProgFuncs (++ ccfuncs)
(FCG.updProgImports (`union` ccimps) prog))
printWhenStatus opts $ "Transformed program written to: " ++ progfile
writeTransformedTAFCY :: Options -> String -> TAProg -> IO ()
writeTransformedTAFCY opts progfile prog = do
ccpath <- getContractCheckerModulePath
ccprog <- runModuleActionQuiet readTypeAnnotatedFlatCurry ccpath
let rnmccprog = rnmProg (progName prog) ccprog
ccimps = progImports rnmccprog
ccfuncs = progFuncs rnmccprog
writeTypeAnnotatedFlatCurryFile progfile
(updProgFuncs (++ ccfuncs)
(updProgImports (`union` ccimps) prog))
printWhenStatus opts $ "Transformed program written to: " ++ progfile
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
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] }
addPreConditionCheck :: TypeExpr -> CombType -> QName -> TypeExpr -> [TAExpr]
-> TAExpr
addPreConditionCheck ty ct qf@(mn,fn) tys args =
AComb ty FuncCall
((mn, maybe "checkPreCondNoShow" (const "checkPreCond") showdicttt),
showDictTypeOf tt ~> ty ~> boolType ~> stringType ~> tt ~> ty)
(maybe [] (:[]) showdicttt ++
[ AComb ty ct (toNoCheckQName qf,tys) args
, AComb boolType ct (toPreCondQName qf, pctype) args
, string2TAFCY fn
, tupleExpr args
])
where
argtypes = map annExpr args
tt = tupleType argtypes
pctype = foldr FuncType boolType argtypes
showdicttt = showDictOf tt
toNoCheckQName :: (String,String) -> (String,String)
toNoCheckQName (mn,fn) = (mn, fn ++ "'NOCHECK")
fromNoCheckQName :: (String,String) -> (String,String)
fromNoCheckQName (mn,fn) =
(mn, let rf = reverse fn
in reverse (drop (if take 8 rf == "KCEHCON'" then 8 else 0) rf))
addPostConditionCheck :: QName -> TARule -> TAExpr
addPostConditionCheck _ (AExternal _ _) =
error $ "Trying to add postcondition to external function!"
addPostConditionCheck qf@(mn,fn) (ARule _ lhs rhs) =
AComb ty FuncCall
((mn, if showdictsexists then "checkPostCond" else "checkPostCondNoShow"),
showDictTypeOf ty ~> showDictTypeOf tt
~> ty ~> (ty ~> boolType) ~> stringType ~> tt ~> ty)
(
(if showdictsexists then catMaybes showdicts else []) ++
[ rhs
, AComb boolType (FuncPartCall 1) (toPostCondQName qf, ty) args
, string2TAFCY fn
, tupleExpr args
])
where
args = map (\ (i,t) -> AVar t i) lhs
tt = tupleType (map annExpr args)
ty = annExpr (last args)
showdicts = [showDictOf ty, showDictOf tt]
showdictsexists = all isJust showdicts
showDictOf :: TypeExpr -> Maybe TAExpr
showDictOf te = case te of
TCons qtc tes -> do
sd <- typeCons2ShowDict qtc
sds <- mapM showDictOf tes
return $ AComb (showDictTypeOf te) (FuncPartCall 1)
(sd, foldr (~>) (showDictTypeOf te) (map showDictTypeOf tes))
sds
_ -> Nothing
where
typeCons2ShowDict (mn,tc)
| mn == "Prelude"
= maybe Nothing (Just . pre) (preludeType2ShowDict tc)
| otherwise
= Just (mn, "_inst#Prelude.Show#" ++ mn ++ "." ++ tc ++ "#")
preludeType2ShowDict tc
| tc `elem` ["Int", "Float", "Char", "Bool", "Maybe", "Either",
"IOError", "Ordering"]
= Just $ "_inst#Prelude.Show#Prelude." ++ tc ++ "#"
| tc `elem` ["[]","()"] || "(," `isPrefixOf` tc
= Just $ "_inst#Prelude.Show#" ++ tc ++ "#"
| otherwise
= Nothing
showDictTypeOf :: TypeExpr -> TypeExpr
showDictTypeOf te =
FlatCurry.Typed.Build.unitType ~> TCons ("Prelude","_Dict#Show") [te]
addPreConditions :: Options -> TAProg -> IORef VState -> IO TAProg
addPreConditions _ prog vstref = do
newfuns <- mapM addPreCondition (progFuncs prog)
return (updProgFuncs (const (concat newfuns)) prog)
where
addPreCondition fdecl@(AFunc qf ar vis fty rule) = do
ti <- readVerifyInfoRef vstref
return $
if toPreCondQName qf `elem` map funcName (preConds ti)
then let newrule = checkPreCondRule qf rule
in [updFuncRule (const newrule) fdecl,
AFunc (toNoCheckQName qf) ar vis fty rule]
else [fdecl]
checkPreCondRule :: QName -> TARule -> TARule
checkPreCondRule qn (ARule rty rargs _) =
ARule rty rargs (addPreConditionCheck rty FuncCall qn rty
(map (\ (v,t) -> AVar t v) rargs))
checkPreCondRule qn (AExternal _ _) = error $
"addPreConditions: cannot add precondition to external operation '" ++
snd qn ++ "'!"
verifyPreConditions :: Options -> TAProg -> IORef VState -> IO TAProg
verifyPreConditions opts prog vstref = do
newfuns <- mapM (provePreCondition opts vstref) (progFuncs prog)
return (updProgFuncs (const newfuns) prog)
provePreCondition :: Options -> IORef VState -> TAFuncDecl -> IO TAFuncDecl
provePreCondition opts vstref fdecl = do
ti <- readVerifyInfoRef vstref
printWhenIntermediate opts $
"Operation to be checked: " ++ snd (funcName fdecl)
newrule <- optPreConditionInRule opts ti (funcName fdecl)
(funcRule fdecl) vstref
return (updFuncRule (const newrule) fdecl)
optPreConditionInRule :: Options -> VerifyInfo -> QName -> TARule
-> IORef VState -> IO TARule
optPreConditionInRule _ _ _ rl@(AExternal _ _) _ = return rl
optPreConditionInRule opts ti qn@(_,fn) (ARule rty rargs rhs) vstref = do
let targs = zip [1..] (map snd rargs)
st = makeTransState (maximum (0 : map fst rargs ++ allVars rhs) + 1) rargs
(flip evalStateT) st $ do
precondformula <- preCondExpOf ti qn targs
setAssertion precondformula
newrhs <- optPreCondInExp rhs
return (ARule rty rargs newrhs)
where
optPreCondInExp exp = case exp of
AComb ty ct (qf,tys) args ->
if qf == ("Prelude","?") && length args == 2
then optPreCondInExp (AOr ty (args!!0) (args!!1))
else do
precond <- getAssertion
nargs <- mapM optPreCondInExp args
if toPreCondQName qf `elem` map funcName (preConds ti)
then do
lift $ printWhenIntermediate opts $ "Checking call to " ++ snd qf
(bs,_) <- normalizeArgs nargs
bindexps <- mapM (binding2SMT True ti) bs
precondcall <- preCondExpOf ti qf
(zip (map fst bs) (map annExpr args))
let title = "SMT script to verify precondition of '" ++ snd qf ++
"' in function '" ++ fn ++ "'"
vartypes <- getVarTypes
pcproof <- lift $
checkImplication opts vstref title vartypes
precond (tConj bindexps) precondcall
let pcvalid = isJust pcproof
lift $ modifyIORef vstref
(addPreCondToStats (snd qf ++ "("++fn++")") pcvalid)
if pcvalid
then do
lift $ printWhenStatus opts $
fn ++ ": PRECONDITION OF '" ++ snd qf ++ "': VERIFIED"
return $ AComb ty ct (toNoCheckQName qf, tys) nargs
else do
lift $ printWhenStatus opts $
fn ++ ": PRECOND CHECK ADDED TO '" ++ snd qf ++ "'"
return $ AComb ty ct (qf,tys) nargs
else return $ AComb ty ct (qf,tys) nargs
ACase ty ct e brs -> do
ne <- optPreCondInExp e
freshvar <- getFreshVar
be <- binding2SMT True ti (freshvar,ne)
addToAssertion be
addVarTypes [ (freshvar, annExpr ne) ]
nbrs <- mapM (optPreCondInBranch freshvar) brs
return $ ACase ty ct ne nbrs
AOr ty e1 e2 -> do
ne1 <- optPreCondInExp e1
ne2 <- optPreCondInExp e2
return $ AOr ty ne1 ne2
ALet ty bs e -> do
nes <- mapM optPreCondInExp (map snd bs)
ne <- optPreCondInExp e
return $ ALet ty (zip (map fst bs) nes) ne
AFree ty fvs e -> do
ne <- optPreCondInExp e
return $ AFree ty fvs ne
ATyped ty e et -> do
ne <- optPreCondInExp e
return $ ATyped ty ne et
_ -> return exp
optPreCondInBranch dvar branch = do
ABranch p e <- renamePatternVars branch
addToAssertion (tEquVar dvar (pat2SMT p))
ne <- optPreCondInExp e
return (ABranch p ne)
renamePatternVars :: TABranchExpr -> TransStateM TABranchExpr
renamePatternVars (ABranch p e) =
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
verifyPostConditions :: Options -> TAProg -> IORef VState -> IO TAProg
verifyPostConditions opts prog vstref = do
ti <- readVerifyInfoRef vstref
let fdecls = progFuncs prog
newfuns <- provePostConds ti (postConds ti) fdecls
return $ updProgFuncs (const newfuns) prog
where
provePostConds _ [] fdecls = return fdecls
provePostConds ti (pof:pofs) fdecls =
provePostCondition opts ti pof fdecls vstref >>= provePostConds ti pofs
provePostCondition :: Options -> VerifyInfo -> TAFuncDecl -> [TAFuncDecl]
-> IORef VState -> IO [TAFuncDecl]
provePostCondition opts ti postfun allfuns vstref = do
maybe (do putStrLn $ "Postcondition: " ++ pcname ++ "\n" ++
"Operation of this postcondition not found!"
return allfuns)
(\checkfun -> evalStateT (provePC (simpFuncDecl checkfun))
emptyTransState)
(find (\fd -> toPostCondName (snd (funcName fd)) ==
decodeContractName pcname)
allfuns)
where
pcname = snd (funcName postfun)
provePC checkfun = do
let (postmn,postfn) = funcName postfun
mainfunc = snd (funcName checkfun)
orgqn = (postmn, reverse (drop 5 (reverse postfn)))
let farity = funcArity checkfun
ftype = funcType checkfun
targsr = zip [1..] (argTypes ftype ++ [resultType ftype])
bodyformula <- extractPostConditionProofObligation ti
[1 .. farity] (farity+1) (funcRule checkfun)
precondformula <- preCondExpOf ti orgqn (init targsr)
postcondformula <- applyFunc postfun targsr >>= pred2smt
let title = "verify postcondition of '" ++ mainfunc ++ "'..."
lift $ printWhenIntermediate opts $ "Trying to " ++ title
vartypes <- getVarTypes
pcproof <- lift $
checkImplication opts vstref ("SMT script to " ++ title) vartypes
(tConj [precondformula, bodyformula])
tTrue postcondformula
lift $ modifyIORef vstref (addPostCondToStats mainfunc (isJust pcproof))
maybe
(do lift $ (printWhenStatus opts $ mainfunc ++ ": POSTCOND CHECK ADDED")
return (map (addPostConditionTo (funcName postfun)) allfuns) )
(\proof -> do
unless (optNoProof opts) $ lift $
writeFile ("PROOF_" ++ showQNameNoDots orgqn ++ "_" ++
"SatisfiesPostCondition.smt") proof
lift $ printWhenStatus opts $ mainfunc ++ ": POSTCONDITION VERIFIED"
return allfuns )
pcproof
addPostConditionTo :: QName -> TAFuncDecl -> TAFuncDecl
addPostConditionTo pfname fdecl = let fn = funcName fdecl in
if toPostCondQName fn == pfname
then updFuncBody (const (addPostConditionCheck fn (funcRule fdecl))) fdecl
else fdecl
extractPostConditionProofObligation :: VerifyInfo -> [Int] -> Int -> TARule
-> TransStateM Term
extractPostConditionProofObligation _ _ _ (AExternal _ s) =
return $ tComb ("External: " ++ s) []
extractPostConditionProofObligation ti args resvar
(ARule ty orgargs orgexp) = do
let exp = rnmAllVars renameRuleVar orgexp
rtype = resType (length orgargs) (stripForall ty)
put $ makeTransState (maximum (resvar : allVars exp) + 1)
((resvar, rtype) : zip args (map snd orgargs))
binding2SMT True ti (resvar,exp)
where
maxArgResult = maximum (resvar : args)
renameRuleVar r = maybe (r + maxArgResult + 1)
(args!!)
(elemIndex r (map fst orgargs))
resType n te =
if n==0
then te
else case te of
FuncType _ rt -> resType (n-1) rt
_ -> error $ "Internal errror: resType: " ++ show te
preCondExpOf :: VerifyInfo -> QName -> [(Int,TypeExpr)] -> TransStateM Term
preCondExpOf ti qf args =
maybe (return tTrue)
(\fd -> applyFunc fd args >>= pred2smt)
(find (\fd -> decodeContractQName (funcName fd)
== toPreCondQName (fromNoCheckQName qf))
(preConds ti))
postCondExpOf :: VerifyInfo -> QName -> [(Int,TypeExpr)] -> TransStateM Term
postCondExpOf ti qf args =
maybe (return tTrue)
(\fd -> applyFunc fd args >>= pred2smt)
(find (\fd -> decodeContractQName (funcName fd)
== toPostCondQName (fromNoCheckQName 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 exp of
AVar _ i -> return (TSVar i)
ALit _ l -> return (lit2SMT l)
AComb _ ct (qf,ftype) args ->
if qf == pre "not" && length args == 1
then do barg <- pred2smt (head args)
return (tNot barg)
else do bargs <- mapM pred2smt args
return (TComb (cons2SMT (ct /= ConsCall || not (null bargs))
False qf ftype) bargs)
_ -> error $ "Translation of some Boolean expressions into SMT " ++
"not yet supported:\n" ++ show (unAnnExpr exp)
binding2SMT :: Bool -> VerifyInfo -> (Int,TAExpr) -> TransStateM Term
binding2SMT odemanded vi (oresvar,oexp) =
exp2smt odemanded (oresvar, simpExpr oexp)
where
exp2smt demanded (resvar,exp) = case exp of
AVar _ i -> return $ if resvar==i then tTrue
else tEquVar resvar (TSVar i)
ALit _ l -> return (tEquVar resvar (lit2SMT l))
AComb ty ct (qf,_) args ->
if qf == pre "?" && length args == 2
then exp2smt demanded (resvar, AOr ty (args!!0) (args!!1))
else do
(bs,nargs) <- normalizeArgs args
bindexps <- mapM (exp2smt (isPrimOp qf || optStrict (toolOpts vi))) bs
comb2smt qf ty ct nargs bs bindexps
ALet _ bs e -> do
addVarTypes (map fst bs)
bindexps <- mapM (exp2smt False) (map (\ ((i,_),ae) -> (i,ae)) bs)
bexp <- exp2smt demanded (resvar,e)
return (tConj (bindexps ++ [bexp]))
AOr _ e1 e2 -> do
bexp1 <- exp2smt demanded (resvar,e1)
bexp2 <- exp2smt demanded (resvar,e2)
return (tDisj [bexp1, bexp2])
ACase _ _ e brs -> do
freshvar <- getFreshVar
addVarTypes [(freshvar, annExpr e)]
argbexp <- exp2smt demanded (freshvar,e)
bbrs <- mapM branch2smt (map (\b -> (freshvar,b)) brs)
return (tConj [argbexp, tDisj bbrs])
ATyped _ e _ -> exp2smt demanded (resvar,e)
AFree _ _ _ -> error "Free variables not yet supported!"
where
comb2smt 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 arg2smt nargs))]))
| qf == pre "apply"
=
return tTrue
| isPrimOp qf
= return (tConj (bindexps ++
[tEquVar resvar (TComb (cons2SMT True False qf rtype)
(map arg2smt nargs))]))
| otherwise
= do let targs = zip (map fst bs) (map annExpr nargs)
precond <- preCondExpOf vi qf targs
postcond <- postCondExpOf vi qf (targs ++ [(resvar,rtype)])
return
(tConj (bindexps ++ if demanded then [precond,postcond] else []))
branch2smt (cvar, (ABranch p e)) = do
branchbexp <- exp2smt demanded (resvar,e)
addVarTypes patvars
return (tConj [ tEquVar cvar (pat2SMT p), branchbexp])
where
patvars = if isConsPattern p
then patArgs p
else []
arg2smt e = case e of AVar _ i -> TSVar i
ALit _ l -> lit2SMT l
_ -> error $ "Not normalized: " ++ show 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)
unzipBranches :: [TABranchExpr] -> ([TAPattern],[TAExpr])
unzipBranches [] = ([],[])
unzipBranches (ABranch p e : brs) = (p:xs,e:ys)
where (xs,ys) = unzipBranches brs
checkImplication :: Options -> IORef VState -> String -> [(Int,TypeExpr)]
-> Term -> Term -> Term -> IO (Maybe String)
checkImplication opts vstref scripttitle vartypes assertion impbindings imp =
if optVerify opts
then checkImplicationWithSMT opts vstref scripttitle vartypes
assertion impbindings imp
else return Nothing
checkImplicationWithSMT :: Options -> IORef VState -> String -> [(Int,TypeExpr)]
-> Term -> Term -> Term -> IO (Maybe String)
checkImplicationWithSMT opts vstref scripttitle vartypes
assertion impbindings imp = do
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,fdecls,ndinfo) <- funcs2SMT opts vstref allsyms
smttypes <- genSMTTypes vstref vartypes fdecls [assertion,impbindings,imp]
let freshvar = maximum (map fst vartypes) + 1
([assertionC,impbindingsC,impC],newix) =
nondetTransL ndinfo freshvar [assertion,impbindings,imp]
smt = smttypes ++
[ EmptyLine, smtfuncs, EmptyLine
, Comment "Free variables:" ] ++
map typedVar2SMT
(vartypes ++ map toChoiceVar [freshvar .. newix-1]) ++
[ EmptyLine
, Comment "Boolean formula of assertion (known properties):"
, sAssert assertionC, EmptyLine
, Comment "Bindings of implication:"
, sAssert impbindingsC, EmptyLine
, Comment "Assert negated implication:"
, sAssert (tNot impC), EmptyLine
, Comment "check satisfiability:"
, CheckSat
, Comment "if unsat, we can omit this part of the contract check"
]
smtstdtypes <- readInclude "Prelude.smt"
smtchoice <- if or (map snd ndinfo)
then readInclude "Prelude_Choice.smt"
else return ""
let smtprelude = smtstdtypes ++ smtchoice
callSMT opts $ "; " ++ scripttitle ++ "\n\n" ++ smtprelude ++ showSMT smt
where
readInclude f = getIncludePath f >>= readFile
toChoiceVar i = (i, TCons (pre "Choice") [])
genSMTTypes :: IORef VState -> [(Int,TypeExpr)] -> [TAFuncDecl] -> [Term]
-> IO [Command]
genSMTTypes vstref vartypes fdecls smtterms = do
let
alltypes = concatMap typesOfFunc fdecls ++ map snd vartypes
alltcons = foldr union [] (map tconsOfTypeExpr alltypes)
allsorts = concatMap sortIdsOfSort (concatMap sortsOfTerm smtterms)
(pretypes,usertypes) = partition ((== "Prelude") . fst) alltcons
presorts = nub (filter (`notElem` (map tcons2SMT pretypes)) allsorts) ++
map tcons2SMT pretypes
vst <- readIORef vstref
let udecls = map (maybe (error "Internal error: some datatype not found!") id)
(map (tdeclOf vst) usertypes)
return $ concatMap preludeSort2SMT presorts ++
[ EmptyLine ] ++
(if null udecls
then []
else [ Comment "User-defined datatypes:" ] ++
map tdecl2SMT udecls)
callSMT :: Options -> String -> IO (Maybe String)
callSMT opts smtinput = do
printWhenIntermediate opts $ "SMT SCRIPT:\n" ++ showWithLineNums smtinput
printWhenIntermediate opts $ "CALLING Z3..."
(ecode,out,err) <- evalCmd "z3"
["-smt2", "-in", "-T:" ++ show (optTimeout opts)]
smtinput
when (ecode>0) $ do printWhenIntermediate opts $ "EXIT CODE: " ++ show ecode
writeFile "error.smt" smtinput
printWhenIntermediate opts $ "RESULT:\n" ++ out
unless (null err) $ printWhenIntermediate opts $ "ERROR:\n" ++ err
let unsat = let ls = lines out in not (null ls) && head ls == "unsat"
return $ if unsat
then Just $ "; proved by: z3 -smt2 <SMTFILE>\n\n" ++ smtinput
else Nothing
nondetTrans :: [(QName,Bool)] -> Int -> Term -> (Term,Int)
nondetTrans ndinfo ix trm = case trm of
TConst _ -> (trm,ix)
TSVar _ -> (trm,ix)
TComb f args -> let (targs,i1) = nondetTransL ndinfo ix args
in if maybe False
(\qn -> maybe False id (lookup qn ndinfo))
(untransOpName (qidName f))
then (TComb (addChoiceType f) (TSVar i1 : targs), i1+1)
else (TComb f targs, i1)
Forall vs arg -> let (targ,ix1) = nondetTrans ndinfo ix arg
in (Forall vs targ, ix1)
Exists vs arg -> let (targ,ix1) = nondetTrans ndinfo ix arg
in (Exists vs targ, ix1)
ESMT.Let bs e -> let (tbt,ix1) = nondetTransL ndinfo ix (map snd bs)
(te,ix2) = nondetTrans ndinfo ix1 e
in (ESMT.Let (zip (map fst bs) tbt) te, ix2)
where
addChoiceType (Id n) = Id n
addChoiceType (As n tp) = As n (SComb "Func" [SComb "Choice" [], tp])
nondetTransL :: [(QName,Bool)] -> Int -> [Term] -> ([Term],Int)
nondetTransL _ i [] = ([],i)
nondetTransL ndinfo i (t:ts) =
let (t1,i1) = nondetTrans ndinfo i t
(ts1,i2) = nondetTransL ndinfo i1 ts
in (t1:ts1, i2)
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
getIncludePath :: String -> IO String
getIncludePath incfile = do
ppinclude <- fmap (</> "include" </> incfile) getPackagePath
exppinclude <- doesFileExist ppinclude
if exppinclude
then return ppinclude
else do
let localinclude = "include" </> incfile
exlocalinclude <- doesFileExist localinclude
if exlocalinclude
then return localinclude
else do putStrLn $
"Warning: '" ++ localinclude ++ "' required but not found!"
return incfile
fileInPath :: String -> IO Bool
fileInPath file = do
path <- getEnv "PATH"
dirs <- return $ splitOn ":" path
(fmap (any id)) $ mapM (doesFileExist . (</> file)) dirs
showQNameNoDots :: QName -> String
showQNameNoDots = map (\c -> if c=='.' then '_' else c) . showQName
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)
|