Source file gen_principle.ml
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
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
open Util
open Names
open Indfun_common
module RelDecl = Context.Rel.Declaration
module ERelevance = EConstr.ERelevance
let observe_tac s =
observe_tac ~header:(Pp.str "observation") (fun _ _ -> Pp.str s)
let rec abstract_glob_constr c = function
| [] -> c
| Constrexpr.CLocalDef (x, _, b, t) :: bl ->
Constrexpr_ops.mkLetInC (x, b, t, abstract_glob_constr c bl)
| Constrexpr.CLocalAssum (idl, _, k, t) :: bl ->
List.fold_right
(fun x b -> Constrexpr_ops.mkLambdaC ([x], k, t, b))
idl
(abstract_glob_constr c bl)
| Constrexpr.CLocalPattern _ :: bl -> assert false
let interp_casted_constr_with_implicits env sigma impls c =
Constrintern.intern_gen Pretyping.WithoutTypeConstraint env sigma ~impls c
let build_newrecursive lnameargsardef =
let env0 = Global.env () in
let sigma = Evd.from_env env0 in
let rec_sign, rec_impls =
List.fold_left
(fun (env, impls) {Vernacexpr.fname = {CAst.v = recname}; binders; rtype} ->
let arityc = Constrexpr_ops.mkCProdN binders rtype in
let arity, _ctx = Constrintern.interp_type env0 sigma arityc in
let evd = Evd.from_env env0 in
let evd, (_, (_, impls')) =
Constrintern.interp_context_evars ~program_mode:false env evd binders
in
let impl =
Constrintern.compute_internalization_data env0 evd recname
Constrintern.Recursive arity impls'
in
let open Context.Named.Declaration in
let r = ERelevance.relevant in
( EConstr.push_named
(LocalAssum (Context.make_annot recname r, arity))
env
, Id.Map.add recname impl impls ))
(env0, Constrintern.empty_internalization_env)
lnameargsardef
in
let recdef =
let f {Vernacexpr.binders; body_def} =
match body_def with
| Some body_def ->
let def = abstract_glob_constr body_def binders in
interp_casted_constr_with_implicits rec_sign sigma rec_impls def
| None ->
CErrors.user_err
(Pp.str "Body of Function must be given.")
in
Vernacstate.System.protect (List.map f) lnameargsardef
in
(recdef, rec_impls)
let is_rec names =
let open Glob_term in
let names = List.fold_right Id.Set.add names Id.Set.empty in
let check_id id names = Id.Set.mem id names in
let rec lookup names gt =
match DAst.get gt with
| GVar id -> check_id id names
| GRef _ | GEvar _ | GPatVar _ | GSort _ | GHole _ | GGenarg _
| GInt _ | GFloat _ | GString _ ->
false
| GCast (b, _, _) -> lookup names b
| GRec _ -> CErrors.user_err (Pp.str "GRec not handled")
| GIf (b, _, lhs, rhs) ->
lookup names b || lookup names lhs || lookup names rhs
| GProd (na, _, _, t, b) | GLambda (na, _, _, t, b) ->
lookup names t
|| lookup (Nameops.Name.fold_right Id.Set.remove na names) b
| GLetIn (na, _, b, t, c) ->
lookup names b
|| Option.cata (lookup names) true t
|| lookup (Nameops.Name.fold_right Id.Set.remove na names) c
| GLetTuple (nal, _, t, b) ->
lookup names t
|| lookup
(List.fold_left
(fun acc na -> Nameops.Name.fold_right Id.Set.remove na acc)
names nal)
b
| GApp (c, args) | GProj (_, args, c) -> List.exists (lookup names) (c :: args)
| GArray (_u, t, def, ty) ->
Array.exists (lookup names) t || lookup names def || lookup names ty
| GCases (_, _, el, brl) ->
List.exists (fun (e, _) -> lookup names e) el
|| List.exists (lookup_br names) brl
and lookup_br names {CAst.v = idl, _, rt} =
let new_names = List.fold_right Id.Set.remove idl names in
lookup new_names rt
in
lookup names
let rec rebuild_bl aux bl typ =
let open Constrexpr in
match (bl, typ) with
| [], _ -> (List.rev aux, typ)
| CLocalAssum (nal, _, bk, _) :: bl', typ -> rebuild_nal aux bk bl' nal typ
| CLocalDef (na, _, _, _) :: bl', {CAst.v = CLetIn (_, nat, ty, typ')} ->
rebuild_bl (Constrexpr.CLocalDef (na, None, nat, ty) :: aux) bl' typ'
| _ -> assert false
and rebuild_nal aux bk bl' nal typ =
let open Constrexpr in
match (nal, typ) with
| _, {CAst.v = CProdN ([], typ)} -> rebuild_nal aux bk bl' nal typ
| [], _ -> rebuild_bl aux bl' typ
| ( na :: nal
, {CAst.v = CProdN (CLocalAssum (na' :: nal', _, bk', nal't) :: rest, typ')} )
->
if Name.equal na.CAst.v na'.CAst.v || Name.is_anonymous na'.CAst.v then
let assum = CLocalAssum ([na], None, bk, nal't) in
let new_rest =
if nal' = [] then rest else CLocalAssum (nal', None, bk', nal't) :: rest
in
rebuild_nal (assum :: aux) bk bl' nal
(CAst.make @@ CProdN (new_rest, typ'))
else
let assum = CLocalAssum ([na'], None, bk, nal't) in
let new_rest =
if nal' = [] then rest else CLocalAssum (nal', None, bk', nal't) :: rest
in
rebuild_nal (assum :: aux) bk bl' (na :: nal)
(CAst.make @@ CProdN (new_rest, typ'))
| _ -> assert false
let rebuild_bl aux bl typ = rebuild_bl aux bl typ
let recompute_binder_list (rec_order, fixpoint_exprl) =
let typel, sigma = ComFixpoint.interp_fixpoint_short rec_order fixpoint_exprl in
let constr_expr_typel =
with_full_print
(List.map (fun c ->
Constrextern.extern_constr (Global.env ()) sigma
(EConstr.of_constr c)))
typel
in
let fixpoint_exprl_with_new_bl =
List.map2
(fun ({Vernacexpr.binders} as fp) fix_typ ->
let binders, rtype = rebuild_bl [] binders fix_typ in
{fp with Vernacexpr.binders; rtype})
fixpoint_exprl constr_expr_typel
in
fixpoint_exprl_with_new_bl
let rec local_binders_length = function
| [] -> 0
| Constrexpr.CLocalDef _ :: bl -> 1 + local_binders_length bl
| Constrexpr.CLocalAssum (idl, _, _, _) :: bl ->
List.length idl + local_binders_length bl
| Constrexpr.CLocalPattern _ :: bl -> assert false
let prepare_body {Vernacexpr.binders} rt =
let n = local_binders_length binders in
let fun_args, rt' = chop_rlambda_n n rt in
(fun_args, rt')
let build_functional_principle env (sigma : Evd.evar_map) old_princ_type sorts funs
_i proof_tac hook =
let mutr_nparams =
(Induction.compute_elim_sig sigma (EConstr.of_constr old_princ_type))
.Induction.nparams
in
let new_principle_type =
Functional_principles_types.compute_new_princ_type_from_rel (Global.env ())
(Array.map Constr.mkConstU funs)
(Array.map (fun s -> EConstr.ESorts.kind sigma s) sorts) old_princ_type
in
let sigma, _ =
Typing.type_of ~refresh:true env sigma
(EConstr.of_constr new_principle_type)
in
let map (c, u) = EConstr.mkConstU (c, EConstr.EInstance.make u) in
let ftac = proof_tac (Array.map map funs) mutr_nparams in
let uctx = Evd.ustate sigma in
let typ = EConstr.of_constr new_principle_type in
let body, typ, univs, _safe, _uctx =
Declare.build_by_tactic env ~uctx ~poly:false ~typ ftac
in
let hook = Declare.Hook.make (hook new_principle_type) in
(body, typ, univs, hook, sigma)
let change_property_sort evd toSort princ princName =
let open Context.Rel.Declaration in
let toSort = EConstr.ESorts.kind evd toSort in
let princ = EConstr.of_constr princ in
let princ_info = Induction.compute_elim_sig evd princ in
let change_sort_in_predicate decl =
LocalAssum
( EConstr.Unsafe.to_binder_annot @@ get_annot decl
, let args, ty =
Term.decompose_prod (EConstr.Unsafe.to_constr (get_type decl))
in
let s = Constr.destSort ty in
Global.add_constraints
(UnivSubst.enforce_leq_sort
toSort s Univ.Constraints.empty);
Term.compose_prod args (Constr.mkSort toSort) )
in
let evd, princName_as_constr =
Evd.fresh_global (Global.env ()) evd
(Option.get (Constrintern.locate_reference (Libnames.qualid_of_ident princName)))
in
let init =
let nargs =
princ_info.Induction.nparams + List.length princ_info.Induction.predicates
in
Constr.mkApp
( EConstr.Unsafe.to_constr princName_as_constr
, Array.init nargs (fun i -> Constr.mkRel (nargs - i)) )
in
( evd
, Term.it_mkLambda_or_LetIn
(Term.it_mkLambda_or_LetIn init
(List.map change_sort_in_predicate princ_info.Induction.predicates))
(EConstr.Unsafe.to_rel_context princ_info.Induction.params) )
let generate_functional_principle (evd : Evd.evar_map ref) old_princ_type sorts
new_princ_name funs i proof_tac =
try
let f = funs.(i) in
let sigma, type_sort = Evd.fresh_sort_in_family !evd Sorts.InType in
evd := sigma;
let new_sorts =
match sorts with
| None -> Array.make (Array.length funs) type_sort
| Some a -> a
in
let base_new_princ_name, new_princ_name =
match new_princ_name with
| Some id -> (id, id)
| None ->
let id_of_f = Label.to_id (Constant.label (fst f)) in
(id_of_f, Indrec.make_elimination_ident id_of_f (EConstr.ESorts.family !evd type_sort))
in
let names = ref [new_princ_name] in
let hook new_principle_type _ =
if Option.is_empty sorts then (
let register_with_sort fam_sort =
let evd' = Evd.from_env (Global.env ()) in
let evd', s = Evd.fresh_sort_in_family evd' fam_sort in
let name =
Indrec.make_elimination_ident base_new_princ_name fam_sort
in
let evd', value =
change_property_sort evd' s new_principle_type new_princ_name
in
let evd' =
fst
(Typing.type_of ~refresh:true (Global.env ()) evd'
(EConstr.of_constr value))
in
let univs = Evd.univ_entry ~poly:false evd' in
let ce = Declare.definition_entry ~univs value in
ignore
(Declare.declare_constant ~name
~kind:Decls.(IsDefinition Scheme)
(Declare.DefinitionEntry ce));
Declare.definition_message name;
names := name :: !names
in
register_with_sort Sorts.InProp;
register_with_sort Sorts.InSet )
in
let body, types, univs, hook, sigma0 =
build_functional_principle (Global.env ()) !evd old_princ_type new_sorts funs i proof_tac
hook
in
evd := sigma0;
let uctx = Evd.ustate sigma in
let entry = Declare.definition_entry ~univs ?types body in
let (_ : Names.GlobRef.t) =
Declare.declare_entry ~name:new_princ_name ~hook
~kind:Decls.(IsProof Theorem)
~impargs:[] ~uctx entry
in
()
with e when CErrors.noncritical e -> raise (Defining_principle e)
let generate_principle (evd : Evd.evar_map ref) pconstants on_error is_general
do_built fix_rec_l recdefs
(continue_proof :
int
-> Names.Constant.t array
-> EConstr.constr array
-> int
-> unit Proofview.tactic) : unit =
let names =
List.map (function {Vernacexpr.fname = {CAst.v = name}} -> name) fix_rec_l
in
let fun_bodies = List.map2 prepare_body fix_rec_l recdefs in
let funs_args = List.map fst fun_bodies in
let funs_types =
List.map (function {Vernacexpr.rtype} -> rtype) fix_rec_l
in
try
Glob_term_to_relation.build_inductive !evd pconstants funs_args funs_types
recdefs;
if do_built then begin
let f_R_mut = Libnames.qualid_of_ident @@ mk_rel_id (List.nth names 0) in
let ind_kn =
fst
(locate_with_msg
Pp.(Libnames.pr_qualid f_R_mut ++ str ": Not an inductive type!")
locate_ind f_R_mut)
in
let fname_kn {Vernacexpr.fname} =
let f_ref = Libnames.qualid_of_ident ?loc:fname.CAst.loc fname.CAst.v in
locate_with_msg
Pp.(Libnames.pr_qualid f_ref ++ str ": Not an inductive type!")
locate_constant f_ref
in
let funs_kn = Array.of_list (List.map fname_kn fix_rec_l) in
let _ =
List.map_i
(fun i _x ->
let env = Global.env () in
let princ = Indrec.lookup_eliminator env (ind_kn, i) Sorts.InProp in
let evd = ref (Evd.from_env env) in
let evd', uprinc = Evd.fresh_global env !evd princ in
let _ = evd := evd' in
let sigma, princ_type =
Typing.type_of ~refresh:true env !evd uprinc
in
evd := sigma;
let princ_type = EConstr.Unsafe.to_constr princ_type in
generate_functional_principle evd princ_type None None
(Array.of_list pconstants)
i
(continue_proof 0 [|funs_kn.(i)|]))
0 fix_rec_l
in
Array.iter (add_Function is_general) funs_kn;
()
end
with e when CErrors.noncritical e -> on_error names e
let register_struct is_rec (rec_order, fixpoint_exprl) =
let open EConstr in
match fixpoint_exprl with
| [{Vernacexpr.fname; univs; binders; rtype; body_def}] when not is_rec ->
let body =
match body_def with
| Some body -> body
| None ->
CErrors.user_err
Pp.(str "Body of Function must be given.")
in
ComDefinition.do_definition ~name:fname.CAst.v ~poly:false
~kind:Decls.Definition univs binders None body (Some rtype);
let evd, rev_pconstants =
List.fold_left
(fun (evd, l) {Vernacexpr.fname} ->
let evd, c =
Evd.fresh_global (Global.env ()) evd
(Option.get (Constrintern.locate_reference
(Libnames.qualid_of_ident fname.CAst.v)))
in
let cst, u = destConst evd c in
let u = EInstance.kind evd u in
(evd, (cst, u) :: l))
(Evd.from_env (Global.env ()), [])
fixpoint_exprl
in
(None, evd, List.rev rev_pconstants)
| _ ->
let pm, p = ComFixpoint.do_mutually_recursive ~program_mode:false ~poly:false ~kind:(IsDefinition Fixpoint) (CFixRecOrder rec_order, fixpoint_exprl) in
assert (Option.is_empty pm && Option.is_empty p);
let evd, rev_pconstants =
List.fold_left
(fun (evd, l) {Vernacexpr.fname} ->
let evd, c =
Evd.fresh_global (Global.env ()) evd
(Option.get (Constrintern.locate_reference
(Libnames.qualid_of_ident fname.CAst.v)))
in
let cst, u = destConst evd c in
let u = EInstance.kind evd u in
(evd, (cst, u) :: l))
(Evd.from_env (Global.env ()), [])
fixpoint_exprl
in
(None, evd, List.rev rev_pconstants)
let generate_correction_proof_wf f_ref tcc_lemma_ref is_mes functional_ref
eq_ref rec_arg_num rec_arg_type relation (_ : int)
(_ : Names.Constant.t array) (_ : EConstr.constr array) (_ : int) :
unit Proofview.tactic =
Functional_principles_proofs.prove_principle_for_gen
(f_ref, functional_ref, eq_ref)
tcc_lemma_ref is_mes rec_arg_num rec_arg_type relation
let generate_type env evd g_to_f f graph =
let open Context.Rel.Declaration in
let open EConstr in
let open EConstr.Vars in
let evd', graph =
Evd.fresh_global env !evd
(GlobRef.IndRef (fst (destInd !evd graph)))
in
evd := evd';
let sigma, graph_arity = Typing.type_of env !evd graph in
evd := sigma;
let ctxt, _ = decompose_prod_decls !evd graph_arity in
let fun_ctxt, res_type =
match ctxt with
| [] | [_] -> CErrors.anomaly (Pp.str "Not a valid context.")
| decl :: fun_ctxt -> (fun_ctxt, RelDecl.get_type decl)
in
let rec args_from_decl i accu = function
| [] -> accu
| LocalDef _ :: l -> args_from_decl (succ i) accu l
| _ :: l ->
let t = mkRel i in
args_from_decl (succ i) (t :: accu) l
in
let filter decl =
match RelDecl.get_name decl with Name id -> Some id | Anonymous -> None
in
let named_ctxt = Id.Set.of_list (List.map_filter filter fun_ctxt) in
let res_id =
Namegen.next_ident_away_in_goal env (Id.of_string "_res") named_ctxt
in
let fv_id =
Namegen.next_ident_away_in_goal env (Id.of_string "fv")
(Id.Set.add res_id named_ctxt)
in
let args_as_rels = Array.of_list (args_from_decl 1 [] fun_ctxt) in
let make_eq = make_eq () in
let res_eq_f_of_args =
mkApp (make_eq, [|lift 2 res_type; mkRel 1; mkRel 2|])
in
let args_and_res_as_rels = Array.of_list (args_from_decl 3 [] fun_ctxt) in
let args_and_res_as_rels = Array.append args_and_res_as_rels [|mkRel 1|] in
let graph_applied = mkApp (graph, args_and_res_as_rels) in
let pre_ctxt =
LocalAssum (Context.make_annot (Name res_id) ERelevance.relevant, lift 1 res_type)
:: LocalDef
( Context.make_annot (Name fv_id) ERelevance.relevant
, mkApp (f, args_as_rels)
, res_type )
:: fun_ctxt
in
if g_to_f then
( LocalAssum (Context.make_annot Anonymous ERelevance.relevant, graph_applied)
:: pre_ctxt
, lift 1 res_eq_f_of_args
, graph )
else
( LocalAssum (Context.make_annot Anonymous ERelevance.relevant, res_eq_f_of_args)
:: pre_ctxt
, lift 1 graph_applied
, graph )
(**
[find_induction_principle f] searches and returns the [body] and the [type] of [f_rect]
WARNING: while convertible, [type_of body] and [type] can be non equal
*)
let find_induction_principle env evd f =
let f_as_constant, _u =
match EConstr.kind !evd f with
| Constr.Const c' -> c'
| _ -> CErrors.user_err Pp.(str "Must be used with a function")
in
match find_Function_infos f_as_constant with
| None -> raise Not_found
| Some infos -> (
match infos.rect_lemma with
| None -> raise Not_found
| Some rect_lemma ->
let evd', rect_lemma =
Evd.fresh_global env !evd (GlobRef.ConstRef rect_lemma)
in
let evd', typ =
Typing.type_of ~refresh:true env evd' rect_lemma
in
evd := evd';
(rect_lemma, typ) )
let rec generate_fresh_id x avoid i =
if i == 0 then []
else
let id = Namegen.next_ident_away_in_goal (Global.env ()) x (Id.Set.of_list avoid) in
id :: generate_fresh_id x (id :: avoid) (pred i)
let prove_fun_correct evd graphs_constr schemes lemmas_types_infos i :
unit Proofview.tactic =
let open Constr in
let open EConstr in
let open Context.Rel.Declaration in
let open Tacmach in
let open Tactics in
let open Tacticals in
Proofview.Goal.enter (fun g ->
let graph_ind, u = destInd evd graphs_constr.(i) in
let kn = fst graph_ind in
let mib, _ = Global.lookup_inductive graph_ind in
let f_principle, princ_type = schemes.(i) in
let princ_type = Reductionops.nf_zeta (Global.env ()) evd princ_type in
let princ_infos = Induction.compute_elim_sig evd princ_type in
let nb_fun_args =
Termops.nb_prod (Proofview.Goal.sigma g) (Proofview.Goal.concl g) - 2
in
let args_names = generate_fresh_id (Id.of_string "x") [] nb_fun_args in
let ids = args_names @ pf_ids_of_hyps g in
let principle_id =
Namegen.next_ident_away_in_goal (Global.env ()) (Id.of_string "princ")
(Id.Set.of_list ids)
in
let ids = principle_id :: ids in
let branches = List.rev princ_infos.Induction.branches in
let intro_pats =
List.map
(fun decl ->
List.map
(fun id ->
CAst.make @@ Tactypes.IntroNaming (Namegen.IntroIdentifier id))
(generate_fresh_id (Id.of_string "y") ids
(List.length
(fst (decompose_prod_decls evd (RelDecl.get_type decl))))))
branches
in
let eq_ind = make_eq () in
let eq_construct = mkConstructUi (destInd evd eq_ind, 1) in
let ind_number = ref 0 and min_constr_number = ref 0 in
let prove_branch i pat =
let pre_args =
List.fold_right
(fun {CAst.v = pat} acc ->
match pat with
| Tactypes.IntroNaming (Namegen.IntroIdentifier id) -> id :: acc
| _ -> CErrors.anomaly (Pp.str "Not an identifier."))
pat []
in
let constructor_args g =
List.fold_right
(fun hid acc ->
let type_of_hid = pf_get_hyp_typ hid g in
let sigma = Proofview.Goal.sigma g in
match EConstr.kind sigma type_of_hid with
| Prod (_, _, t') -> (
match EConstr.kind sigma t' with
| Prod (_, t'', t''') -> (
match (EConstr.kind sigma t'', EConstr.kind sigma t''') with
| App (eq, args), App (graph', _)
when EConstr.eq_constr sigma eq eq_ind
&& Array.exists
(EConstr.eq_constr_nounivs sigma graph')
graphs_constr ->
args.(2)
:: mkApp
( mkVar hid
, [| args.(2)
; mkApp (eq_construct, [|args.(0); args.(2)|]) |] )
:: acc
| _ -> mkVar hid :: acc )
| _ -> mkVar hid :: acc )
| _ -> mkVar hid :: acc)
pre_args []
in
let constructor_args g =
let params_id =
fst (List.chop princ_infos.Induction.nparams args_names)
in
List.map mkVar params_id @ constructor_args g
in
let constructor =
let constructor_num = i - !min_constr_number in
let length =
Array.length
mib.Declarations.mind_packets.(!ind_number)
.Declarations.mind_consnames
in
if constructor_num <= length then ((kn, !ind_number), constructor_num)
else begin
incr ind_number;
min_constr_number := !min_constr_number + length;
((kn, !ind_number), 1)
end
in
let app_constructor g =
applist (mkConstructU (constructor, u), constructor_args g)
in
let res, hres =
match
generate_fresh_id (Id.of_string "z") ids 2
with
| [res; hres] -> (res, hres)
| _ -> assert false
in
tclTHENLIST
[ observe_tac "h_intro_patterns "
(match pat with [] -> tclIDTAC | _ -> intro_patterns false pat)
;
reduce
(Genredexpr.Cbv
{ Redops.all_flags with
Genredexpr.rDelta = false
; Genredexpr.rConst = [] })
Locusops.onConcl
; observe_tac "toto " (Proofview.tclUNIT ())
;
observe_tac "introducing" (tclMAP Simple.intro [res; hres])
;
observe_tac "rewriting res value" (Equality.rewriteLR (mkVar hres))
;
observe_tac "exact"
(Proofview.Goal.enter (fun g -> exact_check (app_constructor g)))
]
in
let lemmas =
Array.map
(fun (_, (ctxt, concl)) ->
match ctxt with
| [] | [_] | [_; _] -> CErrors.anomaly (Pp.str "bad context.")
| hres :: res :: decl :: ctxt ->
let res =
EConstr.it_mkLambda_or_LetIn
(EConstr.it_mkProd_or_LetIn concl [hres; res])
( LocalAssum (RelDecl.get_annot decl, RelDecl.get_type decl)
:: ctxt )
in
res)
lemmas_types_infos
in
let param_names = fst (List.chop princ_infos.nparams args_names) in
let params = List.map mkVar param_names in
let lemmas =
Array.to_list (Array.map (fun c -> applist (c, params)) lemmas)
in
let bindings =
let params_bindings, avoid =
List.fold_left2
(fun (bindings, avoid) decl p ->
let id =
Namegen.next_ident_away
(Nameops.Name.get_id (RelDecl.get_name decl))
(Id.Set.of_list avoid)
in
(p :: bindings, id :: avoid))
([], pf_ids_of_hyps g)
princ_infos.params (List.rev params)
in
let lemmas_bindings =
List.rev
(fst
(List.fold_left2
(fun (bindings, avoid) decl p ->
let id =
Namegen.next_ident_away
(Nameops.Name.get_id (RelDecl.get_name decl))
(Id.Set.of_list avoid)
in
( Reductionops.nf_zeta (Proofview.Goal.env g)
(Proofview.Goal.sigma g) p
:: bindings
, id :: avoid ))
([], avoid) princ_infos.predicates lemmas))
in
params_bindings @ lemmas_bindings
in
tclTHENLIST
[ observe_tac "principle"
(assert_by (Name principle_id) princ_type (exact_check f_principle))
; observe_tac "intro args_names" (tclMAP Simple.intro args_names)
;
observe_tac "idtac" tclIDTAC
; tclTHENS
(observe_tac "functional_induction"
(Proofview.Goal.enter (fun gl ->
let term =
mkApp (mkVar principle_id, Array.of_list bindings)
in
tclTYPEOFTHEN ~refresh:true term (fun _ _ -> apply term))))
(List.map_i
(fun i pat ->
observe_tac
("proving branch " ^ string_of_int i)
(prove_branch i pat))
1 intro_pats) ])
let thin = Tactics.clear
let tauto =
let open Ltac_plugin in
let dp = List.map Id.of_string ["Tauto"; "Init"; "Corelib"] in
let mp = ModPath.MPfile (DirPath.make dp) in
let kn = KerName.make mp (Label.make "tauto") in
Proofview.tclBIND (Proofview.tclUNIT ()) (fun () ->
let body = Tacenv.interp_ltac kn in
Tacinterp.eval_tactic body)
let generalize_dependent_of x hyp =
let open Context.Named.Declaration in
let open Tacticals in
Proofview.Goal.enter (fun g ->
tclMAP
(function
| LocalAssum ({Context.binder_name = id}, t)
when (not (Id.equal id hyp))
&& Termops.occur_var (Proofview.Goal.env g)
(Proofview.Goal.sigma g) x t ->
tclTHEN (Generalize.generalize [EConstr.mkVar id]) (thin [id])
| _ -> Proofview.tclUNIT ())
(Proofview.Goal.hyps g))
let rec intros_with_rewrite () =
observe_tac "intros_with_rewrite" (intros_with_rewrite_aux ())
and intros_with_rewrite_aux () : unit Proofview.tactic =
let open Constr in
let open EConstr in
let open Tacmach in
let open Tactics in
let open Tacticals in
Proofview.Goal.enter (fun g ->
let eq_ind = make_eq () in
let sigma = Proofview.Goal.sigma g in
match EConstr.kind sigma (Proofview.Goal.concl g) with
| Prod (_, t, t') -> (
match EConstr.kind sigma t with
| App (eq, args) when EConstr.eq_constr sigma eq eq_ind ->
if
Reductionops.is_conv (Proofview.Goal.env g) (Proofview.Goal.sigma g)
args.(1) args.(2)
then
let id = pf_get_new_id (Id.of_string "y") g in
tclTHENLIST [Simple.intro id; thin [id]; intros_with_rewrite ()]
else if
isVar sigma args.(1)
&& Environ.evaluable_named
(destVar sigma args.(1))
(Proofview.Goal.env g)
then
tclTHENLIST
[ unfold_in_concl
[ ( Locus.AllOccurrences
, Evaluable.EvalVarRef (destVar sigma args.(1)) ) ]
; tclMAP
(fun id ->
tclTRY
(unfold_in_hyp
[ ( Locus.AllOccurrences
, Evaluable.EvalVarRef (destVar sigma args.(1)) ) ]
(destVar sigma args.(1), Locus.InHyp)))
(pf_ids_of_hyps g)
; intros_with_rewrite () ]
else if
isVar sigma args.(2)
&& Environ.evaluable_named
(destVar sigma args.(2))
(Proofview.Goal.env g)
then
tclTHENLIST
[ unfold_in_concl
[ ( Locus.AllOccurrences
, Evaluable.EvalVarRef (destVar sigma args.(2)) ) ]
; tclMAP
(fun id ->
tclTRY
(unfold_in_hyp
[ ( Locus.AllOccurrences
, Evaluable.EvalVarRef (destVar sigma args.(2)) ) ]
(destVar sigma args.(2), Locus.InHyp)))
(pf_ids_of_hyps g)
; intros_with_rewrite () ]
else if isVar sigma args.(1) then
let id = pf_get_new_id (Id.of_string "y") g in
tclTHENLIST
[ Simple.intro id
; generalize_dependent_of (destVar sigma args.(1)) id
; tclTRY (Equality.rewriteLR (mkVar id))
; intros_with_rewrite () ]
else if isVar sigma args.(2) then
let id = pf_get_new_id (Id.of_string "y") g in
tclTHENLIST
[ Simple.intro id
; generalize_dependent_of (destVar sigma args.(2)) id
; tclTRY (Equality.rewriteRL (mkVar id))
; intros_with_rewrite () ]
else
let id = pf_get_new_id (Id.of_string "y") g in
tclTHENLIST
[ Simple.intro id
; tclTRY (Equality.rewriteLR (mkVar id))
; intros_with_rewrite () ]
| Ind _
when EConstr.eq_constr sigma t
(EConstr.of_constr
( UnivGen.constr_of_monomorphic_global (Global.env ())
@@ Rocqlib.lib_ref "core.False.type" )) ->
tauto
| Case (_, _, _, _, _, v, _) ->
tclTHENLIST [simplest_case v; intros_with_rewrite ()]
| LetIn _ ->
tclTHENLIST
[ reduce
(Genredexpr.Cbv {Redops.all_flags with Genredexpr.rDelta = false})
Locusops.onConcl
; intros_with_rewrite () ]
| _ ->
let id = pf_get_new_id (Id.of_string "y") g in
tclTHENLIST [Simple.intro id; intros_with_rewrite ()] )
| LetIn _ ->
tclTHENLIST
[ reduce
(Genredexpr.Cbv {Redops.all_flags with Genredexpr.rDelta = false})
Locusops.onConcl
; intros_with_rewrite () ]
| _ -> Proofview.tclUNIT ())
let rec reflexivity_with_destruct_cases () =
let open Constr in
let open EConstr in
let open Tacmach in
let open Tactics in
let open Tacticals in
Proofview.Goal.enter (fun g ->
let destruct_case () =
try
match
EConstr.kind (Proofview.Goal.sigma g)
(snd (destApp (Proofview.Goal.sigma g) (Proofview.Goal.concl g))).(
2)
with
| Case (_, _, _, _, _, v, _) ->
tclTHENLIST
[ simplest_case v
; intros
; observe_tac "reflexivity_with_destruct_cases"
(reflexivity_with_destruct_cases ()) ]
| _ -> reflexivity
with e when CErrors.noncritical e -> reflexivity
in
let eq_ind = make_eq () in
let my_inj_flags =
Some
{ Equality.keep_proof_equalities = false
; injection_pattern_l2r_order = false
}
in
let discr_inject =
onAllHypsAndConcl (fun sc ->
match sc with
| None -> Proofview.tclUNIT ()
| Some id ->
Proofview.Goal.enter (fun g ->
match
EConstr.kind (Proofview.Goal.sigma g) (pf_get_hyp_typ id g)
with
| App (eq, [|_; t1; t2|])
when EConstr.eq_constr (Proofview.Goal.sigma g) eq eq_ind ->
tclFIRST [
Equality.discrHyp id;
tclTHENLIST
[ Equality.injHyp my_inj_flags ~injection_in_context:false None id
; thin [id]
; intros_with_rewrite () ];
Proofview.tclUNIT ()
]
| _ -> Proofview.tclUNIT ()))
in
tclFIRST
[ observe_tac "reflexivity_with_destruct_cases : reflexivity" reflexivity
; observe_tac "reflexivity_with_destruct_cases : destruct_case"
(destruct_case ())
;
observe_tac "reflexivity_with_destruct_cases : others"
(tclTHEN (tclPROGRESS discr_inject)
(reflexivity_with_destruct_cases ())) ])
let prove_fun_complete funcs graphs schemes lemmas_types_infos i :
unit Proofview.tactic =
let open EConstr in
let open Tacmach in
let open Tactics in
let open Tacticals in
Proofview.Goal.enter (fun g ->
let lemmas =
Array.map
(fun (_, (ctxt, concl)) ->
Reductionops.nf_zeta (Proofview.Goal.env g) (Proofview.Goal.sigma g)
(EConstr.it_mkLambda_or_LetIn concl ctxt))
lemmas_types_infos
in
let f = funcs.(i) in
let graph_principle =
Reductionops.nf_zeta (Proofview.Goal.env g) (Proofview.Goal.sigma g)
(EConstr.of_constr schemes.(i))
in
tclTYPEOFTHEN graph_principle (fun sigma princ_type ->
let princ_infos = Induction.compute_elim_sig sigma princ_type in
let nb_fun_args =
Termops.nb_prod sigma (Proofview.Goal.concl g) - 2
in
let args_names =
generate_fresh_id (Id.of_string "x") [] nb_fun_args
in
let ids = args_names @ pf_ids_of_hyps g in
let res, hres, graph_principle_id =
match generate_fresh_id (Id.of_string "z") ids 3 with
| [res; hres; graph_principle_id] -> (res, hres, graph_principle_id)
| _ -> assert false
in
let ids = res :: hres :: graph_principle_id :: ids in
let branches = List.rev princ_infos.branches in
let intro_pats =
List.map
(fun decl ->
List.map
(fun id -> id)
(generate_fresh_id (Id.of_string "y") ids
(Termops.nb_prod (Proofview.Goal.sigma g)
(RelDecl.get_type decl))))
branches
in
let rewrite_tac j ids : unit Proofview.tactic =
let graph_def = graphs.(j) in
let infos =
match
find_Function_infos
(fst (destConst (Proofview.Goal.sigma g) funcs.(j)))
with
| None -> CErrors.user_err Pp.(str "No graph found")
| Some infos -> infos
in
if
infos.is_general
|| Rtree.is_infinite Declareops.eq_recarg
graph_def.Declarations.mind_recargs
then
let eq_lemma =
try Option.get infos.equation_lemma
with Option.IsNone ->
CErrors.anomaly (Pp.str "Cannot find equation lemma.")
in
tclTHENLIST
[ tclMAP Simple.intro ids
; Equality.rewriteLR (UnsafeMonomorphic.mkConst eq_lemma)
;
reduce
(Genredexpr.Cbv
{Redops.all_flags with Genredexpr.rDelta = false})
Locusops.onConcl
; Generalize.generalize (List.map mkVar ids)
; thin ids ]
else
unfold_in_concl
[ ( Locus.AllOccurrences
, Evaluable.EvalConstRef
(fst (destConst (Proofview.Goal.sigma g) f)) ) ]
in
let ind_number = ref 0 in
let min_constr_number = ref 0 in
let prove_branch i this_branche_ids =
let this_ind_number =
let constructor_num = i - !min_constr_number in
let length =
Array.length graphs.(!ind_number).Declarations.mind_consnames
in
if constructor_num <= length then !ind_number
else begin
incr ind_number;
min_constr_number := !min_constr_number + length;
!ind_number
end
in
tclTHENLIST
[
observe_tac "rewrite_tac"
(rewrite_tac this_ind_number this_branche_ids)
;
observe_tac "intros_with_rewrite (all)" (intros_with_rewrite ())
;
observe_tac "reflexivity" (reflexivity_with_destruct_cases ())
]
in
let params_names = fst (List.chop princ_infos.nparams args_names) in
let open EConstr in
let params = List.map mkVar params_names in
tclTHENLIST
[ tclMAP Simple.intro (args_names @ [res; hres])
; observe_tac "h_generalize"
(Generalize.generalize
[ mkApp
( applist (graph_principle, params)
, Array.map (fun c -> applist (c, params)) lemmas ) ])
; Simple.intro graph_principle_id
; observe_tac ""
(tclTHENS
(observe_tac "elim"
(elim false None
(mkVar hres, Tactypes.NoBindings)
(Some (mkVar graph_principle_id, Tactypes.NoBindings))))
(List.map_i
(fun i pat ->
observe_tac "prove_branch" (prove_branch i pat))
1 intro_pats)) ]))
exception No_graph_found
let get_funs_constant mp =
let open Constr in
let exception Not_Rec in
let get_funs_constant const e : (Names.Constant.t * int) array =
match Constr.kind (Term.strip_lam e) with
| Fix (_, (na, _, _)) ->
Array.mapi
(fun i na ->
match na.Context.binder_name with
| Name id ->
let const = Constant.make2 mp (Label.of_id id) in
(const, i)
| Anonymous -> CErrors.anomaly (Pp.str "Anonymous fix."))
na
| _ -> [|(const, 0)|]
in
function
| const ->
let find_constant_body const =
let env = Global.env () in
let body = Environ.lookup_constant const env in
match body.Declarations.const_body with
| Def body ->
let body =
Tacred.cbv_norm_flags ~strong:true
(RedFlags.mkflags [RedFlags.fZETA])
env
(Evd.from_env env)
(EConstr.of_constr body)
in
let body = EConstr.Unsafe.to_constr body in
body
| Undef _ | OpaqueDef _ | Primitive _ | Symbol _ ->
CErrors.user_err Pp.(str "Cannot define a principle over an axiom ")
in
let f = find_constant_body const in
let l_const = get_funs_constant const f in
let l_bodies =
List.map find_constant_body (Array.to_list (Array.map fst l_const))
in
let l_params, _l_fixes =
List.split (List.map Term.decompose_lambda l_bodies)
in
let _check_params =
let first_params = List.hd l_params in
List.iter
(fun params ->
if
not
(List.equal
(fun (n1, c1) (n2, c2) ->
Context.eq_annot Name.equal Sorts.relevance_equal n1 n2 && Constr.equal c1 c2)
first_params params)
then CErrors.user_err Pp.(str "Not a mutal recursive block"))
l_params
in
let _check_bodies =
try
let is_first body =
match Constr.kind body with
| Fix ((idxs, _), (na, ta, ca)) -> (idxs, na, ta, ca)
| _ ->
if is_first && Int.equal (List.length l_bodies) 1 then raise Not_Rec
else CErrors.user_err Pp.(str "Not a mutal recursive block")
in
let first_infos = extract_info true (List.hd l_bodies) in
let check body =
let eq_infos (ia1, na1, ta1, ca1) (ia2, na2, ta2, ca2) =
Array.equal Int.equal ia1 ia2
&& Array.equal (Context.eq_annot Name.equal Sorts.relevance_equal) na1 na2
&& Array.equal Constr.equal ta1 ta2
&& Array.equal Constr.equal ca1 ca2
in
if not (eq_infos first_infos (extract_info false body)) then
CErrors.user_err Pp.(str "Not a mutal recursive block")
in
List.iter check l_bodies
with Not_Rec -> ()
in
l_const
let make_scheme evd (fas : (Constr.pconstant * Sorts.family) list) : _ list =
let exception Found_type of int in
let env = Global.env () in
let funs = List.map fst fas in
let first_fun = List.hd funs in
let funs_mp = KerName.modpath (Constant.canonical (fst first_fun)) in
let first_fun_kn =
match find_Function_infos (fst first_fun) with
| None -> raise No_graph_found
| Some finfos -> fst finfos.graph_ind
in
let this_block_funs_indexes = get_funs_constant funs_mp (fst first_fun) in
let this_block_funs =
Array.map (fun (c, _) -> (c, snd first_fun)) this_block_funs_indexes
in
let funs_indexes =
let this_block_funs_indexes = Array.to_list this_block_funs_indexes in
let eq c1 c2 = Environ.QConstant.equal env c1 c2 in
List.map
(function cst -> List.assoc_f eq (fst cst) this_block_funs_indexes)
funs
in
let ind_list =
List.map
(fun idx ->
let ind = (first_fun_kn, idx) in
((ind, EConstr.EInstance.make @@ snd first_fun), true, EConstr.ESorts.prop))
funs_indexes
in
let sigma, schemes = Indrec.build_mutual_induction_scheme env !evd ind_list in
let _ = evd := sigma in
let l_schemes =
List.map
(Retyping.get_type_of env sigma
%> EConstr.Unsafe.to_constr )
schemes
in
let i = ref (-1) in
let sorts =
List.rev_map
(fun (_, x) ->
let sigma, fs = Evd.fresh_sort_in_family !evd x in
evd := sigma;
fs)
fas
in
let first_type, other_princ_types =
match l_schemes with
| s :: l_schemes -> (s, l_schemes)
| _ -> CErrors.anomaly (Pp.str "")
in
let opaque =
let finfos =
match find_Function_infos (fst first_fun) with
| None -> raise Not_found
| Some finfos -> finfos
in
match finfos.equation_lemma with
| None -> Vernacexpr.Transparent
| Some equation ->
if Declareops.is_opaque (Global.lookup_constant equation) then
Vernacexpr.Opaque
else Vernacexpr.Transparent
in
let body, typ, univs, _hook, sigma0 =
try
build_functional_principle (Global.env ()) !evd first_type (Array.of_list sorts)
this_block_funs 0
(Functional_principles_proofs.prove_princ_for_struct evd false 0
(Array.of_list (List.map fst funs)))
(fun _ _ -> ())
with e when CErrors.noncritical e -> raise (Defining_principle e)
in
evd := sigma0;
incr i;
if List.is_empty other_princ_types then [(body, typ, univs, opaque)]
else
let other_fun_princ_types =
let funs = Array.map Constr.mkConstU this_block_funs in
let sorts = Array.of_list sorts in
let sorts = Array.map (fun s -> EConstr.ESorts.kind sigma s) sorts in
List.map
(Functional_principles_types.compute_new_princ_type_from_rel (Global.env ()) funs sorts)
other_princ_types
in
let first_princ_body = body in
let ctxt, fix = Term.decompose_lambda_decls first_princ_body in
let (idxs, _), ((_, ta, _) as decl) = Constr.destFix fix in
let other_result =
List.map
(fun scheme_type ->
incr i;
observe (Printer.pr_lconstr_env env sigma scheme_type);
let type_concl = Term.strip_prod_decls scheme_type in
let applied_f =
List.hd (List.rev (snd (Constr.decompose_app_list type_concl)))
in
let f = fst (Constr.decompose_app applied_f) in
try
Array.iteri
(fun j t ->
let t = Term.strip_prod_decls t in
let applied_g =
List.hd (List.rev (snd (Constr.decompose_app_list t)))
in
let g = fst (Constr.decompose_app applied_g) in
if Constr.equal f g then raise (Found_type j);
observe
Pp.(
Printer.pr_lconstr_env env sigma f
++ str " <> "
++ Printer.pr_lconstr_env env sigma g))
ta;
let body, typ, univs, _hook, sigma0 =
build_functional_principle (Global.env ()) !evd
(List.nth other_princ_types (!i - 1))
(Array.of_list sorts) this_block_funs !i
(Functional_principles_proofs.prove_princ_for_struct evd false
!i
(Array.of_list (List.map fst funs)))
(fun _ _ -> ())
in
evd := sigma0;
(body, typ, univs, opaque)
with Found_type i ->
let princ_body =
Term.it_mkLambda_or_LetIn (Constr.mkFix ((idxs, i), decl)) ctxt
in
(princ_body, Some scheme_type, univs, opaque))
other_fun_princ_types
in
(body, typ, univs, opaque) :: other_result
let derive_correctness (funs : Constr.pconstant list) (graphs : inductive list)
=
let open EConstr in
assert (funs <> []);
assert (graphs <> []);
let funs = Array.of_list funs and graphs = Array.of_list graphs in
let map (c, u) = mkConstU (c, EInstance.make u) in
let funs_constr = Array.map map funs in
funind_purify
(fun () ->
let env = Global.env () in
let evd = ref (Evd.from_env env) in
let graphs_constr = Array.map UnsafeMonomorphic.mkInd graphs in
let lemmas_types_infos =
Util.Array.map2_i
(fun i f_constr graph ->
let type_of_lemma_ctxt, type_of_lemma_concl, graph =
generate_type env evd false f_constr graph
in
let type_info = (type_of_lemma_ctxt, type_of_lemma_concl) in
graphs_constr.(i) <- graph;
let type_of_lemma =
EConstr.it_mkProd_or_LetIn type_of_lemma_concl type_of_lemma_ctxt
in
let sigma, _ = Typing.type_of env !evd type_of_lemma in
evd := sigma;
let type_of_lemma =
Reductionops.nf_zeta env !evd type_of_lemma
in
observe
Pp.(
str "type_of_lemma := "
++ Printer.pr_leconstr_env env !evd type_of_lemma);
(type_of_lemma, type_info))
funs_constr graphs_constr
in
let schemes =
try
if not (Int.equal (Array.length funs_constr) 1) then raise Not_found;
[|find_induction_principle env evd funs_constr.(0)|]
with Not_found ->
Array.of_list
(List.map
(fun (body, typ, _opaque, _univs) ->
(EConstr.of_constr body, EConstr.of_constr (Option.get typ)))
(make_scheme evd
(Array.map_to_list (fun const -> (const, Sorts.InType)) funs)))
in
let proving_tac =
prove_fun_correct !evd graphs_constr schemes lemmas_types_infos
in
Array.iteri
(fun i f_as_constant ->
let f_id = Label.to_id (Constant.label (fst f_as_constant)) in
let lem_id = mk_correct_id f_id in
let typ, _ = lemmas_types_infos.(i) in
let info = Declare.Info.make () in
let cinfo = Declare.CInfo.make ~name:lem_id ~typ () in
let lemma = Declare.Proof.start ~cinfo ~info !evd in
let lemma = fst @@ Declare.Proof.by (proving_tac i) lemma in
let (_ : _ list) =
Declare.Proof.save_regular ~proof:lemma
~opaque:Vernacexpr.Transparent ~idopt:None
in
let finfo =
match find_Function_infos (fst f_as_constant) with
| None -> raise Not_found
| Some finfo -> finfo
in
let _, lem_cst_constr =
Evd.fresh_global (Global.env ()) !evd
(Option.get (Constrintern.locate_reference (Libnames.qualid_of_ident lem_id)))
in
let lem_cst, _ = EConstr.destConst !evd lem_cst_constr in
update_Function {finfo with correctness_lemma = Some lem_cst})
funs;
let env = Global.env () in
let lemmas_types_infos =
Util.Array.map2_i
(fun i f_constr graph ->
let type_of_lemma_ctxt, type_of_lemma_concl, graph =
generate_type env evd true f_constr graph
in
let type_info = (type_of_lemma_ctxt, type_of_lemma_concl) in
graphs_constr.(i) <- graph;
let type_of_lemma =
EConstr.it_mkProd_or_LetIn type_of_lemma_concl type_of_lemma_ctxt
in
let type_of_lemma = Reductionops.nf_zeta env !evd type_of_lemma in
observe
Pp.(
str "type_of_lemma := "
++ Printer.pr_leconstr_env env !evd type_of_lemma);
(type_of_lemma, type_info))
funs_constr graphs_constr
in
let ((kn, _) as graph_ind), u = destInd !evd graphs_constr.(0) in
let mib, _mip = Inductive.lookup_mind_specif env graph_ind in
let sigma, scheme =
let sigma, inds = CArray.fold_left_map_i (fun i sigma _ ->
let sigma, s = Evd.fresh_sort_in_family ~rigid:UnivRigid sigma InType in
sigma, (((kn, i), u), true, s))
!evd
mib.mind_packets
in
Indrec.build_mutual_induction_scheme env sigma
(Array.to_list inds)
in
let schemes = Array.map_of_list EConstr.Unsafe.to_constr scheme in
let proving_tac =
prove_fun_complete funs_constr mib.Declarations.mind_packets schemes
lemmas_types_infos
in
Array.iteri
(fun i f_as_constant ->
let f_id = Label.to_id (Constant.label (fst f_as_constant)) in
let lem_id = mk_complete_id f_id in
let info = Declare.Info.make () in
let cinfo =
Declare.CInfo.make ~name:lem_id ~typ:(fst lemmas_types_infos.(i)) ()
in
let lemma = Declare.Proof.start ~cinfo sigma ~info in
let lemma =
fst
(Declare.Proof.by
(observe_tac
("prove completeness (" ^ Id.to_string f_id ^ ")")
(proving_tac i))
lemma)
in
let (_ : _ list) =
Declare.Proof.save_regular ~proof:lemma
~opaque:Vernacexpr.Transparent ~idopt:None
in
let finfo =
match find_Function_infos (fst f_as_constant) with
| None -> raise Not_found
| Some finfo -> finfo
in
let _, lem_cst_constr =
Evd.fresh_global (Global.env ()) !evd
(Option.get (Constrintern.locate_reference (Libnames.qualid_of_ident lem_id)))
in
let lem_cst, _ = destConst !evd lem_cst_constr in
update_Function {finfo with completeness_lemma = Some lem_cst})
funs)
()
let warn_funind_cannot_build_inversion =
CWarnings.create ~name:"funind-cannot-build-inversion" ~category:CWarnings.CoreCategories.funind
Pp.(
fun e' ->
strbrk "Cannot build inversion information"
++ if do_observe () then fnl () ++ CErrors.print e' else mt ())
let derive_inversion env fix_names =
try
let evd' = Evd.from_env env in
let evd', fix_names_as_constant =
List.fold_right
(fun id (evd, l) ->
let evd, c =
Evd.fresh_global env evd
(Option.get (Constrintern.locate_reference (Libnames.qualid_of_ident id)))
in
let cst, u = EConstr.destConst evd c in
(evd, (cst, EConstr.EInstance.kind evd u) :: l))
fix_names (evd', [])
in
List.iter
(fun c -> ignore (find_Function_infos (fst c)))
fix_names_as_constant;
try
let _evd', lind =
List.fold_right
(fun id (evd, l) ->
let evd, id =
Evd.fresh_global env evd
(Option.get (Constrintern.locate_reference
(Libnames.qualid_of_ident (mk_rel_id id))))
in
(evd, fst (EConstr.destInd evd id) :: l))
fix_names (evd', [])
in
derive_correctness fix_names_as_constant lind
with e when CErrors.noncritical e -> warn_funind_cannot_build_inversion e
with e when CErrors.noncritical e -> warn_funind_cannot_build_inversion e
let register_wf interactive_proof ?(is_mes = false) fname rec_impls wf_rel_expr
wf_arg using_lemmas args ret_type body pre_hook =
let type_of_f = Constrexpr_ops.mkCProdN args ret_type in
let rec_arg_num =
let names =
List.map
CAst.(with_val (fun x -> x))
(Constrexpr_ops.names_of_local_assums args)
in
List.index Name.equal (Name wf_arg) names
in
let unbounded_eq =
let f_app_args =
CAst.make
@@ Constrexpr.CAppExpl
( (Libnames.qualid_of_ident fname, None)
, List.map
(function
| {CAst.v = Anonymous} -> assert false
| {CAst.v = Name e} -> Constrexpr_ops.mkIdentC e)
(Constrexpr_ops.names_of_local_assums args) )
in
CAst.make
@@ Constrexpr.CApp
( Constrexpr_ops.mkRefC (Libnames.qualid_of_string "Logic.eq")
, [(f_app_args, None); (body, None)] )
in
let eq = Constrexpr_ops.mkCProdN args unbounded_eq in
let hook ((f_ref, _) as fconst) tcc_lemma_ref (functional_ref, _) (eq_ref, _)
rec_arg_num rec_arg_type _nb_args relation =
try
pre_hook [fconst]
(generate_correction_proof_wf f_ref tcc_lemma_ref is_mes functional_ref
eq_ref rec_arg_num rec_arg_type relation);
derive_inversion (Global.env ()) [fname]
with e when CErrors.noncritical e ->
()
in
Recdef.recursive_definition ~interactive_proof ~is_mes fname rec_impls
type_of_f wf_rel_expr rec_arg_num eq hook using_lemmas
let register_mes interactive_proof fname rec_impls wf_mes_expr wf_rel_expr_opt
wf_arg using_lemmas args ret_type body =
let wf_arg_type, wf_arg =
match wf_arg with
| None -> (
match args with
| [Constrexpr.CLocalAssum ([{CAst.v = Name x}], _, _k, t)] -> (t, x)
| _ -> CErrors.user_err (Pp.str "Recursive argument must be specified") )
| Some wf_args -> (
try
match
List.find
(function
| Constrexpr.CLocalAssum (l, _, _k, t) ->
List.exists
(function
| {CAst.v = Name id} -> Id.equal id wf_args | _ -> false)
l
| _ -> false)
args
with
| Constrexpr.CLocalAssum (_, _, _k, t) -> (t, wf_args)
| _ -> assert false
with Not_found -> assert false )
in
let wf_rel_from_mes, is_mes =
match wf_rel_expr_opt with
| None ->
let ltof =
let make_dir l = DirPath.make (List.rev_map Id.of_string l) in
Libnames.qualid_of_path
(Libnames.make_path
(make_dir ["Arith"; "Wf_nat"])
(Id.of_string "ltof"))
in
let fun_from_mes =
let applied_mes =
Constrexpr_ops.mkAppC (wf_mes_expr, [Constrexpr_ops.mkIdentC wf_arg])
in
Constrexpr_ops.mkLambdaC
( [CAst.make @@ Name wf_arg]
, Constrexpr_ops.default_binder_kind
, wf_arg_type
, applied_mes )
in
let wf_rel_from_mes =
Constrexpr_ops.mkAppC
(Constrexpr_ops.mkRefC ltof, [wf_arg_type; fun_from_mes])
in
(wf_rel_from_mes, true)
| Some wf_rel_expr ->
let wf_rel_with_mes =
let a = Names.Id.of_string "___a" in
let b = Names.Id.of_string "___b" in
Constrexpr_ops.mkLambdaC
( [CAst.make @@ Name a; CAst.make @@ Name b]
, Constrexpr.Default Glob_term.Explicit
, wf_arg_type
, Constrexpr_ops.mkAppC
( wf_rel_expr
, [ Constrexpr_ops.mkAppC
(wf_mes_expr, [Constrexpr_ops.mkIdentC a])
; Constrexpr_ops.mkAppC
(wf_mes_expr, [Constrexpr_ops.mkIdentC b]) ] ) )
in
(wf_rel_with_mes, false)
in
register_wf interactive_proof ~is_mes fname rec_impls wf_rel_from_mes wf_arg
using_lemmas args ret_type body
let do_generate_principle_aux pconstants on_error register_built
interactive_proof (rec_order, fixpoint_exprl as fix) : Declare.Proof.t option =
List.iter
(fun {Vernacexpr.notations} ->
if not (List.is_empty notations) then
CErrors.user_err (Pp.str "Function does not support notations for now"))
fixpoint_exprl;
let lemma, _is_struct =
match rec_order with
| [ Some { CAst.v = Constrexpr.CWfRec (wf_x, wf_rel) } ] ->
let ( {Vernacexpr.fname; univs = _; binders; rtype; body_def} as
fixpoint_expr ) =
match recompute_binder_list fix with
| [e] -> e
| _ -> assert false
in
let fixpoint_exprl = [fixpoint_expr] in
let body =
match body_def with
| Some body -> body
| None ->
CErrors.user_err
(Pp.str "Body of Function must be given.")
in
let recdefs, rec_impls = build_newrecursive fixpoint_exprl in
let using_lemmas = [] in
let pre_hook pconstants =
generate_principle
(ref (Evd.from_env (Global.env ())))
pconstants on_error true register_built fixpoint_exprl recdefs
in
if register_built then
( register_wf interactive_proof fname.CAst.v rec_impls wf_rel
wf_x.CAst.v using_lemmas binders rtype body pre_hook
, false )
else (None, false)
| [ Some { CAst.v = Constrexpr.CMeasureRec (wf_x, wf_mes, wf_rel_opt) } ] ->
let ( {Vernacexpr.fname; univs = _; binders; rtype; body_def} as
fixpoint_expr ) =
match recompute_binder_list fix with
| [e] -> e
| _ -> assert false
in
let fixpoint_exprl = [fixpoint_expr] in
let recdefs, rec_impls = build_newrecursive fixpoint_exprl in
let using_lemmas = [] in
let body =
match body_def with
| Some body -> body
| None ->
CErrors.user_err
Pp.(str "Body of Function must be given.")
in
let pre_hook pconstants =
generate_principle
(ref (Evd.from_env (Global.env ())))
pconstants on_error true register_built fixpoint_exprl recdefs
in
if register_built then
( register_mes interactive_proof fname.CAst.v rec_impls wf_mes wf_rel_opt
(Option.map (fun x -> x.CAst.v) wf_x)
using_lemmas binders rtype body pre_hook
, true )
else (None, true)
| _ ->
List.iter
(function
| Some { CAst.v = (Constrexpr.CMeasureRec _ | Constrexpr.CWfRec _) } ->
CErrors.user_err
(Pp.str
"Cannot use mutual definition with well-founded recursion \
or measure")
| _ -> () )
rec_order;
let fixpoint_exprl = recompute_binder_list fix in
let fix_names =
List.map (function {Vernacexpr.fname} -> fname.CAst.v) fixpoint_exprl
in
let recdefs, _rec_impls = build_newrecursive fixpoint_exprl in
let is_rec = List.exists (is_rec fix_names) recdefs in
let lemma, evd, pconstants =
if register_built then register_struct is_rec (rec_order, fixpoint_exprl)
else (None, Evd.from_env (Global.env ()), pconstants)
in
let evd = ref evd in
generate_principle (ref !evd) pconstants on_error false register_built
fixpoint_exprl recdefs
(Functional_principles_proofs.prove_princ_for_struct evd
interactive_proof);
if register_built then derive_inversion (Global.env ()) fix_names;
(lemma, true)
in
lemma
let warn_cannot_define_graph =
CWarnings.create ~name:"funind-cannot-define-graph" ~category:CWarnings.CoreCategories.funind
(fun (names, error) ->
Pp.(strbrk "Cannot define graph(s) for " ++ hv 1 names ++ error))
let warn_cannot_define_principle =
CWarnings.create ~name:"funind-cannot-define-principle" ~category:CWarnings.CoreCategories.funind
(fun (names, error) ->
Pp.(
strbrk "Cannot define induction principle(s) for " ++ hv 1 names ++ error))
let warning_error names e =
let e_explain e =
match e with
| ToShow e -> Pp.(spc () ++ CErrors.print e)
| _ -> if do_observe () then Pp.(spc () ++ CErrors.print e) else Pp.mt ()
in
match e with
| Building_graph e ->
let names =
Pp.(prlist_with_sep (fun _ -> str "," ++ spc ()) Ppconstr.pr_id names)
in
warn_cannot_define_graph (names, e_explain e)
| Defining_principle e ->
let names =
Pp.(prlist_with_sep (fun _ -> str "," ++ spc ()) Ppconstr.pr_id names)
in
warn_cannot_define_principle (names, e_explain e)
| _ -> raise e
let error_error names e =
let e_explain e =
match e with
| ToShow e -> Pp.(spc () ++ CErrors.print e)
| _ -> if do_observe () then Pp.(spc () ++ CErrors.print e) else Pp.mt ()
in
match e with
| Building_graph e ->
CErrors.user_err
Pp.(
str "Cannot define graph(s) for "
++ hv 1
(prlist_with_sep (fun _ -> str "," ++ spc ()) Ppconstr.pr_id names)
++ e_explain e)
| _ -> raise e
let rec chop_n_arrow n t =
let exception Stop of Constrexpr.constr_expr in
let open Constrexpr in
if n <= 0 then t
else
match t.CAst.v with
| Constrexpr.CProdN (nal_ta', t') -> (
try
let new_n =
let rec aux (n : int) = function
| [] -> n
| CLocalAssum (nal, _, k, t'') :: nal_ta' ->
let nal_l = List.length nal in
if n >= nal_l then aux (n - nal_l) nal_ta'
else
let new_t' =
CAst.make
@@ Constrexpr.CProdN
( CLocalAssum (snd (List.chop n nal), None, k, t'') :: nal_ta'
, t' )
in
raise (Stop new_t')
| _ -> CErrors.anomaly (Pp.str "Not enough products.")
in
aux n nal_ta'
in
chop_n_arrow new_n t'
with Stop t -> t )
| _ -> CErrors.anomaly (Pp.str "Not enough products.")
let rec add_args id new_args =
let open Libnames in
let open Constrexpr in
CAst.map (function
| CRef (qid, _) as b ->
if qualid_is_ident qid && Id.equal (qualid_basename qid) id then
CAppExpl ((qid, None), new_args)
else b
| CFix _ | CCoFix _ -> CErrors.anomaly ~label:"add_args " (Pp.str "todo.")
| CProdN (nal, b1) ->
CProdN
( List.map
(function
| CLocalAssum (nal, r, k, b2) ->
CLocalAssum (nal, r, k, add_args id new_args b2)
| CLocalDef (na, r, b1, t) ->
CLocalDef
( na, r
, add_args id new_args b1
, Option.map (add_args id new_args) t )
| CLocalPattern _ ->
CErrors.user_err (Pp.str "pattern with quote not allowed here."))
nal
, add_args id new_args b1 )
| CLambdaN (nal, b1) ->
CLambdaN
( List.map
(function
| CLocalAssum (nal, r, k, b2) ->
CLocalAssum (nal, r, k, add_args id new_args b2)
| CLocalDef (na, r, b1, t) ->
CLocalDef
( na, r
, add_args id new_args b1
, Option.map (add_args id new_args) t )
| CLocalPattern _ ->
CErrors.user_err (Pp.str "pattern with quote not allowed here."))
nal
, add_args id new_args b1 )
| CLetIn (na, b1, t, b2) ->
CLetIn
( na
, add_args id new_args b1
, Option.map (add_args id new_args) t
, add_args id new_args b2 )
| CAppExpl ((qid, us), exprl) ->
if qualid_is_ident qid && Id.equal (qualid_basename qid) id then
CAppExpl
((qid, us), new_args @ List.map (add_args id new_args) exprl)
else CAppExpl ((qid, us), List.map (add_args id new_args) exprl)
| CApp (b, bl) ->
CApp
( add_args id new_args b
, List.map (fun (e, o) -> (add_args id new_args e, o)) bl )
| CProj (expl, f, bl, b) ->
CProj
(expl, f
, List.map (fun (e, o) -> (add_args id new_args e, o)) bl
, add_args id new_args b)
| CCases (sty, b_option, cel, cal) ->
CCases
( sty
, Option.map (add_args id new_args) b_option
, List.map
(fun (b, na, b_option) -> (add_args id new_args b, na, b_option))
cel
, List.map
CAst.(map (fun (cpl, e) -> (cpl, add_args id new_args e)))
cal )
| CLetTuple (nal, (na, b_option), b1, b2) ->
CLetTuple
( nal
, (na, Option.map (add_args id new_args) b_option)
, add_args id new_args b1
, add_args id new_args b2 )
| CIf (b1, (na, b_option), b2, b3) ->
CIf
( add_args id new_args b1
, (na, Option.map (add_args id new_args) b_option)
, add_args id new_args b2
, add_args id new_args b3 )
| (CHole _ | CGenarg _ | CGenargGlob _ | CPatVar _ | CEvar _ | CPrim _ | CSort _) as b -> b
| CCast (b1, k, b2) ->
CCast (add_args id new_args b1, k, add_args id new_args b2)
| CRecord pars ->
CRecord (List.map (fun (e, o) -> (e, add_args id new_args o)) pars)
| CNotation _ -> CErrors.anomaly ~label:"add_args " (Pp.str "CNotation.")
| CGeneralization _ ->
CErrors.anomaly ~label:"add_args " (Pp.str "CGeneralization.")
| CDelimiters _ ->
CErrors.anomaly ~label:"add_args " (Pp.str "CDelimiters.")
| CArray _ -> CErrors.anomaly ~label:"add_args " (Pp.str "CArray."))
let rec get_args b t :
Constrexpr.local_binder_expr list
* Constrexpr.constr_expr
* Constrexpr.constr_expr =
let open Constrexpr in
match b.CAst.v with
| Constrexpr.CLambdaN ((CLocalAssum (nal, _, k, ta) as d) :: rest, b') ->
let n = List.length nal in
let nal_tas, b'', t'' =
get_args
(CAst.make ?loc:b.CAst.loc @@ Constrexpr.CLambdaN (rest, b'))
(chop_n_arrow n t)
in
(d :: nal_tas, b'', t'')
| Constrexpr.CLambdaN ([], b) -> ([], b, t)
| _ -> ([], b, t)
let make_graph (f_ref : GlobRef.t) =
let open Constrexpr in
let env = Global.env () in
let sigma = Evd.from_env env in
let c, c_body =
match f_ref with
| GlobRef.ConstRef c ->
if Environ.mem_constant c env then (c, Environ.lookup_constant c env) else
CErrors.user_err
Pp.(
str "Cannot find "
++ Termops.pr_global_env env (ConstRef c))
| _ -> CErrors.user_err Pp.(str "Not a function reference")
in
match c_body.Declarations.const_body with
| Undef _ | Primitive _ | Symbol _ | OpaqueDef _ -> CErrors.user_err (Pp.str "Cannot build a graph over an axiom!")
| Def body ->
let extern_body, extern_type =
with_full_print
(fun () ->
( Constrextern.extern_constr env sigma (EConstr.of_constr body)
, Constrextern.extern_type env sigma
(EConstr.of_constr c_body.Declarations.const_type) ))
()
in
let nal_tas, b, t = get_args extern_body extern_type in
let expr_list =
match b.CAst.v with
| Constrexpr.CFix (l_id, fixexprl) ->
let l =
List.map
(fun (id, _, recexp, bl, t, b) ->
let {CAst.loc; v = rec_id} =
match Option.get recexp with
| {CAst.v = CStructRec id} -> id
| {CAst.v = CWfRec (id, _)} -> id
| {CAst.v = CMeasureRec (oid, _, _)} -> Option.get oid
in
let new_args =
List.flatten
(List.map
(function
| Constrexpr.CLocalDef (na, _, _, _) -> []
| Constrexpr.CLocalAssum (nal, _, _, _) ->
List.map
(fun {CAst.loc; v = n} ->
CAst.make ?loc
@@ CRef
( Libnames.qualid_of_ident ?loc
@@ Nameops.Name.get_id n
, None ))
nal
| Constrexpr.CLocalPattern _ -> assert false)
nal_tas)
in
let b' = add_args id.CAst.v new_args b in
Some (CAst.make (CStructRec (CAst.make rec_id))),
{ Vernacexpr.fname = id
; univs = None
; binders = nal_tas @ bl
; rtype = t
; body_def = Some b'
; notations = [] })
fixexprl
in
l
| _ ->
let fname = CAst.make (Label.to_id (Constant.label c)) in
[ None, { Vernacexpr.fname
; univs = None
; binders = nal_tas
; rtype = t
; body_def = Some b
; notations = [] } ]
in
let mp = Constant.modpath c in
let expr_list = List.split expr_list in
let pstate =
do_generate_principle_aux [(c, UVars.Instance.empty)] error_error false
false expr_list
in
assert (Option.is_empty pstate);
List.iter
(fun {Vernacexpr.fname = {CAst.v = id}} ->
add_Function false (Constant.make2 mp (Label.of_id id)))
(snd expr_list)
let do_generate_principle_interactive fixl : Declare.Proof.t =
match do_generate_principle_aux [] warning_error true true fixl with
| Some lemma -> lemma
| None ->
CErrors.anomaly (Pp.str "indfun: leaving no open proof in interactive mode")
let do_generate_principle fixl : unit =
match do_generate_principle_aux [] warning_error true false fixl with
| Some _lemma ->
CErrors.anomaly
(Pp.str "indfun: leaving a goal open in non-interactive mode")
| None -> ()
let build_scheme fas =
let env = Global.env () in
let evd = ref (Evd.from_env env) in
let pconstants =
List.map
(fun (_, f, sort) ->
let f_as_constant =
try Smartlocate.global_with_alias f
with Not_found ->
CErrors.user_err
Pp.(str "Cannot find " ++ Libnames.pr_qualid f ++ str ".")
in
let evd', f = Evd.fresh_global env !evd f_as_constant in
let _ = evd := evd' in
let sigma, _ = Typing.type_of ~refresh:true env !evd f in
evd := sigma;
let c, u =
try EConstr.destConst !evd f
with Constr.DestKO ->
CErrors.user_err
Pp.(
Printer.pr_econstr_env env !evd f
++ spc ()
++ str "should be the named of a globally defined function")
in
((c, EConstr.EInstance.kind !evd u), sort))
fas
in
let bodies_types = make_scheme evd pconstants in
List.iter2
(fun (princ_id, _, _) (body, types, univs, opaque) ->
let (_ : Constant.t) =
let opaque = if opaque = Vernacexpr.Opaque then true else false in
let def_entry = Declare.definition_entry ~univs ~opaque ?types body in
Declare.declare_constant ~name:princ_id
~kind:Decls.(IsProof Theorem)
(Declare.DefinitionEntry def_entry)
in
Declare.definition_message princ_id)
fas bodies_types
let build_case_scheme fa =
let env = Global.env () in
let sigma = Evd.from_env env in
let funs =
let _, f, _ = fa in
try
let open GlobRef in
match Smartlocate.global_with_alias f with
| ConstRef c -> c
| IndRef _ | ConstructRef _ | VarRef _ -> assert false
with Not_found ->
CErrors.user_err
Pp.(str "Cannot find " ++ Libnames.pr_qualid f ++ str ".")
in
let sigma, (_, u) = Evd.fresh_constant_instance env sigma funs in
let first_fun = funs in
let funs_mp = Constant.modpath first_fun in
let first_fun_kn =
match find_Function_infos first_fun with
| None -> raise No_graph_found
| Some finfos -> fst finfos.graph_ind
in
let this_block_funs_indexes = get_funs_constant funs_mp first_fun in
let this_block_funs =
Array.map (fun (c, _) -> (c, u)) this_block_funs_indexes
in
let funs_indexes =
let this_block_funs_indexes = Array.to_list this_block_funs_indexes in
let eq c1 c2 = Environ.QConstant.equal env c1 c2 in
List.assoc_f eq funs this_block_funs_indexes
in
let ind, sf =
let ind = (first_fun_kn, funs_indexes) in
((ind, EConstr.EInstance.empty) , EConstr.ESorts.prop)
in
let sigma, scheme =
Indrec.build_case_analysis_scheme_default env sigma ind sf
in
let scheme, scheme_type = Indrec.eval_case_analysis scheme in
let sorts = (fun (_, _, x) -> EConstr.ESorts.make @@ fst @@ UnivGen.fresh_sort_in_family x) fa in
let princ_name = (fun (x, _, _) -> x) fa in
let (_ : unit) =
generate_functional_principle
(ref (Evd.from_env (Global.env ())))
(EConstr.Unsafe.to_constr scheme_type)
(Some [|sorts|])
(Some princ_name) this_block_funs 0
(Functional_principles_proofs.prove_princ_for_struct
(ref (Evd.from_env (Global.env ())))
false 0 [|funs|])
in
()