Source file hints.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
open Pp
open Util
open CErrors
open Names
open Constr
open Context
open Evd
open EConstr
open Vars
open Environ
open Mod_subst
open Globnames
open Libobject
open Namegen
open Libnames
open Termops
open Inductiveops
open Typeclasses
open Pattern
open Patternops
open Clenv
open Tacred
open Printer
module NamedDecl = Context.Named.Declaration
type debug = Debug | Info | Off
exception Bound
let rec head_bound sigma t = match EConstr.kind sigma t with
| Prod (_, _, b) -> head_bound sigma b
| LetIn (_, _, _, b) -> head_bound sigma b
| App (c, _) -> head_bound sigma c
| Case (_, _, _, _, _, c, _) -> head_bound sigma c
| Ind (ind, _) -> GlobRef.IndRef ind
| Const (c, _) -> GlobRef.ConstRef c
| Construct (c, _) -> GlobRef.ConstructRef c
| Var id -> GlobRef.VarRef id
| Proj (p, _) -> GlobRef.ConstRef (Projection.constant p)
| Cast (c, _, _) -> head_bound sigma c
| Evar _ | Rel _ | Meta _ | Sort _ | Fix _ | Lambda _
| CoFix _ | Int _ | Float _ | Array _ -> raise Bound
let head_constr sigma c =
try head_bound sigma c
with Bound -> user_err (Pp.str "Head identifier must be a constant, section variable, \
(co)inductive type, (co)inductive type constructor, or projection.")
let decompose_app_bound sigma t =
let t = strip_outer_cast sigma t in
let _,ccl = decompose_prod_assum sigma t in
let hd,args = decompose_app_vect sigma ccl in
let open GlobRef in
match EConstr.kind sigma hd with
| Const (c,u) -> ConstRef c, args
| Ind (i,u) -> IndRef i, args
| Construct (c,u) -> ConstructRef c, args
| Var id -> VarRef id, args
| Proj (p, c) -> ConstRef (Projection.constant p), Array.cons c args
| _ -> raise Bound
(** Compute the set of section variables that remain in the named context.
Starts from the top to the bottom of the context, stops at the first
different declaration between the named hyps and the section context. *)
let secvars_of_hyps hyps =
let secctx = Global.named_context () in
let open Context.Named.Declaration in
let pred, all =
List.fold_left (fun (pred,all) decl ->
try let _ = Context.Named.lookup (get_id decl) hyps in
(Id.Pred.add (get_id decl) pred, all)
with Not_found -> (pred, false))
(Id.Pred.empty,true) secctx
in
if all then Id.Pred.full
else pred
let empty_hint_info =
{ hint_priority = None; hint_pattern = None }
type 'a hint_ast =
| Res_pf of 'a
| ERes_pf of 'a
| Give_exact of 'a
| Res_pf_THEN_trivial_fail of 'a
| Unfold_nth of evaluable_global_reference
| Extern of Pattern.constr_pattern option * Genarg.glob_generic_argument
type 'a hints_path_atom_gen =
| PathHints of 'a list
| PathAny
type hints_path_atom = GlobRef.t hints_path_atom_gen
type 'a hints_path_gen =
| PathAtom of 'a hints_path_atom_gen
| PathStar of 'a hints_path_gen
| PathSeq of 'a hints_path_gen * 'a hints_path_gen
| PathOr of 'a hints_path_gen * 'a hints_path_gen
| PathEmpty
| PathEpsilon
type pre_hints_path = Libnames.qualid hints_path_gen
type hints_path = GlobRef.t hints_path_gen
type hint_term =
| IsGlobRef of GlobRef.t
| IsConstr of constr * Univ.ContextSet.t option
type 'a with_uid = {
obj : 'a;
uid : KerName.t;
}
type raw_hint = constr * types * Univ.ContextSet.t option
type hint = {
hint_term : constr;
hint_type : types;
hint_uctx : Univ.ContextSet.t option;
hint_clnv : clausenv;
}
type 'a with_metadata =
{ pri : int
(** A number lower is higher priority *)
; pat : constr_pattern option
(** A pattern for the concl of the Goal *)
; name : hints_path_atom
(** A potential name to refer to the hint *)
; db : string option
(** The database from which the hint comes *)
; secvars : Id.Pred.t
(** The set of section variables the hint depends on *)
; code : 'a
(** the tactic to apply when the concl matches pat *)
}
type full_hint = hint hint_ast with_uid with_metadata
type hint_entry = GlobRef.t option *
raw_hint hint_ast with_uid with_metadata
type hint_mode =
| ModeInput
| ModeNoHeadEvar
| ModeOutput
type 'a hints_transparency_target =
| HintsVariables
| HintsConstants
| HintsReferences of 'a list
type import_level = HintLax | HintWarn | HintStrict
let hint_as_term h = (h.hint_uctx, h.hint_term)
let warn_hint_to_string = function
| HintLax -> "Lax"
| HintWarn -> "Warn"
| HintStrict -> "Strict"
let string_to_warn_hint = function
| "Lax" -> HintLax
| "Warn" -> HintWarn
| "Strict" -> HintStrict
| _ -> user_err Pp.(str "Only the following values are accepted: Lax, Warn, Strict.")
let warn_hint =
Goptions.declare_interpreted_string_option_and_ref
~depr:false
~key:["Loose"; "Hint"; "Behavior"]
~value:HintLax
string_to_warn_hint
warn_hint_to_string
let fresh_key =
let id = Summary.ref ~name:"HINT-COUNTER" 0 in
fun () ->
let cur = incr id; !id in
let lbl = Id.of_string ("_" ^ string_of_int cur) in
let kn = Lib.make_kn lbl in
let (mp, _) = KerName.repr kn in
let lbl = Id.of_string_soft (Printf.sprintf "%s#%i"
(ModPath.to_string mp) cur)
in
KerName.make mp (Label.of_id lbl)
let pri_order_int (id1, {pri=pri1}) (id2, {pri=pri2}) =
let d = pri1 - pri2 in
if Int.equal d 0 then id2 - id1
else d
let pri_order t1 t2 = pri_order_int t1 t2 <= 0
type stored_data = int * full_hint
module Bounded_net :
sig
type t
val empty : TransparentState.t option -> t
val add : t -> Pattern.constr_pattern -> stored_data -> t
val lookup : Environ.env -> Evd.evar_map -> t -> EConstr.constr -> stored_data list
end =
struct
module Data = struct type t = stored_data let compare = pri_order_int end
module Bnet = Btermdn.Make(Data)
type diff = Pattern.constr_pattern * stored_data
type data = Bnet of (TransparentState.t option * Bnet.t) | Diff of diff * data ref
type t = data ref
let empty st = ref (Bnet (st, Bnet.empty))
let add net p v = ref (Diff ((p, v), net))
let rec force env net = match !net with
| Bnet dn -> dn
| Diff ((p, v), rem) ->
let st, dn = force env rem in
let p = Bnet.pattern env st p in
let dn = Bnet.add dn p v in
let () = net := (Bnet (st, dn)) in
st, dn
let lookup env sigma net p =
let st, dn = force env net in
Bnet.lookup env sigma st dn p
end
type search_entry = {
sentry_nopat : stored_data list;
sentry_pat : stored_data list;
sentry_bnet : Bounded_net.t;
sentry_mode : hint_mode array list;
}
let empty_se st = {
sentry_nopat = [];
sentry_pat = [];
sentry_bnet = Bounded_net.empty st;
sentry_mode = [];
}
let eq_pri_auto_tactic (_, x) (_, y) = KerName.equal x.code.uid y.code.uid
let add_tac pat t se =
match pat with
| None ->
if List.exists (eq_pri_auto_tactic t) se.sentry_nopat then se
else { se with sentry_nopat = List.insert pri_order t se.sentry_nopat }
| Some pat ->
if List.exists (eq_pri_auto_tactic t) se.sentry_pat then se
else { se with
sentry_pat = List.insert pri_order t se.sentry_pat;
sentry_bnet = Bounded_net.add se.sentry_bnet pat t; }
let rebuild_dn st se =
let dn' =
List.fold_left
(fun dn (id, t) ->
Bounded_net.add dn (Option.get t.pat) (id, t))
(Bounded_net.empty st) se.sentry_pat
in
{ se with sentry_bnet = dn' }
let lookup_tacs env sigma concl se =
let l' = Bounded_net.lookup env sigma se.sentry_bnet concl in
let sl' = List.stable_sort pri_order_int l' in
List.merge pri_order_int se.sentry_nopat sl'
let strip_params env sigma c =
match EConstr.kind sigma c with
| App (f, args) ->
(match EConstr.kind sigma f with
| Const (cst,_) ->
(match Structures.PrimitiveProjections.find_opt cst with
| Some p ->
let p = Projection.make p false in
let npars = Projection.npars p in
if Array.length args > npars then
mkApp (mkProj (p, args.(npars)),
Array.sub args (npars+1) (Array.length args - (npars + 1)))
else c
| None -> c)
| _ -> c)
| _ -> c
let merge_context_set_opt sigma ctx = match ctx with
| None -> sigma
| Some ctx -> Evd.merge_context_set Evd.univ_flexible sigma ctx
let instantiate_hint env sigma p =
let mk_clenv (c, cty, ctx) =
let sigma = merge_context_set_opt sigma ctx in
let cl = mk_clenv_from env sigma (c,cty) in
let templval = { cl.templval with rebus = strip_params env sigma cl.templval.rebus } in
let cl = mk_clausenv empty_env cl.evd templval cl.templtyp in
{ hint_term = c; hint_type = cty; hint_uctx = ctx; hint_clnv = cl; }
in
let code = match p.code.obj with
| Res_pf c -> Res_pf (mk_clenv c)
| ERes_pf c -> ERes_pf (mk_clenv c)
| Res_pf_THEN_trivial_fail c ->
Res_pf_THEN_trivial_fail (mk_clenv c)
| Give_exact c -> Give_exact (mk_clenv c)
| (Unfold_nth _ | Extern _) as h -> h
in
{ p with code = { p.code with obj = code } }
let hints_path_atom_eq h1 h2 = match h1, h2 with
| PathHints l1, PathHints l2 -> List.equal GlobRef.equal l1 l2
| PathAny, PathAny -> true
| _ -> false
let rec hints_path_eq h1 h2 = match h1, h2 with
| PathAtom h1, PathAtom h2 -> hints_path_atom_eq h1 h2
| PathStar h1, PathStar h2 -> hints_path_eq h1 h2
| PathSeq (l1, r1), PathSeq (l2, r2) ->
hints_path_eq l1 l2 && hints_path_eq r1 r2
| PathOr (l1, r1), PathOr (l2, r2) ->
hints_path_eq l1 l2 && hints_path_eq r1 r2
| PathEmpty, PathEmpty -> true
| PathEpsilon, PathEpsilon -> true
| _ -> false
let path_matches hp hints =
let rec aux hp hints k =
match hp, hints with
| PathAtom _, [] -> false
| PathAtom PathAny, (_ :: hints') -> k hints'
| PathAtom p, (h :: hints') ->
if hints_path_atom_eq p h then k hints' else false
| PathStar hp', hints ->
k hints || aux hp' hints (fun hints' -> aux hp hints' k)
| PathSeq (hp, hp'), hints ->
aux hp hints (fun hints' -> aux hp' hints' k)
| PathOr (hp, hp'), hints ->
aux hp hints k || aux hp' hints k
| PathEmpty, _ -> false
| PathEpsilon, hints -> k hints
in aux hp hints (fun hints' -> true)
let rec matches_epsilon = function
| PathAtom _ -> false
| PathStar _ -> true
| PathSeq (p, p') -> matches_epsilon p && matches_epsilon p'
| PathOr (p, p') -> matches_epsilon p || matches_epsilon p'
| PathEmpty -> false
| PathEpsilon -> true
let rec is_empty = function
| PathAtom _ -> false
| PathStar _ -> false
| PathSeq (p, p') -> is_empty p || is_empty p'
| PathOr (p, p') -> matches_epsilon p && matches_epsilon p'
| PathEmpty -> true
| PathEpsilon -> false
let path_seq p p' =
match p, p' with
| PathEpsilon, p' -> p'
| p, PathEpsilon -> p
| p, p' -> PathSeq (p, p')
let rec path_derivate hp hint =
let rec derivate_atoms hints hints' =
match hints, hints' with
| gr :: grs, gr' :: grs' when GlobRef.equal gr gr' -> derivate_atoms grs grs'
| [], [] -> PathEpsilon
| [], hints -> PathEmpty
| grs, [] -> PathAtom (PathHints grs)
| _, _ -> PathEmpty
in
match hp with
| PathAtom PathAny -> PathEpsilon
| PathAtom (PathHints grs) ->
(match grs, hint with
| h :: _, PathAny -> PathEmpty
| hints, PathHints hints' -> derivate_atoms hints hints'
| _, _ -> assert false)
| PathStar p -> if path_matches p [hint] then hp else PathEpsilon
| PathSeq (hp, hp') ->
let hpder = path_derivate hp hint in
if matches_epsilon hp then
PathOr (path_seq hpder hp', path_derivate hp' hint)
else if is_empty hpder then PathEmpty
else path_seq hpder hp'
| PathOr (hp, hp') ->
PathOr (path_derivate hp hint, path_derivate hp' hint)
| PathEmpty -> PathEmpty
| PathEpsilon -> PathEmpty
let rec normalize_path h =
match h with
| PathStar PathEpsilon -> PathEpsilon
| PathSeq (PathEmpty, _) | PathSeq (_, PathEmpty) -> PathEmpty
| PathSeq (PathEpsilon, p) | PathSeq (p, PathEpsilon) -> normalize_path p
| PathOr (PathEmpty, p) | PathOr (p, PathEmpty) -> normalize_path p
| PathOr (p, q) ->
let p', q' = normalize_path p, normalize_path q in
if hints_path_eq p p' && hints_path_eq q q' then h
else normalize_path (PathOr (p', q'))
| PathSeq (p, q) ->
let p', q' = normalize_path p, normalize_path q in
if hints_path_eq p p' && hints_path_eq q q' then h
else normalize_path (PathSeq (p', q'))
| _ -> h
let path_derivate hp hint = normalize_path (path_derivate hp hint)
let pp_hints_path_atom prg a =
match a with
| PathAny -> str"_"
| PathHints grs -> pr_sequence prg grs
let pp_hints_path_gen prg =
let rec aux = function
| PathAtom pa -> pp_hints_path_atom prg pa
| PathStar (PathAtom PathAny) -> str"_*"
| PathStar p -> str "(" ++ aux p ++ str")*"
| PathSeq (p, p') -> aux p ++ spc () ++ aux p'
| PathOr (p, p') ->
str "(" ++ aux p ++ spc () ++ str"|" ++ cut () ++ spc () ++
aux p' ++ str ")"
| PathEmpty -> str"emp"
| PathEpsilon -> str"eps"
in aux
let pp_hints_path = pp_hints_path_gen pr_global
let glob_hints_path_atom p =
match p with
| PathHints g -> PathHints (List.map Nametab.global g)
| PathAny -> PathAny
let glob_hints_path =
let rec aux = function
| PathAtom pa -> PathAtom (glob_hints_path_atom pa)
| PathStar p -> PathStar (aux p)
| PathSeq (p, p') -> PathSeq (aux p, aux p')
| PathOr (p, p') -> PathOr (aux p, aux p')
| PathEmpty -> PathEmpty
| PathEpsilon -> PathEpsilon
in aux
let subst_path_atom subst p =
match p with
| PathAny -> p
| PathHints grs ->
let gr' gr = fst (subst_global subst gr) in
let grs' = List.Smart.map gr' grs in
if grs' == grs then p else PathHints grs'
let rec subst_hints_path subst hp =
match hp with
| PathAtom p ->
let p' = subst_path_atom subst p in
if p' == p then hp else PathAtom p'
| PathStar p -> let p' = subst_hints_path subst p in
if p' == p then hp else PathStar p'
| PathSeq (p, q) ->
let p' = subst_hints_path subst p in
let q' = subst_hints_path subst q in
if p' == p && q' == q then hp else PathSeq (p', q')
| PathOr (p, q) ->
let p' = subst_hints_path subst p in
let q' = subst_hints_path subst q in
if p' == p && q' == q then hp else PathOr (p', q')
| _ -> hp
type hint_db_name = string
type mode_match =
| NoMode
| WithMode of hint_mode array
type 'a with_mode =
| ModeMatch of mode_match * 'a
| ModeMismatch
module Hint_db :
sig
type t
val empty : ?name:hint_db_name -> TransparentState.t -> bool -> t
val map_none : secvars:Id.Pred.t -> t -> full_hint list
val map_all : secvars:Id.Pred.t -> GlobRef.t -> t -> full_hint list
val map_eauto : Environ.env -> evar_map -> secvars:Id.Pred.t ->
(GlobRef.t * constr array) -> constr -> t -> full_hint list with_mode
val map_auto : Environ.env -> evar_map -> secvars:Id.Pred.t ->
(GlobRef.t * constr array) -> constr -> t -> full_hint list
val add_list : env -> evar_map -> hint_entry list -> t -> t
val remove_one : Environ.env -> GlobRef.t -> t -> t
val remove_list : Environ.env -> GlobRef.t list -> t -> t
val iter : (GlobRef.t option -> hint_mode array list -> full_hint list -> unit) -> t -> unit
val use_dn : t -> bool
val transparent_state : t -> TransparentState.t
val set_transparent_state : t -> TransparentState.t -> t
val add_cut : hints_path -> t -> t
val add_mode : GlobRef.t -> hint_mode array -> t -> t
val cut : t -> hints_path
val unfolds : t -> Id.Set.t * Cset.t
val add_modes : hint_mode array list GlobRef.Map.t -> t -> t
val modes : t -> hint_mode array list GlobRef.Map.t
val fold : (GlobRef.t option -> hint_mode array list -> full_hint list -> 'a -> 'a) ->
t -> 'a -> 'a
end =
struct
type t = {
hintdb_state : TransparentState.t;
hintdb_cut : hints_path;
hintdb_unfolds : Id.Set.t * Cset.t;
hintdb_max_id : int;
use_dn : bool;
hintdb_map : search_entry GlobRef.Map.t;
hintdb_nopat : (GlobRef.t option * stored_data) list;
hintdb_name : string option;
}
let next_hint_id db =
let h = db.hintdb_max_id in
{ db with hintdb_max_id = succ db.hintdb_max_id }, h
let empty ?name st use_dn = { hintdb_state = st;
hintdb_cut = PathEmpty;
hintdb_unfolds = (Id.Set.empty, Cset.empty);
hintdb_max_id = 0;
use_dn = use_dn;
hintdb_map = GlobRef.Map.empty;
hintdb_nopat = [];
hintdb_name = name; }
let dn_ts db = if db.use_dn then (Some db.hintdb_state) else None
let find key db =
try GlobRef.Map.find key db.hintdb_map
with Not_found -> empty_se (dn_ts db)
let realize_tac secvars (id,tac) =
if Id.Pred.subset tac.secvars secvars then Some tac
else
None
let head_evar sigma c =
let rec hrec c = match EConstr.kind sigma c with
| Evar (evk,_) -> evk
| App (c,_) -> hrec c
| Cast (c,_,_) -> hrec c
| _ -> raise Evarutil.NoHeadEvar
in
hrec c
let match_mode sigma m arg =
match m with
| ModeInput -> not (occur_existential sigma arg)
| ModeNoHeadEvar ->
(try ignore(head_evar sigma arg); false
with Evarutil.NoHeadEvar -> true)
| ModeOutput -> true
let matches_mode sigma args mode =
if Array.length mode == Array.length args &&
Array.for_all2 (match_mode sigma) mode args then Some mode
else None
let matches_modes sigma args modes =
if List.is_empty modes then Some NoMode
else
try Some (WithMode (List.find_map (matches_mode sigma args) modes))
with Not_found -> None
let merge_entry secvars db nopat pat =
let h = List.sort pri_order_int (List.map snd db.hintdb_nopat) in
let h = List.merge pri_order_int h nopat in
let h = List.merge pri_order_int h pat in
List.map_filter (realize_tac secvars) h
let map_none ~secvars db =
merge_entry secvars db [] []
let map_all ~secvars k db =
let se = find k db in
merge_entry secvars db se.sentry_nopat se.sentry_pat
let map_auto env sigma ~secvars (k,args) concl db =
let se = find k db in
let pat = lookup_tacs env sigma concl se in
merge_entry secvars db [] pat
let map_eauto env sigma ~secvars (k,args) concl db =
let se = find k db in
match matches_modes sigma args se.sentry_mode with
| Some m ->
let pat = lookup_tacs env sigma concl se in
ModeMatch (m, merge_entry secvars db [] pat)
| None -> ModeMismatch
let is_exact = function
| Give_exact _ -> true
| _ -> false
let addkv gr id v db =
let idv = id, { v with db = db.hintdb_name } in
match gr with
| None ->
let is_present (_, (_, v')) = KerName.equal v.code.uid v'.code.uid in
if not (List.exists is_present db.hintdb_nopat) then
{ db with hintdb_nopat = (gr,idv) :: db.hintdb_nopat }
else db
| Some gr ->
let pat =
if not db.use_dn && is_exact v.code.obj then None
else v.pat
in
let oval = find gr db in
{ db with hintdb_map = GlobRef.Map.add gr (add_tac pat idv oval) db.hintdb_map }
let rebuild_db st' db =
let db' =
{ db with hintdb_map = GlobRef.Map.map (rebuild_dn (Some st')) db.hintdb_map;
hintdb_state = st'; hintdb_nopat = [] }
in
List.fold_left (fun db (gr,(id,v)) -> addkv gr id v db) db' db.hintdb_nopat
let add_one env sigma (k, v) db =
let v = instantiate_hint env sigma v in
let st',db,rebuild =
match v.code.obj with
| Unfold_nth egr ->
let addunf ts (ids, csts) =
let open TransparentState in
match egr with
| EvalVarRef id ->
{ ts with tr_var = Id.Pred.add id ts.tr_var }, (Id.Set.add id ids, csts)
| EvalConstRef cst ->
{ ts with tr_cst = Cpred.add cst ts.tr_cst }, (ids, Cset.add cst csts)
in
let state, unfs = addunf db.hintdb_state db.hintdb_unfolds in
state, { db with hintdb_unfolds = unfs }, true
| _ -> db.hintdb_state, db, false
in
let db = if db.use_dn && rebuild then rebuild_db st' db else db in
let db, id = next_hint_id db in
addkv k id v db
let add_list env sigma l db = List.fold_left (fun db k -> add_one env sigma k db) db l
let remove_sdl p sdl = List.filter p sdl
let remove_he st p se =
let sl1' = remove_sdl p se.sentry_nopat in
let sl2' = remove_sdl p se.sentry_pat in
if sl1' == se.sentry_nopat && sl2' == se.sentry_pat then se
else rebuild_dn st { se with sentry_nopat = sl1'; sentry_pat = sl2' }
let remove_list env grs db =
let filter (_, h) =
match h.name with PathHints [gr] -> not (List.mem_f GlobRef.equal gr grs) | _ -> true in
let hintmap = GlobRef.Map.map (remove_he (dn_ts db) filter) db.hintdb_map in
let hintnopat = List.filter (fun (ge, sd) -> filter sd) db.hintdb_nopat in
{ db with hintdb_map = hintmap; hintdb_nopat = hintnopat }
let remove_one env gr db = remove_list env [gr] db
let get_entry se =
let h = List.merge pri_order_int se.sentry_nopat se.sentry_pat in
List.map snd h
let iter f db =
let iter_se k se = f (Some k) se.sentry_mode (get_entry se) in
f None [] (List.map (fun x -> snd (snd x)) db.hintdb_nopat);
GlobRef.Map.iter iter_se db.hintdb_map
let fold f db accu =
let accu = f None [] (List.map (fun x -> snd (snd x)) db.hintdb_nopat) accu in
GlobRef.Map.fold (fun k se -> f (Some k) se.sentry_mode (get_entry se)) db.hintdb_map accu
let transparent_state db = db.hintdb_state
let set_transparent_state db st =
if db.use_dn then rebuild_db st db
else { db with hintdb_state = st }
let add_cut path db =
{ db with hintdb_cut = normalize_path (PathOr (db.hintdb_cut, path)) }
let add_mode gr m db =
let se = find gr db in
let se = { se with sentry_mode = m :: se.sentry_mode } in
{ db with hintdb_map = GlobRef.Map.add gr se db.hintdb_map }
let cut db = db.hintdb_cut
let unfolds db = db.hintdb_unfolds
let add_modes modes db =
let f gr e me =
Some { e with sentry_mode = me.sentry_mode @ e.sentry_mode }
in
let mode_entries = GlobRef.Map.map (fun m -> { (empty_se (dn_ts db)) with sentry_mode = m }) modes in
{ db with hintdb_map = GlobRef.Map.union f db.hintdb_map mode_entries }
let modes db = GlobRef.Map.map (fun se -> se.sentry_mode) db.hintdb_map
let use_dn db = db.use_dn
end
module Hintdbmap = String.Map
type hint_db = Hint_db.t
let searchtable = Summary.ref ~name:"searchtable" Hintdbmap.empty
let statustable = Summary.ref ~name:"statustable" KNmap.empty
let searchtable_map name =
Hintdbmap.find name !searchtable
let searchtable_add (name,db) =
searchtable := Hintdbmap.add name db !searchtable
let current_db_names () = Hintdbmap.domain !searchtable
let current_db () = Hintdbmap.bindings !searchtable
let current_pure_db () = List.map snd (current_db ())
let error_no_such_hint_database x =
user_err (str "No such Hint database: " ++ str x ++ str ".")
let rec nb_hyp sigma c = match EConstr.kind sigma c with
| Prod(_,_,c2) -> if noccurn sigma 1 c2 then 1+(nb_hyp sigma c2) else nb_hyp sigma c2
| _ -> 0
let with_uid c = { obj = c; uid = fresh_key () }
let secvars_of_idset s =
Id.Set.fold (fun id p ->
if is_section_variable (Global.env ()) id then
Id.Pred.add id p
else p) s Id.Pred.empty
let secvars_of_constr env sigma c =
secvars_of_idset (Termops.global_vars_set env sigma c)
let secvars_of_global env gr =
secvars_of_idset (vars_of_global env gr)
let make_exact_entry env sigma info ?(name=PathAny) (c, cty, ctx) =
let secvars = secvars_of_constr env sigma c in
let cty = strip_outer_cast sigma cty in
match EConstr.kind sigma cty with
| Prod _ -> failwith "make_exact_entry"
| _ ->
let hd =
try head_bound sigma cty
with Bound -> failwith "make_exact_entry"
in
let pri = match info.hint_priority with None -> 0 | Some p -> p in
let pat = match info.hint_pattern with
| Some pat -> snd pat
| None ->
Patternops.pattern_of_constr env sigma (EConstr.to_constr ~abort_on_undefined_evars:false sigma cty)
in
(Some hd,
{ pri; pat = Some pat; name;
db = None; secvars;
code = with_uid (Give_exact (c, cty, ctx)); })
let make_apply_entry env sigma hnf info ?(name=PathAny) (c, cty, ctx) =
let cty = if hnf then hnf_constr env sigma cty else cty in
match EConstr.kind sigma cty with
| Prod _ ->
let sigma' = merge_context_set_opt sigma ctx in
let ce = mk_clenv_from env sigma' (c,cty) in
let c' = clenv_type ce in
let hd =
try head_bound ce.evd c'
with Bound -> failwith "make_apply_entry" in
let miss = clenv_missing ce in
let nmiss = List.length miss in
let secvars = secvars_of_constr env sigma c in
let pri = match info.hint_priority with None -> nb_hyp sigma' cty + nmiss | Some p -> p in
let pat = match info.hint_pattern with
| Some p -> snd p
| None ->
Patternops.pattern_of_constr env ce.evd (EConstr.to_constr ~abort_on_undefined_evars:false sigma c')
in
if Int.equal nmiss 0 then
(Some hd,
{ pri; pat = Some pat; name;
db = None;
secvars;
code = with_uid (Res_pf(c,cty,ctx)); })
else
(Some hd,
{ pri; pat = Some pat; name;
db = None; secvars;
code = with_uid (ERes_pf(c,cty,ctx)); })
| _ -> failwith "make_apply_entry"
let fresh_global_or_constr env sigma cr = match cr with
| IsGlobRef gr ->
let (c, ctx) = UnivGen.fresh_global_instance env gr in
let ctx = if Environ.is_polymorphic env gr then Some ctx else None in
(EConstr.of_constr c, ctx)
| IsConstr (c, ctx) -> (c, ctx)
let make_resolves env sigma (eapply, hnf) info ~check ?name cr =
let c, ctx = fresh_global_or_constr env sigma cr in
let cty = Retyping.get_type_of env sigma c in
let try_apply f =
try
let (_, hint) as ans = f (c, cty, ctx) in
match hint.code.obj with
| ERes_pf _ -> if not eapply then None else Some ans
| _ -> Some ans
with Failure _ -> None
in
let ents = List.map_filter try_apply
[make_exact_entry env sigma info ?name;
make_apply_entry env sigma hnf info ?name]
in
if check && List.is_empty ents then
user_err
(pr_leconstr_env env sigma c ++ spc() ++
(if eapply then str"cannot be used as a hint."
else str "can be used as a hint only for eauto."));
ents
let make_resolve_hyp env sigma hname =
let decl = EConstr.lookup_named hname env in
let c = mkVar hname in
try
[make_apply_entry env sigma true empty_hint_info
~name:(PathHints [GlobRef.VarRef hname])
(c, NamedDecl.get_type decl, None)]
with
| Failure _ -> []
| e when noncritical e -> anomaly (Pp.str "make_resolve_hyp.")
let make_unfold eref =
let g = global_of_evaluable_reference eref in
(Some g,
{ pri = 4;
pat = None;
name = PathHints [g];
db = None;
secvars = secvars_of_global (Global.env ()) g;
code = with_uid (Unfold_nth eref) })
let make_extern pri pat tacast =
let hdconstr = match pat with
| None -> None
| Some c ->
try Some (head_pattern_bound c)
with BoundPattern ->
user_err (Pp.str "Head pattern or sub-pattern must be a global constant, a section variable, \
an if, case, or let expression, an application, or a projection.")
in
(hdconstr,
{ pri = pri;
pat = pat;
name = PathAny;
db = None;
secvars = Id.Pred.empty;
code = with_uid (Extern (pat, tacast)) })
let make_mode ref m =
let open Term in
let ty, _ = Typeops.type_of_global_in_context (Global.env ()) ref in
let ctx, t = decompose_prod ty in
let n = List.length ctx in
let m' = Array.of_list m in
if not (n == Array.length m') then
user_err
(pr_global ref ++ str" has " ++ int n ++
str" arguments while the mode declares " ++ int (Array.length m') ++ str ".")
else m'
let make_trivial env sigma ?(name=PathAny) r =
let c,ctx = fresh_global_or_constr env sigma r in
let sigma = merge_context_set_opt sigma ctx in
let t = hnf_constr env sigma (Retyping.get_type_of env sigma c) in
let hd = head_constr sigma t in
let ce = mk_clenv_from env sigma (c,t) in
(Some hd,
{ pri=1;
pat = Some (Patternops.pattern_of_constr env ce.evd (EConstr.to_constr sigma (clenv_type ce)));
name = name;
db = None;
secvars = secvars_of_constr env sigma c;
code= with_uid (Res_pf_THEN_trivial_fail(c,t,ctx)) })
let get_db dbname =
try searchtable_map dbname
with Not_found -> Hint_db.empty ~name:dbname TransparentState.empty false
let add_hint dbname hintlist =
let check (_, h) =
let () = if KNmap.mem h.code.uid !statustable then
user_err Pp.(str "Conflicting hint keys. This can happen when including \
twice the same module.")
in
statustable := KNmap.add h.code.uid false !statustable
in
let () = List.iter check hintlist in
let db = get_db dbname in
let env = Global.env () in
let sigma = Evd.from_env env in
let db' = Hint_db.add_list env sigma hintlist db in
searchtable_add (dbname,db')
let add_transparency dbname target b =
let open TransparentState in
let db = get_db dbname in
let st = Hint_db.transparent_state db in
let st' =
match target with
| HintsVariables -> { st with tr_var = (if b then Id.Pred.full else Id.Pred.empty) }
| HintsConstants -> { st with tr_cst = (if b then Cpred.full else Cpred.empty) }
| HintsReferences grs ->
List.fold_left (fun st gr ->
match gr with
| EvalConstRef c -> { st with tr_cst = (if b then Cpred.add else Cpred.remove) c st.tr_cst }
| EvalVarRef v -> { st with tr_var = (if b then Id.Pred.add else Id.Pred.remove) v st.tr_var })
st grs
in searchtable_add (dbname, Hint_db.set_transparent_state db st')
let remove_hint dbname grs =
let env = Global.env () in
let db = get_db dbname in
let db' = Hint_db.remove_list env grs db in
searchtable_add (dbname, db')
let add_cut dbname path =
let db = get_db dbname in
let db' = Hint_db.add_cut path db in
searchtable_add (dbname, db')
let add_mode dbname l m =
let db = get_db dbname in
let db' = Hint_db.add_mode l m db in
searchtable_add (dbname, db')
type db_obj = {
db_local : bool;
db_name : string;
db_use_dn : bool;
db_ts : TransparentState.t;
}
let cache_db (_, {db_name=name; db_use_dn=b; db_ts=ts}) =
searchtable_add (name, Hint_db.empty ~name ts b)
let load_db _ x = cache_db x
let classify_db db = if db.db_local then Dispose else Substitute db
let inDB : db_obj -> obj =
declare_object {(default_object "AUTOHINT_DB") with
cache_function = cache_db;
load_function = load_db;
subst_function = (fun (_,x) -> x);
classify_function = classify_db; }
let create_hint_db l n ts b =
let hint = {db_local=l; db_name=n; db_use_dn=b; db_ts=ts} in
Lib.add_anonymous_leaf (inDB hint)
type hint_action =
| AddTransparency of {
grefs : evaluable_global_reference hints_transparency_target;
state : bool;
}
| AddHints of hint_entry list
| RemoveHints of GlobRef.t list
| AddCut of hints_path
| AddMode of { gref : GlobRef.t; mode : hint_mode array }
type hint_locality = Local | Export | SuperGlobal
type hint_obj = {
hint_local : hint_locality;
hint_name : string;
hint_action : hint_action;
}
let is_trivial_action = function
| AddTransparency { grefs } ->
begin match grefs with
| HintsVariables | HintsConstants -> false
| HintsReferences l -> List.is_empty l
end
| AddHints l -> List.is_empty l
| RemoveHints l -> List.is_empty l
| AddCut _ | AddMode _ -> false
let rec is_section_path = function
| PathAtom PathAny -> false
| PathAtom (PathHints grs) ->
let check c = isVarRef c && Lib.is_in_section c in
List.exists check grs
| PathStar p -> is_section_path p
| PathSeq (p, q) | PathOr (p, q) -> is_section_path p || is_section_path q
| PathEmpty | PathEpsilon -> false
let superglobal h = match h.hint_local with
| SuperGlobal -> true
| Local | Export -> false
let load_autohint _ (kn, h) =
let name = h.hint_name in
let superglobal = superglobal h in
match h.hint_action with
| AddTransparency { grefs; state } ->
if superglobal then add_transparency name grefs state
| AddHints hints ->
if superglobal then add_hint name hints
| RemoveHints hints ->
if superglobal then remove_hint name hints
| AddCut paths ->
if superglobal then add_cut name paths
| AddMode { gref; mode } ->
if superglobal then add_mode name gref mode
let open_autohint i (kn, h) =
let superglobal = superglobal h in
if Int.equal i 1 then match h.hint_action with
| AddHints hints ->
let () =
if not superglobal then
let filter (_, h) = not @@ KNmap.mem h.code.uid !statustable in
add_hint h.hint_name (List.filter filter hints)
in
let add (_, hint) = statustable := KNmap.add hint.code.uid true !statustable in
List.iter add hints
| AddCut paths ->
if not superglobal then add_cut h.hint_name paths
| AddTransparency { grefs; state } ->
if not superglobal then add_transparency h.hint_name grefs state
| RemoveHints hints ->
if not superglobal then remove_hint h.hint_name hints
| AddMode { gref; mode } ->
if not superglobal then add_mode h.hint_name gref mode
let cache_autohint (kn, obj) =
load_autohint 1 (kn, obj); open_autohint 1 (kn, obj)
let subst_autohint (subst, obj) =
let subst_key gr =
let (gr', t) = subst_global subst gr in
match t with
| None -> gr'
| Some t ->
(try head_bound Evd.empty (EConstr.of_constr t.Univ.univ_abstracted_value)
with Bound -> gr')
in
let subst_mps subst c = EConstr.of_constr (subst_mps subst (EConstr.Unsafe.to_constr c)) in
let subst_aux ((c, t, ctx) as h) =
let c' = subst_mps subst c in
let t' = subst_mps subst t in
if c==c' && t'==t then h else (c', t', ctx)
in
let subst_hint (k,data as hint) =
let k' = Option.Smart.map subst_key k in
let env = Global.env () in
let sigma = Evd.from_env env in
let pat' = Option.Smart.map (subst_pattern env sigma subst) data.pat in
let code' = match data.code.obj with
| Res_pf h ->
let h' = subst_aux h in
if h == h' then data.code.obj else Res_pf h'
| ERes_pf h ->
let h' = subst_aux h in
if h == h' then data.code.obj else ERes_pf h'
| Give_exact h ->
let h' = subst_aux h in
if h == h' then data.code.obj else Give_exact h'
| Res_pf_THEN_trivial_fail h ->
let h' = subst_aux h in
if h == h' then data.code.obj else Res_pf_THEN_trivial_fail h'
| Unfold_nth ref ->
let ref' = subst_evaluable_reference subst ref in
if ref==ref' then data.code.obj else Unfold_nth ref'
| Extern (pat, tac) ->
let pat' = Option.Smart.map (subst_pattern env sigma subst) data.pat in
let tac' = Genintern.generic_substitute subst tac in
if pat==pat' && tac==tac' then data.code.obj else Extern (pat', tac')
in
let name' = subst_path_atom subst data.name in
let uid' = subst_kn subst data.code.uid in
let data' =
if data.code.uid == uid' && data.pat == pat' &&
data.name == name' && data.code.obj == code' then data
else { data with pat = pat'; name = name'; code = { obj = code'; uid = uid' } }
in
if k' == k && data' == data then hint else (k',data')
in
let action = match obj.hint_action with
| AddTransparency { grefs = target; state = b } ->
let target' =
match target with
| HintsVariables -> target
| HintsConstants -> target
| HintsReferences grs ->
let grs' = List.Smart.map (subst_evaluable_reference subst) grs in
if grs == grs' then target
else HintsReferences grs'
in
if target' == target then obj.hint_action else AddTransparency { grefs = target'; state = b }
| AddHints hints ->
let hints' = List.Smart.map subst_hint hints in
if hints' == hints then obj.hint_action else AddHints hints'
| RemoveHints grs ->
let grs' = List.Smart.map (subst_global_reference subst) grs in
if grs == grs' then obj.hint_action else RemoveHints grs'
| AddCut path ->
let path' = subst_hints_path subst path in
if path' == path then obj.hint_action else AddCut path'
| AddMode { gref = l; mode = m } ->
let l' = subst_global_reference subst l in
if l' == l then obj.hint_action else AddMode { gref = l'; mode = m }
in
if action == obj.hint_action then obj else { obj with hint_action = action }
let is_hint_local = function Local -> true | Export | SuperGlobal -> false
let classify_autohint obj =
if is_hint_local obj.hint_local || is_trivial_action obj.hint_action then Dispose
else Substitute obj
let discharge_autohint (_, obj) =
if is_hint_local obj.hint_local then None
else
let action = match obj.hint_action with
| AddTransparency { grefs; state } ->
let grefs = match grefs with
| HintsVariables | HintsConstants -> grefs
| HintsReferences grs ->
let filter = function
| EvalConstRef c -> true
| EvalVarRef id -> not @@ Lib.is_in_section (GlobRef.VarRef id)
in
let grs = List.filter filter grs in
HintsReferences grs
in
AddTransparency { grefs; state }
| AddHints _ | RemoveHints _ ->
assert false
| AddCut path ->
if is_section_path path then AddHints [] else obj.hint_action
| AddMode { gref; mode } ->
if Lib.is_in_section gref then
if isVarRef gref then AddHints []
else
let (_, params) = Lib.section_instance gref in
let mode = Array.append (Array.make (Array.length params) ModeOutput) mode in
AddMode { gref; mode }
else obj.hint_action
in
if is_trivial_action action then None
else Some { obj with hint_action = action }
let hint_cat = create_category "hints"
let inAutoHint : hint_obj -> obj =
declare_object {(default_object "AUTOHINT") with
cache_function = cache_autohint;
load_function = load_autohint;
open_function = simple_open ~cat:hint_cat open_autohint;
subst_function = subst_autohint;
classify_function = classify_autohint;
discharge_function = discharge_autohint;
}
let check_locality locality =
let not_local what =
CErrors.user_err
Pp.(str "This command does not support the " ++
str what ++ str " attribute in sections.")
in
if Global.sections_are_opened () then
match locality with
| Local -> ()
| SuperGlobal -> not_local "global"
| Export -> not_local "export"
let make_hint ~locality name action =
{
hint_local = locality;
hint_name = name;
hint_action = action;
}
let warn_deprecated_hint_without_locality =
CWarnings.create ~name:"deprecated-hint-without-locality" ~category:"deprecated"
(fun () -> strbrk "The default value for hint locality is currently \
\"local\" in a section and \"global\" otherwise, but is scheduled to change \
in a future release. For the time being, adding hints outside of sections \
without specifying an explicit locality attribute is therefore deprecated. It is \
recommended to use \"export\" whenever possible. Use the attributes \
#[local], #[global] and #[export] depending on your choice. For example: \
\"#[export] Hint Unfold foo : bar.\"")
let default_hint_locality () =
if Global.sections_are_opened () then Local else
let () = warn_deprecated_hint_without_locality () in
SuperGlobal
let remove_hints ~locality dbnames grs =
let () = check_locality locality in
let dbnames = if List.is_empty dbnames then ["core"] else dbnames in
List.iter
(fun dbname ->
let hint = make_hint ~locality dbname (RemoveHints grs) in
Lib.add_anonymous_leaf (inAutoHint hint))
dbnames
let add_resolves env sigma clist ~locality dbnames =
List.iter
(fun dbname ->
let r =
List.flatten (List.map (fun (pri, hnf, path, gr) ->
make_resolves env sigma (true, hnf)
pri ~check:true ~name:path gr) clist)
in
let check (_, hint) = match hint.code.obj with
| ERes_pf (c, cty, ctx) ->
let sigma' = merge_context_set_opt sigma ctx in
let ce = mk_clenv_from env sigma' (c,cty) in
let miss = clenv_missing ce in
let nmiss = List.length miss in
let variables = str (CString.plural nmiss "variable") in
Feedback.msg_info (
strbrk "The hint " ++
pr_leconstr_env env sigma' c ++
strbrk " will only be used by eauto, because applying " ++
pr_leconstr_env env sigma' c ++
strbrk " would leave " ++ variables ++ Pp.spc () ++
Pp.prlist_with_sep Pp.pr_comma Name.print (List.map (Evd.meta_name ce.evd) miss) ++
strbrk " as unresolved existential " ++ variables ++ str "."
)
| _ -> ()
in
let () = if not !Flags.quiet then List.iter check r in
let hint = make_hint ~locality dbname (AddHints r) in
Lib.add_anonymous_leaf (inAutoHint hint))
dbnames
let add_unfolds l ~locality dbnames =
List.iter
(fun dbname ->
let hint = make_hint ~locality dbname (AddHints (List.map make_unfold l)) in
Lib.add_anonymous_leaf (inAutoHint hint))
dbnames
let add_cuts l ~locality dbnames =
List.iter
(fun dbname ->
let hint = make_hint ~locality dbname (AddCut l) in
Lib.add_anonymous_leaf (inAutoHint hint))
dbnames
let add_mode l m ~locality dbnames =
List.iter
(fun dbname ->
let m' = make_mode l m in
let hint = make_hint ~locality dbname (AddMode { gref = l; mode = m' }) in
Lib.add_anonymous_leaf (inAutoHint hint))
dbnames
let add_transparency l b ~locality dbnames =
List.iter
(fun dbname ->
let hint = make_hint ~locality dbname (AddTransparency { grefs = l; state = b }) in
Lib.add_anonymous_leaf (inAutoHint hint))
dbnames
let add_extern info tacast ~locality dbname =
let pat = match info.hint_pattern with
| None -> None
| Some (_, pat) -> Some pat
in
let hint = make_hint ~locality dbname
(AddHints [make_extern (Option.get info.hint_priority) pat tacast]) in
Lib.add_anonymous_leaf (inAutoHint hint)
let add_externs info tacast ~locality dbnames =
List.iter (add_extern info tacast ~locality) dbnames
let add_trivials env sigma l ~locality dbnames =
List.iter
(fun dbname ->
let l = List.map (fun (name, c) -> make_trivial env sigma ~name c) l in
let hint = make_hint ~locality dbname (AddHints l) in
Lib.add_anonymous_leaf (inAutoHint hint))
dbnames
type hnf = bool
type nonrec hint_info = hint_info
type hints_entry =
| HintsResolveEntry of (hint_info * hnf * hints_path_atom * hint_term) list
| HintsImmediateEntry of (hints_path_atom * hint_term) list
| HintsCutEntry of hints_path
| HintsUnfoldEntry of evaluable_global_reference list
| HintsTransparencyEntry of evaluable_global_reference hints_transparency_target * bool
| HintsModeEntry of GlobRef.t * hint_mode list
| HintsExternEntry of hint_info * Genarg.glob_generic_argument
let default_prepare_hint_ident = Id.of_string "H"
exception Found of constr * types
let prepare_hint env init (sigma,c) =
let sigma = Typeclasses.resolve_typeclasses ~fail:false env sigma in
let sigma = Evd.nf_univ_variables sigma in
let c = Evarutil.nf_evar sigma c in
let c = drop_extra_implicit_args sigma c in
let vars = ref (collect_vars sigma c) in
let subst = ref [] in
let rec find_next_evar c = match EConstr.kind sigma c with
| Evar (evk,args as ev) ->
let t = Evarutil.nf_evar sigma (existential_type sigma ev) in
let t = List.fold_right (fun (e,id) c -> replace_term sigma e id c) !subst t in
if not (closed0 sigma c) then
user_err Pp.(str "Hints with holes dependent on a bound variable not supported.");
if occur_existential sigma t then
user_err Pp.(str "Not clever enough to deal with evars dependent in other evars.");
raise (Found (c,t))
| _ -> EConstr.iter sigma find_next_evar c in
let rec iter c =
try find_next_evar c; c
with Found (evar,t) ->
let id = next_ident_away_from default_prepare_hint_ident (fun id -> Id.Set.mem id !vars) in
vars := Id.Set.add id !vars;
subst := (evar,mkVar id)::!subst;
mkNamedLambda (make_annot id Sorts.Relevant) t (iter (replace_term sigma evar (mkVar id) c)) in
let c' = iter c in
let diff = Univ.ContextSet.diff (Evd.universe_context_set sigma) (Evd.universe_context_set init) in
(c', diff)
let warn_non_local_section_hint =
CWarnings.create ~name:"non-local-section-hint" ~category:"automation"
(fun () -> strbrk "This hint is not local but depends on a section variable. It will disappear when the section is closed.")
let is_notlocal = function
| Local -> false
| Export | SuperGlobal -> true
let add_hints ~locality dbnames h =
let () = match h with
| HintsResolveEntry _ | HintsImmediateEntry _ | HintsUnfoldEntry _ | HintsExternEntry _ ->
check_locality locality
| HintsTransparencyEntry ((HintsVariables | HintsConstants), _) -> ()
| HintsTransparencyEntry (HintsReferences grs, _) ->
let iter gr =
let gr = global_of_evaluable_reference gr in
if is_notlocal locality && isVarRef gr && Lib.is_in_section gr then warn_non_local_section_hint ()
in
List.iter iter grs
| HintsCutEntry p ->
if is_notlocal locality && is_section_path p then warn_non_local_section_hint ()
| HintsModeEntry (gr, _) ->
if is_notlocal locality && isVarRef gr && Lib.is_in_section gr then warn_non_local_section_hint ()
in
if String.List.mem "nocore" dbnames then
user_err Pp.(str "The hint database \"nocore\" is meant to stay empty.");
assert (not (List.is_empty dbnames));
let env = Global.env() in
let sigma = Evd.from_env env in
match h with
| HintsResolveEntry lhints -> add_resolves env sigma lhints ~locality dbnames
| HintsImmediateEntry lhints -> add_trivials env sigma lhints ~locality dbnames
| HintsCutEntry lhints -> add_cuts lhints ~locality dbnames
| HintsModeEntry (l,m) -> add_mode l m ~locality dbnames
| HintsUnfoldEntry lhints -> add_unfolds lhints ~locality dbnames
| HintsTransparencyEntry (lhints, b) ->
add_transparency lhints b ~locality dbnames
| HintsExternEntry (info, tacexp) ->
add_externs info tacexp ~locality dbnames
let hint_globref gr = IsGlobRef gr
let hint_constr (c, diff) = IsConstr (c, diff)
let expand_constructor_hints env sigma lems =
List.map_append (fun (evd,lem) ->
match EConstr.kind sigma lem with
| Ind (ind,u) ->
List.init (nconstructors env ind)
(fun i -> IsGlobRef (GlobRef.ConstructRef ((ind,i+1))))
| _ ->
let (c, ctx) = prepare_hint env sigma (evd,lem) in
let ctx = if Univ.ContextSet.is_empty ctx then None else Some ctx in
[IsConstr (c, ctx)]) lems
let constructor_hints env sigma eapply lems =
let lems = expand_constructor_hints env sigma lems in
List.map_append (fun lem ->
make_resolves env sigma (eapply, true) empty_hint_info ~check:true lem) lems
let make_local_hint_db env sigma ts eapply lems =
let map c = c env sigma in
let lems = List.map map lems in
let sign = EConstr.named_context env in
let ts = match ts with
| None -> Hint_db.transparent_state (searchtable_map "core")
| Some ts -> ts
in
let hintlist = List.map_append (fun decl -> make_resolve_hyp env sigma (Named.Declaration.get_id decl)) sign in
Hint_db.empty ts false
|> Hint_db.add_list env sigma hintlist
|> Hint_db.add_list env sigma (constructor_hints env sigma eapply lems)
let make_local_hint_db env sigma ?ts eapply lems =
make_local_hint_db env sigma ts eapply lems
let make_db_list dbnames =
let use_core = not (List.mem "nocore" dbnames) in
let dbnames = List.remove String.equal "nocore" dbnames in
let dbnames = if use_core then "core"::dbnames else dbnames in
let lookup db =
try searchtable_map db with Not_found -> error_no_such_hint_database db
in
List.map lookup dbnames
let push_resolves env sigma hint db =
let name = PathHints [hint] in
let entries = make_resolves env sigma (true, false) empty_hint_info ~check:false ~name (IsGlobRef hint) in
Hint_db.add_list env sigma entries db
let push_resolve_hyp env sigma decl db =
let entries = make_resolve_hyp env sigma decl in
Hint_db.add_list env sigma entries db
let pr_hint_elt env sigma h = pr_econstr_env env sigma h.hint_term
let pr_hint env sigma h = match h.obj with
| Res_pf c -> (str"simple apply " ++ pr_hint_elt env sigma c)
| ERes_pf c -> (str"simple eapply " ++ pr_hint_elt env sigma c)
| Give_exact c -> (str"exact " ++ pr_hint_elt env sigma c)
| Res_pf_THEN_trivial_fail c ->
(str"simple apply " ++ pr_hint_elt env sigma c ++ str" ; trivial")
| Unfold_nth c ->
str"unfold " ++ pr_evaluable_reference c
| Extern (_, tac) ->
str "(*external*) " ++ Pputils.pr_glb_generic env sigma tac
let pr_id_hint env sigma (id, v) =
let pr_pat p = str", pattern " ++ pr_lconstr_pattern_env env sigma p in
(pr_hint env sigma v.code ++ str"(level " ++ int v.pri ++ pr_opt_no_spc pr_pat v.pat
++ str", id " ++ int id ++ str ")" ++ spc ())
let pr_hint_list env sigma hintlist =
(str " " ++ hov 0 (prlist (pr_id_hint env sigma) hintlist) ++ fnl ())
let pr_hints_db env sigma (name,db,hintlist) =
(str "In the database " ++ str name ++ str ":" ++
if List.is_empty hintlist then (str " nothing" ++ fnl ())
else (fnl () ++ pr_hint_list env sigma hintlist))
let pr_hint_list_for_head env sigma c =
let dbs = current_db () in
let validate (name, db) =
let hints = List.map (fun v -> 0, v) (Hint_db.map_all ~secvars:Id.Pred.full c db) in
(name, db, hints)
in
let valid_dbs = List.map validate dbs in
if List.is_empty valid_dbs then
(str "No hint declared for :" ++ pr_global c)
else
hov 0
(str"For " ++ pr_global c ++ str" -> " ++ fnl () ++
hov 0 (prlist (pr_hints_db env sigma) valid_dbs))
let pr_hint_ref ref = pr_hint_list_for_head ref
let pr_hint_term env sigma cl =
try
let dbs = current_db () in
let valid_dbs =
let fn = try
let hdc = decompose_app_bound sigma cl in
if occur_existential sigma cl then
(fun db -> match Hint_db.map_eauto env sigma ~secvars:Id.Pred.full hdc cl db with
| ModeMatch (_, l) -> l
| ModeMismatch -> [])
else Hint_db.map_auto env sigma ~secvars:Id.Pred.full hdc cl
with Bound -> Hint_db.map_none ~secvars:Id.Pred.full
in
let fn db = List.map (fun x -> 0, x) (fn db) in
List.map (fun (name, db) -> (name, db, fn db)) dbs
in
if List.is_empty valid_dbs then
(str "No hint applicable for current goal")
else
(str "Applicable Hints :" ++ fnl () ++
hov 0 (prlist (pr_hints_db env sigma) valid_dbs))
with Match_failure _ | Failure _ ->
(str "No hint applicable for current goal")
let pr_applicable_hint pf =
let env = Global.env () in
let Proof.{goals;sigma} = Proof.data pf in
match goals with
| [] -> CErrors.user_err Pp.(str "No focused goal.")
| g::_ ->
pr_hint_term env sigma (Evd.evar_concl (Evd.find sigma g))
let pp_hint_mode = function
| ModeInput -> str"+"
| ModeNoHeadEvar -> str"!"
| ModeOutput -> str"-"
let pr_hint_db_env env sigma db =
let pr_mode = prvect_with_sep spc pp_hint_mode in
let pr_modes l =
if List.is_empty l then mt ()
else str" (modes " ++ prlist_with_sep pr_comma pr_mode l ++ str")"
in
let content =
let fold head modes hintlist accu =
let goal_descr = match head with
| None -> str "For any goal"
| Some head -> str "For " ++ pr_global head ++ pr_modes modes
in
let hints = pr_hint_list env sigma (List.map (fun x -> (0, x)) hintlist) in
let hint_descr = hov 0 (goal_descr ++ str " -> " ++ hints) in
accu ++ hint_descr
in
Hint_db.fold fold db (mt ())
in
let { TransparentState.tr_var = ids; tr_cst = csts } = Hint_db.transparent_state db in
hov 0
((if Hint_db.use_dn db then str"Discriminated database"
else str"Non-discriminated database")) ++ fnl () ++
hov 2 (str"Unfoldable variable definitions: " ++ pr_idpred ids) ++ fnl () ++
hov 2 (str"Unfoldable constant definitions: " ++ pr_cpred csts) ++ fnl () ++
hov 2 (str"Cut: " ++ pp_hints_path (Hint_db.cut db)) ++ fnl () ++
content
let pr_hint_db_by_name env sigma dbname =
try
let db = searchtable_map dbname in pr_hint_db_env env sigma db
with Not_found ->
error_no_such_hint_database dbname
let pr_searchtable env sigma =
let fold name db accu =
accu ++ str "In the database " ++ str name ++ str ":" ++ fnl () ++
pr_hint_db_env env sigma db ++ fnl ()
in
Hintdbmap.fold fold !searchtable (mt ())
let print_mp mp =
try
let qid = Nametab.shortest_qualid_of_module mp in
str " from " ++ pr_qualid qid
with Not_found -> mt ()
let is_imported h = try KNmap.find h.uid !statustable with Not_found -> true
let hint_trace = Evd.Store.field ()
let log_hint h =
let open Proofview.Notations in
Proofview.tclEVARMAP >>= fun sigma ->
let store = get_extra_data sigma in
match Store.get store hint_trace with
| None ->
assert false
| Some trace ->
let trace = KNmap.add h.uid h trace in
let store = Store.set store hint_trace trace in
Proofview.Unsafe.tclEVARS (set_extra_data store sigma)
let warn_non_imported_hint =
CWarnings.create ~name:"non-imported-hint" ~category:"automation"
(fun (hint,mp) ->
strbrk "Hint used but not imported: " ++ hint ++ print_mp mp)
let warn env sigma h =
let hint = pr_hint env sigma h in
let mp = KerName.modpath h.uid in
warn_non_imported_hint (hint,mp)
let wrap_hint_warning t =
let open Proofview.Notations in
Proofview.tclEVARMAP >>= fun sigma ->
let store = get_extra_data sigma in
let old = Store.get store hint_trace in
let store = Store.set store hint_trace KNmap.empty in
Proofview.Unsafe.tclEVARS (set_extra_data store sigma) >>= fun () ->
t >>= fun ans ->
Proofview.tclENV >>= fun env ->
Proofview.tclEVARMAP >>= fun sigma ->
let store = get_extra_data sigma in
let hints = match Store.get store hint_trace with
| None -> assert false
| Some hints -> hints
in
let () = KNmap.iter (fun _ h -> warn env sigma h) hints in
let store = match old with
| None -> Store.remove store hint_trace
| Some v -> Store.set store hint_trace v
in
Proofview.Unsafe.tclEVARS (set_extra_data store sigma) >>= fun () ->
Proofview.tclUNIT ans
let wrap_hint_warning_fun env sigma t =
let store = get_extra_data sigma in
let old = Store.get store hint_trace in
let store = Store.set store hint_trace KNmap.empty in
let (ans, sigma) = t (set_extra_data store sigma) in
let store = get_extra_data sigma in
let hints = match Store.get store hint_trace with
| None -> assert false
| Some hints -> hints
in
let () = KNmap.iter (fun _ h -> warn env sigma h) hints in
let store = match old with
| None -> Store.remove store hint_trace
| Some v -> Store.set store hint_trace v
in
(ans, set_extra_data store sigma)
let run_hint tac k = match warn_hint () with
| HintLax -> k tac.obj
| HintWarn ->
if is_imported tac then k tac.obj
else Proofview.tclTHEN (log_hint tac) (k tac.obj)
| HintStrict ->
if is_imported tac then k tac.obj
else
let info = Exninfo.reify () in
Proofview.tclZERO ~info (UserError (str "Tactic failure."))
module FullHint =
struct
type t = full_hint
let priority (h : t) = h.pri
let pattern (h : t) = h.pat
let database (h : t) = h.db
let run (h : t) k = run_hint h.code k
let print env sigma (h : t) = pr_hint env sigma h.code
let name (h : t) = h.name
let repr (h : t) = h.code.obj
end
let connect_hint_clenv h gl =
let { hint_uctx = ctx; hint_clnv = clenv } = h in
let sigma = Tacmach.project gl in
let evd = Evd.evars_reset_evd ~with_conv_pbs:true ~with_univs:false sigma clenv.evd in
match h.hint_uctx with
| Some ctx ->
let (subst, ctx) = UnivGen.fresh_universe_context_set_instance ctx in
let emap c = Vars.subst_univs_level_constr subst c in
let evd = Evd.merge_context_set Evd.univ_flexible evd ctx in
Clenv.mk_clausenv
(Proofview.Goal.env gl)
(Evd.map_metas emap evd)
(Evd.map_fl emap clenv.templval)
(Evd.map_fl emap clenv.templtyp)
| None ->
Clenv.mk_clausenv
(Proofview.Goal.env gl)
evd
clenv.templval
clenv.templtyp
let fresh_hint env sigma h =
let { hint_term = c; hint_uctx = ctx } = h in
match h.hint_uctx with
| None -> sigma, c
| Some ctx ->
let (subst, ctx) = UnivGen.fresh_universe_context_set_instance ctx in
let c = Vars.subst_univs_level_constr subst c in
let sigma = Evd.merge_context_set Evd.univ_flexible sigma ctx in
sigma, c
let hint_res_pf ?with_evars ?with_classes ?flags h =
Proofview.Goal.enter begin fun gl ->
let clenv = connect_hint_clenv h gl in
Clenv.res_pf ?with_evars ?with_classes ?flags clenv
end