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
|
import Data.List ( intercalate, nub, replace, sort, sortBy )
import Numeric(readNat)
import System.Environment ( getArgs )
import System.IO ( hFlush, stdout )
import System.Directory ( createDirectory, doesDirectoryExist )
import System.FilePath ( dropExtension, splitFileName, takeDirectory )
import FlatCurry.ShowIntMod
import Debug.Profile
import qualified FlatCurry.Types as FC
import qualified Data.Table.RBTree as Table ( TableRBT, empty, lookup
, toList, update )
import LetDropping
import NondetAnalysis
import ReadFlatTRS
import TRS
analysisDir :: String
analysisDir = ".curry/analysis"
createAnalysisDir :: String -> IO ()
createAnalysisDir base = do
let anadir = takeDirectory base ++ "/" ++ analysisDir
exanadir <- doesDirectoryExist anadir
if exanadir then return ()
else createDirectory anadir
ndInfoFileName :: String -> String
ndInfoFileName file =
let (dir,base) = splitFileName file
basemod = dropExtension base
in dir ++ "/" ++ analysisDir ++ "/" ++ basemod ++ ".ndinfo"
strictInfoFileName :: String -> String
strictInfoFileName file =
let (dir,base) = splitFileName file
basemod = dropExtension base
in dir ++ "/" ++ analysisDir ++ "/" ++ basemod ++ ".strictinfo"
data ADom a = ADom a
(Int -> a)
(String -> [a] -> a)
([Term] -> [a] -> Maybe (Sub a))
(a -> a -> Bool)
(a -> String)
(String -> [a] -> Maybe a)
adomBottom :: ADom a -> a
adomBottom (ADom abottom _ _ _ _ _ _) = abottom
adomShow :: ADom a -> (a -> String)
adomShow (ADom _ _ _ _ _ ashow _) = ashow
abstractCall :: ADom a -> (String,[Term]) -> (String,[a])
abstractCall (ADom _ avar acons _ _ _ _) (f,cargs) = (f, map cons2aterm cargs)
where
cons2aterm (Var v) = avar v
cons2aterm (Func Cons c args) = acons c (map cons2aterm args)
cons2aterm (Func Def _ _) = error "cons2aterm: Func Def occurred"
data SemEq aterm = Eq String [aterm] aterm
deriving (Eq, Ord)
type SemInt aterm = [SemEq aterm]
type Sub a = [(Int,a)]
data CTerm = CBot | CVar Int | CCons String [CTerm]
deriving (Eq, Ord)
matchCTerms :: [Term] -> [CTerm] -> Maybe (Sub CTerm)
matchCTerms [] [] = Just []
matchCTerms [] (_:_) = Nothing
matchCTerms (_:_) [] = Nothing
matchCTerms (x:xs) (y:ys) = combineSubst (match x y) (matchCTerms xs ys)
where
combineSubst Nothing _ = Nothing
combineSubst (Just _ ) Nothing = Nothing
combineSubst (Just s1) (Just s2) = Just (s1++s2)
match :: Term -> CTerm -> Maybe (Sub CTerm)
match (Var v) t = Just [(v,t)]
match (Func _ pf pargs) t = case t of
CBot -> Nothing
CVar _ -> Nothing
CCons tf targs -> if pf==tf then matchCTerms pargs targs else Nothing
lessCSpecific :: CTerm -> CTerm -> Bool
lessCSpecific CBot _ = True
lessCSpecific (CVar _) _ = False
lessCSpecific (CCons c1 args1) t2 = case t2 of
CCons c2 args2 -> c1==c2 && all (uncurry lessCSpecific) (zip args1 args2)
_ -> False
showCTerm :: CTerm -> String
showCTerm CBot = "_"
showCTerm (CVar i) = 'x' : show i
showCTerm (CCons f []) = f
showCTerm (CCons f args@(_:_)) =
f ++ "(" ++ intercalate "," (map showCTerm args) ++ ")"
concreteDom :: ADom CTerm
concreteDom = ADom CBot (error "Cannot handle free variables") CCons
matchCTerms lessCSpecific showCTerm (\_ _ -> Nothing)
data DTerm = DBot | DCons String [DTerm] | CutVar
deriving (Eq, Ord)
matchDTerms :: [Term] -> [DTerm] -> Maybe (Sub DTerm)
matchDTerms [] [] = Just []
matchDTerms [] (_:_) = Nothing
matchDTerms (_:_) [] = Nothing
matchDTerms (x:xs) (y:ys) = combineSubst (match x y) (matchDTerms xs ys)
where
combineSubst Nothing _ = Nothing
combineSubst (Just _ ) Nothing = Nothing
combineSubst (Just s1) (Just s2) = Just (s1++s2)
match :: Term -> DTerm -> Maybe (Sub DTerm)
match (Var v) t = Just [(v,t)]
match (Func _ pf pargs) t = case t of
DBot -> Nothing
CutVar -> Just (map (\v->(v,CutVar)) (concatMap varsOf pargs))
DCons tf targs -> if pf==tf then matchDTerms pargs targs else Nothing
consDTerm :: Int -> String -> [DTerm] -> DTerm
consDTerm maxdepth c args = cutDTerm maxdepth (DCons c args)
cutDTerm :: Int -> DTerm -> DTerm
cutDTerm _ DBot = DBot
cutDTerm _ CutVar = CutVar
cutDTerm d (DCons c args) | d==0 = CutVar
| otherwise = DCons c (map (cutDTerm (d-1)) args)
lessDSpecific :: DTerm -> DTerm -> Bool
lessDSpecific DBot _ = True
lessDSpecific CutVar t = t==CutVar
lessDSpecific (DCons c1 args1) t2 = case t2 of
DCons c2 args2 -> c1==c2 && all (uncurry lessDSpecific) (zip args1 args2)
_ -> False
applyPrimDTerm :: String -> [DTerm] -> Maybe DTerm
applyPrimDTerm f args
| f `elem` allStrictOps
= if DBot `elem` args
then Just DBot
else Just CutVar
| f `elem` fstP2StrictOps
= if head args == DBot
then Just DBot
else Just (args!!1)
| f == "failed"
= Just DBot
| otherwise = Nothing
where
allStrictOps = ["+","-","*","mod","div","<","<=",">",">=","==","/=",
"=:=","show","isEmpty"]
fstP2StrictOps = ["cond","set1"]
showDTerm :: DTerm -> String
showDTerm DBot = "_"
showDTerm CutVar = "*"
showDTerm (DCons f []) = f
showDTerm (DCons f args@(x:xs))
| f == ":" && length xs == 1 =
showDTerm x ++ ":" ++ showDTerm (head xs)
| take 2 f == "(," =
"(" ++ intercalate "," (map showDTerm args) ++ ")"
| otherwise =
f ++ "(" ++ intercalate "," (map showDTerm args) ++ ")"
depthDom :: Int -> ADom DTerm
depthDom k = ADom DBot (const CutVar) (consDTerm k) matchDTerms lessDSpecific
showDTerm applyPrimDTerm
eqSemInt :: Eq a => SemInt a -> SemInt a -> Bool
eqSemInt = (==)
insertSemEq :: Ord a => SemEq a -> SemInt a -> SemInt a
insertSemEq x [] = [x]
insertSemEq x (y:ys) | x == y = y : ys
| x <= y = x : y : ys
| otherwise = y : insertSemEq x ys
updateSemEq :: Ord a => (SemEq a -> SemEq a -> Bool)
-> SemEq a -> SemInt a -> SemInt a
updateSemEq _ x [] = [x]
updateSemEq lessSpecificEq x (y:ys)
| x == y = y : ys
| lessSpecificEq y x = updateSemEq lessSpecificEq x ys
| lessSpecificEq x y = y : ys
| x <= y = x : y : ys
| otherwise = y : updateSemEq lessSpecificEq x ys
lessSpecificEqCallPattern :: (a->a->Bool) -> SemEq a -> SemEq a -> Bool
lessSpecificEqCallPattern lessSpecific (Eq f1 args1 v1) (Eq f2 args2 v2) =
f1==f2 && all (uncurry lessSpecific) (zip args1 args2) && lessSpecific v1 v2
lessSpecificEqResult :: Eq a => (a->a->Bool) -> SemEq a -> SemEq a -> Bool
lessSpecificEqResult lessSpecific (Eq f1 args1 v1) (Eq f2 args2 v2) =
f1==f2 && args1==args2 && lessSpecific v1 v2
transformInt :: Eq a => ADom a -> (SemEq a -> SemInt a -> SemInt a)
-> [Rule] -> SemInt a -> SemInt a -> SemInt a
transformInt (ADom abottom avar acons matchterms _ _ applyprim)
insertsem trs mains int =
foldr insertsem mains
(concatMap (\ (Eq fi argsi _) ->
maybe (concatMap (applyRule fi argsi) (fRules fi))
(\ares -> [Eq fi argsi ares])
(applyprim fi argsi))
int)
where
fRules f = let rules = funcRules f trs
in if null rules
then error ("Rules of operation '"++f++"' not found!")
else rules
applyRule fi argsi (largs,rhs) =
maybe []
(\s -> map (Eq fi argsi) (evalInt s int rhs)
++ concatMap (newSemEq s) (fSubterms rhs))
(matchterms largs argsi)
newSemEq s (f,args) =
map (\iargs -> Eq f iargs abottom) (extendListMap (evalInt s int) args)
evalInt sub _ (Var v) = [maybe (avar v) id (lookup v sub)]
evalInt sub eqs (Func Cons c args) =
map (acons c) (extendListMap (evalInt sub eqs) args)
evalInt sub eqs (Func Def f args) =
let evalargs = extendListMap (evalInt sub eqs) args
in abottom :
concatMap (\ (Eq fi argsi r) ->
if any (\eargs->fi==f && eargs==argsi) evalargs then [r] else [])
eqs
extendListMap :: (a -> [b]) -> [a] -> [[b]]
extendListMap _ [] = [[]]
extendListMap f (x:xs) = [ y:ys | y <- f x, ys <- extendListMap f xs]
runFixpoint :: Eq a => ADom a
-> (SemEq a -> SemInt a -> SemInt a)
-> [Rule] -> [(String,[a])] -> Bool
-> ([SemEq a] -> [SemEq a] -> Bool)
-> IO (SemInt a)
runFixpoint adom insertsem rules mainacalls withprint semeq = do
let trm = transformInt adom insertsem rules
(foldr insertsem [] (map main2int mainacalls))
if withprint then return () else putStr "Iterating:"
garbageCollect
pi1 <- getProcessInfos
fpsem <- computeFixpoint withprint 0 (showSemInt adom) semeq trm []
getProcessInfos >>= printTiming pi1
return fpsem
where
main2int (f,aterms) = Eq f aterms (adomBottom adom)
computeFixpoint :: Bool -> Int -> (a->String) -> (a->a->Bool) -> (a->a) -> a
-> IO a
computeFixpoint withprint n prt eq f v = do
if withprint then putStrLn (show n ++ ": " ++ prt v)
else putStr (' ':show n) >> hFlush stdout
let fv = f v
if eq v fv
then do putStrLn $ "\nFixpoint reached after " ++ show n ++ " iterations"
return v
else computeFixpoint withprint (n+1) prt eq f fv
showSemInt :: ADom a -> SemInt a -> String
showSemInt adom eqs =
let semIntLine = "{" ++ intercalate ", " (map showEq eqs) ++ "}"
in show (length eqs) ++ " semantic equations:\n" ++
if length semIntLine < 80
then semIntLine
else "{" ++ intercalate ",\n " (map showEq eqs) ++ "}"
where
showe = adomShow adom
showEq (Eq f args r) =
f ++ (if null args
then []
else '(' : intercalate "," (map showe args) ++ ")")
++ " = " ++ showe r
getMainCall :: [Rule] -> (String,[Term])
getMainCall rules = ("main", genArgs (arityOf "main" rules))
where
genArgs n = map Var [1..n]
genMainCalls :: ADom a -> [Rule] -> [(String,[a])]
genMainCalls (ADom abot avar _ _ _ _ _) rules =
concatMap genStrictCalls (allFunctions rules)
where
genStrictCalls (f,n) = map genStrictCall [1..n]
where genStrictCall i = (f, replace abot (i-1) (map avar [1..n]))
printProgram :: ADom a -> [Rule] -> [(String,[a])] -> IO ()
printProgram adom rules maincalls = do
putStrLn $ "\nRewrite rules:\n\n" ++ showTRS rules
putStrLn $ "\nMain calls: " ++
intercalate ", " (map showATermCall maincalls)
putStrLn ""
where
showATerm = adomShow adom
showATermCall (f,args) =
f ++ (if null args
then []
else '(' : intercalate "," (map showATerm args) ++ ")")
type WorkSemInt a = Table.TableRBT String [([a],a,[String])]
fEqsOfWorkSem :: String -> WorkSemInt a -> [([a],a,[String])]
fEqsOfWorkSem f ws = maybe [] id (Table.lookup f ws)
processWorkList :: Eq a => ADom a -> (SemEq a->SemEq a->Bool) -> Bool -> [Rule]
-> [(String,[a])] -> WorkSemInt a -> IO (SemInt a)
processWorkList _ _ _ _ [] finals =
return (concatMap (\ (f,feqs) -> map (\ (args,res,_) -> Eq f args res) feqs)
(Table.toList finals))
processWorkList adom@(ADom abottom avar acons matchterms _ _ applyprim)
lessSpecificEq withprint trs wl@((fc,eargs) : working) finals = do
if withprint
then putStr (" W" ++ show (length wl) ++
"/F" ++ show (length (Table.toList finals)))
else return ()
let fcRules = let rules = funcRules fc trs
in if null rules
then error ("Rules of operation '"++fc++"' not found!")
else rules
(newwss,newfeqss) = maybe (unzip (map applyRule fcRules))
(\ares -> ([],[[(eargs,ares,[])]]))
(applyprim fc eargs)
(newws,newfeqs) = (concat newwss, concat newfeqss)
betterCalls = filter isBetterCall newws
betterEquations = filter hasBetterResult
(if null newfeqs
then [(eargs,abottom,[])]
else newfeqs)
bestEquations = filter (\e-> not (any (\ei->ei/=e && leqEqDep e ei)
betterEquations))
betterEquations
activatedEqs =
if null bestEquations
then []
else concatMap (\ (f,feqs) -> concatMap (\ (args,_,deps) ->
if fc `elem` deps then [(f,args)] else []) feqs)
(Table.toList finals)
processWorkList adom lessSpecificEq withprint trs
(foldr insertIfBetterCall working
(betterCalls ++ activatedEqs))
(foldr insertBetterIntoRemaining finals bestEquations)
where
insertBetterIntoRemaining bettereq wsem =
let oldfceqs = fEqsOfWorkSem fc wsem
in Table.update fc
(bettereq : filter (\oldeq -> not (leqEq oldeq bettereq)) oldfceqs)
wsem
insertIfBetterCall eq wlist =
if any (leqCall eq) wlist
then wlist
else eq : filter (\e -> not (leqCall e eq)) wlist
where
leqCall (f,args) (f',args') =
lessSpecificEq (Eq f args abottom) (Eq f' args' abottom)
isBetterCall (f,args) =
not (any (\ (args',_,_) ->
lessSpecificEq (Eq f args abottom) (Eq f args' abottom))
(fEqsOfWorkSem f finals))
hasBetterResult eq = not (any (leqEq eq) (fEqsOfWorkSem fc finals))
leqEq (args,r,_) (args',r',_) =
lessSpecificEq (Eq fc args r) (Eq fc args' r')
leqEqDep (args,r,ds) (args',r',ds') =
lessSpecificEq (Eq fc args r) (Eq fc args' r') && all (`elem` ds') ds
applyRule (largs,rhs) =
maybe ([],[])
(\s -> (concatMap (newCall s) (fSubterms rhs),
map (\ri -> (eargs,ri,depFuncs))
(evalInt s finals rhs)))
(matchterms largs eargs)
where
depFuncs = funcsInTerm rhs
newCall s (f,args) = map (\iargs->(f,iargs))
(extendListMap (evalInt s finals) args)
evalInt sub _ (Var v) = [maybe (avar v) id (lookup v sub)]
evalInt sub eqs (Func Cons c args) =
map (acons c) (extendListMap (evalInt sub eqs) args)
evalInt sub eqs (Func Def f args) =
let evalargs = extendListMap (evalInt sub eqs) args
results = concatMap (\ (argsi,r,_) ->
if any (\evargs->evargs==argsi) evalargs
then [r]
else [])
(fEqsOfWorkSem f eqs)
in if null results then [abottom] else results
runFixpointWL :: Eq a => ADom a -> (SemEq a -> SemEq a -> Bool) -> [Rule]
-> [(String,[a])] -> Bool
-> IO (SemInt a)
runFixpointWL adom lessSpecificEq rules maincalls withprint = do
garbageCollect
pi1 <- getProcessInfos
finals <- processWorkList adom lessSpecificEq withprint rules
maincalls (Table.empty (<=))
pi2 <- getProcessInfos
printTiming pi1 pi2
return finals
printTiming :: [(ProcessInfo,Int)] -> [(ProcessInfo,Int)] -> IO ()
printTiming startPInfos stopPInfos = do
putStrLn $ "Run time: "
++ (showInfoDiff startPInfos stopPInfos RunTime) ++ " msec."
putStrLn $ "Elapsed time: "
++ (showInfoDiff startPInfos stopPInfos ElapsedTime) ++ " msec."
putStrLn $ "Garbage collections: "
++ (showInfoDiff startPInfos stopPInfos GarbageCollections)
where
showInfoDiff infos1 infos2 item =
maybe "n/a"
(\i1 -> show (maybe 0 id (lookup item infos2) - i1))
(lookup item infos1)
main :: IO ()
main = do
args <- getArgs
let (depth,max,wlist,callpat,prog) = checkArgs (1,False,True,False,"") args
if callpat
then callPatternAnalysis depth max wlist (dropExtension prog)
else transformNondet depth max wlist (dropExtension prog)
mainCallError :: [String] -> _
mainCallError args = error $ unlines
[ "Illegal arguments: " ++ unwords args
, ""
, "Usage: curry-ndopt [-d <k>] [-max] [-fix|-wlist] [-call] <module_name>"
, ""
, "Options:"
, "<k> : term depth (default: 1)"
, "-max : compute only maximal abstract elements in fixpoints"
, "-fix : use simple fixpoint iteration"
, "-wlist: use working list fixpoint computation (default)"
, "-call : compute only call patterns (and do not transform program)"
]
checkArgs :: (Int,Bool,Bool,Bool,String) -> [String]
-> (Int,Bool,Bool,Bool,String)
checkArgs (depth,max,wlist,callpat,prog) args = case args of
[] -> mainCallError []
("-d":ks:margs) -> let k = case readNat ks of
[(n,"")] -> n
_ -> mainCallError args
in checkArgs (k,max,wlist,callpat,prog) margs
("-max":margs) -> checkArgs (depth,True,wlist,callpat,prog) margs
("-wlist":margs) -> checkArgs (depth,max,True,callpat,prog) margs
("-fix":margs) -> checkArgs (depth,max,False,callpat,prog) margs
("-call" :margs) -> checkArgs (depth,max,wlist,True,prog) margs
[mainmod] -> (depth,max,wlist,callpat,mainmod)
_ -> mainCallError []
callPatternAnalysis :: Int -> Bool -> Bool -> String -> IO ()
callPatternAnalysis termdepth keepmax withwlist modname = do
rules <- readRules modname
let absdom = depthDom termdepth
maincalls = [abstractCall absdom (getMainCall rules)]
lessSpecificEq = lessSpecificEqCallPattern lessDSpecific
printProgram absdom rules maincalls
let seminsertion = if keepmax then updateSemEq lessSpecificEq
else insertSemEq
fpsem <- if not withwlist
then runFixpoint absdom seminsertion rules maincalls False eqSemInt
else runFixpointWL absdom lessSpecificEq rules maincalls False
putStrLn (showSemInt absdom (sort fpsem))
transformNondet :: Int -> Bool -> Bool -> String -> IO ()
transformNondet termdepth keepmax withwlist modname = do
(FC.Prog _ imports typedecls _ _, rules) <- readFlatCurryRules modname
let absdom = depthDom termdepth
maincalls = genMainCalls absdom rules
lessSpecificEq = lessSpecificEqResult lessDSpecific
printProgram absdom rules maincalls
let seminsertion = if keepmax then updateSemEq lessSpecificEq
else insertSemEq
fpsem <- if not withwlist
then runFixpoint absdom seminsertion rules maincalls False eqSemInt
else runFixpointWL absdom lessSpecificEq rules maincalls False
putStrLn (showSemInt absdom (sort fpsem))
let strinfos = sortFuncInfos (extractStrictness absdom fpsem)
putStrLn ('\n' : showStrictness strinfos)
createAnalysisDir modname
writeFile (strictInfoFileName modname) (show strinfos)
ndinfos <- getNondetInfos modname >>= return . sortFuncInfos
putStrLn ("Computed non-determinism information:\n"++show ndinfos++"\n")
writeFile (ndInfoFileName modname) (show ndinfos)
let (transrules,numopts) = transformRules ndinfos strinfos rules
newprog = letDropping $ unApply transrules
newprogtxt = showTRS newprog
putStrLn $ "Transformed program (stored in '"++modname++"_O.curry'):"
putStrLn newprogtxt
writeFile (modname++"_O.curry")
(unlines (map ("import "++) (filter (/="Prelude") imports)) ++
concatMap showDataDeclAsCurry typedecls ++ newprogtxt)
putStrLn $ "Number of performed optimizations: " ++ show numopts
where
showDataDeclAsCurry fd =
showCurryDataDecl (FC.showQNameInModule (dataModule fd)) fd
unApply :: [Rule] -> [Rule]
unApply = map unApplyInRule . filter (not . applyRule)
where
applyRule (Rule f _ _) = f == "apply"
unApplyInRule :: Rule -> Rule
unApplyInRule (Rule f args exp) = Rule f args (unApplyInExp exp)
unApplyInExp :: Term -> Term
unApplyInExp (Var i) = Var i
unApplyInExp (Func Cons c args) = Func Cons c (map unApplyInExp args)
unApplyInExp (Func Def f args) =
if f=="apply" && length args == 2
then Func Def "$" args
else Func Def f (map unApplyInExp args)
transformRules :: [(String,Bool)] -> [(String,[Int])] -> [Rule] -> ([Rule],Int)
transformRules ndinfos strinfos rules =
let (newrules,numopts) = unzip $
map (\ (Rule f args exp) ->
let (newrhs,_,numopt) = transformExp ndinfos strinfos exp
in (Rule f args newrhs, numopt))
rules
in (newrules, foldr (+) 0 numopts)
transformExp :: [(String,Bool)] -> [(String,[Int])] -> Term -> (Term,Bool,Int)
transformExp _ _ (Var i) = (Var i, False, 0)
transformExp ndinfos strinfos (Func Cons c args) =
let (targs,ndargs,numopts) = unzip3 (map (transformExp ndinfos strinfos) args)
in (Func Cons c targs, or ndargs, foldr (+) 0 numopts)
transformExp ndinfos strinfos (Func Def f args) =
let (targs,ndargs,numopts) = unzip3 (map (transformExp ndinfos strinfos) args)
isndexp = (maybe False id (lookup f ndinfos)) || or ndargs
fsargs = maybe [] id (lookup f strinfos)
argopts = foldr (+) 0 numopts
strictapplies = foldr (\si sargs -> replace (ndargs!!(si-1)) (si-1) sargs)
(take (length args) (repeat False))
fsargs
in if null fsargs || not (or ndargs) || not (or strictapplies)
then (Func Def f targs, isndexp, argopts)
else (strictApply (Func Def f []) strictapplies targs, isndexp, argopts+1)
where
strictApply exp [] [] = exp
strictApply exp (str:strs) (x:xs) =
strictApply (Func Def (if str then "$!" else "$") [exp,x]) strs xs
extractStrictness :: Eq a => ADom a -> SemInt a -> [(String,[Int])]
extractStrictness adom aint = map checkStrictArgs allfuncs
where
abot = adomBottom adom
allfuncs = nub (map (\ (Eq f args _) -> (f,length args)) aint)
checkStrictArgs (f,n) = (f,concatMap checkStrictArg [1..n])
where
checkStrictArg i =
let argibotEqs = filter (\ (Eq g args _) -> f==g && args!!(i-1) == abot)
aint
in if not (null argibotEqs) && all (\ (Eq _ _ r) -> r==abot) argibotEqs
then [i]
else []
sortFuncInfos :: [(String,a)] -> [(String,a)]
sortFuncInfos = sortBy (\i1 i2 -> fst i1 <= fst i2)
showStrictness :: [(String,[Int])] -> String
showStrictness info =
"Computed strictness information:\n"++
unlines (map (\ (f,sargs) -> if null sargs
then f ++ " not strict"
else f ++ " strict at " ++
intercalate "," (map show sargs))
info)
dataModule :: FC.TypeDecl -> String
dataModule (FC.Type tname _ _ _) = fst tname
dataModule (FC.TypeSyn tname _ _ _) = fst tname
dataModule (FC.TypeNew tname _ _ _) = fst tname
prog2DirFile :: String -> String
prog2DirFile = ("benchmarks_callpattern/" ++)
bench :: Int -> String -> IO ()
bench k file = do
putStrLn (take 70 (repeat '='))
rules <- readRules (prog2DirFile file)
let absdom = depthDom k
maincalls = [abstractCall absdom (getMainCall rules)]
printProgram absdom rules maincalls
putStrLn $ "\nTotal number of rules: " ++ show (length rules)
putStrLn "\nRunning simple call analysis..."
semsimple <- runFixpoint absdom insertSemEq
rules maincalls False eqSemInt
putStrLn (showSemInt absdom semsimple)
putStrLn "\nRunning call analysis with ordered insertion..."
semord <- runFixpoint absdom (updateSemEq
(lessSpecificEqCallPattern lessDSpecific))
rules maincalls False eqSemInt
putStrLn (showSemInt absdom semord)
putStrLn "\nRunning call analysis with working lists..."
semwl <- runFixpointWL absdom (lessSpecificEqCallPattern lessDSpecific) rules maincalls False >>=
return . sort
if semord==semwl
then return ()
else putStrLn (showSemInt absdom semwl)
runBench :: IO ()
runBench = do
bench 1 "addadd"
bench 2 "addlast"
bench 1 "bertf0"
bench 1 "bertconc"
bench 1 "doublecoin"
bench 1 "family"
bench 2 "halfdouble"
bench 1 "head"
bench 1 "lastapp"
bench 8 "readfile"
bench 2 "mapadddouble"
bench 1 "risers"
bench 1 "tails"
|