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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
|
module CPM.Diff.Behavior
( ComparisonInfo (..)
, createBaseTemp
, getBaseTemp
, genCurryCheckProgram
, diffBehavior
, preparePackageDirs
, preparePackageAndDir
, preparePackages
, findFunctionsToCompare
) where
import AbstractCurry.Build ( baseType, (~>), cmtfunc, cfunc, simpleRule
, applyF, pVars, applyE)
import AbstractCurry.Pretty (defaultOptions, ppCTypeExpr, showCProg)
import AbstractCurry.Select (publicFuncNames, funcName, functions, funcArity
, funcType, argTypes, typeName, types, tconsOfType
, resultType, isIOType)
import AbstractCurry.Transform (updCFuncDecl)
import AbstractCurry.Types ( CurryProg (..), CFuncDecl (..), CVisibility (..)
, CTypeExpr (..), CPattern (..), CExpr (..)
, CTypeDecl (..), CConsDecl (..), CFieldDecl (..)
, CVarIName, QName)
import Char (isAlphaNum)
import Directory (createDirectory, doesDirectoryExist, getTemporaryDirectory)
import Distribution (lookupModuleSource)
import FilePath ((</>), joinPath)
import Function (both)
import List ( intercalate, intersect, nub, splitOn, isPrefixOf, isInfixOf
, find, delete, (\\), nubBy )
import Maybe ( isJust, fromJust, fromMaybe, listToMaybe )
import Pretty ( pPrint, text, indent, vcat, (<+>), (<$$>) )
import System ( getEnviron, setEnviron, unsetEnviron )
import Analysis.Types ( Analysis )
import Analysis.ProgInfo ( ProgInfo, emptyProgInfo, combineProgInfo
, lookupProgInfo)
import Analysis.Termination ( productivityAnalysis, Productivity(..) )
import Analysis.TypeUsage ( typesInValuesAnalysis )
import CASS.Server ( analyzeGeneric )
import CPM.AbstractCurry ( readAbstractCurryFromDeps, loadPathForPackage )
import CPM.Config ( Config (curryExec) )
import CPM.Diff.API as APIDiff
import CPM.Diff.CurryComments (readComments, getFuncComment)
import CPM.Diff.Rename (prefixPackageAndDeps)
import CPM.ErrorLogger
import CPM.FileUtil ( copyDirectory, recreateDirectory, inDirectory
, joinSearchPath)
import CPM.Package ( Package, Version, name, version, showVersion, packageId
, exportedModules, loadPackageSpec)
import CPM.PackageCache.Global as GC
import CPM.PackageCopy (resolveAndCopyDependencies)
import CPM.Repository (Repository)
data ComparisonInfo = ComparisonInfo
{ infPackageA :: Package
, infPackageB :: Package
, infDirA :: String
, infDirB :: String
, infSourceDirA :: String
, infSourceDirB :: String
, infPrefixA :: String
, infPrefixB :: String
, infModMapA :: [(String, String)]
, infModMapB :: [(String, String)]
}
createBaseTemp :: IO (ErrorLogger String)
createBaseTemp = getTemporaryDirectory >>=
\tmpDir ->
let
tmp = tmpDir </> "CPM" </> "bdiff"
in recreateDirectory tmp >> succeedIO tmp
getBaseTemp :: IO (ErrorLogger String)
getBaseTemp = getTemporaryDirectory >>=
\tmpDir -> succeedIO $ tmpDir </> "CPM" </> "bdiff"
infoText :: String
infoText = unlines
[ "Running behavior diff where the raw output of CurryCheck is shown."
, "The test operations are named after the operations they compare."
, "If a test fails, their implementations semantically differ." ]
diffBehavior :: Config
-> Repository
-> GC.GlobalCache
-> ComparisonInfo
-> Bool
-> Maybe [String]
-> IO (ErrorLogger ())
diffBehavior cfg repo gc info useanalysis cmods = getBaseTemp |>=
\baseTmp -> findFunctionsToCompare cfg repo gc (infSourceDirA info)
(infSourceDirB info) useanalysis cmods |>=
\(acyCache, loadpath, funcs, removed) ->
let
filteredFuncs = maybe funcs
(\mods -> filter ((`elem` mods) . fst . funcName . snd) funcs)
cmods
filteredNames = map snd filteredFuncs
in log Debug ("Filtered operations to be checked: " ++
showFuncNames filteredNames) |>
case funcs of
[] -> printRemoved removed >> succeedIO ()
_ -> do
putStrLn infoText
printRemoved removed
putStrLn $
"Comparing operations " ++ showFuncNames filteredNames ++ "\n"
genCurryCheckProgram cfg repo gc filteredFuncs info acyCache loadpath
|> callCurryCheck cfg info baseTmp
where
printRemoved removed =
if null removed then done
else putStrLn (renderRemoved removed) >> putStrLn ""
renderRemoved :: [(CFuncDecl, FilterReason)] -> String
renderRemoved rs =
pPrint $ text "The following operations are not compared:" <$$>
vcat (map renderReason rs)
where
renderReason (f, r) = indent 4 $ (text $ showQName (funcName f)) <+>
text "-" <+> reasonText r
reasonText NoReason = text "Unknown reason"
reasonText Diffing = text "Different function types or function missing"
reasonText NonMatchingTypes = text "Some types inside the function type differ"
reasonText HighArity = text "Arity too high"
reasonText IOAction = text "IO action"
reasonText NoCompare = text "Marked NOCOMPARE"
reasonText FuncArg = text "Takes functions as arguments"
reasonText NonTerm = text "Possibly non-terminating"
callCurryCheck :: Config -> ComparisonInfo -> String -> IO (ErrorLogger ())
callCurryCheck cfg info baseTmp = do
oldPath <- getEnviron "CURRYPATH"
let currybin = curryExec cfg
currypath = infDirA info ++ ":" ++ infDirB info
setEnviron "CURRYPATH" currypath
log Debug ("Run `curry check Compare' in `" ++ baseTmp ++ "' with") |>
log Debug ("CURRYPATH=" ++ currypath) |> succeedIO ()
ecode <- inDirectory baseTmp $ showExecCmd (currybin ++ " check Compare")
setEnviron "CURRYPATH" oldPath
log Debug "CurryCheck finished" |> succeedIO ()
if ecode==0
then succeedIO ()
else log Error "CurryCheck detected behavior error!"
genCurryCheckProgram :: Config
-> Repository
-> GC.GlobalCache
-> [(Bool,CFuncDecl)]
-> ComparisonInfo
-> ACYCache -> [String]
-> IO (ErrorLogger ())
genCurryCheckProgram cfg repo gc prodfuncs info acyCache loadpath =
getBaseTemp |>= \baseTmp ->
let translatorGenerator = uncurry $ genTranslatorFunction cfg repo gc info in
foldEL translatorGenerator (acyCache, emptyTrans)
translateTypes |>= \(_, transMap) ->
let (limittypes,testFunctions) = unzip (map (genTestFunction info transMap)
prodfuncs)
transFunctions = transFuncs transMap
limittconss = nub (concatMap tconsOfType (concat limittypes))
limittcmods = nub (map fst limittconss)
in
foldEL addLimitType (acyCache,[]) limittconss |>= \ (_,limittdecls) -> do
typeinfos <- analyzeModules "recursive type" typesInValuesAnalysis loadpath
limittcmods
let limitFunctions = concatMap (genLimitFunction typeinfos) limittdecls
prog = CurryProg "Compare" imports []
(testFunctions ++ transFunctions ++ limitFunctions) []
let prodops = map snd (filter fst prodfuncs)
unless (null prodops) $ putStrLn $
"Productive operations (currently not fully supported for all types):\n" ++
showFuncNames prodops ++ "\n"
writeFile (baseTmp </> "Compare.curry")
(progcmts ++ "\n" ++ showCProg prog ++ "\n")
succeedIO ()
where
addLimitType (acy,tdecls) qn =
findTypeInModules cfg repo gc info acy qn |>= \ (acy',tdecl) ->
succeedIO (acy', tdecl:tdecls)
progcmts = unlines $ map ("-- "++)
[ "This file contains properties to compare packages"
, packageId (infPackageA info) ++
" and " ++ packageId (infPackageB info) ++ "."
, ""
, "It should be processed by 'curry check Compare' with setting"
, "export CURRYPATH=" ++ infDirA info ++ ":" ++ infDirB info
]
allReferencedTypes = nub ((concat $ map (argTypes . funcType . snd) prodfuncs)
++ map (resultType . funcType . snd) prodfuncs)
translateTypes = filter (needToTranslatePart info) allReferencedTypes
mods = map (fst . funcName . snd) prodfuncs
modsA = map (\mod -> (infPrefixA info) ++ "_" ++ mod) mods
modsB = map (\mod -> (infPrefixB info) ++ "_" ++ mod) mods
imports = modsA ++ modsB ++ ["Test.EasyCheck"]
genLimitFunction :: ProgInfo [QName] -> CTypeDecl -> [CFuncDecl]
genLimitFunction typeinfos tdecl = case tdecl of
CType tc _ tvs consdecls ->
[cmtfunc ("Limit operation for type " ++ tcname)
(transCTCon2Limit tc) (length tvs + 2) Private
(foldr (~>) (limitFunType (CTCons tc (map CTVar tvs)))
(map (limitFunType . CTVar) tvs))
(cdecls2rules tc tvs consdecls)]
_ -> error $ "Cannot generate limit function for type " ++ tcname
where
tcname = showQName (typeName tdecl)
limitFunType texp = baseType ("Nat","Nat") ~> texp ~> texp
var2limitfun (i,ti) = (i,"lf"++ti)
cdecls2rules tc tvs cdecls =
if null cdecls
then [simpleRule [CPVar (0,"_"), CPVar (1,"x")] (CVar (1,"x"))]
else concatMap (cdecl2rules tvs (nullaryConsOf cdecls)) cdecls
where
nullaryConsOf [] = error $ "Cannot generate limit operation for types " ++
"without nullary constructors: " ++ showQName tc
nullaryConsOf (CCons qc _ [] : _ ) = qc
nullaryConsOf (CCons _ _ (_:_) : cs) = nullaryConsOf cs
nullaryConsOf (CRecord _ _ _ : cs) = nullaryConsOf cs
cdecl2rules tvs tnull (CCons qc _ texps) =
let lfunargs = map (CPVar . var2limitfun) tvs
argvars = map (\i -> (i,"x"++show i)) [0 .. length texps - 1]
isRecursive t = t `elem` fromMaybe [] (lookupProgInfo t typeinfos)
isRecursiveCons = any isRecursive (concatMap tconsOfType texps)
in
(if isRecursiveCons
then [simpleRule (lfunargs ++ [CPComb ("Nat","Z") [],
CPComb qc (map CPVar argvars)])
(applyF tnull [])]
else []) ++
[simpleRule
(lfunargs ++ [if isRecursiveCons then CPComb ("Nat","S") [CPVar (0,"n")]
else CPVar (0,"n"),
CPComb qc (map CPVar argvars)])
(applyF qc (map (\ (te,v) -> applyE (type2LimOp te)
[CVar (0,"n"), CVar v]) (zip texps argvars)))]
cdecl2rules _ _ (CRecord qc _ _) =
error $ "Cannot generate limit operation for record field " ++ showQName qc
type2LimOp (CTVar tv) = CVar (var2limitfun tv)
type2LimOp (CFuncType _ _) =
error "type2LimOp: cannot generate limit operation for function type"
type2LimOp (CTCons tc ts) = applyF (transCTCon2Limit tc) (map type2LimOp ts)
genTestFunction :: ComparisonInfo -> TransMap -> (Bool, CFuncDecl)
-> ([CTypeExpr], CFuncDecl)
genTestFunction info tm (isprod,f) =
(if isprod then [newResultType] else [],
cmtfunc ("Check equivalence of operation " ++ fmod ++ "." ++ fname ++
if isprod then " up to a depth limit" else "")
(modName, testName) (realArity f) Private newType
[if isprod
then let limitvar = (100,"limit") in
simpleRule (if isprod then CPVar limitvar : vars else vars)
(applyF ("Test.EasyCheck", "<~>")
[applyE (type2LimitFunc newResultType) [CVar limitvar, callA],
applyE (type2LimitFunc newResultType) [CVar limitvar, callB]])
else simpleRule vars (applyF ("Test.EasyCheck", "<~>") [callA, callB])])
where
(fmod,fname) = funcName f
modName = "Compare"
testName = "test_" ++
combineTuple (both (replace' '.' '_') $ (fmod, encodeCurryId fname)) "_"
vars = pVars (realArity f)
modA = (infPrefixA info) ++ "_" ++ fmod
modB = (infPrefixB info) ++ "_" ++ fmod
instantiatedFunc = instantiateBool $ funcType f
newResultType = mapTypes info (instantiateBool (resultType (funcType f)))
newType = let ftype = mapTypes info $ genTestFuncType f
in if isprod then baseType ("Nat","Nat") ~> ftype
else ftype
returnTransform = case findTrans tm (resultType $ instantiatedFunc) of
Nothing -> id
Just tr -> \t -> applyF (modName, tr) [t]
callA = returnTransform $ applyF (modA, fname)
$ map (\(CPVar v) -> CVar v) vars
callB = applyF (modB, fname) $ map transformedVar
$ zip (argTypes $ instantiatedFunc) vars
transformedVar (CTVar _, CPVar v) = CVar v
transformedVar (CFuncType _ _, CPVar v) = CVar v
transformedVar (t@(CTCons _ _), CPVar v) = case findTrans tm t of
Just n -> applyF ("Compare", n) [CVar v]
Nothing -> CVar v
transformedVar (CTVar _, CPLit _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CTVar _, CPComb _ _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CTVar _, CPAs _ _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CTVar _, CPFuncComb _ _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CTVar _, CPLazy _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CTVar _, CPRecord _ _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CFuncType _ _, CPLit _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CFuncType _ _, CPComb _ _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CFuncType _ _, CPAs _ _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CFuncType _ _, CPFuncComb _ _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CFuncType _ _, CPLazy _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CFuncType _ _, CPRecord _ _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CTCons _ _, CPLit _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CTCons _ _, CPComb _ _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CTCons _ _, CPAs _ _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CTCons _ _, CPFuncComb _ _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CTCons _ _, CPLazy _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
transformedVar (CTCons _ _, CPRecord _ _) = error "CPM.Diff.Behavior.transformedVar: This case should be impossible to reach"
encodeCurryId :: String -> String
encodeCurryId [] = []
encodeCurryId (c:cs)
| isAlphaNum c || c == '_' = c : encodeCurryId cs
| otherwise = let oc = ord c
in int2hex (oc `div` 16) : int2hex (oc `mod` 16) : encodeCurryId cs
where
int2hex i = if i<10 then chr (ord '0' + i)
else chr (ord 'A' + i - 10)
needToTranslatePart :: ComparisonInfo -> CTypeExpr -> Bool
needToTranslatePart _ (CTVar _) = False
needToTranslatePart info (CFuncType e1 e2) =
needToTranslatePart info e1 || needToTranslatePart info e2
needToTranslatePart info (CTCons n es) =
isMappedType info n || any (needToTranslatePart info) es
isMappedType :: ComparisonInfo -> (String, String) -> Bool
isMappedType info (mod, _) = isJust $ lookup mod (infModMapA info)
data TransMap = TransMap [(CTypeExpr, String)] Int [CFuncDecl]
emptyTrans :: TransMap
emptyTrans = TransMap [] 0 []
addEntry :: TransMap -> CTypeExpr -> (TransMap, String)
addEntry (TransMap m n fs) e =
(TransMap ((e, "tt_" ++ show n) : m) (n + 1) fs, "tt_" ++ show n)
addFunc :: TransMap -> CFuncDecl -> TransMap
addFunc (TransMap m n fs) f = TransMap m n (f:fs)
findTrans :: TransMap -> CTypeExpr -> Maybe String
findTrans (TransMap m _ _) e = lookup e m
transFuncs :: TransMap -> [CFuncDecl]
transFuncs (TransMap _ _ fs) = fs
predefinedType :: (String, String) -> Maybe CTypeDecl
predefinedType x = case x of
("Prelude", "[]") -> Just $ CType ("Prelude", "[]") Public [(0, "a")] [
CCons ("Prelude", "[]") Public []
, CCons ("Prelude", ":") Public
[CTVar (0, "a"), CTCons ("Prelude", "[]") [CTVar (0, "a")]]]
("Prelude", "(,)") -> Just $ CType ("Prelude", "(,)") Public [(0, "a"), (1, "b")] [
CCons ("Prelude", "(,)") Public [CTVar (0, "a"), CTVar (1, "b")]]
("Prelude", "(,,)") -> Just $ CType ("Prelude", "(,,)") Public [(0, "a"), (1, "b"), (2, "c")] [
CCons ("Prelude", "(,,)") Public [CTVar (0, "a"), CTVar (1, "b"), CTVar (2, "c")]]
("Prelude", "(,,,)") -> Just $ CType ("Prelude", "(,,,)") Public [(0, "a"), (1, "b"), (2, "c"), (3, "d")] [
CCons ("Prelude", "(,,,)") Public [CTVar (0, "a"), CTVar (1, "b"), CTVar (2, "c"), CTVar (3, "d")]]
_ -> Nothing
data ACYCache = ACYCache [(String, [(String, CurryProg)])]
emptyACYCache :: ACYCache
emptyACYCache = ACYCache []
findModule :: String -> ACYCache -> Maybe CurryProg
findModule mod (ACYCache ps) = case lookup mod ps of
Nothing -> Nothing
Just ms -> listToMaybe $ map snd ms
findModuleDir :: String -> String -> ACYCache -> Maybe CurryProg
findModuleDir dir mod (ACYCache ps) = case lookup mod ps of
Nothing -> Nothing
Just ms -> lookup dir ms
addModule :: String -> CurryProg -> ACYCache -> ACYCache
addModule mod p (ACYCache ps) = case lookup mod ps of
Just _ -> ACYCache ps
Nothing -> ACYCache $ (mod, [("", p)]):ps
addModuleDir :: String -> String -> CurryProg -> ACYCache -> ACYCache
addModuleDir dir mod p (ACYCache ps) = case lookup mod ps of
Just ms -> case lookup dir ms of
Just _ -> ACYCache ps
Nothing -> ACYCache $ (mod, (dir, p):ms):(delete (mod, ms) ps)
Nothing -> ACYCache $ (mod, [(dir, p)]):ps
genTranslatorFunction :: Config
-> Repository
-> GC.GlobalCache
-> ComparisonInfo
-> ACYCache
-> TransMap
-> CTypeExpr
-> IO (ErrorLogger (ACYCache, TransMap))
genTranslatorFunction _ _ _ _ _ _ (CTVar _) =
error $ "CPM.Diff.Behavior.genTranslatorFunction: " ++
"Cannot generate translator function for CTVar"
genTranslatorFunction _ _ _ _ _ _ te@(CFuncType _ _) =
error $ "CPM.Diff.Behavior.genTranslatorFunction: " ++
"Cannot generate translator function for CFuncType:\n" ++
pPrint (ppCTypeExpr defaultOptions te)
genTranslatorFunction cfg repo gc info acy tm t@(CTCons (mod, n) _) =
if isJust $ findTrans tm t'
then succeedIO (acy, tm)
else findTypeInModules cfg repo gc info acy (mod,n) |>=
\(acy', typeDecl) -> (succeedIO $ instantiate typeDecl t') |>=
\instTypeDecl -> (succeedIO $ addEntry tm t') |>=
\(tm', name) -> foldEL (uncurry $ genTranslatorFunction cfg repo gc info)
(acy', tm') (transExprs instTypeDecl) |>=
\(acy'', tm'') ->
let
aType = prefixMappedTypes (infPrefixA info) t'
bType = prefixMappedTypes (infPrefixB info) t'
fType = CFuncType aType bType
fName = ("Compare", name)
mapIfNeeded modMap m =
if isMappedType info (m, "") then fromJust $ lookup m modMap
else m
mapIfNeededA = mapIfNeeded (infModMapA info)
mapIfNeededB = mapIfNeeded (infModMapB info)
transformer (i, CTVar _) = CVar (i, "x" ++ (show i))
transformer (i, CFuncType _ _) = CVar (i, "x" ++ (show i))
transformer (i, e@(CTCons _ _)) = case findTrans tm'' e of
Nothing -> CVar (i, "x" ++ (show i))
Just tn -> applyF ("Compare", tn) [CVar (i, "x" ++ (show i))]
ruleForCons (CCons (m, cn) _ es) = simpleRule [pattern] call
where
pattern = CPComb (mapIfNeededA m, cn) (pVars (length es))
call = applyF (mapIfNeededB m, cn) $ map transformer
$ zip (take (length es) [0..]) es
ruleForCons (CRecord (m, cn) _ fs) = simpleRule [pattern] call
where
pattern = CPComb (mapIfNeededA m, cn) (pVars (length fs))
call = applyF (mapIfNeededB m, cn) $ map transformer
$ zip (take (length fs) [0..]) (map (\(CField _ _ es) -> es) fs)
synRule e = simpleRule [CPVar (0, "x0")] call
where
call = transformer (0, e)
in case instTypeDecl of
CType _ _ _ cs -> succeedIO $
(acy'', addFunc tm'' (cfunc fName 1 Public fType (map ruleForCons cs)))
CTypeSyn _ _ _ e -> succeedIO $
(acy'', addFunc tm'' (cfunc fName 1 Public fType [synRule e]))
CNewType _ _ _ c -> succeedIO $
(acy'', addFunc tm'' (cfunc fName 1 Public fType [ruleForCons c]))
where
t' = instantiateBool t
transExprs cs = filter (needToTranslatePart info) $ nub $ extractExprs cs
extractExprs (CType _ _ _ es) = concat $ map extractExprsCons es
extractExprs (CTypeSyn _ _ _ e) = [e]
extractExprs (CNewType _ _ _ c) = extractExprsCons c
extractExprsCons (CCons _ _ es) = es
extractExprsCons (CRecord _ _ fs) = map (\(CField _ _ es) -> es) fs
prefixMappedTypes pre (CTCons (mod', n') te') =
if isMappedType info (mod', n')
then CTCons (pre ++ "_" ++ mod', n') $ map (prefixMappedTypes pre) te'
else CTCons (mod', n') $ map (prefixMappedTypes pre) te'
prefixMappedTypes _ (CTVar v) = CTVar v
prefixMappedTypes pre (CFuncType e1 e2) =
CFuncType (prefixMappedTypes pre e1) (prefixMappedTypes pre e2)
findTypeInModules :: Config -> Repository -> GC.GlobalCache -> ComparisonInfo
-> ACYCache -> QName -> IO (ErrorLogger (ACYCache, CTypeDecl))
findTypeInModules cfg repo gc info acy (mod,n) =
case predefinedType (mod, n) of
Just ty -> succeedIO (acy, ty)
Nothing ->
(case findModule mod acy of
Just p -> succeedIO $ p
Nothing -> resolveAndCopyDependencies cfg repo gc
(infSourceDirA info) |>= \deps ->
readAbstractCurryFromDeps (infSourceDirA info) deps mod >>=
succeedIO) |>= \prog ->
case filter ((== n) . snd . typeName) (types prog) of
[] -> failIO $ "No type defined '" ++ n ++ "' in module '"
++ mod ++ "'"
(x:_) -> succeedIO (addModule mod prog acy, x)
maybeReplaceVar :: [(CVarIName, CTypeExpr)] -> CTypeExpr -> CTypeExpr
maybeReplaceVar vm (CTVar v) = case lookup v vm of
Nothing -> CTVar v
Just e' -> e'
maybeReplaceVar vm (CTCons n es) = CTCons n $ map (maybeReplaceVar vm) es
maybeReplaceVar vm (CFuncType e1 e2) =
CFuncType (maybeReplaceVar vm e1) (maybeReplaceVar vm e2)
instantiate :: CTypeDecl -> CTypeExpr -> CTypeDecl
instantiate (CType n v vs cs) (CTCons _ es) = CType n v vs $ map cons cs
where
varMap = zip vs es
cons (CCons n' v' es') = CCons n' v' $ map (maybeReplaceVar varMap) es'
cons (CRecord n' v' fs') = CRecord n' v' $ map maybeReplaceField fs'
maybeReplaceField (CField n'' v'' e) =
CField n'' v'' $ maybeReplaceVar varMap e
instantiate (CTypeSyn n v vs e) (CTCons _ es) =
CTypeSyn n v vs $ maybeReplaceVar varMap e
where
varMap = zip vs es
instantiate (CNewType n v vs c) (CTCons _ es) = CNewType n v vs $ cons c
where
varMap = zip vs es
cons (CCons n' v' es') = CCons n' v' $ map (maybeReplaceVar varMap) es'
cons (CRecord n' v' fs') = CRecord n' v' $ map maybeReplaceField fs'
maybeReplaceField (CField n'' v'' e) = CField n'' v'' $ maybeReplaceVar varMap e
instantiate (CType _ _ _ _) (CTVar _) = error "CPM.Diff.Behavior.instantiate: Cannot instantiate CTVar"
instantiate (CTypeSyn _ _ _ _) (CTVar _) = error "CPM.Diff.Behavior.instantiate: Cannot instantiate CTVar"
instantiate (CNewType _ _ _ _) (CTVar _) = error "CPM.Diff.Behavior.instantiate: Cannot instantiate CTVar"
instantiate (CType _ _ _ _) (CFuncType _ _) = error "CPM.Diff.Behavior.instantiate: Cannot instantiate CFuncType"
instantiate (CTypeSyn _ _ _ _) (CFuncType _ _) = error "CPM.Diff.Behavior.instantiate: Cannot instantiate CFuncType"
instantiate (CNewType _ _ _ _) (CFuncType _ _) = error "CPM.Diff.Behavior.instantiate: Cannot instantiate CFuncType"
mapTypes :: ComparisonInfo -> CTypeExpr -> CTypeExpr
mapTypes info (CFuncType a b) = CFuncType (mapTypes info a) (mapTypes info b)
mapTypes _ v@(CTVar _) = v
mapTypes info (CTCons (m, n) ts) = case lookup m mapA of
Nothing -> CTCons (m, n) $ map (mapTypes info) ts
Just m' -> CTCons (m', n) $ map (mapTypes info) ts
where
mapA = infModMapA info
realArity :: CFuncDecl -> Int
realArity (CFunc _ _ _ t _) = arityOfType t
realArity (CmtFunc _ _ _ _ t _) = arityOfType t
arityOfType :: CTypeExpr -> Int
arityOfType (CFuncType _ b) = 1 + arityOfType b
arityOfType (CTVar _) = 0
arityOfType (CTCons _ _) = 0
type2LimitFunc :: CTypeExpr -> CExpr
type2LimitFunc (CTVar _) =
error "type2LimitFunc: cannot generate limit operation for type variable"
type2LimitFunc (CFuncType _ _) =
error "type2LimitFunc: cannot generate limit operation for function type"
type2LimitFunc (CTCons tc ts) =
applyF (transCTCon2Limit tc) (map type2LimitFunc ts)
transCTCon2Limit :: QName -> QName
transCTCon2Limit (_,tcn) = ("Compare", "limit" ++ trans tcn)
where
trans n | n=="[]" = "List"
| n=="()" = "Unit"
| "(," `isPrefixOf` n = "Tuple" ++ show (length n - 1)
| otherwise = n
genTestFuncType :: CFuncDecl -> CTypeExpr
genTestFuncType f = replaceResultType t (CTCons ("Test.EasyCheck", "Prop") [])
where t = instantiateBool $ funcType f
instantiateBool :: CTypeExpr -> CTypeExpr
instantiateBool (CTVar _) = CTCons ("Prelude", "Bool") []
instantiateBool (CTCons n ts) = CTCons n $ map instantiateBool ts
instantiateBool (CFuncType a b) = CFuncType (instantiateBool a) (instantiateBool b)
replaceResultType :: CTypeExpr -> CTypeExpr -> CTypeExpr
replaceResultType (CFuncType a (CTVar _)) z = CFuncType a z
replaceResultType (CFuncType a (CTCons _ _)) z = CFuncType a z
replaceResultType (CFuncType a b@(CFuncType _ _)) z = CFuncType a (replaceResultType b z)
replaceResultType (CTVar _) z = z
replaceResultType (CTCons _ _) z = z
combineTuple :: (String, String) -> String -> String
combineTuple (a, b) s = a ++ s ++ b
showQName :: QName -> String
showQName qn = combineTuple qn "."
showFuncNames :: [CFuncDecl] -> String
showFuncNames = intercalate ", " . map (showQName . funcName)
replace' :: a -> a -> [a] -> [a]
replace' _ _ [] = []
replace' o n (x:xs) | x == o = n : replace' o n xs
| otherwise = x : replace' o n xs
findFunctionsToCompare :: Config
-> Repository
-> GC.GlobalCache
-> String
-> String
-> Bool
-> Maybe [String]
-> IO (ErrorLogger (ACYCache, [String],
[(Bool,CFuncDecl)], [(CFuncDecl, FilterReason)]))
findFunctionsToCompare cfg repo gc dirA dirB useanalysis cmods =
loadPackageSpec dirA |>= \pkgA ->
loadPackageSpec dirB |>= \pkgB ->
resolveAndCopyDependencies cfg repo gc dirA |>= \depsA ->
succeedIO (maybe (intersect (exportedModules pkgA) (exportedModules pkgB))
id
cmods) |>= \mods ->
log Debug ("Comparing modules: "++ intercalate " " mods) |>
APIDiff.compareModulesInDirs cfg repo gc dirA dirB (Just mods) |>= \diffs ->
findAllFunctions dirA dirB pkgA depsA emptyACYCache mods |>=
\(acy, allFuncs) ->
log Debug ("All public functions: " ++ showFuncNames allFuncs) |>
let areDiffThenFilter = thenFilter allFuncs Diffing
areHighArityThenFilter = thenFilter allFuncs HighArity
areIOActionThenFilter = thenFilter allFuncs IOAction
areNoCompareThenFilter = thenFilter allFuncs NoCompare
areNonMatchingThenFilter = thenFilter allFuncs NonMatchingTypes
haveFuncArgThenFilter = thenFilter allFuncs FuncArg
in
(emptyFilter ((liftFilter $ filterDiffingFunctions diffs) acy allFuncs)
`areDiffThenFilter`
liftFilter filterHighArity `areHighArityThenFilter`
liftFilter filterIOAction `areIOActionThenFilter`
filterNoCompare dirA dirB depsA `areNoCompareThenFilter`
filterNonMatchingTypes dirA dirB depsA `areNonMatchingThenFilter`
filterFuncArg dirA dirB depsA `haveFuncArgThenFilter`
liftFilter id ) |>= terminationFilter pkgA dirA depsA useanalysis
terminationFilter :: Package -> String -> [Package] -> Bool
-> (ACYCache, [CFuncDecl], [(CFuncDecl, FilterReason)])
-> IO (ErrorLogger (ACYCache, [String], [(Bool,CFuncDecl)],
[(CFuncDecl, FilterReason)]))
terminationFilter _ _ _ False (a,fs,rm) =
succeedIO (a, [], map (\f->(False,f)) fs, rm)
terminationFilter pkgA dirA depsA True (acy, funcs, rm) = do
let currypath = loadPathForPackage pkgA dirA depsA
mods = nub (map (fst . funcName) funcs)
ainfo <- analyzeModules "productivity" productivityAnalysis currypath mods
modscmts <- mapIO (getCompare currypath) mods
let termfuns = concatMap (\md -> md ("TERMINATE" `isInfixOf`)) modscmts
prodfuns = concatMap (\md -> md ("PRODUCTIVE" `isInfixOf`)) modscmts
log Debug ("Functions marked with TERMINATE: " ++ showFuncNames termfuns)
|> succeedIO ()
log Debug ("Functions marked with PRODUCTIVE: " ++ showFuncNames prodfuns)
|> succeedIO ()
let infoOf f = fromMaybe Looping (lookupProgInfo (funcName f) ainfo)
ntfuncs = filter (\f -> infoOf f == Looping &&
f `notElem` termfuns && f `notElem` prodfuns)
funcs
succeedIO (acy, currypath,
map (\f -> (not (infoOf f == Terminating || f `elem` termfuns), f))
(funcs \\ ntfuncs),
rm ++ map (\f -> (f,NonTerm)) ntfuncs)
where
getCompare currypath modname = do
src <- lookupModuleSource currypath modname
(_,comments) <- case src of
Nothing -> error $ "Module not found: " ++ modname
Just (_, file) -> readComments file
return (\p -> filter (\f -> let (mn,fn) = funcName f
in mn == modname &&
p (getFuncComment fn comments))
funcs)
analyzeModules :: String -> Analysis a -> [String] -> [String]
-> IO (ProgInfo a)
analyzeModules ananame analysis currypath mods = do
log Debug ("Running " ++ ananame ++ " analysis on modules: " ++
intercalate ", " mods) |>
log Debug ("CURRYPATH=" ++ joinSearchPath currypath) |> succeedIO ()
anainfos <- mapIO (analyzeModule analysis currypath) mods
log Debug "Analysis finished" |> succeedIO ()
return $ foldr combineProgInfo emptyProgInfo anainfos
analyzeModule :: Analysis a -> [String] -> String -> IO (ProgInfo a)
analyzeModule analysis currypath mod = do
setEnviron "CURRYPATH" (joinSearchPath currypath)
aresult <- analyzeGeneric analysis mod
unsetEnviron "CURRYPATH"
either return
(\e -> do putStrLn "WARNING: error occurred during analysis:"
putStrLn e
putStrLn "Ignoring analysis information"
return emptyProgInfo)
aresult
emptyFilter :: IO (ErrorLogger (ACYCache, [CFuncDecl]))
-> IO (ErrorLogger (ACYCache, [CFuncDecl], [(CFuncDecl, FilterReason)]))
emptyFilter st = st |>= \(a, fs) -> succeedIO (a, fs, [])
data FilterReason = NoReason
| HighArity
| IOAction
| NoCompare
| NonMatchingTypes
| Diffing
| FuncArg
| NonTerm
thenFilter :: [CFuncDecl]
-> FilterReason
-> IO (ErrorLogger (ACYCache, [CFuncDecl], [(CFuncDecl, FilterReason)]))
-> (ACYCache -> [CFuncDecl] -> IO (ErrorLogger (ACYCache, [CFuncDecl])))
-> IO (ErrorLogger (ACYCache, [CFuncDecl], [(CFuncDecl, FilterReason)]))
thenFilter allFuncs r st f =
st |>=
\(a, fs, rm) -> f a fs |>=
\(a', fs') -> succeedIO (a', fs', rm ++ zip (findMissing rm fs) (repeat r))
where
findMissing rm fs = (allFuncs \\ (map fst rm)) \\ fs
liftFilter :: ([CFuncDecl] -> [CFuncDecl])
-> (ACYCache -> [CFuncDecl] -> IO (ErrorLogger (ACYCache, [CFuncDecl])))
liftFilter f = \a fs -> succeedIO (a, f fs)
filterFuncArg :: String -> String -> [Package] -> ACYCache -> [CFuncDecl]
-> IO (ErrorLogger (ACYCache, [CFuncDecl]))
filterFuncArg = filterFuncsDeep checkFunc
where
checkFunc (CFuncType _ _) = True
checkFunc (CTVar _) = False
checkFunc (CTCons _ _) = False
filterFuncsDeep :: (CTypeExpr -> Bool) -> String -> String -> [Package]
-> ACYCache -> [CFuncDecl]
-> IO (ErrorLogger (ACYCache, [CFuncDecl]))
filterFuncsDeep tpred dirA _ deps acy allFuncs =
foldEL checkFunc (acy, [], []) allFuncs |>=
\(acy', _, fns) -> succeedIO (acy', fns)
where
findType n m = case predefinedType n of
Nothing -> find ((== n) . typeName) $ filter isTypePublic $ types m
Just ty -> Just ty
checkFunc (a, c, fs) f =
(foldEL checkTypeExpr (a, c, False) $ argTypes $ funcType f) |>=
\(a', c', r) -> if r then succeedIO (a', c', fs)
else succeedIO (a', c', f:fs)
checkTypeExpr (a, c, r) t@(CFuncType e1 e2) =
if t `elem` c
then succeedIO (a, c, r)
else if tpred t
then succeedIO (a, c, True)
else checkTypeExpr (a, c, r) e1 |>=
\ (a', c', r') -> checkTypeExpr (a', e1:c', r') e2 |>=
\ (a'', c'', r'') -> succeedIO (a'', e2:c'', r || r' || r'')
checkTypeExpr (a, c, r) (CTVar _) = succeedIO (a, c, r)
checkTypeExpr (a, c, r) t@(CTCons n@(mod, _) es) =
if t `elem` c
then succeedIO (a, c, r)
else if tpred t
then succeedIO (a, c, True)
else foldEL checkTypeExpr (a, c, r) es |>=
\(a', c', _) -> readCached dirA deps a' mod |>=
\(a'', prog) -> case findType n prog of
Nothing -> failIO $ "Type '" ++ show n ++ "' not found."
Just t' -> checkType a'' (t:c') t' |>=
\(a''', c'', r'') -> succeedIO (a''', c'', r || r'')
checkType a ts (CType _ _ _ cs) = foldEL checkCons (a, ts, False) cs
checkType a ts (CTypeSyn _ _ _ e) = checkTypeExpr (a, ts, False) e
checkType a ts (CNewType _ _ _ c) = checkCons (a, ts, False) c
checkCons (a, ts, r) (CCons _ _ es) = foldEL checkTypeExpr (a, ts, r) es
checkCons (a, ts, r) (CRecord _ _ fs) =
let es = map (\(CField _ _ e) -> e) fs
in foldEL checkTypeExpr (a, ts, r) es
filterNoCompare :: String -> String -> [Package] -> ACYCache -> [CFuncDecl]
-> IO (ErrorLogger (ACYCache, [CFuncDecl]))
filterNoCompare dirA dirB _ a fs =
mapIO (readComments . modPath dirA) modules >>= \allCommentsA ->
mapIO (readComments . modPath dirB) modules >>= \allCommentsB ->
let commentsA = funcsWithComments $ zip modules allCommentsA
commentsB = funcsWithComments $ zip modules allCommentsB
in succeedIO $ (a, filter (not . noCompare commentsA commentsB) fs)
where
modules = nub $ map (fst . funcName) fs
modPath dir mod = dir </> "src" </> joinPath (splitOn "." mod) ++ ".curry"
funcsWithComments cmts = zip fs (map (getFuncComment' cmts) fs)
getFuncComment' cmts f =
let
mname = fst $ funcName f
lname = snd $ funcName f
in case lookup mname cmts of
Nothing -> ""
Just cs -> getFuncComment lname $ snd cs
noCompare cmtsA cmtsB f = noCompare' cmtsA f || noCompare' cmtsB f
noCompare' cmts f = case lookup f cmts of
Nothing -> False
Just c -> "NOCOMPARE" `isInfixOf` c
filterHighArity :: [CFuncDecl] -> [CFuncDecl]
filterHighArity = filter ((<= 5) . length . argTypes . funcType)
filterIOAction :: [CFuncDecl] -> [CFuncDecl]
filterIOAction = filter (not . isIOType . resultType . funcType)
filterDiffingFunctions :: [(String, Differences)] -> [CFuncDecl] -> [CFuncDecl]
filterDiffingFunctions diffs allFuncs = nub $ concatMap filterModule modules
where
modules = nub $ map (fst . funcName) allFuncs
diffsForModule mod = case lookup mod diffs of
Nothing -> []
Just (_, funcDiffs, _, _) -> map funcDiffName funcDiffs
funcDiffName (Addition f) = funcName f
funcDiffName (Removal f) = funcName f
funcDiffName (Change _ f) = funcName f
filterModule mod = filter (not . (`elem` (diffsForModule mod)) . funcName)
(funcsForModule mod)
funcsForModule mod = filter ((== mod) . fst . funcName) allFuncs
filterNonMatchingTypes :: String -> String -> [Package] -> ACYCache
-> [CFuncDecl] -> IO (ErrorLogger (ACYCache, [CFuncDecl]))
filterNonMatchingTypes dirA dirB deps acyCache allFuncs =
foldEL funcTypesCompatible (acyCache, [], []) allFuncs |>=
\(acy, _, fns) -> succeedIO (acy, fns)
where
allTypes f = let ft = funcType f in (resultType ft):(argTypes ft)
onlyCons = filter isConsType
funcTypesCompatible (a, seen, fs) f =
(foldEL typesCompatible (a, seen, True) $ onlyCons $ allTypes f) |>=
\(a', seen', c) -> if c
then succeedIO (a', seen', f:fs)
else succeedIO (a', seen', fs)
typesCompatible (a, seen, r) t = case lookup t seen of
Just b -> succeedIO (a, seen, b && r)
Nothing -> typesEqual t dirA dirB deps a [] |>=
\(a', r') -> succeedIO (a', ((t, r'):seen), r' && r)
typesEqual :: CTypeExpr -> String -> String -> [Package] -> ACYCache
-> [CTypeExpr] -> IO (ErrorLogger (ACYCache, Bool))
typesEqual t@(CTCons n _) dirA dirB deps acyCache checked =
if t `elem` checked
then succeedIO (acyCache, True)
else readCached dirA deps acyCache mod |>= \(acy',modA) ->
readCached dirB deps acy' mod |>= \(acy'', modB) ->
let typeA = findType modA
typeB = findType modB
in typesEqual' typeA typeB acy''
where
(mod, _) = n
findType m = case predefinedType n of
Nothing -> find ((== n) . typeName) $ filter isTypePublic $ types m
Just ty -> Just ty
typesEqual' :: Maybe CTypeDecl -> Maybe CTypeDecl -> ACYCache
-> IO (ErrorLogger (ACYCache, Bool))
typesEqual' (Just (CType n1 v1 tvs1 cs1)) (Just (CType n2 v2 tvs2 cs2)) acy =
if n1 == n2 && v1 == v2 && tvs1 == tvs2 && cs1 == cs2
then foldEL (\(a, r) (c1, c2) -> consEqual a c1 c2 |>= \(a', r') ->
succeedIO (a', r && r')) (acy, True) (zip cs1 cs2)
else succeedIO (acy, False)
typesEqual' (Just (CTypeSyn n1 v1 tvs1 e1))
(Just (CTypeSyn n2 v2 tvs2 e2)) acy =
if n1 == n2 && v1 == v2 && tvs1 == tvs2 && e1 == e2
then if isConsType e1
then typesEqual e1 dirA dirB deps acy (t:checked)
else succeedIO (acy, True)
else succeedIO (acy, False)
typesEqual' (Just (CNewType n1 v1 tvs1 c1))
(Just (CNewType n2 v2 tvs2 c2)) acy =
if n1 == n2 && v1 == v2 && tvs1 == tvs2 && c1 == c2
then consEqual acy c1 c2
else succeedIO (acy, False)
typesEqual' (Just (CType _ _ _ _)) (Just (CTypeSyn _ _ _ _)) acy =
succeedIO (acy, False)
typesEqual' (Just (CType _ _ _ _)) (Just (CNewType _ _ _ _)) acy =
succeedIO (acy, False)
typesEqual' (Just (CTypeSyn _ _ _ _)) (Just (CType _ _ _ _)) acy =
succeedIO (acy, False)
typesEqual' (Just (CTypeSyn _ _ _ _)) (Just (CNewType _ _ _ _)) acy =
succeedIO (acy, False)
typesEqual' (Just (CNewType _ _ _ _)) (Just (CType _ _ _ _)) acy =
succeedIO (acy, False)
typesEqual' (Just (CNewType _ _ _ _)) (Just (CTypeSyn _ _ _ _)) acy =
succeedIO (acy, False)
typesEqual' Nothing (Just _) acy = succeedIO (acy, False)
typesEqual' (Just _) Nothing acy = succeedIO (acy, False)
typesEqual' Nothing Nothing acy = succeedIO (acy, False)
consEqual :: ACYCache -> CConsDecl -> CConsDecl
-> IO (ErrorLogger (ACYCache, Bool))
consEqual acy (CCons _ _ es1) (CCons _ _ es2) =
foldEL esEqual (acy, True) (zip es1 es2)
where
esEqual (a, r) (e1, e2) = if e1 == e2
then if isConsType e1
then typesEqual e1 dirA dirB deps a (t:checked)
else succeedIO (acy, r)
else succeedIO (acy, False)
consEqual acy (CRecord _ _ fs1) (CRecord _ _ fs2) =
foldEL fEqual (acy, True) (zip fs1 fs2)
where
fEqual (a, r) (f1@(CField _ _ e1), f2@(CField _ _ _)) = if f1 == f2
then if isConsType e1
then typesEqual e1 dirA dirB deps a (t:checked)
else succeedIO (acy, r)
else succeedIO (acy, False)
consEqual acy (CCons _ _ _) (CRecord _ _ _) = succeedIO (acy, False)
consEqual acy (CRecord _ _ _) (CCons _ _ _) = succeedIO (acy, False)
typesEqual (CTVar _) _ _ _ _ _ = failIO "typesEqual called on CTVar"
typesEqual (CFuncType _ _) _ _ _ _ _ = failIO "typesEqual called on CFuncType"
isTypePublic :: CTypeDecl -> Bool
isTypePublic (CType _ v _ _) = v == Public
isTypePublic (CTypeSyn _ v _ _) = v == Public
isTypePublic (CNewType _ v _ _) = v == Public
isConsType :: CTypeExpr -> Bool
isConsType (CTCons _ _) = True
isConsType (CTVar _) = False
isConsType (CFuncType _ _) = False
readCached :: String -> [Package] -> ACYCache -> String
-> IO (ErrorLogger (ACYCache, CurryProg))
readCached dir deps acyCache mod = case findModuleDir dir mod acyCache of
Just p -> succeedIO (acyCache, p)
Nothing -> do prog <- readAbstractCurryFromDeps dir deps mod
succeedIO (addModuleDir dir mod prog acyCache, prog)
findAllFunctions :: String -> String -> Package -> [Package] -> ACYCache
-> [String] -> IO (ErrorLogger (ACYCache, [CFuncDecl]))
findAllFunctions dirA dirB _ deps acyCache mods =
log Debug ("Finding public functions of modules: " ++ intercalate "," mods) |>
log Debug ("in package directories " ++ dirA ++ " and " ++ dirB) |>
foldEL findForMod (acyCache, []) mods |>=
\(a, fs) -> succeedIO (a, nub fs)
where
findForMod (acy,fdecls) mod =
readCached dirA deps acy mod |>= \(_, progA) ->
readCached dirB deps acy mod |>= \(acy'', progB) ->
let funcsA = filter isPublic $ functions progA
funcsB = filter isPublic $ functions progB
in succeedIO (acy'', fdecls ++ nubBy (\a b -> funcName a == funcName b)
(funcsA ++ funcsB))
isPublic :: CFuncDecl -> Bool
isPublic (CFunc _ _ Public _ _) = True
isPublic (CFunc _ _ Private _ _) = False
isPublic (CmtFunc _ _ _ Public _ _) = True
isPublic (CmtFunc _ _ _ Private _ _) = False
preparePackages :: Config
-> Repository
-> GC.GlobalCache
-> String
-> Version
-> String
-> Version
-> IO (ErrorLogger ComparisonInfo)
preparePackages cfg repo gc nameA verA nameB verB =
GC.tryFindPackage gc nameA verA |>=
\pkgA -> findPackageDir cfg pkgA |>=
\dirA -> GC.tryFindPackage gc nameB verB |>=
\pkgB -> findPackageDir cfg pkgB |>=
\dirB -> preparePackageDirs cfg repo gc dirA dirB
preparePackageAndDir :: Config
-> Repository
-> GC.GlobalCache
-> String
-> String
-> Version
-> IO (ErrorLogger ComparisonInfo)
preparePackageAndDir cfg repo gc dirA nameB verB = GC.tryFindPackage gc nameB verB |>=
\pkgB -> findPackageDir cfg pkgB |>=
\dirB -> preparePackageDirs cfg repo gc dirA dirB
preparePackageDirs :: Config
-> Repository
-> GC.GlobalCache
-> String
-> String
-> IO (ErrorLogger ComparisonInfo)
preparePackageDirs cfg repo gc dirA dirB =
createBaseTemp |>= \baseTmp ->
loadPackageSpec dirA |>= \specA ->
loadPackageSpec dirB |>= \specB ->
let versionPrefixA = versionPrefix specA
versionPrefixB = versionPrefix specB
copyDirA = baseTmp </> ("src_" ++ versionPrefixA)
copyDirB = baseTmp </> ("src_" ++ versionPrefixB)
destDirA = baseTmp </> ("dest_" ++ versionPrefixA)
destDirB = baseTmp </> ("dest_" ++ versionPrefixB)
in
log Debug ("Copying " ++ packageId specA ++
" from " ++ dirA ++ " into " ++ copyDirA) |>
log Debug ("and transforming it into " ++ destDirA) |>
log Debug ("Copying " ++ packageId specB ++
" from " ++ dirB ++ " into " ++ copyDirB) |>
log Debug ("and transforming it into " ++ destDirB) |>
copyAndPrefixPackage cfg repo gc dirA versionPrefixA
copyDirA destDirA |>= \modMapA ->
copyAndPrefixPackage cfg repo gc dirB versionPrefixB
copyDirB destDirB |>= \modMapB ->
succeedIO $ ComparisonInfo
{ infPackageA = specA
, infPackageB = specB
, infDirA = destDirA
, infDirB = destDirB
, infSourceDirA = copyDirA
, infSourceDirB = copyDirB
, infPrefixA = versionPrefixA
, infPrefixB = versionPrefixB
, infModMapA = modMapA
, infModMapB = modMapB }
versionPrefix :: Package -> String
versionPrefix pkg = "V_" ++ (showVersion' $ version pkg)
copyAndPrefixPackage :: Config
-> Repository
-> GC.GlobalCache
-> String
-> String
-> String
-> String
-> IO (ErrorLogger [(String, String)])
copyAndPrefixPackage cfg repo gc pkgDir prefix srcDir destDir =
copyDirectory pkgDir srcDir >> createDirectory destDir >> succeedIO () |>
prefixPackageAndDeps cfg repo gc srcDir (prefix ++ "_") destDir
showVersion' :: Version -> String
showVersion' (maj, min, pat, Nothing) =
intercalate "_" [show maj, show min, show pat]
showVersion' (maj, min, pat, Just pre) =
intercalate "_" [show maj, show min, show pat, pre]
findPackageDir :: Config -> Package -> IO (ErrorLogger String)
findPackageDir cfg pkg = do
exists <- doesDirectoryExist srcDir
if not exists
then failIO $ "Package " ++ (packageId pkg) ++ " not installed"
else succeedIO srcDir
where
srcDir = GC.installedPackageDir cfg pkg
|