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
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
|
import Char ( toUpper )
import Directory ( createDirectoryIfMissing )
import Distribution ( curryCompiler, installDir )
import FilePath ( (</>), pathSeparator, takeDirectory )
import GetOpt
import List
import Maybe ( fromJust, isJust )
import System ( system, exitWith, getArgs, getPID, setEnviron )
import AbstractCurry.Types
import AbstractCurry.Files ( readCurryWithParseOptions, readUntypedCurry )
import AbstractCurry.Select
import AbstractCurry.Build
import qualified AbstractCurry.Pretty as ACPretty
import AbstractCurry.Transform ( renameCurryModule, trCTypeExpr, updCProg
, updQNamesInCProg, updQNamesInCFuncDecl )
import Analysis.Termination ( Productivity(..) )
import Contract.Names
import qualified FlatCurry.Types as FC
import FlatCurry.Files
import qualified FlatCurry.Goodies as FCG
import System.Console.ANSI.Codes
import System.CurryPath ( modNameToPath, lookupModuleSourceInLoadPath
, stripCurrySuffix )
import System.FrontendExec ( defaultParams, setQuiet )
import Text.CSV ( writeCSVFile )
import Text.Pretty ( pPrint )
import CC.AnalysisHelpers ( getTerminationInfos, getProductivityInfos
, getUnsafeModuleInfos, dropPublicSuffix )
import CC.Config ( packagePath, packageVersion )
import CC.Helpers ( ccLoadPath )
import CC.Options
import CheckDetUsage ( checkDetUse, containsDetOperations)
import Contract.Usage ( checkContractUsage )
import DefaultRuleUsage ( checkDefaultRules, containsDefaultRules )
import PropertyUsage
import SimplifyPostConds ( simplifyPostConditionsWithTheorems )
import TheoremUsage ( determinismTheoremFor, existsProofFor
, getModuleProofFiles, getTheoremFunctions )
import UsageCheck ( checkBlacklistUse, checkSetUse )
ccBanner :: String
ccBanner = unlines [bannerLine,bannerText,bannerLine]
where
bannerText = "CurryCheck: a tool for testing Curry programs (Version " ++
packageVersion ++ " of 28/08/2020)"
bannerLine = take (length bannerText) (repeat '-')
usageText :: String
usageText = usageInfo ("Usage: curry-check [options] <module names>\n") options
maxArity :: Int
maxArity = 5
defTypeSuffix :: String
defTypeSuffix = "_ON_BASETYPE"
postCondSuffix :: String
postCondSuffix = "SatisfiesPostCondition"
satSpecSuffix :: String
satSpecSuffix = "SatisfiesSpecification"
isDetSuffix :: String
isDetSuffix = "IsDeterministic"
data Test = PropTest QName CTypeExpr Int
| IOTest QName Int
| EquivTest QName QName QName CTypeExpr Int
isIOTest :: Test -> Bool
isIOTest t = case t of IOTest _ _ -> True
_ -> False
isUnitTest :: Test -> Bool
isUnitTest t = case t of PropTest _ texp _ -> null (argTypes texp)
_ -> False
isPropTest :: Test -> Bool
isPropTest t = case t of PropTest _ texp _ -> not (null (argTypes texp))
_ -> False
isEquivTest :: Test -> Bool
isEquivTest t = case t of EquivTest _ _ _ _ _ -> True
_ -> False
equivTestOps :: Test -> [QName]
equivTestOps t = case t of EquivTest _ f1 f2 _ _ -> [f1,f2]
_ -> []
testName :: Test -> QName
testName (PropTest n _ _) = n
testName (IOTest n _) = n
testName (EquivTest n _ _ _ _) = n
testLine :: Test -> Int
testLine (PropTest _ _ n) = n
testLine (IOTest _ n) = n
testLine (EquivTest _ _ _ _ n) = n
genTestMsg :: String -> Test -> String
genTestMsg file test =
snd (testName test) ++
" (module " ++ file ++ ", line " ++ show (testLine test) ++ ")"
genTestName :: Test -> String
genTestName test =
let (modName, fName) = testName test
in fName ++ "_" ++ modNameToId modName
data TestModule = TestModule
{ orgModuleName :: String
, testModuleName :: String
, staticErrors :: [String]
, propTests :: [Test]
, generators :: [QName]
, preConditions :: [QName]
}
staticErrorTestMod :: String -> [String] -> TestModule
staticErrorTestMod modname staterrs =
TestModule modname modname staterrs [] [] []
testThisModule :: TestModule -> Bool
testThisModule tm = null (staticErrors tm) && not (null (propTests tm))
userTestDataOfModule :: TestModule -> [(QName,Bool)]
userTestDataOfModule testmod = concatMap testDataOf (propTests testmod)
where
testDataOf (IOTest _ _) = []
testDataOf (PropTest _ texp _) =
map (\t -> (t,False)) (filter (\ (mn,_) -> mn /= preludeName)
(unionOn tconsOf (argTypes texp)))
testDataOf (EquivTest _ _ _ texp _) =
map (\t -> (t,True)) (unionOn tconsOf (argTypes texp))
equivPropTypes :: TestModule -> [QName]
equivPropTypes testmod = concatMap equivTypesOf (propTests testmod)
where
equivTypesOf (IOTest _ _) = []
equivTypesOf (PropTest _ _ _) = []
equivTypesOf (EquivTest _ _ _ texp _) = tconsOf (resultType texp)
genTestFuncs :: Options -> (QName -> Bool) -> (QName -> Productivity) -> String
-> TestModule -> IO [CFuncDecl]
genTestFuncs opts terminating productivity mainmod tm =
liftM (filter (not . null . funcRules))
(mapM genTestFunc (propTests tm))
where
genTestFunc test = case test of
PropTest name t _ -> testFuncWithRules (propBody name t test)
IOTest name _ -> testFuncWithRules (ioTestBody name test)
EquivTest name f1 f2 t _ ->
if "'TERMINATE" `isSuffixOf` map toUpper (snd name) ||
(isTerminating f1 && isTerminating f2)
then do putStrLnIfDebug opts $
"Generating equivalence test for TERMINATING " ++
"operations for test: " ++ snd name
testFuncWithRules $ equivBodyTerm f1 f2 t test
else
if "'PRODUCTIVE" `isSuffixOf` map toUpper (snd name) ||
optEquiv opts /= Safe ||
(isProductive f1 && isProductive f2)
then do putStrLnIfDebug opts $
"Generating equivalence test for PRODUCTIVE " ++
"operations for test: " ++ snd name
testFuncWithRules $ equivBodyAny f1 f2 t test
else testFuncWithRules []
where
testFuncWithRules rs =
return $ cfunc (mainmod, genTestName test) 0 Public
(emptyClassType (ioType (maybeType stringType))) rs
isTerminating f = terminating f || productivity f == Terminating
isProductive f = productivity f `notElem` [NoInfo, Looping]
msgOf test = string2ac $ genTestMsg (orgModuleName tm) test
testmname = testModuleName tm
easyCheckFuncName arity =
if arity>maxArity
then error $ "Properties with more than " ++ show maxArity ++
" parameters are currently not supported!"
else (easyCheckExecModule,"checkWithValues" ++ show arity)
equivBodyTerm f1 f2 texp test =
let xvars = map (\i -> (i,"x"++show i)) [1 .. arityOfType texp]
pxvars = map (\i -> (i,"px"++show i)) [1 .. arityOfType texp]
pvalOfFunc = ctype2typeop mainmod "pvalOf_" (resultType texp)
in propOrEquivBody
(map (\t -> ctype2BotType mainmod False t) (argTypes texp))
test
(cLambda (map CPVar pxvars)
(letExpr
(map (\ (x,px,te) -> CLocalPat (CPVar x)
(CSimpleRhs (applyE (ctype2typeop mainmod "from_P_" te)
[CVar px]) []))
(zip3 xvars pxvars (argTypes texp)))
(addPreCond (preConditions tm) [f1,f2] xvars
(applyF (easyCheckModule,"<~>")
[applyE pvalOfFunc [applyF f1 (map CVar xvars)],
applyE pvalOfFunc [applyF f2 (map CVar xvars)]]))))
equivBodyAny f1 f2 texp test =
let xvars = map (\i -> (i,"x"++show i)) [1 .. arityOfType texp]
pxvars = map (\i -> (i,"px"++show i)) [1 .. arityOfType texp]
pvar = (2,"p")
pvalOfFunc = ctype2typeop mainmod "peval_" (resultType texp)
in propOrEquivBody
(map (\t -> ctype2BotType mainmod False t) (argTypes texp) ++
[ctype2BotType mainmod True (resultType texp)])
test
(cLambda (map CPVar pxvars ++ [CPVar pvar])
(letExpr
(map (\ (x,px,te) -> CLocalPat (CPVar x)
(CSimpleRhs (applyE (ctype2typeop mainmod "from_P_" te)
[CVar px]) []))
(zip3 xvars pxvars (argTypes texp)))
(addPreCond (preConditions tm) [f1,f2] xvars
(applyF (easyCheckModule,"<~>")
[applyE pvalOfFunc [applyF f1 (map CVar xvars), CVar pvar],
applyE pvalOfFunc [applyF f2 (map CVar xvars), CVar pvar]]))))
propBody qname texp test =
propOrEquivBody (map (\t -> t) (argTypes texp))
test (CSymbol (testmname,snd qname))
propOrEquivBody argtypes test propexp =
[simpleRule [] $
CLetDecl [CLocalPat (CPVar msgvar) (CSimpleRhs (msgOf test) [])]
(applyF (easyCheckExecModule, "checkPropWithMsg")
[ CVar msgvar
, applyF (easyCheckFuncName (length argtypes)) $
[configOpWithMaxFail, CVar msgvar] ++
(map (\ t ->
applyF (easyCheckModule,"valuesOfSearchTree")
[if isPAKCS || useUserDefinedGen t || isFloatType t
then type2genop mainmod tm True t
else applyF (searchTreeModule,"someSearchTree")
[CTyped (constF (pre "unknown"))
(emptyClassType t)]])
argtypes) ++
[transFuncArgsInProp mainmod argtypes propexp]
])]
where
useUserDefinedGen texp = case texp of
CTVar _ -> error "No polymorphic generator!"
CFuncType _ _ -> True
CTApply _ _ -> maybe (error "No generator for type applications!")
(\ (qt,_) -> hasDefinedGen qt)
(tconsArgsOfType texp)
CTCons qt -> hasDefinedGen qt
where
hasDefinedGen (mn,tc) =
isJust (find (\qn -> "gen"++tc == snd qn) (generators tm)) ||
mn==mainmod && "_Constant" `isSuffixOf` tc
configOpWithMaxTest =
let n = optMaxTest opts
in if n==0 then stdConfigOp
else applyF (easyCheckExecModule,"setMaxTest")
[cInt n, stdConfigOp]
configOpWithMaxFail =
let n = optMaxFail opts
in if n==0 then configOpWithMaxTest
else applyF (easyCheckExecModule,"setMaxFail")
[cInt n, configOpWithMaxTest]
msgvar = (0,"msg")
stdConfigOp = constF (easyCheckConfig opts)
ioTestBody (_, name) test =
[simpleRule [] $ applyF (easyCheckExecModule,"checkPropIOWithMsg")
[stdConfigOp, msgOf test, CSymbol (testmname,name)]]
easyCheckConfig :: Options -> QName
easyCheckConfig opts =
(easyCheckExecModule,
if isQuiet opts then "quietConfig" else
if optVerb opts > 2 then "verboseConfig"
else "easyConfig")
type2genop :: String -> TestModule -> Bool -> CTypeExpr -> CExpr
type2genop _ _ _ (CTVar _) = error "No polymorphic generator!"
type2genop mainmod tm top (CFuncType ta tb) =
applyF (mainmod, if top then "genFunc" else "genFunction")
(map (type2genop mainmod tm False) [ta,tb])
type2genop mainmod tm _ (CTCons qt) =
constF (typename2genopname mainmod (generators tm) qt)
type2genop mainmod tm _ te@(CTApply _ _) =
maybe (error "No generator for type applications!")
(\ (qt,targs) ->
applyF (typename2genopname mainmod (generators tm) qt)
(map (type2genop mainmod tm False) targs))
(tconsArgsOfType te)
isFloatType :: CTypeExpr -> Bool
isFloatType texp = case texp of CTCons tc -> tc == (preludeName,"Float")
_ -> False
typename2genopname :: String -> [QName] -> QName -> QName
typename2genopname mainmod definedgenops (mn,tc)
| isJust maybeuserdefined
= fromJust maybeuserdefined
| mn==preludeName
= (generatorModule, "gen" ++ transQN tc)
| otherwise
= (mainmod, "gen_" ++ modNameToId mn ++ "_" ++ transQN tc)
where
maybeuserdefined = find (\qn -> "gen"++tc == snd qn) definedgenops
transQN :: String -> String
transQN tcons | tcons == "[]" = "List"
| tcons == ":" = "Cons"
| tcons == "()" = "Unit"
| tcons == "(,)" = "Pair"
| tcons == "(,,)" = "Triple"
| tcons == "(,,,)" = "Tuple4"
| tcons == "(,,,,)" = "Tuple5"
| otherwise = tcons
transFuncArgsInProp :: String -> [CTypeExpr] -> CExpr -> CExpr
transFuncArgsInProp mainmod argtypes propexp
| any isFunctionalType argtypes
= CLambda (map CPVar vars)
(let (nvars,locals) = unzip (map ftype2let (zip argtypes vars))
in letExpr (concat locals) (applyE propexp (map CVar nvars)))
| otherwise = propexp
where
vars = map (\i -> (i,"x"++show i)) [1 .. length argtypes]
ftype2let (texp,v@(j,xj)) =
if isFunctionalType texp
then let fx = (j + length argtypes, 'f':xj)
in (fx,
[CLocalPat (CPVar fx)
(CSimpleRhs (applyF (mainmod,"list2Func") [CVar v]) [])])
else (v,[])
makeAllPublic :: CurryProg -> CurryProg
makeAllPublic (CurryProg modname imports dfltdecl clsdecls instdecls
typedecls functions opdecls) =
CurryProg modname stimports dfltdecl clsdecls instdecls
typedecls publicFunctions opdecls
where
stimports = if generatorModule `elem` imports &&
searchTreeModule `notElem` imports
then searchTreeModule : imports
else imports
publicFunctions = map makePublic $ map ignoreComment functions
ignoreComment :: CFuncDecl -> CFuncDecl
(CmtFunc _ name arity visibility typeExpr rules) =
CFunc name arity visibility typeExpr rules
ignoreComment x@(CFunc _ _ _ _ _) = x
makePublic :: CFuncDecl -> CFuncDecl
makePublic (CFunc name arity _ typeExpr rules) =
CFunc name arity Public typeExpr rules
makePublic (CmtFunc cmt name arity _ typeExpr rules) =
CmtFunc cmt name arity Public typeExpr rules
classifyTest :: Options -> CurryProg -> CFuncDecl -> Test
classifyTest opts prog test =
if isPropIOType (typeOfQualType (funcType test))
then IOTest tname 0
else maybe (PropTest tname (typeOfQualType (funcType test)) 0)
expsToEquivTest
(isEquivProperty test)
where
tname = funcName test
expsToEquivTest exps = case exps of
(CSymbol f1,CSymbol f2) ->
EquivTest tname f1 f2 (defaultingType (funcTypeOf f1)) 0
(CTyped (CSymbol f1) qtexp, CSymbol f2) ->
EquivTest tname f1 f2 (defaultingType qtexp) 0
(CSymbol f1, CTyped (CSymbol f2) qtexp) ->
EquivTest tname f1 f2 (defaultingType qtexp) 0
(CTyped (CSymbol f1) qtexp, CTyped (CSymbol f2) _) ->
EquivTest tname f1 f2 (defaultingType qtexp) 0
(e1,e2) -> error $ "Illegal equivalence property '" ++
snd tname ++ "':\n" ++
showCExpr e1 ++ " <=> " ++ showCExpr e2
defaultingType = poly2defaultType opts . typeOfQualType . defaultQualType
funcTypeOf f = maybe (error $ "Cannot find type of " ++ show f ++ "!")
funcType
(find (\fd -> funcName fd == f) (functions prog))
transformTests :: Options -> [String] -> [CFuncDecl] -> CurryProg
-> IO ([CFuncDecl],[CFuncDecl],[QName],CurryProg)
transformTests opts prfnames theofuncs
prog@(CurryProg mname imps dfltdecl clsdecls instdecls
typeDecls functions opDecls) = do
simpfuncs <- simplifyPostConditionsWithTheorems (optVerb opts) theofuncs funcs
let preCondOps = preCondOperations simpfuncs
postCondOps = map ((\ (mn,fn) -> (mn, fromPostCondName fn)) . funcName)
(funDeclsWith isPostCondName simpfuncs)
specOps = map ((\ (mn,fn) -> (mn, fromSpecName fn)) . funcName)
(funDeclsWith isSpecName simpfuncs)
postCondTests =
concatMap (genPostCondTest preCondOps postCondOps prfnames) funcs
specOpTests = concatMap (genSpecTest opts preCondOps specOps prfnames) funcs
grSpecOpTests = if optEquiv opts == Ground then specOpTests else []
(realtests,ignoredtests) = partition fst $
if not (optProp opts)
then []
else concatMap (poly2default opts) $
filter (\fd -> not (existsProofFor (orgQName (funcName fd))
prfnames))
usertests ++
(if optSpec opts then grSpecOpTests ++ postCondTests else [])
return (map snd realtests ++
(if optSpec opts && optEquiv opts /= Ground then specOpTests else []),
map snd ignoredtests,
preCondOps,
CurryProg mname
(nub (easyCheckModule:imps))
dfltdecl clsdecls instdecls
typeDecls
(simpfuncs ++ map snd (realtests ++ ignoredtests))
opDecls)
where
(rawusertests, funcs) = partition isProperty functions
usertests = if optEquiv opts == Ground
then map equivProp2Ground rawusertests
else rawusertests
equivProp2Ground fdecl =
maybe fdecl
(\ _ -> case classifyTest opts prog fdecl of
EquivTest _ f1 f2 texp _ ->
let ar = arityOfType texp
cvars = map (\i -> (i,"x"++show i)) [1 .. ar]
in stFunc (funcName fdecl) ar Public (propResultType texp)
[simpleRule (map CPVar cvars)
(applyF (easyCheckModule,"<~>")
[applyF f1 (map CVar cvars),
applyF f2 (map CVar cvars)])]
_ -> error "transformTests: internal error"
)
(isEquivProperty fdecl)
transformDetTests :: Options -> [String] -> CurryProg
-> ([CFuncDecl],[CFuncDecl],CurryProg)
transformDetTests opts prooffiles
(CurryProg mname imports dfltdecl clsdecls instdecls
typeDecls functions opDecls) =
(map snd realtests, map snd ignoredtests,
CurryProg mname
(nub (easyCheckModule:imports))
dfltdecl clsdecls instdecls
typeDecls
(map (revertDetOpTrans detOpNames) functions ++
map snd (realtests ++ ignoredtests))
opDecls)
where
preCondOps = preCondOperations functions
detOpTests = genDetOpTests prooffiles preCondOps functions
detOpNames = map (stripIsDet . funcName) detOpTests
stripIsDet (mn,fn) = (mn, take (length fn -15) fn)
(realtests,ignoredtests) = partition fst $
if not (optProp opts)
then []
else concatMap (poly2default opts)
(if optDet opts then detOpTests else [])
preCondOperations :: [CFuncDecl] -> [QName]
preCondOperations fdecls =
map ((\ (mn,fn) -> (mn,fromPreCondName fn)) . funcName)
(funDeclsWith isPreCondName fdecls)
funDeclsWith :: (String -> Bool) -> [CFuncDecl] -> [CFuncDecl]
funDeclsWith pred = filter (pred . snd . funcName)
propResultType :: CTypeExpr -> CTypeExpr
propResultType te = case te of
CFuncType from to -> CFuncType from (propResultType to)
_ -> baseType (propTypesModule,"Prop")
genPostCondTest :: [QName] -> [QName] -> [String] -> CFuncDecl -> [CFuncDecl]
genPostCondTest prefuns postops prooffnames (CmtFunc _ qf ar vis texp rules) =
genPostCondTest prefuns postops prooffnames (CFunc qf ar vis texp rules)
genPostCondTest prefuns postops prooffnames
(CFunc qf@(mn,fn) _ _ (CQualType clscon texp) _) =
if qf `notElem` postops || existsProofFor (orgQName postname) prooffnames
then []
else
[CFunc postname ar Public
(CQualType clscon (propResultType texp))
[simpleRule (map CPVar cvars) $
addPreCond prefuns [qf] cvars postprop ]]
where
postname = (mn, fn ++ postCondSuffix)
ar = arityOfType texp
cvars = map (\i -> (i,"x"++show i)) [1 .. ar]
rcall = applyF qf (map CVar cvars)
postprop = applyF (easyCheckModule,"always")
[applyF (mn,toPostCondName fn)
(map CVar cvars ++ [rcall])]
genSpecTest :: Options -> [QName] -> [QName] -> [String] -> CFuncDecl
-> [CFuncDecl]
genSpecTest opts prefuns specops prooffnames (CmtFunc _ qf ar vis texp rules) =
genSpecTest opts prefuns specops prooffnames (CFunc qf ar vis texp rules)
genSpecTest opts prefuns specops prooffnames
(CFunc qf@(mn,fn) _ _ (CQualType clscon texp) _)
| qf `notElem` specops || existsProofFor (orgQName sptname) prooffnames
= []
| optEquiv opts == Ground
= [genSpecGroundEquivTest prefuns qf clscon texp]
| otherwise
= [CFunc sptname 0 Public
(emptyClassType (propResultType unitType))
[simpleRule [] (applyF (easyCheckModule,"<=>")
[constF qf, constF (mn,toSpecName fn)])]]
where
sptname = (mn, fn ++ satSpecSuffix)
genSpecGroundEquivTest :: [QName] -> QName -> CContext -> CTypeExpr -> CFuncDecl
genSpecGroundEquivTest prefuns qf@(mn,fn) clscon texp =
CFunc (mn, fn ++ satSpecSuffix) ar Public
(CQualType (addShowContext clscon) (propResultType texp))
[simpleRule (map CPVar cvars) $
addPreCond prefuns [qf,qfspec] cvars
(applyF (easyCheckModule,"<~>")
[applyF qf (map CVar cvars),
applyF (mn,toSpecName fn) (map CVar cvars)])]
where
ar = arityOfType texp
cvars = map (\i -> (i,"x"++show i)) [1 .. ar]
qfspec = (mn, toSpecName fn)
addPreCond :: [QName] -> [QName] -> [CVarIName] -> CExpr -> CExpr
addPreCond prefuns fs pvars propexp =
let preconds = concatMap precondCall fs
in if null preconds
then propexp
else applyF (easyCheckModule,"==>")
[foldr1 (\x y -> applyF (pre "&&") [x,y]) preconds, propexp]
where
precondCall qn@(mn,fn) =
if qn `elem` prefuns
then [applyF (mn, toPreCondName fn) (map CVar pvars)]
else []
revertDetOpTrans :: [QName] -> CFuncDecl -> CFuncDecl
revertDetOpTrans detops (CmtFunc _ qf ar vis texp rules) =
revertDetOpTrans detops (CFunc qf ar vis texp rules)
revertDetOpTrans detops fdecl@(CFunc qf@(mn,fn) ar vis texp _) =
if qf `elem` detops
then CFunc qf ar vis texp [simpleRule [] (constF (mn,fn++"_ORGNDFUN"))]
else fdecl
genDetOpTests :: [String] -> [QName] -> [CFuncDecl] -> [CFuncDecl]
genDetOpTests prooffiles prefuns fdecls =
map (genDetProp prefuns) (filter (isDetOrgOp . funcName) fdecls)
where
isDetOrgOp (mn,fn) =
"_ORGNDFUN" `isSuffixOf` fn &&
not (existsProofFor (mnorg, determinismTheoremFor (take (length fn - 9) fn))
prooffiles)
where mnorg = take (length mn - 10) mn
genDetProp :: [QName] -> CFuncDecl -> CFuncDecl
genDetProp prefuns (CmtFunc _ qf ar vis texp rules) =
genDetProp prefuns (CFunc qf ar vis texp rules)
genDetProp prefuns (CFunc (mn,fn) ar _ (CQualType clscon texp) _) =
CFunc (mn, forg ++ isDetSuffix) ar Public
(CQualType (foldr addEqShowContext (addShowContext clscon) rtypevars)
(propResultType texp))
[simpleRule (map CPVar cvars) $
addPreCond prefuns [(mn,forg)] cvars rnumcall ]
where
rtypevars = tvarsOfType (resultType texp)
forg = take (length fn - 9) fn
cvars = map (\i -> (i,"x"++show i)) [1 .. ar]
forgcall = applyF (mn,forg) (map CVar cvars)
rnumcall = applyF (easyCheckModule,"#<") [forgcall, cInt 2]
poly2default :: Options -> CFuncDecl -> [(Bool,CFuncDecl)]
poly2default opts (CmtFunc _ name arity vis ftype rules) =
poly2default opts (CFunc name arity vis ftype rules)
poly2default opts fdecl@(CFunc (mn,fname) arity vis qftype rs)
| isPolyType ftype
= [(False,fdecl)
,(True, CFunc (mn,fname++defTypeSuffix) arity vis
(emptyClassType (poly2defaultType opts ftype))
[simpleRule [] (applyF (mn,fname) [])])
]
| otherwise
= [(True, CFunc (mn,fname) arity vis (CQualType clscon ftype) rs)]
where
CQualType clscon ftype = defaultQualType qftype
poly2defaultType :: Options -> CTypeExpr -> CTypeExpr
poly2defaultType opts texp = p2dt texp
where
p2dt (CTVar _) = baseType (pre (optDefType opts))
p2dt (CFuncType t1 t2) = CFuncType (p2dt t1) (p2dt t2)
p2dt (CTApply t1 t2) = CTApply (p2dt t1) (p2dt t2)
p2dt (CTCons ct) = CTCons ct
defaultQualType :: CQualTypeExpr -> CQualTypeExpr
defaultQualType (CQualType (CContext allclscon) ftype) =
CQualType (CContext deffractxt) deffratype
where
(numcons,nonnumcons) =
partition (\ (cls,te) -> (cls == pre "Num" || cls == pre "Integral")
&& isTVar te)
allclscon
defnumtype = def2TConsInType numcons (pre "Int") ftype
defnumctxt = removeNonTVarClassContexts
(map (\ (cls,con) ->
(cls, def2TConsInType numcons (pre "Int") con))
nonnumcons)
(fracons,nonfracons) =
partition (\ (cls,te) -> cls == pre "Fractional" && isTVar te) defnumctxt
deffratype = def2TConsInType fracons (pre "Float") defnumtype
deffractxt = removeNonTVarClassContexts
(map (\ (cls,con) ->
(cls, def2TConsInType fracons (pre "Float") con))
nonfracons)
removeNonTVarClassContexts = filter (\ (_,te) -> isTVar te)
def2TConsInType clscons tcons texp =
foldr (tvar2TCons tcons) texp (map snd clscons)
tvar2TCons tcons texp = case texp of
CTVar tv -> substTVar tv (CTCons tcons)
_ -> id
substTVar tvariname texp =
trCTypeExpr (\tv -> if tv==tvariname then texp else CTVar tv)
CTCons CFuncType CTApply
isTVar te = case te of CTVar _ -> True
_ -> False
addShowContext :: CContext -> CContext
addShowContext (CContext clscons) =
CContext (nub (clscons ++ (map (\t -> (pre "Show",t)) (map snd clscons))))
addEqShowContext :: CTVarIName -> CContext -> CContext
addEqShowContext tvar (CContext clscons) =
CContext (nub (clscons ++ map (\c -> (pre c, CTVar tvar)) ["Eq","Show"]))
orgTestName :: QName -> QName
orgTestName (mn,tname)
| defTypeSuffix `isSuffixOf` tname
= orgTestName (mn, stripSuffix tname defTypeSuffix)
| isDetSuffix `isSuffixOf` tname
= orgTestName (mn, take (length tname - 15) tname)
| postCondSuffix `isSuffixOf` tname
= orgTestName (mn, stripSuffix tname postCondSuffix)
| satSpecSuffix `isSuffixOf` tname
= orgTestName (mn, stripSuffix tname satSpecSuffix)
| otherwise = (mn,tname)
orgQName :: QName -> QName
orgQName (mn,fn)
| publicSuffix `isSuffixOf` mn
= (stripSuffix mn publicSuffix, fn)
| publicdetSuffix `isSuffixOf` mn
= (stripSuffix mn publicdetSuffix, fn)
| otherwise = (mn,fn)
where
publicSuffix = "_PUBLIC"
publicdetSuffix = "_PUBLICDET"
analyseModule :: Options -> String -> IO [TestModule]
analyseModule opts modname = do
putStrIfNormal opts $ withColor opts blue $
"Analyzing module '" ++ modname ++ "'...\n"
catch (readCurryWithParseOptions modname (setQuiet True defaultParams) >>=
analyseCurryProg opts modname)
(\_ -> return [staticErrorTestMod modname
["Module '"++modname++"': incorrect source program"]])
staticProgAnalysis :: Options -> String -> String -> CurryProg
-> IO ([String],[(QName,String)])
staticProgAnalysis opts modname progtxt prog = do
putStrIfDetails opts "Checking source code for static errors...\n"
fcyprog <- readFlatCurry modname
useerrs <- if optSource opts then checkBlacklistUse prog else return []
seterrs <- if optSource opts then checkSetUse fcyprog
else return []
let defruleerrs = if optSource opts then checkDefaultRules prog else []
untypedprog <- readUntypedCurry modname
let detuseerrs = if optSource opts then checkDetUse untypedprog else []
contracterrs = checkContractUsage modname
(map (\fd -> (snd (FCG.funcName fd), FCG.funcType fd))
(FCG.progFuncs fcyprog))
staticerrs = concat [seterrs,useerrs,defruleerrs,detuseerrs,contracterrs]
missingCPP =
if (containsDefaultRules prog || containsDetOperations untypedprog)
&& not (containsPPOptionLine progtxt)
then ["'" ++ modname ++
"' uses default rules or det. operations but not the preprocessor!",
"Hint: insert line: {-# OPTIONS_CYMAKE -F --pgmF=currypp #-}"]
else []
return (missingCPP,staticerrs)
analyseCurryProg :: Options -> String -> CurryProg -> IO [TestModule]
analyseCurryProg opts modname orgprog = do
let prog = renameProp2EasyCheck orgprog
(topdir,srcfilename) <- lookupModuleSourceInLoadPath modname >>=
return .
maybe (error $ "Source file of module '"++modname++"' not found!") id
let srcdir = takeDirectory srcfilename
putStrLnIfDebug opts $ "Source file: " ++ srcfilename
prooffiles <- if optProof opts
then getModuleProofFiles srcdir modname
else return []
unless (null prooffiles) $ putStrIfDetails opts $
unlines ("Proof files found:" : map ("- " ++) prooffiles)
progtxt <- readFile srcfilename
(missingCPP,staticoperrs) <- staticProgAnalysis opts modname progtxt prog
let words = map firstWord (lines progtxt)
staticerrs = missingCPP ++ map (showOpError words) staticoperrs
putStrIfDetails opts "Generating property tests...\n"
theofuncs <- if optProof opts then getTheoremFunctions srcdir prog
else return []
let pubmodname = modname++"_PUBLIC"
rnm2pub mn@(mod,n) | mod == modname = (pubmodname,n)
| otherwise = mn
theopubfuncs = map (updQNamesInCFuncDecl rnm2pub) theofuncs
(rawTests,ignoredTests,preCondOps,pubmod) <-
transformTests opts prooffiles theopubfuncs
. renameCurryModule pubmodname . makeAllPublic $ prog
let (rawDetTests,ignoredDetTests,pubdetmod) =
transformDetTests opts prooffiles
. renameCurryModule (modname++"_PUBLICDET")
. makeAllPublic $ prog
unless (not (null staticerrs) || null rawTests && null rawDetTests) $
putStrIfNormal opts $
"Properties to be tested:\n" ++
unwords (map (snd . funcName) (rawTests++rawDetTests)) ++ "\n"
unless (not (null staticerrs) || null ignoredTests && null ignoredDetTests) $
putStrIfNormal opts $
"Properties ignored for testing:\n" ++
unwords (map (snd . funcName) (ignoredTests++ignoredDetTests)) ++ "\n"
let tm = TestModule modname
(progName pubmod)
staticerrs
(addLinesNumbers words
(map (classifyTest opts pubmod) rawTests))
(generatorsOfProg pubmod)
preCondOps
dettm = TestModule modname
(progName pubdetmod)
[]
(addLinesNumbers words
(map (classifyTest opts pubdetmod) rawDetTests))
(generatorsOfProg pubmod)
[]
when (testThisModule tm) $ writeCurryProgram opts topdir pubmod ""
when (testThisModule dettm) $ writeCurryProgram opts topdir pubdetmod ""
return (if testThisModule dettm then [tm,dettm] else [tm])
where
showOpError words (qf,err) =
snd qf ++ " (module " ++ modname ++ ", line " ++
show (getLineNumber words qf) ++"): " ++ err
addLinesNumbers words = map (addLineNumber words)
addLineNumber :: [String] -> Test -> Test
addLineNumber words (PropTest name texp _) =
PropTest name texp $ getLineNumber words (orgTestName name)
addLineNumber words (IOTest name _) =
IOTest name $ getLineNumber words (orgTestName name)
addLineNumber words (EquivTest name f1 f2 texp _) =
EquivTest name f1 f2 texp $ getLineNumber words (orgTestName name)
getLineNumber :: [String] -> QName -> Int
getLineNumber words (_, name) = maybe 0 (+1) (elemIndex name words)
generatorsOfProg :: CurryProg -> [QName]
generatorsOfProg = map funcName . filter isGen . functions
where
isGen fdecl = "gen" `isPrefixOf` snd (funcName fdecl) &&
isSearchTreeType (resultType (typeOfQualType (funcType fdecl)))
isSearchTreeType (CTVar _) = False
isSearchTreeType (CFuncType _ _) = False
isSearchTreeType (CTCons _) = False
isSearchTreeType te@(CTApply _ _) =
maybe False ((==searchTreeTC) . fst) (tconsArgsOfType te)
genBottomType :: String -> FC.TypeDecl -> CTypeDecl
genBottomType _ (FC.TypeSyn _ _ _ _) =
error "genBottomType: cannot translate type synonyms"
genBottomType mainmod (FC.Type qtc@(_,tc) _ tvars consdecls) =
CType (mainmod,t2bt tc) Public (map transTVar tvars)
(simpleCCons (mainmod,"Bot_"++transQN tc) Public [] :
if isPrimExtType qtc
then [simpleCCons (mainmod,"Value_"++tc) Public [baseType qtc]]
else map transConsDecl consdecls)
[pre "Eq"]
where
transConsDecl (FC.Cons (_,cons) _ _ argtypes) =
simpleCCons (mainmod,t2bt cons) Public (map transTypeExpr argtypes)
transTypeExpr (FC.TVar i) = CTVar (transTVar i)
transTypeExpr (FC.FuncType t1 t2) =
CFuncType (transTypeExpr t1) (transTypeExpr t2)
transTypeExpr (FC.TCons (_,tcons) tes) =
applyTC (mainmod,t2bt tcons) (map transTypeExpr tes)
transTypeExpr (FC.ForallType _ _) =
error "genBottomType: cannot handle forall types"
transTVar i = (i,'a':show i)
isPrimExtType :: QName -> Bool
isPrimExtType (mn,tc) = mn == preludeName && tc `elem` ["Int","Float","Char"]
defaultValueOfBasicExtType :: String -> CLiteral
defaultValueOfBasicExtType tn
| tn == "Int" = CIntc 0
| tn == "Float" = CFloatc 0.0
| tn == "Char" = CCharc 'A'
| otherwise = error $ "defaultValueOfBasicExtType: unknown type: "++tn
ctype2BotType :: String -> Bool -> CTypeExpr -> CTypeExpr
ctype2BotType _ _ (CTVar i) = CTVar i
ctype2BotType mainmod con (CFuncType t1 t2) =
CFuncType (ctype2BotType mainmod con t1) (ctype2BotType mainmod con t2)
ctype2BotType mainmod con (CTApply t1 t2) =
CTApply (ctype2BotType mainmod con t1) (ctype2BotType mainmod con t2)
ctype2BotType mainmod con (CTCons qtc) =
CTCons (mainmod, t2bt (snd qtc) ++
if con && isPrimExtType qtc then "_Constant" else "")
t2bt :: String -> String
t2bt s = "P_" ++ transQN s
genPeval :: String -> FC.TypeDecl -> CFuncDecl
genPeval _ (FC.TypeSyn _ _ _ _) =
error "genPeval: cannot translate type synonyms"
genPeval mainmod (FC.Type qtc@(_,tc) _ tvars consdecls) =
cmtfunc ("Evaluate a `"++tc++"` value up to a partial approxmiation.")
(mainmod,"peval_"++transQN tc) 1 Public
(emptyClassType
(foldr1 (~>) (map (\ (a,b) -> CTVar a ~> CTVar b ~> CTVar b)
(zip polyavars polyrvars) ++
[applyTC qtc (map CTVar polyavars),
applyTC (mainmod,t2bt tc) (map CTVar polyrvars),
applyTC (mainmod,t2bt tc) (map CTVar polyrvars)])))
(simpleRule (map CPVar (polyavars ++ [(0,"_")]) ++ [CPComb botSym []])
(constF botSym) :
if isPrimExtType qtc
then [valueRule]
else map genConsRule consdecls)
where
botSym = (mainmod,"Bot_"++transQN tc)
polyavars = [ (i,"a"++show i) | i <- tvars]
polyrvars = [ (i,"b"++show i) | i <- tvars]
genConsRule (FC.Cons qc@(_,cons) _ _ argtypes) =
let args = [(i,"x"++show i) | i <- [0 .. length argtypes - 1]]
pargs = [(i,"y"++show i) | i <- [0 .. length argtypes - 1]]
pcons = (mainmod,t2bt cons)
in simpleRule (map CPVar polyavars ++
[CPComb qc (map CPVar args), CPComb pcons (map CPVar pargs)])
(applyF pcons
(map (\ (e1,e2,te) ->
applyE (ftype2pvalOf mainmod "peval" polyavars te)
[e1,e2])
(zip3 (map CVar args) (map CVar pargs) argtypes)))
valueRule =
let xvar = (0,"x")
yvar = (1,"y")
valcons = (mainmod,"Value_"++tc)
in guardedRule [CPVar xvar, CPComb valcons [CPVar yvar]]
[(constF (pre "True"),
applyF valcons [CVar xvar])]
[]
genPValOf :: String -> FC.TypeDecl -> CFuncDecl
genPValOf _ (FC.TypeSyn _ _ _ _) =
error "genPValOf: cannot translate type synonyms"
genPValOf mainmod (FC.Type qtc@(_,tc) _ tvars consdecls) =
cmtfunc ("Map a `"++tc++"` value into all its partial approximations.")
(mainmod,"pvalOf_"++transQN tc) 1 Public
(emptyClassType
(foldr1 (~>) (map (\ (a,b) -> CTVar a ~> CTVar b)
(zip polyavars polyrvars) ++
[applyTC qtc (map CTVar polyavars),
applyTC (mainmod,t2bt tc) (map CTVar polyrvars)])))
(simpleRule (map CPVar (polyavars ++ [(0,"_")]))
(constF (mainmod,"Bot_"++transQN tc)) :
if isPrimExtType qtc
then [valueRule]
else map genConsRule consdecls)
where
polyavars = [ (i,"a"++show i) | i <- tvars]
polyrvars = [ (i,"b"++show i) | i <- tvars]
genConsRule (FC.Cons qc@(_,cons) _ _ argtypes) =
let args = [(i,"x"++show i) | i <- [0 .. length argtypes - 1]]
in simpleRule (map CPVar polyavars ++ [CPComb qc (map CPVar args)])
(applyF (mainmod,t2bt cons)
(map (\ (e,te) ->
applyE (ftype2pvalOf mainmod "pvalOf" polyavars te) [e])
(zip (map CVar args) argtypes)))
valueRule =
let var = (0,"x")
in simpleRule [CPVar var] (applyF (mainmod,"Value_"++tc) [CVar var])
ftype2pvalOf :: String -> String -> [(Int,String)] -> FC.TypeExpr -> CExpr
ftype2pvalOf mainmod pvalname polyvars (FC.TCons (_,tc) texps) =
applyF (mainmod,pvalname++"_"++transQN tc)
(map (ftype2pvalOf mainmod pvalname polyvars) texps)
ftype2pvalOf _ _ _ (FC.FuncType _ _) =
error "genPValOf: cannot handle functional types in as constructor args"
ftype2pvalOf _ _ polyvars (FC.TVar i) =
maybe (error "genPValOf: unbound type variable")
CVar
(find ((==i) . fst) polyvars)
ftype2pvalOf _ _ _ (FC.ForallType _ _) =
error "genPValOf: forall type occurred"
ctype2typeop :: String -> String -> CTypeExpr -> CExpr
ctype2typeop mainmod opname (CTCons (_,tc)) =
constF (mainmod,opname++transQN tc)
ctype2typeop mainmod opname te@(CTApply _ _) =
maybe (error "genPValOf: cannot handle type applications")
(\ ((_,tc),targs) -> applyF (mainmod,opname++transQN tc)
(map (ctype2typeop mainmod opname) targs))
(tconsArgsOfType te)
ctype2typeop _ _ (CFuncType _ _) =
error "genPValOf: cannot handle functional types in as constructor args"
ctype2typeop _ _ (CTVar _) = error "genPValOf: unbound type variable"
genShowP :: String -> FC.TypeDecl -> CInstanceDecl
genShowP _ (FC.TypeSyn _ _ _ _) =
error "genShowP: cannot translate type synonyms"
genShowP mainmod (FC.Type qtc@(_,tc) _ tvars consdecls) =
CInstance (pre "Show")
(CContext (map (\tv -> (pre "Show", CTVar tv)) polyavars))
(applyTC (mainmod,t2bt tc) (map CTVar polyavars))
[cfunc
(pre "show") 1 Public
(emptyClassType
(applyTC (mainmod,t2bt tc) (map CTVar polyavars) ~> stringType))
(simpleRule [CPComb (mainmod, "Bot_" ++ transQN tc) []]
(constF (mainmod, "bottomValue")) :
if isPrimExtType qtc
then [valueRule]
else map genConsRule consdecls)]
where
polyavars = [ (i,"a"++show i) | i <- tvars]
genConsRule (FC.Cons (_,cons) _ _ argtypes) =
let args = [(i,"x"++show i) | i <- [0 .. length argtypes - 1]]
showargs = map (\v -> applyF (pre "show") [CVar v]) args
in simpleRule [CPComb (mainmod,t2bt cons) (map CPVar args)]
(if null showargs
then string2ac cons
else applyF (mainmod,"constrValue")
[list2ac (string2ac cons : showargs)])
valueRule =
let var = (0,"x")
in simpleRule [CPComb (mainmod,"Value_"++tc) [CPVar var]]
(applyF (pre "show") [CVar var])
genFromP :: String -> FC.TypeDecl -> CFuncDecl
genFromP _ (FC.TypeSyn _ _ _ _) =
error "genFromP: cannot translate type synonyms"
genFromP mainmod (FC.Type qtc@(_,tc) _ tvars consdecls) =
cmtfunc ("Map a partial `"++tc++"` value into its real value (or fail).")
(mainmod,"from_P_"++transQN tc) 1 Public
(emptyClassType
(foldr1 (~>) (map (\ (a,b) -> CTVar a ~> CTVar b)
(zip polyavars polyrvars) ++
[applyTC (mainmod,t2bt tc) (map CTVar polyavars),
applyTC qtc (map CTVar polyrvars)])))
(simpleRule (map CPVar polyavars ++
[CPComb (mainmod,"Bot_"++transQN tc) []])
(constF (pre "failed")) :
if isPrimExtType qtc
then [valueRule]
else map genConsRule consdecls)
where
polyavars = [ (i,"a"++show i) | i <- tvars]
polyrvars = [ (i,"b"++show i) | i <- tvars]
genConsRule (FC.Cons qc@(_,cons) _ _ argtypes) =
let args = [(i,"x"++show i) | i <- [0 .. length argtypes - 1]]
in simpleRule (map CPVar polyavars ++
[CPComb (mainmod,t2bt cons) (map CPVar args)])
(applyF qc
(map (\ (e,te) ->
applyE (ftype2fromP mainmod "from_P_" polyavars te) [e])
(zip (map CVar args) argtypes)))
valueRule =
let var = (0,"x")
in simpleRule [CPComb (mainmod,"Value_"++tc) [CPVar var]] (CVar var)
ftype2fromP :: String -> String -> [(Int,String)] -> FC.TypeExpr -> CExpr
ftype2fromP mainmod pvalname polyvars (FC.TCons (_,tc) texps) =
applyF (mainmod,pvalname++transQN tc)
(map (ftype2fromP mainmod pvalname polyvars) texps)
ftype2fromP _ _ _ (FC.FuncType _ _) =
error "genFromP: cannot handle functional types in as constructor args"
ftype2fromP _ _ polyvars (FC.TVar i) =
maybe (error "genFromP: unbound type variable")
CVar
(find ((==i) . fst) polyvars)
ftype2fromP _ _ _ (FC.ForallType _ _) =
error "genFromP: forall type occurred"
ctypedecl2ftypedecl :: CTypeDecl -> FC.TypeDecl
ctypedecl2ftypedecl (CTypeSyn _ _ _ _) =
error "ctypedecl2ftypedecl: cannot translate type synonyms"
ctypedecl2ftypedecl (CNewType _ _ _ _ _) =
error "ctypedecl2ftypedecl: cannot translate newtype"
ctypedecl2ftypedecl (CType qtc _ tvars consdecls _) =
FC.Type qtc FC.Public (map fst tvars) (map transConsDecl consdecls)
where
transConsDecl (CCons _ _ qc _ argtypes) =
FC.Cons qc (length argtypes) FC.Public (map transTypeExpr argtypes)
transConsDecl (CRecord _ _ _ _ _) =
error "ctypedecl2ftypedecl: cannot translate records"
transTypeExpr (CTVar (i,_)) = FC.TVar i
transTypeExpr (CFuncType t1 t2) =
FC.FuncType (transTypeExpr t1) (transTypeExpr t2)
transTypeExpr (CTCons qtcons) = FC.TCons qtcons []
transTypeExpr te@(CTApply _ _) =
maybe (error "ctypedecl2ftypedecl: cannot translate type applications")
(\ (qtcons,tes) -> FC.TCons qtcons (map transTypeExpr tes))
(tconsArgsOfType te)
genMainTestModule :: Options -> String -> [TestModule] -> IO [Test]
genMainTestModule opts mainmod orgtestmods = do
let alltests = concatMap propTests orgtestmods
equivtestops = nub (concatMap equivTestOps alltests)
terminfos <- if optEquiv opts == Autoselect
then getTerminationInfos opts (nub (map fst equivtestops))
else return (const False)
prodinfos <- if optEquiv opts == Safe
then getProductivityInfos opts (nub (map fst equivtestops))
else return (const NoInfo)
unsafeinfos <- if optIOTest opts
then return (const [])
else getUnsafeModuleInfos opts
(nub (map (fst . testName) alltests))
let (testmods,rmtestnames) = removeNonExecTests opts unsafeinfos orgtestmods
testtypes = nub (concatMap userTestDataOfModule testmods)
unless (null rmtestnames) $ do
putStrIfNormal opts $ unlines
[withColor opts red $ "Properties not tested (due to I/O or unsafe):",
unwords (map snd rmtestnames)]
(fcprogs,testtypedecls) <- collectAllTestTypeDecls opts [] [] testtypes
let equvatypes = map fst (filter snd testtypedecls)
equvrtypes <- collectAllTestTypeDecls opts fcprogs []
(map (\t->(t,True))
(nub (concatMap equivPropTypes testmods)))
>>= return . map fst . snd
let bottypes = map (genBottomType mainmod) (union equvatypes equvrtypes)
showinsts = map (genShowP mainmod) (union equvatypes equvrtypes)
frompfuns = map (genFromP mainmod) equvatypes
pevalfuns = map (genPeval mainmod) equvrtypes
pvalfuns = map (genPValOf mainmod) equvrtypes
generators = map (genTestDataGenerator mainmod)
(map fst (filter (not . snd) testtypedecls) ++
map ctypedecl2ftypedecl bottypes) ++
map (genPartialPrimDataGenerator mainmod)
(map FCG.typeName
(filter (isPrimExtType . FCG.typeName) equvrtypes))
testfuncs <- liftM concat
(mapM (genTestFuncs opts terminfos prodinfos mainmod) testmods)
let mainFunction = genMainFunction opts mainmod testfuncs
imports = nub $ [ easyCheckModule, easyCheckExecModule
, searchTreeModule, generatorModule
, "List", "Char", "Maybe", "System", "Debug.Profile"
, "System.Console.ANSI.Codes" ] ++
map (fst . fst) testtypes ++
map testModuleName testmods
appendix <- readFile (packagePath </> "include" </> "TestAppendix.curry")
writeCurryProgram opts "."
(CurryProg mainmod imports Nothing [] showinsts bottypes
(mainFunction : testfuncs ++ generators ++
frompfuns ++ pvalfuns ++ pevalfuns)
[])
appendix
let (finaltests,droppedtests) =
partition ((`elem` map (snd . funcName) testfuncs) . genTestName)
(concatMap propTests testmods)
unless (null droppedtests) $ putStrIfNormal opts $
"\nPOSSIBLY NON-TERMINATING TESTS REMOVED: " ++
unwords (map (snd . testName) droppedtests) ++ "\n"
return finaltests
genMainFunction :: Options -> String -> [CFuncDecl] -> CFuncDecl
genMainFunction opts testModule testfuncs =
CFunc (testModule, "main") 0 Public (emptyClassType (ioType unitType))
[simpleRule [] body]
where
body = CDoExpr $
(if isQuiet opts
then []
else [CSExpr (applyF (pre "putStrLn")
[string2ac "Executing all tests..."])]) ++
[ CSPat (cpvar "x1") $
applyF (testModule, "runPropertyTests")
[constF (pre (if optColor opts then "True" else "False")),
constF (pre (if optTime opts then "True" else "False")),
list2ac $ map (constF . funcName) testfuncs]
, CSExpr $ applyF (pre "when")
[applyF (pre "/=") [cvar "x1", cInt 0],
applyF ("System", "exitWith") [cvar "x1"]]
]
removeNonExecTests :: Options -> (QName -> [String]) -> [TestModule]
-> ([TestModule], [QName])
removeNonExecTests opts unsafeinfos testmods =
(map removeTests testmods,
concatMap (map testName . filter (not . isExecTest) . propTests) testmods)
where
removeTests tm = tm { propTests = filter isExecTest (propTests tm) }
isExecTest test = optIOTest opts ||
(not (isIOTest test) && null (unsafeinfos (tmod,tmod)))
where tmod = dropPublicSuffix (fst (testName test))
collectAllTestTypeDecls :: Options -> [FC.Prog] -> [(FC.TypeDecl,Bool)]
-> [(QName,Bool)]
-> IO ([FC.Prog],[(FC.TypeDecl,Bool)])
collectAllTestTypeDecls opts fcprogs tdecls testtypenames = do
newprogs <- readFlatProgsIfNecessary fcprogs (map (fst . fst) testtypenames)
let newtesttypedecls = map (findTypeDecl newprogs) testtypenames
alltesttypedecls = tdecls ++ newtesttypedecls
newtcons = filter (\ ((mn,_),genpart) -> genpart || mn /= preludeName)
(nub (concatMap allTConsOfType newtesttypedecls)
\\ map (\(t,p) -> (FCG.typeName t,p)) alltesttypedecls)
if null newtcons
then return (newprogs,alltesttypedecls)
else collectAllTestTypeDecls opts newprogs alltesttypedecls newtcons
where
readFlatProgsIfNecessary progs [] = return progs
readFlatProgsIfNecessary progs (mn:mns) =
if mn `elem` map FCG.progName progs
then readFlatProgsIfNecessary progs mns
else do putStrIfDetails opts $
"Reading data types defined in module '" ++ mn ++ "'...\n"
fprog <- readFlatCurry mn
readFlatProgsIfNecessary (fprog:progs) mns
findTypeDecl :: [FC.Prog] -> (QName,Bool) -> (FC.TypeDecl,Bool)
findTypeDecl fcyprogs (qt@(mn,_),genpartial) =
let fprog = maybe (error $ "Cannot find module " ++ mn)
id
(find (\p -> FCG.progName p == mn) fcyprogs)
in maybe (error $ "Definition of type '" ++ FC.showQNameInModule "" qt ++
"' not found!")
(\td -> (td,genpartial))
(find (\t -> FCG.typeName t == qt) (FCG.progTypes fprog))
allTConsOfType :: (FC.TypeDecl,Bool) -> [(QName,Bool)]
allTConsOfType (td,genpart) = map (\t->(t,genpart)) (allTConsInDecl td)
allTConsInDecl :: FC.TypeDecl -> [QName]
allTConsInDecl = FCG.trType (\_ _ _ -> concatMap allTConsInConsDecl)
(\_ _ _ -> allTConsInTypeExpr)
allTConsInConsDecl :: FC.ConsDecl -> [QName]
allTConsInConsDecl = FCG.trCons (\_ _ _ -> concatMap allTConsInTypeExpr)
allTConsInTypeExpr :: FC.TypeExpr -> [QName]
allTConsInTypeExpr =
FCG.trTypeExpr (\_ -> []) (\tc targs -> tc : concat targs) (++) (flip const)
genTestDataGenerator :: String -> FC.TypeDecl -> CFuncDecl
genTestDataGenerator mainmod tdecl = type2genData tdecl
where
qt = FCG.typeName tdecl
qtString = FC.showQNameInModule "" qt
type2genData (FC.TypeSyn _ _ _ _) =
error $ "Cannot create generator for type synonym " ++ qtString
type2genData (FC.Type _ _ tvars cdecls)
| null cdecls
= error $ "Cannot create value generator for type '" ++ qtString ++
"' without constructors!"
| otherwise
= cmtfunc
("Generator for " ++ "`" ++ qtString ++ "` values.")
(typename2genopname mainmod [] qt) (length tvars) Public
(emptyClassType
(foldr (~>) (CTApply (CTCons searchTreeTC) (applyTC qt ctvars))
(map (\v -> applyTC searchTreeTC [v]) ctvars)))
[simpleRule (map CPVar cvars)
(foldr1 (\e1 e2 -> applyF choiceGen [e1,e2])
(map cons2gen cdecls))]
where
cons2gen (FC.Cons qn ar _ ctypes)
| ar>maxArity
= error $ "Test data constructors with more than " ++ show maxArity ++
" arguments are currently not supported!"
| otherwise
= applyF (generatorModule, "genCons" ++ show ar)
([CSymbol qn] ++ map type2gen ctypes)
type2gen (FC.TVar i) = CVar (i,"a"++show i)
type2gen (FC.FuncType _ _) =
error $ "Type '" ++ qtString ++
"': cannot create value generators for functions!"
type2gen (FC.TCons qtc argtypes) =
applyF (typename2genopname mainmod [] qtc) (map type2gen argtypes)
type2gen (FC.ForallType _ _) =
error $ "Type '" ++ qtString ++
"': cannot create value generators for forall types!"
ctvars = map (\i -> CTVar (i,"a"++show i)) tvars
cvars = map (\i -> (i,"a"++show i)) tvars
genPartialPrimDataGenerator :: String -> QName -> CFuncDecl
genPartialPrimDataGenerator mainmod (_,tn) =
cmtfunc
("Generator for (constant) partial " ++ "`" ++ tn ++ "` values.")
(mainmod, "gen_" ++ mainmod ++ "_P_" ++ tn ++ "_Constant")
0 Public
(emptyClassType (applyTC searchTreeTC [baseType (mainmod,t2bt tn)]))
[simpleRule []
(applyF choiceGen
[applyF (generatorModule, "genCons0") [constF (mainmod,"Bot_"++tn)],
applyF (generatorModule, "genCons1")
[constF (mainmod,"Value_"++tn),
applyF (searchTreeModule,"Value")
[CLit (defaultValueOfBasicExtType tn)]]])]
cleanup :: Options -> String -> [TestModule] -> IO ()
cleanup opts mainmod modules =
unless (optKeep opts) $ do
removeCurryModule mainmod
mapIO_ removeCurryModule (map testModuleName modules)
where
removeCurryModule modname =
lookupModuleSourceInLoadPath modname >>=
maybe done
(\ (_,srcfilename) -> do
system $ installDir </> "bin" </> "cleancurry" ++ " " ++ modname
system $ "rm -f " ++ srcfilename
done )
printTestStatistics :: Options -> [String] -> String -> Int -> [Test] -> IO ()
printTestStatistics opts mods testmodname retcode tests = do
let numtests = sumOf (const True)
unittests = sumOf isUnitTest
proptests = sumOf isPropTest
equvtests = sumOf isEquivTest
iotests = sumOf isIOTest
outs = "TOTAL NUMBER OF TESTS: " ++ show numtests ++
" (UNIT: " ++ show unittests ++ ", PROPERTIES: " ++
show proptests ++ ", EQUIVALENCE: " ++ show equvtests ++
(if optIOTest opts then ", IO: " ++ show iotests else "") ++ ")"
csvheader = ["Return code", "Total", "Unit", "Prop", "Equiv", "IO",
"Modules"]
csvdata = [retcode,numtests,unittests,proptests,equvtests,iotests]
unless (isQuiet opts || retcode /= 0 || numtests == 0) $
putStrLn $ withColor opts green outs
let statfile = optStatFile opts
unless (null statfile) $ do
writeCSVFile statfile [csvheader, map show csvdata ++ [unwords mods]]
putStrIfDetails opts $ "Statistics written to '" ++ show statfile ++ "'.\n"
where
sumOf p = length . filter p $ tests
main :: IO ()
main = do
argv <- getArgs
pid <- getPID
let (funopts, args, opterrors) = getOpt Permute options argv
opts <- processOpts (foldl (flip id) defaultOptions funopts)
unless (null opterrors)
(putStr (unlines opterrors) >> putStrLn usageText >> exitWith 1)
putStrIfNormal opts ccBanner
when (null args || optHelp opts) (putStrLn usageText >> exitWith 1)
let mods = map stripCurrySuffix args
mapIO_ checkModuleName mods
currypath <- ccLoadPath
setEnviron "CURRYPATH" currypath
testModules <- mapIO (analyseModule opts) mods
let staticerrs = concatMap staticErrors (concat testModules)
finaltestmodules = filter testThisModule (concat testModules)
testmodname = if null (optMainProg opts)
then "TEST" ++ show pid
else optMainProg opts
if not (null staticerrs)
then do showStaticErrors opts staticerrs
putStrLn $ withColor opts red "Testing aborted!"
cleanup opts testmodname finaltestmodules
printTestStatistics opts mods testmodname 1 []
exitWith 1
else
if null finaltestmodules
then do
printTestStatistics opts mods testmodname 0 []
exitWith 0
else do
putStrIfNormal opts $ withColor opts blue $
"Generating main test module '"++testmodname++"'..."
putStrIfDetails opts "\n"
finaltests <- genMainTestModule opts testmodname finaltestmodules
showGeneratedModule opts "main test" testmodname
putStrIfNormal opts $ withColor opts blue $ "and compiling it...\n"
let runcmd = unwords $
[ installDir </> "bin" </> "curry"
, "--noreadline"
, ":set -time"
, ":set " ++ if optVerb opts > 3 then "v1" else "v0"
, ":set parser -Wnone"
, if null currypath then "" else ":set path " ++ currypath
, ":l "++testmodname,":eval main :q" ]
putStrLnIfDebug opts $ "Executing command:\n" ++ runcmd
ret <- system runcmd
cleanup opts testmodname finaltestmodules
printTestStatistics opts mods testmodname ret finaltests
exitWith ret
where
showStaticErrors opts errs = putStrLn $ withColor opts red $
unlines (line : "STATIC ERRORS IN PROGRAMS:" : errs) ++ line
checkModuleName mn =
when (pathSeparator `elem` mn) $ do
putStrLn $ "Module names with path prefixes not allowed: " ++ mn
exitWith 1
line = take 78 (repeat '=')
showGeneratedModule :: Options -> String -> String -> IO ()
showGeneratedModule opts mkind modname = when (optVerb opts > 3) $ do
putStrLn $ '\n' : line
putStrLn $ "Generated " ++ mkind ++ " module `" ++ modname ++ ".curry':"
putStrLn line
readFile (modname ++ ".curry") >>= putStr
putStrLn line
where
line = take 78 (repeat '=')
renameProp2EasyCheck :: CurryProg -> CurryProg
renameProp2EasyCheck prog =
updCProg id (map rnmMod) id id id id id id
(updQNamesInCProg (\ (mod,n) -> (rnmMod mod,n)) prog)
where
rnmMod mod | mod == propModule = easyCheckModule
| otherwise = mod
firstWord :: String -> String
firstWord = head . splitOn "\t" . head . splitOn " "
stripSuffix :: String -> String -> String
stripSuffix str suf = if suf `isSuffixOf` str
then take (length str - length suf) str
else str
modNameToId :: String -> String
modNameToId = intercalate "_" . split (=='.')
arityOfType :: CTypeExpr -> Int
arityOfType = length . argTypes
searchTreeModule :: String
searchTreeModule = "Control.SearchTree"
searchTreeTC :: QName
searchTreeTC = (searchTreeModule,"SearchTree")
generatorModule :: String
generatorModule = "Control.SearchTree.Generators"
choiceGen :: QName
choiceGen = (generatorModule,"|||")
writeCurryProgram :: Options -> String -> CurryProg -> String -> IO ()
writeCurryProgram opts srcdir p appendix = do
let progfile = srcdir </> modNameToPath (progName p) ++ ".curry"
putStrLnIfDebug opts $ "Writing program: " ++ progfile
writeFile progfile
(ACPretty.showCProg p ++ "\n" ++ appendix ++ "\n")
isPAKCS :: Bool
isPAKCS = curryCompiler == "pakcs"
containsPPOptionLine :: String -> Bool
containsPPOptionLine = any isOptionLine . lines
where
isOptionLine s = "{-# OPTIONS_CYMAKE " `isPrefixOf` s
&& "currypp" `isInfixOf` s
tconsOf :: CTypeExpr -> [QName]
tconsOf (CTVar _) = []
tconsOf (CFuncType from to) = union (tconsOf from) (tconsOf to)
tconsOf (CTCons tc) = [tc]
tconsOf (CTApply tc ta) = union (tconsOf tc) (tconsOf ta)
unionOn :: Eq b => (a -> [b]) -> [a] -> [b]
unionOn f = foldr union [] . map f
showCTypeExpr :: CTypeExpr -> String
showCTypeExpr = pPrint . ACPretty.ppCTypeExpr ACPretty.defaultOptions
showCExpr :: CExpr -> String
showCExpr = pPrint . ACPretty.ppCExpr ACPretty.defaultOptions
cLambda :: [CPattern] -> CExpr -> CExpr
cLambda pats body | null pats = body
| otherwise = CLambda pats body
|