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
|
module ToAgda(theoremToAgda) where
import AbstractCurry.Types
import AbstractCurry.Select
import AbstractCurry.Build
import Directory
import FilePath ((</>))
import List
import Maybe (fromJust)
import Rewriting.Files
import Rewriting.Term
import Rewriting.Rules
import Rewriting.CriticalPairs
import Time
import PropertyUsage
import VerifyOptions
import VerifyPackageConfig ( packagePath )
import Analysis.ProgInfo (ProgInfo, lookupProgInfo)
import Analysis.Deterministic (Deterministic(..))
import Analysis.TotallyDefined (Completeness(..))
theoremToAgda :: Options -> QName -> [CFuncDecl] -> [CTypeDecl] -> IO ()
theoremToAgda opts qtheo@(_,theoname) allfuncs alltypes = do
let (rename, orgtypedrules) = funcDeclsToTypedRules allfuncs
transform = if optScheme opts == "nondet" then transformRuleWithNondet
else transformRuleWithChoices
typedrules = concatMap (transform opts) orgtypedrules
(theorules,funcrules) = partition (\ (fn,_,_,_) -> fn == qtheo)
typedrules
mname = "TO-PROVE-" ++ theoname
hrule = take 75 (repeat '-')
agdaprog = unlines $
agdaHeader opts mname ++
[hrule, "-- Translated Curry operations:",""] ++
map typeDeclAsAgda alltypes ++
showTypedTRSAsAgda opts rename [] funcrules ++
[hrule, ""] ++
concatMap (theoremAsAgda rename) theorules ++
[hrule]
let agdafile = mname ++ ".agda"
when (optVerb opts > 1 || not (optStore opts)) $ putStr agdaprog
when (optStore opts) $ do
writeFile agdafile agdaprog
when (optScheme opts == "nondet") $
mapIO_ copyImport ["nondet.agda","nondet-thms.agda"]
when (optVerb opts > 0) $ putStrLn $
"Agda module '" ++ agdafile ++ "' written.\n" ++
"If you completed the proof, rename it to 'PROOF-" ++ theoname ++ ".agda'."
agdaHeader :: Options -> String -> [String]
opts mname =
[ "-- Agda program using the Iowa Agda library\n"
, "open import bool\n"
, "module " ++ mname ] ++
(if optScheme opts == "choice"
then [" (Choice : Set)\n (choose : Choice \8594 \120121)"
, " (lchoice : Choice \8594 Choice)\n (rchoice : Choice \8594 Choice)"]
else []) ++
[" where\n"
, unlines (map (\im -> "open import " ++ im)
(["eq","nat","list","maybe"] ++
(if optScheme opts == "nondet" then ["nondet","nondet-thms"]
else [])))
]
funcDeclsToTypedRules :: [CFuncDecl]
-> (QName -> String, [(QName, [String], CTypeExpr, TRS QName)])
funcDeclsToTypedRules fdecls = (rename, typedrules)
where
typedrules = map funcDeclToTypedRule fdecls
allrules = concatMap (\ (_,_,_,rules) -> rules) typedrules
rename = rename4agda (allNamesOfTRS allrules)
allNamesOfTRS :: TRS a -> [a]
allNamesOfTRS =
foldr union [] . map allNamesOfTerm . concatMap (\ (lhs,rhs) -> [lhs,rhs])
allNamesOfTerm :: Term a -> [a]
allNamesOfTerm (TermVar _) = []
allNamesOfTerm (TermCons f ts) = foldr union [f] (map allNamesOfTerm ts)
rename4agda :: [QName] -> QName -> String
rename4agda allnames qn@(mn,fn)
| (mn,fn) == pre ":" = "_::_"
| (mn,fn) == pre "+" = "_+_"
| (mn,fn) == pre "*" = "_*_"
| (mn,fn) == pre "True" = "tt"
| (mn,fn) == pre "False" = "ff"
| (mn,fn) == nat "Z" = "zero"
| (mn,fn) == nat "S" = "suc"
| (mn,fn) == pre "<" = "_<_"
| (mn,fn) == pre ">" = "_>_"
| (mn,fn) == pre "<=" = "_\8804_"
| (mn,fn) == pre ">=" = "_\8805_"
| otherwise
= maybe fn
(const (showQName qn))
(find (\ (q,f) -> f==fn && q /= mn) allnames)
funcDeclToTypedRule :: CFuncDecl -> (QName, [String], CTypeExpr, TRS QName)
funcDeclToTypedRule (CFunc qn ar vis texp rules) =
funcDeclToTypedRule (CmtFunc "" qn ar vis texp rules)
funcDeclToTypedRule fdecl@(CmtFunc _ _ _ _ texp _) =
let (fn, trs) = fromFuncDecl fdecl
in (fn, [], texp, trs)
elimOverlappingRules :: Options
-> Bool
-> (QName, [String], CTypeExpr, TRS QName)
-> [(QName, [String], CTypeExpr, TRS QName)]
elimOverlappingRules opts withpartialfail (fn,cmt,texp,trs)
| lookupProgInfo fn detinfo == Just Det || null critPairs
= [(fn,cmt,texp,trs)]
| otherwise
= (fn, cmt ++ [splitCmt], texp,
[(TermCons fn newargs,
foldr1 (\x y -> TermCons (pre "?") [x,y])
(map (\i -> TermCons (addRuleName fn i) newargs)
[1 .. length trs]))]) :
map (\ (i,(TermCons _ args, rhs)) ->
let rname = addRuleName fn i
in (rname,
["Rule " ++ show i ++ " of operation '" ++ showQName fn ++"':"],
texp,
[(TermCons rname args, rhs)] ++
if withpartialfail then [failRule rname] else []))
(zip [1 .. length trs] trs)
where
detinfo = detInfos opts
critPairs = cPairs trs
arity = case head trs of (TermCons _ args,_) -> length args
_ -> error "elimOverlappingRules: no arity"
newargs = map TermVar [1 .. arity]
failRule f = (TermCons f (map TermVar [0 .. (arity-1)]),
TermCons (pre "failed") [])
splitCmt = "Overlapping rules of '" ++ showQName fn ++
"' split into a new operation for each rule."
addRuleName :: QName -> Int -> QName
addRuleName (mn,fn) i = (mn, fn ++ "-rule" ++ show i)
stripRuleName :: QName -> QName
stripRuleName (mn,fn) =
(mn, if take 5 (tail (reverse fn)) == "elur-"
then take (length fn - 6) fn
else fn )
transformRuleWithChoices :: Options
-> (QName, [String], CTypeExpr, TRS QName)
-> [(QName, [String], CTypeExpr, TRS QName)]
transformRuleWithChoices opts (fn,cmt,texp,trs)
| lookupProgInfo fn detinfo == Just Det
= [(fn, cmt ++ concatMap theoremComment trs, texp, map transTheorem trs)]
| otherwise
= map (\ (f,c,t,rs) -> (f, c ++ concatMap theoremComment rs,
baseType (pre "Choice") ~> t,
map (transTheorem . addChoices) rs))
(elimOverlappingRules opts False (fn,cmt,texp,trs))
where
detinfo = detInfos opts
choicevar = TermVar 46
transTheorem rl@(lhs,rhs) =
if isTheoremRule opts rl then (lhs, prop2agda rhs) else rl
rl@(_,rhs) =
if isTheoremRule opts rl
then case rhs of
TermVar _ -> []
TermCons f _ ->
case snd f of
"-=-" -> []
"<~>" -> []
"always" -> []
_ -> noTheoremTranslateCmt
else []
prop2agda v@(TermVar _) = v
prop2agda t@(TermCons f args) =
case snd f of
"-=-" -> TermCons (pre "_\8801_" ) args
"<~>" -> TermCons (pre "_\8801_" ) args
"always" -> TermCons (pre "_\8801_" ) (args ++ [agdaTrue])
_ -> t
addChoices (lhs,rhs) =
(addLhsChoice choicevar lhs,
snd (addChoiceInTerm (choicesFor (numNondetOps rhs) choicevar) rhs))
addLhsChoice _ v@(TermVar _) = v
addLhsChoice ch (TermCons f args) = TermCons f (ch : args)
isNondetOp f = lookupProgInfo (stripRuleName f) detinfo == Just NDet
numNondetOps (TermVar _) = 0
numNondetOps (TermCons f args) =
(if f == curryChoice || isNondetOp f then 1 else 0) +
sum (map numNondetOps args)
addChoiceInTerm chs v@(TermVar _) = (chs,v)
addChoiceInTerm chs (TermCons f args)
| f == pre "?" && length args == 2
= let (chs1,cargs) = addChoiceInTerms (tail chs) args
in (chs1, TermCons (pre "if_then_else")
(TermCons (pre "choose") [head chs] : cargs))
| isNondetOp f
= let (chs1,cargs) = addChoiceInTerms (tail chs) args
in (chs1, TermCons f (head chs : cargs))
| otherwise
= let (chs1,cargs) = addChoiceInTerms chs args
in (chs1, TermCons f cargs)
addChoiceInTerms ch [] = (ch,[])
addChoiceInTerms ch (t:ts) = let (ch1,ct ) = addChoiceInTerm ch t
(ch2,cts) = addChoiceInTerms ch1 ts
in (ch2,ct:cts)
choicesFor :: Int -> Term QName -> [Term QName]
choicesFor n ch =
if n <= 1
then [ch]
else
map (\c -> TermCons (pre "lchoice") [c]) (choicesFor (n `div` 2) ch) ++
map (\c -> TermCons (pre "rchoice") [c]) (choicesFor (n - n `div` 2) ch)
noTheoremTranslateCmt :: [String]
noTheoremTranslateCmt =
["WARNING: cannot translate property into an Agda theorem!"]
transformRuleWithNondet :: Options
-> (QName, [String], CTypeExpr, TRS QName)
-> [(QName, [String], CTypeExpr, TRS QName)]
transformRuleWithNondet opts (fn,cmt,texp,trs)
| lookupProgInfo fn detinfo == Just Det
= [(fn, cmt ++ concatMap theoremComment trs, texp, map transTheorem trs)]
| otherwise
= map (\ (f,c,t,rs) -> (f, c ++ concatMap theoremComment rs,
addNDToResultType t,
map addNondet rs ++ failRule f))
(elimOverlappingRules opts True (fn,cmt,texp,trs))
where
detinfo = detInfos opts
arity = case head trs of (TermCons _ args,_) -> length args
_ -> error "transformRuleWithNondet: no arity"
failRule f = if lookupProgInfo fn (patInfos opts) == Just Complete
|| not (null (cPairs trs))
then []
else [(TermCons f (map TermVar [0 .. (arity-1)]),
TermCons (nondet "Fail") [])]
addNDToResultType te = case te of
CFuncType t1 t2 -> CFuncType t1 (addNDToResultType t2)
_ -> CTCons (pre "ND") [te]
addNondet rl@(lhs,rhs)
| isTheoremRule opts rl
= (lhs, prop2agda $ case rhs of TermVar _ -> rhs
TermCons f args ->
TermCons f (map addNondetInTerm args))
| otherwise
= (lhs, addNondetInTerm rhs)
transTheorem rl@(lhs,rhs) =
if isTheoremRule opts rl then (lhs, prop2agda rhs) else rl
rl@(_,rhs) =
if isTheoremRule opts rl
then case rhs of
TermVar _ -> []
TermCons f _ -> case snd f of
"-=-" -> adaptOrderCmt
"<~>" -> adaptOrderCmt
"always" -> []
"eventually"-> []
"failing" -> []
_ -> noTheoremTranslateCmt
else []
where
adaptOrderCmt =
["This theorem should be adapted since the left- and right-hand sides",
"might have their values in a different order in the tree!"]
prop2agda v@(TermVar _) = v
prop2agda t@(TermCons (mn,pn) args) =
case pn of
"-=-" -> TermCons (pre "_\8801_" ) args
"<~>" -> TermCons (pre "_\8801_" ) args
"always" -> TermCons (pre "_\8801_" )
[TermCons (mn,"always") args, agdaTrue]
"eventually" -> TermCons (pre "_\8801_" )
[TermCons (mn,"eventually") args, agdaTrue]
"failing" -> TermCons (pre "_\8801_" )
[TermCons (mn,"failing") args, agdaTrue]
_ -> t
isNondetOp f = lookupProgInfo (stripRuleName f) detinfo == Just NDet
addNondetInTerm v@(TermVar _) = agdaVal v
addNondetInTerm t@(TermCons f args)
| f == pre "?" && length args == 2
= TermCons (pre "_??_") (map addNondetInTerm args)
| f == pre "failed" && null args
= TermCons (nondet "Fail") []
| not (hasNondetSubterms t)
= agdaVal (TermCons f args)
| otherwise
= let (detargs,ndargs) = break hasNondetSubterms args
in if isNondetOp f
then
if null ndargs
then t
else addArgsWithNdArg
(TermCons (withNdArgName (length ndargs))
[TermCons f detargs, addNondetInTerm (head ndargs)])
(tail ndargs)
else addArgsWithNdArg
(TermCons (nondet "mapND")
[TermCons f detargs, addNondetInTerm (head ndargs)])
(tail ndargs)
addArgsWithNdArg t [] = t
addArgsWithNdArg t (arg:args) =
if hasNondetSubterms arg
then addArgsWithNdArg
(TermCons (nondet "apply-nd") [t, addNondetInTerm arg]) args
else addArgsWithNdArg (TermCons (nondet "apply-nd") [t,agdaVal arg]) args
withNdArgName i = nondet ("with-nd-arg" ++ (if i>1 then show i else ""))
hasNondetSubterms (TermVar _) = False
hasNondetSubterms (TermCons f args) =
f == (pre "?") || isNondetOp f || any hasNondetSubterms args
agdaVal :: Term QName -> Term QName
agdaVal t = TermCons (nondet "Val") [t]
theoremAsAgda :: (QName -> String) -> (QName, [String], CTypeExpr, TRS QName)
-> [String]
theoremAsAgda _ (_,_,_,[]) = []
theoremAsAgda _ (fn,_,_,(TermVar _ ,_) : _) =
error $ "Theorem '" ++ showQName fn ++ "': variable in left-hand side"
theoremAsAgda rn (fn, cmt, texp, (TermCons _ largs,rhs) : rules) =
map ("-- "++) cmt ++
[rn fn ++ " : " ++ (if null tvars then "" else showForAll tvars) ++
showTypeWOResult largs texp ++ showTermAsAgda False (mapTerm rn rhs)
,showTermAsAgda False (mapTerm rn (TermCons fn largs)) ++ " = ?", ""
] ++ theoremAsAgda rn (fn,cmt,texp,rules)
where
tvars = nub (tvarsOfType texp)
showTypeWOResult [] _ = ""
showTypeWOResult (arg:args) te = case te of
CFuncType t1 t2 -> "(" ++ showTermAsAgda False (mapTerm rn arg) ++ " : " ++
showTypeAsAgda False t1 ++
") \8594 " ++ showTypeWOResult args t2
_ -> error $ "Inconsistent type in theorem '" ++ showQName fn ++ "': " ++
show te
showTypedTRSAsAgda :: Options -> (QName -> String) -> [QName]
-> [(QName,[String],CTypeExpr,TRS QName)] -> [String]
showTypedTRSAsAgda _ _ _ [] = []
showTypedTRSAsAgda opts rn prefuns ((fn,cmt,texp,trs) : morefuncs) =
(concatMap (\ff -> let (f,_,t,_) = fromJust (find (\tf -> fst4 tf == ff)
morefuncs)
in ["-- Forward declaration:",
showTypeSignatureAsAgda (rn f) t,""])
forwardfuncs) ++
map ("-- "++) cmt ++
(if lookupProgInfo fn (patInfos opts) == Just Complete
|| optScheme opts == "nondet"
then []
else ["-- WARNING: function '" ++ showQName fn ++
"' is partial: adapt the code!"] ) ++
(if fn `elem` prefuns then [] else [showTypeSignatureAsAgda (rn fn) texp]) ++
map (showRuleAsAgda rn) trs ++ [""] ++
showTypedTRSAsAgda opts rn (forwardfuncs ++ prefuns) morefuncs
where
forwardfuncs = filter (`elem` map fst4 morefuncs) (allNamesOfTRS trs \\ [fn])
showRuleAsAgda :: (QName -> String) -> Rule QName -> String
showRuleAsAgda rn (lhs,rhs) =
showTermAsAgda False (mapTerm rn lhs) ++ " = " ++
showTermAsAgda False (mapTerm rn rhs)
showTermAsAgda :: Bool -> Term String -> String
showTermAsAgda _ (TermVar v) = showVarAsAgda v
showTermAsAgda withbrackets (TermCons c args) = inBrackets $
if c == "if_then_else" && length args == 3
then let is = map (showTermAsAgda False) args
in unwords ["if", is!!0, "then", is!!1, "else", is!!2]
else
if c == "apply" && length ts == 2
then unwords ts
else
if isInfixOp c && length ts == 2
then unwords [head ts, take (length c - 2) (tail c), head (tail ts)]
else unwords (c : ts)
where
ts = map (showTermAsAgda True) args
inBrackets s = if not (null ts) && withbrackets then "(" ++ s ++ ")" else s
isInfixOp :: String -> Bool
isInfixOp s = length s > 2 && head s == '_' && last s == '_'
showVarAsAgda :: Int -> String
showVarAsAgda v | v >= 0 = if q == 0
then [c]
else c:(show q)
where
(q, r) = divMod v 26
c = "xyzuvwrstijklmnopqabcdefgh" !! r
typeDeclAsAgda :: CTypeDecl -> String
typeDeclAsAgda (CTypeSyn tc _ _ _) =
error $ "Type synonyms not supported: " ++ showQName tc
typeDeclAsAgda (CNewType tc vis tvars consdecl) =
typeDeclAsAgda (CType tc vis tvars [consdecl])
typeDeclAsAgda (CType tc _ tvars constrs) = unlines $
(unwords $
["data", snd tc] ++
map (\tv -> "("++ showTypeAsAgda False (CTVar tv) ++ " : Set)") tvars ++
[": Set where"]) : map typeConsDeclAsAgda constrs
where
typeConsDeclAsAgda (CCons qc _ texps) =
" " ++ snd qc ++ " : " ++
showTypeAsAgda False (foldr CFuncType (CTCons tc (map CTVar tvars)) texps)
typeConsDeclAsAgda (CRecord qc _ _) =
error $ "Records not yet supported: " ++ showQName qc
showTypeSignatureAsAgda :: String -> CTypeExpr -> String
showTypeSignatureAsAgda fn texp =
fn ++ " : " ++ (if null tvars then "" else showForAll tvars) ++
showTypeAsAgda False texp
where
tvars = nub (tvarsOfType texp)
showForAll :: [CTVarIName] -> String
showForAll tvars = "{" ++ unwords (map (showTypeAsAgda False . CTVar) tvars) ++
" : Set} \8594 "
showTypeAsAgda :: Bool -> CTypeExpr -> String
showTypeAsAgda withbrackets texp = case texp of
CFuncType t1 t2 -> inBrackets $ showTypeAsAgda False t1 ++ " \8594 " ++
showTypeAsAgda False t2
CTVar (i,_) -> showVarAsAgda (i + 18)
CTCons tc targs ->
if null targs
then showTCon tc
else inBrackets $ unwords (showTCon tc : map (showTypeAsAgda True) targs)
where
inBrackets s = if withbrackets then "(" ++ s ++ ")" else s
showTCon :: QName -> String
showTCon tc
| tc == pre "[]" = "\120131"
| tc == pre "Int" = "\8469"
| tc == pre "Bool" = "\120121"
| tc == pre "Maybe" = "maybe"
| tc == pre "Choice" = "Choice"
| tc == nat "Nat" = "\8469"
| otherwise = snd tc
curryChoice :: QName
curryChoice = pre "?"
nat :: String -> QName
nat s = ("Nat",s)
nondet :: String -> QName
nondet s = ("nondet",s)
agdaTrue :: Term QName
agdaTrue = TermCons (pre "tt") []
agdaFalse :: Term QName
agdaFalse = TermCons (pre "ff") []
ruleFunc :: Rule QName -> QName
ruleFunc rl@(TermVar _,_) = error $ "Rule with variable lhs: " ++
showRule showQName rl
ruleFunc (TermCons f _,_) = f
isTheoremRule :: Options -> Rule QName -> Bool
isTheoremRule opts (lhs,_) =
case lhs of
TermVar _ -> False
TermCons f _ -> f `elem` optTheorems opts
fst4 :: (a,b,c,d) -> a
fst4 (x,_,_,_) = x
copyImport :: String -> IO ()
copyImport library = do
let importfile = packagePath </> "imports" </> library
libexists <- doesFileExist library
if not libexists
then copyFile importfile library
else do
itime <- getModificationTime importfile
ltime <- getModificationTime library
unless (compareClockTime ltime itime == GT) $ copyFile importfile library
|