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
|
module Curry2SMT where
import IOExts
import List ( isPrefixOf, nub, union )
import Maybe ( fromMaybe )
import ReadNumeric ( readHex )
import FlatCurry.Annotated.Goodies ( argTypes, resultType, unAnnFuncDecl )
import FlatCurry.Types ( showQName )
import ShowFlatCurry ( showCurryFuncDecl )
import ESMT
import FlatCurry.Typed.Read ( getAllFunctions )
import FlatCurry.Typed.Goodies
import FlatCurry.Typed.Names
import FlatCurry.Typed.NonDet2Det
import FlatCurry.Typed.Types
import ToolOptions
import VerifierState
funcs2SMT :: Options -> IORef VState -> [QName]
-> IO (Command, [TAFuncDecl], [(QName,Bool)])
funcs2SMT opts vstref qns = do
funs <- getAllFunctions vstref (nub qns)
unless (null funs) $ printWhenAll opts $ unlines $
"Operations to be axiomatized in SMT:" :
map (showCurryFuncDecl snd snd . unAnnFuncDecl) funs
let ndinfo = nondetOfFuncDecls funs
choicePlan = (TCons (pre "Choice") [],
pre "choose", pre "lchoice", pre "rchoice")
tfuns = map (addChoiceFuncDecl ndinfo choicePlan) funs
unless (null ndinfo) $ printWhenAll opts $
"Non-determinism status of these operations:\n" ++
unlines ((map showND) ndinfo)
unless (null tfuns) $ printWhenAll opts $ unlines $
"Transformed operations to be axiomatized in SMT:" :
map (showCurryFuncDecl snd snd . unAnnFuncDecl) tfuns
return (DefineSigsRec (map fun2SMT tfuns), tfuns, ndinfo)
where
showND ((_,n),nd) = n ++ ": " ++ if nd then "NONDET" else "DET"
fun2SMT :: TAFuncDecl -> ([Ident],FunSig,Term)
fun2SMT (AFunc qn _ _ texp rule) =
let fsig = FunSig (transOpName qn)
(map polytype2psort (argTypes texp))
(polytype2psort (resultType texp))
srule = rule2SMT rule
tpars = union (typeParamsOfFunSig fsig) (typeParamsOfTerm srule)
in (tpars, fsig, srule)
where
rule2SMT (AExternal _ s) =
tEqu (tComb (transOpName qn) []) (tComb ("External:" ++ s) [])
rule2SMT (ARule _ vs exp) =
Forall (map (\ (v,t) -> SV v (polytype2psort t)) vs)
(tEqu lhs (exp2SMT exp))
where
lhs = tComb (transOpName qn) (map (TSVar . fst) vs)
exp2SMT :: TAExpr -> Term
exp2SMT exp = case exp of
AVar _ i -> TSVar i
ALit _ l -> lit2SMT l
AComb _ ct (qn,ftype) args ->
TComb (cons2SMT (ct /= ConsCall || not (null args)) True qn ftype)
(map exp2SMT args)
ACase _ _ e brs -> let be = exp2SMT e
in branches2SMT be brs
ALet _ bs e -> Let (map (\ ((v,_),be) -> (v, exp2SMT be)) bs)
(exp2SMT e)
ATyped _ e _ -> exp2SMT e
AFree _ fvs e -> Forall (map (\ (v,t) -> SV v (polytype2psort t)) fvs)
(exp2SMT e)
AOr _ e1 e2 -> tDisj [exp2SMT e1, exp2SMT e2]
where
branches2SMT _ [] = error "branches2SMT: empty branch list"
branches2SMT be [ABranch p e] = branch2SMT be p e
branches2SMT be (ABranch p e : brs@(_:_)) =
tComb "ite" [patternTest p be,
branch2SMT be p e,
branches2SMT be brs]
branch2SMT _ (ALPattern _ _) e = exp2SMT e
branch2SMT be (APattern _ (qf,_) ps) e = case ps of
[] -> exp2SMT e
_ -> Let (map (\ (s,v) -> (v, tComb s [be]))
(zip (selectors qf) (map fst ps)))
(exp2SMT e)
patternTest :: TAPattern -> Term -> Term
patternTest (ALPattern _ l) be = tEqu be (lit2SMT l)
patternTest (APattern ty (qf,_) _) be = constructorTest True qf be ty
constructorTest :: Bool -> QName -> Term -> TypeExpr -> Term
constructorTest withpoly qn be vartype
| qn == pre "[]"
= tEqu be (sortedConst "nil"
((if withpoly then polytype2psort else polytype2sort) vartype))
| qn `elem` map pre ["[]","True","False","LT","EQ","GT","Nothing"]
= tEqu be (tComb (transOpName qn) [])
| qn `elem` map pre ["Just","Left","Right"]
= tComb ("is-" ++ snd qn) [be]
| otherwise
= tComb ("is-" ++ transOpName qn) [be]
selectors :: QName -> [String]
selectors qf | qf == ("Prelude",":") = ["head","tail"]
| qf == ("Prelude","Left") = ["left"]
| qf == ("Prelude","Right") = ["right"]
| qf == ("Prelude","Just") = ["just"]
| qf == ("Prelude","(,)") = ["first","second"]
| otherwise = map (genSelName qf) [1..]
polytype2sort :: TypeExpr -> Sort
polytype2sort = type2sort [] False False
polytype2psort :: TypeExpr -> Sort
polytype2psort = type2sort [] True False
type2sort :: [QName] -> Bool -> Bool -> TypeExpr -> Sort
type2sort tdcl poly _ (TVar i) =
SComb (if null tdcl then "TVar" ++ (if poly then show i else "")
else 'T' : show i) []
type2sort tdcl poly _ (FuncType dom ran) =
SComb "Func" (map (type2sort tdcl poly True) [dom,ran])
type2sort tdcl poly nested (TCons qc@(mn,tc) targs)
| null tdcl
= SComb (tcons2SMT qc) argtypes
| otherwise
= if qc `elem` tdcl
then if nested
then error $ "Type '" ++ showQName qc ++
"': nested recursive types not supported by SMT!"
else SComb (tcons2SMT qc) []
else SComb (tcons2SMT (mn,tc)) argtypes
where
argtypes = map (type2sort tdcl poly True) targs
type2sort _ _ _ (ForallType _ _) =
error "Curry2SMT.type2SMT: cannot translate ForallType"
tcons2SMT :: QName -> String
tcons2SMT (mn,tc)
| "_Dict#" `isPrefixOf` tc
= "Dict"
| mn == "Prelude" && take 3 tc == "(,,"
= "Tuple" ++ show (length tc - 1)
| mn == "Prelude"
= maybe (encodeSpecialChars tc) id (lookup tc transPrimTCons)
| otherwise
= mn ++ "_" ++ encodeSpecialChars tc
tdecl2SMT :: TypeDecl -> Command
tdecl2SMT (TypeSyn tc _ _ _) =
error $ "Cannot translate type synonym '" ++ showQName tc ++ "' into SMT!"
tdecl2SMT (Type tc _ tvars consdecls) =
DeclareDatatypes
[(tcons2SMT tc, length tvars,
DT (map (\v -> 'T':show v) tvars) (map tconsdecl consdecls))]
where
tconsdecl (Cons qn _ _ texps) =
let cname = transOpName qn
in DCons cname (map (texp2sel qn) (zip [1..] texps))
texp2sel cname (i,texp) = (genSelName cname i,
type2sort [tc] False False texp)
genSelName :: QName -> Int -> String
genSelName qc@(mn,fn) i
| mn == "Prelude" && take 3 fn == "(,,"
= transOpName qc ++ "_" ++ show i
| otherwise
= "sel" ++ show i ++ '-' : transOpName qc
preludeSort2SMT :: String -> [Command]
preludeSort2SMT sn
| take 5 sn == "Tuple"
= let arity = read (drop 5 sn)
texp2sel i = ("Tuple" ++ show arity ++ "_" ++ show i,
SComb ('T' : show i) [])
in [ Comment $ show arity ++ "-tuple type:"
, DeclareDatatypes
[(sn, arity,
DT (map (\v -> 'T':show v) [1 .. arity])
[DCons sn (map texp2sel [1 .. arity])])]]
| sn == "Pair"
= pairType
| sn == "Maybe"
= maybeType
| sn == "Either"
= eitherType
| sn == "Ordering"
= orderingType
| sn == "Unit"
= unitType
| otherwise
= []
pairType :: [Command]
pairType =
[ Comment "Pair type:"
, DeclareDatatypes
[("Pair",2,
DT ["T1", "T2"]
[ DCons "mk-pair" [("first", SComb "T1" []),
("second", SComb "T2" [])]])]]
maybeType :: [Command]
maybeType =
[ Comment "Maybe type:"
, DeclareDatatypes
[("Maybe",1,
DT ["T"]
[ DCons "Nothing" [],
DCons "Just" [("just", SComb "T" [])]])]]
eitherType :: [Command]
eitherType =
[ Comment "Either type:"
, DeclareDatatypes
[("Either",2,
DT ["T1", "T2"]
[ DCons "Left" [("left", SComb "T1" [])],
DCons "Right" [("right", SComb "T2" [])]])]]
orderingType :: [Command]
orderingType =
[ Comment "Ordering type:"
, DeclareDatatypes
[("Ordering",0,
DT [] [ DCons "LT" [], DCons "EQ" [],DCons "GT" [] ])]]
unitType :: [Command]
unitType =
[ Comment "Unit type:"
, DeclareDatatypes [("Unit",0, DT [] [ DCons "unit" []])]]
dictType :: [Command]
dictType =
[ Comment "Dict type (to represent dictionary variables):"
, DeclareDatatypes
[("Dict",1,
DT ["T"]
[ DCons "Dict" [("dict", SComb "T" [])]])]]
cons2SMT :: Bool -> Bool -> QName -> TypeExpr -> QIdent
cons2SMT withas withpoly qf rtype =
if withas && not (isBaseType rtype)
then As (transOpName qf)
((if withpoly then polytype2psort else polytype2sort) rtype)
else Id (transOpName qf)
pat2SMT :: TAPattern -> Term
pat2SMT (ALPattern _ l) = lit2SMT l
pat2SMT (APattern ty (qf,_) ps)
| qf == pre "[]" && null ps
= sortedConst "nil" (polytype2sort ty)
| otherwise
= tComb (transOpName qf) (map (TSVar . fst) ps)
lit2SMT :: Literal -> Term
lit2SMT (Intc i) = TConst (TInt i)
lit2SMT (Floatc f) = TConst (TFloat f)
lit2SMT (Charc c) = TConst (TInt (ord c))
transOpName :: QName -> String
transOpName (mn,fn)
| mn=="Prelude" = fromMaybe tname (lookup fn (transPrimCons ++ preludePrimOps))
| otherwise = tname
where
tname = mn ++ "_" ++ encodeSpecialChars fn
encodeSpecialChars :: String -> String
encodeSpecialChars = concatMap encChar
where
encChar c | c `elem` "#$%[]()!,"
= let oc = ord c
in ['%', int2hex (oc `div` 16), int2hex(oc `mod` 16)]
| otherwise = [c]
int2hex i = if i<10 then chr (ord '0' + i)
else chr (ord 'A' + i - 10)
decodeSpecialChars :: String -> String
decodeSpecialChars [] = []
decodeSpecialChars (c:cs)
| c == '%' = chr (maybe 0 fst (readHex (take 2 cs)))
: decodeSpecialChars (drop 2 cs)
| otherwise = c : decodeSpecialChars cs
untransOpName :: String -> Maybe QName
untransOpName s
| "is-" `isPrefixOf` s
= Nothing
| otherwise
= let (mn,ufn) = break (=='_') s
in if null ufn
then Nothing
else Just (mn, decodeSpecialChars (tail ufn))
|