package coq

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file constr.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
(************************************************************************)
(*         *   The Coq Proof Assistant / The Coq Development Team       *)
(*  v      *         Copyright INRIA, CNRS and contributors             *)
(* <O___,, * (see version control and CREDITS file for authors & dates) *)
(*   \VV/  **************************************************************)
(*    //   *    This file is distributed under the terms of the         *)
(*         *     GNU Lesser General Public License Version 2.1          *)
(*         *     (see LICENSE file for the text of the license)         *)
(************************************************************************)

(* File initially created by Gérard Huet and Thierry Coquand in 1984 *)
(* Extension to inductive constructions by Christine Paulin for Coq V5.6 *)
(* Extension to mutual inductive constructions by Christine Paulin for
   Coq V5.10.2 *)
(* Extension to co-inductive constructions by Eduardo Gimenez *)
(* Optimization of substitution functions by Chet Murthy *)
(* Optimization of lifting functions by Bruno Barras, Mar 1997 *)
(* Hash-consing by Bruno Barras in Feb 1998 *)
(* Restructuration of Coq of the type-checking kernel by Jean-Christophe
   Filliâtre, 1999 *)
(* Abstraction of the syntax of terms and iterators by Hugo Herbelin, 2000 *)
(* Cleaning and lightening of the kernel by Bruno Barras, Nov 2001 *)

(* This file defines the internal syntax of the Calculus of
   Inductive Constructions (CIC) terms together with constructors,
   destructors, iterators and basic functions *)

open Util
open Names
open Univ
open Context

type existential_key = Evar.t
type metavariable = int

(* This defines the strategy to use for verifiying a Cast *)
type cast_kind = VMcast | NATIVEcast | DEFAULTcast

(* This defines Cases annotations *)
type case_style = LetStyle | IfStyle | LetPatternStyle | MatchStyle | RegularStyle
type case_printing =
  { ind_tags : bool list; (** tell whether letin or lambda in the arity of the inductive type *)
    cstr_tags : bool list array; (* whether each pattern var of each constructor is a let-in (true) or not (false) *)
    style     : case_style }

(* INVARIANT:
 * - Array.length ci_cstr_ndecls = Array.length ci_cstr_nargs
 * - forall (i : 0 .. pred (Array.length ci_cstr_ndecls)),
 *          ci_cstr_ndecls.(i) >= ci_cstr_nargs.(i)
 *)
type case_info =
  { ci_ind        : inductive;      (* inductive type to which belongs the value that is being matched *)
    ci_npar       : int;            (* number of parameters of the above inductive type *)
    ci_cstr_ndecls : int array;     (* For each constructor, the corresponding integer determines
                                       the number of values that can be bound in a match-construct.
                                       NOTE: parameters of the inductive type are therefore excluded from the count *)
    ci_cstr_nargs : int array;      (* for each constructor, the corresponding integers determines
                                       the number of values that can be applied to the constructor,
                                       in addition to the parameters of the related inductive type
                                       NOTE: "lets" are therefore excluded from the count
                                       NOTE: parameters of the inductive type are also excluded from the count *)
    ci_relevance : Sorts.relevance;
    ci_pp_info    : case_printing   (* not interpreted by the kernel *)
  }

(********************************************************************)
(*       Constructions as implemented                               *)
(********************************************************************)

(* [constr array] is an instance matching definitional [named_context] in
   the same order (i.e. last argument first) *)
type 'constr pexistential = existential_key * 'constr list
type ('constr, 'types) prec_declaration =
    Name.t binder_annot array * 'types array * 'constr array
type ('constr, 'types) pfixpoint =
    (int array * int) * ('constr, 'types) prec_declaration
type ('constr, 'types) pcofixpoint =
    int * ('constr, 'types) prec_declaration
type 'a puniverses = 'a Univ.puniverses
type pconstant = Constant.t puniverses
type pinductive = inductive puniverses
type pconstructor = constructor puniverses

type 'constr pcase_invert =
  | NoInvert
  | CaseInvert of { indices : 'constr array }

type 'constr pcase_branch = Name.t Context.binder_annot array * 'constr
type 'types pcase_return = Name.t Context.binder_annot array * 'types

type ('constr, 'types, 'univs) pcase =
  case_info * 'univs * 'constr array * 'types pcase_return * 'constr pcase_invert * 'constr * 'constr pcase_branch array

(* [Var] is used for named variables and [Rel] for variables as
   de Bruijn indices. *)
type ('constr, 'types, 'sort, 'univs) kind_of_term =
  | Rel       of int
  | Var       of Id.t
  | Meta      of metavariable
  | Evar      of 'constr pexistential
  | Sort      of 'sort
  | Cast      of 'constr * cast_kind * 'types
  | Prod      of Name.t binder_annot * 'types * 'types
  | Lambda    of Name.t binder_annot * 'types * 'constr
  | LetIn     of Name.t binder_annot * 'constr * 'types * 'constr
  | App       of 'constr * 'constr array
  | Const     of (Constant.t * 'univs)
  | Ind       of (inductive * 'univs)
  | Construct of (constructor * 'univs)
  | Case      of case_info * 'univs * 'constr array * 'types pcase_return * 'constr pcase_invert * 'constr * 'constr pcase_branch array
  | Fix       of ('constr, 'types) pfixpoint
  | CoFix     of ('constr, 'types) pcofixpoint
  | Proj      of Projection.t * 'constr
  | Int       of Uint63.t
  | Float     of Float64.t
  | Array     of 'univs * 'constr array * 'constr * 'types
(* constr is the fixpoint of the previous type. Requires option
   -rectypes of the Caml compiler to be set *)
type t = (t, t, Sorts.t, Instance.t) kind_of_term
type constr = t

type existential = existential_key * constr list

type types = constr

type case_invert = constr pcase_invert
type case_return = types pcase_return
type case_branch = constr pcase_branch
type case = (constr, types, Instance.t) pcase
type rec_declaration = (constr, types) prec_declaration
type fixpoint = (constr, types) pfixpoint
type cofixpoint = (constr, types) pcofixpoint

(*********************)
(* Term constructors *)
(*********************)

(* Constructs a de Bruijn index with number n *)
let rels =
  [|Rel  1;Rel  2;Rel  3;Rel  4;Rel  5;Rel  6;Rel  7; Rel  8;
    Rel  9;Rel 10;Rel 11;Rel 12;Rel 13;Rel 14;Rel 15; Rel 16|]

let mkRel n = if 0<n && n<=16 then rels.(n-1) else Rel n

(* Construct a type *)
let mkSProp  = Sort Sorts.sprop
let mkProp   = Sort Sorts.prop
let mkSet    = Sort Sorts.set
let mkType u = Sort (Sorts.sort_of_univ u)
let mkSort   = function
  | Sorts.SProp -> mkSProp
  | Sorts.Prop -> mkProp (* Easy sharing *)
  | Sorts.Set -> mkSet
  | Sorts.Type _ as s -> Sort s

(* Constructs the term t1::t2, i.e. the term t1 casted with the type t2 *)
(* (that means t2 is declared as the type of t1) *)
let mkCast (t1,k2,t2) =
  match t1 with
  | Cast (c,k1, _) when (k1 == VMcast || k1 == NATIVEcast) && k1 == k2 -> Cast (c,k1,t2)
  | _ -> Cast (t1,k2,t2)

(* Constructs the product (x:t1)t2 *)
let mkProd (x,t1,t2) = Prod (x,t1,t2)

(* Constructs the abstraction [x:t1]t2 *)
let mkLambda (x,t1,t2) = Lambda (x,t1,t2)

(* Constructs [x=c_1:t]c_2 *)
let mkLetIn (x,c1,t,c2) = LetIn (x,c1,t,c2)

(* If lt = [t1; ...; tn], constructs the application (t1 ... tn) *)
(* We ensure applicative terms have at least one argument and the
   function is not itself an applicative term *)
let mkApp (f, a) =
  if Int.equal (Array.length a) 0 then f else
    match f with
      | App (g, cl) -> App (g, Array.append cl a)
      | _ -> App (f, a)

let map_puniverses f (x,u) = (f x, u)
let in_punivs a = (a, Univ.Instance.empty)

(* Constructs a constant *)
let mkConst c = Const (in_punivs c)
let mkConstU c = Const c

(* Constructs an applied projection *)
let mkProj (p,c) = Proj (p,c)

(* Constructs an existential variable *)
let mkEvar e = Evar e

(* Constructs the ith (co)inductive type of the block named kn *)
let mkInd m = Ind (in_punivs m)
let mkIndU m = Ind m

(* Constructs the jth constructor of the ith (co)inductive type of the
   block named kn. *)
let mkConstruct c = Construct (in_punivs c)
let mkConstructU c = Construct c
let mkConstructUi ((ind,u),i) = Construct ((ind,i),u)

(* Constructs the term <p>Case c of c1 | c2 .. | cn end *)
let mkCase (ci, u, params, p, iv, c, ac) = Case (ci, u, params, p, iv, c, ac)

(* If recindxs = [|i1,...in|]
      funnames = [|f1,...fn|]
      typarray = [|t1,...tn|]
      bodies   = [|b1,...bn|]
   then

      mkFix ((recindxs,i),(funnames,typarray,bodies))

   constructs the ith function of the block

    Fixpoint f1 [ctx1] : t1 := b1
    with     f2 [ctx2] : t2 := b2
    ...
    with     fn [ctxn] : tn := bn.

   where the length of the jth context is ij.
*)

let mkFix fix = Fix fix

(* If funnames = [|f1,...fn|]
      typarray = [|t1,...tn|]
      bodies   = [|b1,...bn|]
   then

      mkCoFix (i,(funnames,typsarray,bodies))

   constructs the ith function of the block

    CoFixpoint f1 : t1 := b1
    with       f2 : t2 := b2
    ...
    with       fn : tn := bn.
*)
let mkCoFix cofix= CoFix cofix

(* Constructs an existential variable named "?n" *)
let mkMeta  n =  Meta n

(* Constructs a Variable named id *)
let mkVar id = Var id

let mkRef (gr,u) = let open GlobRef in match gr with
  | ConstRef c -> mkConstU (c,u)
  | IndRef ind -> mkIndU (ind,u)
  | ConstructRef c -> mkConstructU (c,u)
  | VarRef x -> mkVar x

(* Constructs a primitive integer *)
let mkInt i = Int i

(* Constructs an array *)
let mkArray (u,t,def,ty) = Array (u,t,def,ty)

(* Constructs a primitive float number *)
let mkFloat f = Float f

(************************************************************************)
(*    kind_of_term = constructions as seen by the user                 *)
(************************************************************************)

(* User view of [constr]. For [App], it is ensured there is at
   least one argument and the function is not itself an applicative
   term *)

let kind (c:t) = c

let rec kind_nocast_gen kind c =
  match kind c with
  | Cast (c, _, _) -> kind_nocast_gen kind c
  | App (h, outer) as k ->
    (match kind_nocast_gen kind h with
     | App (h, inner) -> App (h, Array.append inner outer)
     | _ -> k)
  | k -> k

let kind_nocast c = kind_nocast_gen kind c

(* The other way around. We treat specifically smart constructors *)
let of_kind = function
| App (f, a) -> mkApp (f, a)
| Cast (c, knd, t) -> mkCast (c, knd, t)
| k -> k

(**********************************************************************)
(*          Non primitive term destructors                            *)
(**********************************************************************)

(* Destructor operations : partial functions
   Raise [DestKO] if the const has not the expected form *)

exception DestKO

let isMeta c = match kind c with Meta _ -> true | _ -> false

(* Destructs a type *)
let isSort c = match kind c with
  | Sort _ -> true
  | _ -> false

let rec isprop c = match kind c with
  | Sort (Sorts.Prop | Sorts.Set) -> true
  | Cast (c,_,_) -> isprop c
  | _ -> false

let rec is_Prop c = match kind c with
  | Sort Sorts.Prop -> true
  | Cast (c,_,_) -> is_Prop c
  | _ -> false

let rec is_Set c = match kind c with
  | Sort Sorts.Set -> true
  | Cast (c,_,_) -> is_Set c
  | _ -> false

let rec is_Type c = match kind c with
  | Sort (Sorts.Type _) -> true
  | Cast (c,_,_) -> is_Type c
  | _ -> false

let is_small = Sorts.is_small
let iskind c = isprop c || is_Type c

(* Tests if an evar *)
let isEvar c = match kind c with Evar _ -> true | _ -> false
let isEvar_or_Meta c = match kind c with
  | Evar _ | Meta _ -> true
  | _ -> false

let isCast c = match kind c with Cast _ -> true | _ -> false
(* Tests if a de Bruijn index *)
let isRel c = match kind c with Rel _ -> true | _ -> false
let isRelN n c =
  match kind c with Rel n' -> Int.equal n n' | _ -> false
(* Tests if a variable *)
let isVar c = match kind c with Var _ -> true | _ -> false
let isVarId id c = match kind c with Var id' -> Id.equal id id' | _ -> false
(* Tests if an inductive *)
let isInd c = match kind c with Ind _ -> true | _ -> false
let isProd c = match kind c with | Prod _ -> true | _ -> false
let isLambda c = match kind c with | Lambda _ -> true | _ -> false
let isLetIn c =  match kind c with LetIn _ -> true | _ -> false
let isApp c = match kind c with App _ -> true | _ -> false
let isConst c = match kind c with Const _ -> true | _ -> false
let isConstruct c = match kind c with Construct _ -> true | _ -> false
let isCase c =  match kind c with Case _ -> true | _ -> false
let isProj c =  match kind c with Proj _ -> true | _ -> false
let isFix c =  match kind c with Fix _ -> true | _ -> false
let isCoFix c =  match kind c with CoFix _ -> true | _ -> false

let isRef c = match kind c with
  | Const _ | Ind _ | Construct _ | Var _ -> true
  | _ -> false

let isRefX x c =
  let open GlobRef in
  match x, kind c with
  | ConstRef c, Const (c', _) -> Constant.CanOrd.equal c c'
  | IndRef i, Ind (i', _) -> Ind.CanOrd.equal i i'
  | ConstructRef i, Construct (i', _) -> Construct.CanOrd.equal i i'
  | VarRef id, Var id' -> Id.equal id id'
  | _ -> false

(* Destructs a de Bruijn index *)
let destRel c = match kind c with
  | Rel n -> n
  | _ -> raise DestKO

(* Destructs an existential variable *)
let destMeta c = match kind c with
  | Meta n -> n
  | _ -> raise DestKO

(* Destructs a variable *)
let destVar c = match kind c with
  | Var id -> id
  | _ -> raise DestKO

let destSort c = match kind c with
  | Sort s -> s
  | _ -> raise DestKO

(* Destructs a casted term *)
let destCast c = match kind c with
  | Cast (t1,k,t2) -> (t1,k,t2)
  | _ -> raise DestKO

(* Destructs the product (x:t1)t2 *)
let destProd c = match kind c with
  | Prod (x,t1,t2) -> (x,t1,t2)
  | _ -> raise DestKO

(* Destructs the abstraction [x:t1]t2 *)
let destLambda c = match kind c with
  | Lambda (x,t1,t2) -> (x,t1,t2)
  | _ -> raise DestKO

(* Destructs the let [x:=b:t1]t2 *)
let destLetIn c = match kind c with
  | LetIn (x,b,t1,t2) -> (x,b,t1,t2)
  | _ -> raise DestKO

(* Destructs an application *)
let destApp c = match kind c with
  | App (f,a) -> (f, a)
  | _ -> raise DestKO

(* Destructs a constant *)
let destConst c = match kind c with
  | Const kn -> kn
  | _ -> raise DestKO

(* Destructs an existential variable *)
let destEvar c = match kind c with
  | Evar (_kn, _a as r) -> r
  | _ -> raise DestKO

(* Destructs a (co)inductive type named kn *)
let destInd c = match kind c with
  | Ind (_kn, _a as r) -> r
  | _ -> raise DestKO

(* Destructs a constructor *)
let destConstruct c = match kind c with
  | Construct (_kn, _a as r) -> r
  | _ -> raise DestKO

(* Destructs a term <p>Case c of lc1 | lc2 .. | lcn end *)
let destCase c = match kind c with
  | Case (ci,u,params,p,iv,c,v) -> (ci,u,params,p,iv,c,v)
  | _ -> raise DestKO

let destProj c = match kind c with
  | Proj (p, c) -> (p, c)
  | _ -> raise DestKO

let destFix c = match kind c with
  | Fix fix -> fix
  | _ -> raise DestKO

let destCoFix c = match kind c with
  | CoFix cofix -> cofix
  | _ -> raise DestKO

let destRef c = let open GlobRef in match kind c with
  | Var x -> VarRef x, Univ.Instance.empty
  | Const (c,u) -> ConstRef c, u
  | Ind (ind,u) -> IndRef ind, u
  | Construct (c,u) -> ConstructRef c, u
  | _ -> raise DestKO

(******************************************************************)
(* Flattening and unflattening of embedded applications and casts *)
(******************************************************************)

let decompose_app c =
  match kind c with
    | App (f,cl) -> (f, Array.to_list cl)
    | _ -> (c,[])

let decompose_appvect c =
  match kind c with
    | App (f,cl) -> (f, cl)
    | _ -> (c,[||])

(****************************************************************************)
(*              Functions to recur through subterms                         *)
(****************************************************************************)

(* [fold f acc c] folds [f] on the immediate subterms of [c]
   starting from [acc] and proceeding from left to right according to
   the usual representation of the constructions; it is not recursive *)

let fold_invert f acc = function
  | NoInvert -> acc
  | CaseInvert {indices} ->
    Array.fold_left f acc indices

let fold f acc c = match kind c with
  | (Rel _ | Meta _ | Var _   | Sort _ | Const _ | Ind _
    | Construct _ | Int _ | Float _) -> acc
  | Cast (c,_,t) -> f (f acc c) t
  | Prod (_,t,c) -> f (f acc t) c
  | Lambda (_,t,c) -> f (f acc t) c
  | LetIn (_,b,t,c) -> f (f (f acc b) t) c
  | App (c,l) -> Array.fold_left f (f acc c) l
  | Proj (_p,c) -> f acc c
  | Evar (_,l) -> List.fold_left f acc l
  | Case (_,_,pms,(_,p),iv,c,bl) ->
    Array.fold_left (fun acc (_, b) -> f acc b) (f (fold_invert f (f (Array.fold_left f acc pms) p) iv) c) bl
  | Fix (_,(_lna,tl,bl)) ->
    Array.fold_left2 (fun acc t b -> f (f acc t) b) acc tl bl
  | CoFix (_,(_lna,tl,bl)) ->
    Array.fold_left2 (fun acc t b -> f (f acc t) b) acc tl bl
  | Array(_u,t,def,ty) ->
    f (f (Array.fold_left f acc t) def) ty

(* [iter f c] iters [f] on the immediate subterms of [c]; it is
   not recursive and the order with which subterms are processed is
   not specified *)

let iter_invert f = function
  | NoInvert -> ()
  | CaseInvert {indices;} ->
    Array.iter f indices

let iter f c = match kind c with
  | (Rel _ | Meta _ | Var _   | Sort _ | Const _ | Ind _
    | Construct _ | Int _ | Float _) -> ()
  | Cast (c,_,t) -> f c; f t
  | Prod (_,t,c) -> f t; f c
  | Lambda (_,t,c) -> f t; f c
  | LetIn (_,b,t,c) -> f b; f t; f c
  | App (c,l) -> f c; Array.iter f l
  | Proj (_p,c) -> f c
  | Evar (_,l) -> List.iter f l
  | Case (_,_,pms,p,iv,c,bl) ->
    Array.iter f pms; f (snd p); iter_invert f iv; f c; Array.iter (fun (_, b) -> f b) bl
  | Fix (_,(_,tl,bl)) -> Array.iter f tl; Array.iter f bl
  | CoFix (_,(_,tl,bl)) -> Array.iter f tl; Array.iter f bl
  | Array(_u,t,def,ty) -> Array.iter f t; f def; f ty

(* [iter_with_binders g f n c] iters [f n] on the immediate
   subterms of [c]; it carries an extra data [n] (typically a lift
   index) which is processed by [g] (which typically add 1 to [n]) at
   each binder traversal; it is not recursive and the order with which
   subterms are processed is not specified *)

let iter_with_binders g f n c = match kind c with
  | (Rel _ | Meta _ | Var _   | Sort _ | Const _ | Ind _
    | Construct _ | Int _ | Float _) -> ()
  | Cast (c,_,t) -> f n c; f n t
  | Prod (_,t,c) -> f n t; f (g n) c
  | Lambda (_,t,c) -> f n t; f (g n) c
  | LetIn (_,b,t,c) -> f n b; f n t; f (g n) c
  | App (c,l) -> f n c; Array.Fun1.iter f n l
  | Evar (_,l) -> List.iter (fun c -> f n c) l
  | Case (_,_,pms,p,iv,c,bl) ->
    Array.Fun1.iter f n pms;
    f (iterate g (Array.length (fst p)) n) (snd p);
    iter_invert (f n) iv;
    f n c;
    Array.Fun1.iter (fun n (ctx, b) -> f (iterate g (Array.length ctx) n) b) n bl
  | Proj (_p,c) -> f n c
  | Fix (_,(_,tl,bl)) ->
      Array.Fun1.iter f n tl;
      Array.Fun1.iter f (iterate g (Array.length tl) n) bl
  | CoFix (_,(_,tl,bl)) ->
      Array.Fun1.iter f n tl;
      Array.Fun1.iter f (iterate g (Array.length tl) n) bl
  | Array(_u,t,def,ty) ->
    Array.iter (f n) t; f n def; f n ty

(* [fold_constr_with_binders g f n acc c] folds [f n] on the immediate
   subterms of [c] starting from [acc] and proceeding from left to
   right according to the usual representation of the constructions as
   [fold_constr] but it carries an extra data [n] (typically a lift
   index) which is processed by [g] (which typically add 1 to [n]) at
   each binder traversal; it is not recursive *)

let fold_constr_with_binders g f n acc c =
  match kind c with
  | (Rel _ | Meta _ | Var _   | Sort _ | Const _ | Ind _
    | Construct _ | Int _ | Float _) -> acc
  | Cast (c,_, t) -> f n (f n acc c) t
  | Prod (_na,t,c) -> f (g  n) (f n acc t) c
  | Lambda (_na,t,c) -> f (g  n) (f n acc t) c
  | LetIn (_na,b,t,c) -> f (g  n) (f n (f n acc b) t) c
  | App (c,l) -> Array.fold_left (f n) (f n acc c) l
  | Proj (_p,c) -> f n acc c
  | Evar (_,l) -> List.fold_left (f n) acc l
  | Case (_,_,pms,p,iv,c,bl) ->
    let fold_ctx n accu (nas, c) =
      f (iterate g (Array.length nas) n) accu c
    in
    Array.fold_left (fold_ctx n) (f n (fold_invert (f n) (fold_ctx n (Array.fold_left (f n) acc pms) p) iv) c) bl
  | Fix (_,(_,tl,bl)) ->
      let n' = iterate g (Array.length tl) n in
      let fd = Array.map2 (fun t b -> (t,b)) tl bl in
      Array.fold_left (fun acc (t,b) -> f n' (f n acc t) b) acc fd
  | CoFix (_,(_,tl,bl)) ->
      let n' = iterate g (Array.length tl) n in
      let fd = Array.map2 (fun t b -> (t,b)) tl bl in
      Array.fold_left (fun acc (t,b) -> f n' (f n acc t) b) acc fd
  | Array(_u,t,def,ty) ->
    f n (f n (Array.fold_left (f n) acc t) def) ty

(* [map f c] maps [f] on the immediate subterms of [c]; it is
   not recursive and the order with which subterms are processed is
   not specified *)

let map_under_context f d =
  let (nas, p) = d in
  let p' = f p in
  if p' == p then d else (nas, p')

let map_branches f bl =
  let bl' = Array.map (map_under_context f) bl in
  if Array.for_all2 (==) bl' bl then bl else bl'

let map_return_predicate f p =
  map_under_context f p

let map_under_context_with_binders g f l d =
  let (nas, p) = d in
  let l = iterate g (Array.length nas) l in
  let p' = f l p in
  if p' == p then d else (nas, p')

let map_branches_with_binders g f l bl =
  let bl' = Array.map (map_under_context_with_binders g f l) bl in
  if Array.for_all2 (==) bl' bl then bl else bl'

let map_return_predicate_with_binders g f l p =
  map_under_context_with_binders g f l p

let map_invert f = function
  | NoInvert -> NoInvert
  | CaseInvert {indices;} as orig ->
    let indices' = Array.Smart.map f indices in
    if indices == indices' then orig
    else CaseInvert {indices=indices';}

let map f c = match kind c with
  | (Rel _ | Meta _ | Var _   | Sort _ | Const _ | Ind _
    | Construct _ | Int _ | Float _) -> c
  | Cast (b,k,t) ->
      let b' = f b in
      let t' = f t in
      if b'==b && t' == t then c
      else mkCast (b', k, t')
  | Prod (na,t,b) ->
      let b' = f b in
      let t' = f t in
      if b'==b && t' == t then c
      else mkProd (na, t', b')
  | Lambda (na,t,b) ->
      let b' = f b in
      let t' = f t in
      if b'==b && t' == t then c
      else mkLambda (na, t', b')
  | LetIn (na,b,t,k) ->
      let b' = f b in
      let t' = f t in
      let k' = f k in
      if b'==b && t' == t && k'==k then c
      else mkLetIn (na, b', t', k')
  | App (b,l) ->
      let b' = f b in
      let l' = Array.Smart.map f l in
      if b'==b && l'==l then c
      else mkApp (b', l')
  | Proj (p,t) ->
      let t' = f t in
      if t' == t then c
      else mkProj (p, t')
  | Evar (e,l) ->
      let l' = List.Smart.map f l in
      if l'==l then c
      else mkEvar (e, l')
  | Case (ci,u,pms,p,iv,b,bl) ->
      let pms' = Array.Smart.map f pms in
      let b' = f b in
      let iv' = map_invert f iv in
      let p' = map_return_predicate f p in
      let bl' = map_branches f bl in
      if b'==b && iv'==iv && p'==p && bl'==bl && pms'==pms then c
      else mkCase (ci, u, pms', p', iv', b', bl')
  | Fix (ln,(lna,tl,bl)) ->
      let tl' = Array.Smart.map f tl in
      let bl' = Array.Smart.map f bl in
      if tl'==tl && bl'==bl then c
      else mkFix (ln,(lna,tl',bl'))
  | CoFix(ln,(lna,tl,bl)) ->
      let tl' = Array.Smart.map f tl in
      let bl' = Array.Smart.map f bl in
      if tl'==tl && bl'==bl then c
      else mkCoFix (ln,(lna,tl',bl'))
  | Array(u,t,def,ty) ->
    let t' = Array.Smart.map f t in
    let def' = f def in
    let ty' = f ty in
    if def'==def && t==t' && ty==ty' then c
    else mkArray(u,t',def',ty')

(* Like {!map} but with an accumulator. *)

let fold_map_invert f acc = function
  | NoInvert -> acc, NoInvert
  | CaseInvert {indices;} as orig ->
    let acc, indices' = Array.fold_left_map f acc indices in
    if indices==indices' then acc, orig
    else acc, CaseInvert {indices=indices';}

let fold_map_under_context f accu d =
  let (nas, p) = d in
  let accu, p' = f accu p in
  if p' == p then accu, d else accu, (nas, p')

let fold_map_branches f accu bl =
  let accu, bl' = Array.Smart.fold_left_map (fold_map_under_context f) accu bl in
  if Array.for_all2 (==) bl' bl then accu, bl else accu, bl'

let fold_map_return_predicate f accu p =
  fold_map_under_context f accu p

let fold_map f accu c = match kind c with
  | (Rel _ | Meta _ | Var _   | Sort _ | Const _ | Ind _
    | Construct _ | Int _ | Float _) -> accu, c
  | Cast (b,k,t) ->
      let accu, b' = f accu b in
      let accu, t' = f accu t in
      if b'==b && t' == t then accu, c
      else accu, mkCast (b', k, t')
  | Prod (na,t,b) ->
      let accu, b' = f accu b in
      let accu, t' = f accu t in
      if b'==b && t' == t then accu, c
      else accu, mkProd (na, t', b')
  | Lambda (na,t,b) ->
      let accu, b' = f accu b in
      let accu, t' = f accu t in
      if b'==b && t' == t then accu, c
      else accu, mkLambda (na, t', b')
  | LetIn (na,b,t,k) ->
      let accu, b' = f accu b in
      let accu, t' = f accu t in
      let accu, k' = f accu k in
      if b'==b && t' == t && k'==k then accu, c
      else accu, mkLetIn (na, b', t', k')
  | App (b,l) ->
      let accu, b' = f accu b in
      let accu, l' = Array.Smart.fold_left_map f accu l in
      if b'==b && l'==l then accu, c
      else accu, mkApp (b', l')
  | Proj (p,t) ->
      let accu, t' = f accu t in
      if t' == t then accu, c
      else accu, mkProj (p, t')
  | Evar (e,l) ->
    (* Doesn't matter, we should not hashcons evars anyways *)
      let accu, l' = List.fold_left_map f accu l in
      if l'==l then accu, c
      else accu, mkEvar (e, l')
  | Case (ci,u,pms,p,iv,b,bl) ->
      let accu, pms' = Array.Smart.fold_left_map f accu pms in
      let accu, p' = fold_map_return_predicate f accu p in
      let accu, iv' = fold_map_invert f accu iv in
      let accu, b' = f accu b in
      let accu, bl' = fold_map_branches f accu bl in
      if pms'==pms && p'==p && iv'==iv && b'==b && bl'==bl then accu, c
      else accu, mkCase (ci, u, pms', p', iv', b', bl')
  | Fix (ln,(lna,tl,bl)) ->
      let accu, tl' = Array.Smart.fold_left_map f accu tl in
      let accu, bl' = Array.Smart.fold_left_map f accu bl in
      if tl'==tl && bl'==bl then accu, c
      else accu, mkFix (ln,(lna,tl',bl'))
  | CoFix(ln,(lna,tl,bl)) ->
      let accu, tl' = Array.Smart.fold_left_map f accu tl in
      let accu, bl' = Array.Smart.fold_left_map f accu bl in
      if tl'==tl && bl'==bl then accu, c
      else accu, mkCoFix (ln,(lna,tl',bl'))
  | Array(u,t,def,ty) ->
    let accu, t' = Array.Smart.fold_left_map f accu t in
    let accu, def' = f accu def in
    let accu, ty' = f accu ty in
    if def'==def && t==t' && ty==ty' then accu, c
    else accu, mkArray(u,t',def',ty')

(* [map_with_binders g f n c] maps [f n] on the immediate
   subterms of [c]; it carries an extra data [n] (typically a lift
   index) which is processed by [g] (which typically add 1 to [n]) at
   each binder traversal; it is not recursive and the order with which
   subterms are processed is not specified *)

let map_with_binders g f l c0 = match kind c0 with
  | (Rel _ | Meta _ | Var _   | Sort _ | Const _ | Ind _
    | Construct _ | Int _ | Float _) -> c0
  | Cast (c, k, t) ->
    let c' = f l c in
    let t' = f l t in
    if c' == c && t' == t then c0
    else mkCast (c', k, t')
  | Prod (na, t, c) ->
    let t' = f l t in
    let c' = f (g l) c in
    if t' == t && c' == c then c0
    else mkProd (na, t', c')
  | Lambda (na, t, c) ->
    let t' = f l t in
    let c' = f (g l) c in
    if t' == t && c' == c then c0
    else mkLambda (na, t', c')
  | LetIn (na, b, t, c) ->
    let b' = f l b in
    let t' = f l t in
    let c' = f (g l) c in
    if b' == b && t' == t && c' == c then c0
    else mkLetIn (na, b', t', c')
  | App (c, al) ->
    let c' = f l c in
    let al' = Array.Fun1.Smart.map f l al in
    if c' == c && al' == al then c0
    else mkApp (c', al')
  | Proj (p, t) ->
    let t' = f l t in
    if t' == t then c0
    else mkProj (p, t')
  | Evar (e, al) ->
    let al' = List.Smart.map (fun c -> f l c) al in
    if al' == al then c0
    else mkEvar (e, al')
  | Case (ci, u, pms, p, iv, c, bl) ->
    let pms' = Array.Fun1.Smart.map f l pms in
    let p' = map_return_predicate_with_binders g f l p in
    let iv' = map_invert (f l) iv in
    let c' = f l c in
    let bl' = map_branches_with_binders g f l bl in
    if pms' == pms && p' == p && iv' == iv && c' == c && bl' == bl then c0
    else mkCase (ci, u, pms', p', iv', c', bl')
  | Fix (ln, (lna, tl, bl)) ->
    let tl' = Array.Fun1.Smart.map f l tl in
    let l' = iterate g (Array.length tl) l in
    let bl' = Array.Fun1.Smart.map f l' bl in
    if tl' == tl && bl' == bl then c0
    else mkFix (ln,(lna,tl',bl'))
  | CoFix(ln,(lna,tl,bl)) ->
    let tl' = Array.Fun1.Smart.map f l tl in
    let l' = iterate g (Array.length tl) l in
    let bl' = Array.Fun1.Smart.map f l' bl in
    mkCoFix (ln,(lna,tl',bl'))
  | Array(u,t,def,ty) ->
    let t' = Array.Fun1.Smart.map f l t in
    let def' = f l def in
    let ty' = f l ty in
    if def'==def && t==t' && ty==ty' then c0
    else mkArray(u,t',def',ty')

(*********************)
(*      Lifting      *)
(*********************)

(* The generic lifting function *)
let rec exliftn el c =
  let open Esubst in
  match kind c with
  | Rel i -> mkRel(reloc_rel i el)
  | _ -> map_with_binders el_lift exliftn el c

(* Lifting the binding depth across k bindings *)

let liftn n k c =
  let open Esubst in
  match el_liftn (pred k) (el_shft n el_id) with
    | ELID -> c
    | el -> exliftn el c

let lift n = liftn n 1

type 'univs instance_compare_fn = (GlobRef.t * int) option ->
  'univs -> 'univs -> bool

type 'constr constr_compare_fn = int -> 'constr -> 'constr -> bool

(* [compare_head_gen_evar k1 k2 u s e eq leq c1 c2] compare [c1] and
   [c2] (using [k1] to expose the structure of [c1] and [k2] to expose
   the structure [c2]) using [eq] to compare the immediate subterms of
   [c1] of [c2] for conversion if needed, [leq] for cumulativity, [u]
   to compare universe instances, and [s] to compare sorts; Cast's,
   application associativity, binders name and Cases annotations are
   not taken into account. Note that as [kind1] and [kind2] are
   potentially different, we cannot use, in recursive case, the
   optimisation that physically equal arrays are equals (hence the
   calls to {!Array.equal_norefl}). *)

let eq_invert eq iv1 iv2 =
  match iv1, iv2 with
  | NoInvert, NoInvert -> true
  | NoInvert, CaseInvert _ | CaseInvert _, NoInvert -> false
  | CaseInvert {indices}, CaseInvert iv2 ->
    Array.equal eq indices iv2.indices

let eq_under_context eq (_nas1, p1) (_nas2, p2) =
  eq p1 p2

let compare_head_gen_leq_with kind1 kind2 leq_universes leq_sorts eq leq nargs t1 t2 =
  match kind_nocast_gen kind1 t1, kind_nocast_gen kind2 t2 with
  | Cast _, _ | _, Cast _ -> assert false (* kind_nocast *)
  | Rel n1, Rel n2 -> Int.equal n1 n2
  | Meta m1, Meta m2 -> Int.equal m1 m2
  | Var id1, Var id2 -> Id.equal id1 id2
  | Int i1, Int i2 -> Uint63.equal i1 i2
  | Float f1, Float f2 -> Float64.equal f1 f2
  | Sort s1, Sort s2 -> leq_sorts s1 s2
  | Prod (_,t1,c1), Prod (_,t2,c2) -> eq 0 t1 t2 && leq 0 c1 c2
  | Lambda (_,t1,c1), Lambda (_,t2,c2) -> eq 0 t1 t2 && eq 0 c1 c2
  | LetIn (_,b1,t1,c1), LetIn (_,b2,t2,c2) -> eq 0 b1 b2 && eq 0 t1 t2 && leq nargs c1 c2
  (* Why do we suddenly make a special case for Cast here? *)
  | App (c1, l1), App (c2, l2) ->
    let len = Array.length l1 in
    Int.equal len (Array.length l2) &&
    leq (nargs+len) c1 c2 && Array.equal_norefl (eq 0) l1 l2
  | Proj (p1,c1), Proj (p2,c2) -> Projection.CanOrd.equal p1 p2 && eq 0 c1 c2
  | Evar (e1,l1), Evar (e2,l2) -> Evar.equal e1 e2 && List.equal (eq 0) l1 l2
  | Const (c1,u1), Const (c2,u2) ->
    (* The args length currently isn't used but may as well pass it. *)
    Constant.CanOrd.equal c1 c2 && leq_universes (Some (GlobRef.ConstRef c1, nargs)) u1 u2
  | Ind (c1,u1), Ind (c2,u2) -> Ind.CanOrd.equal c1 c2 && leq_universes (Some (GlobRef.IndRef c1, nargs)) u1 u2
  | Construct (c1,u1), Construct (c2,u2) ->
    Construct.CanOrd.equal c1 c2 && leq_universes (Some (GlobRef.ConstructRef c1, nargs)) u1 u2
  | Case (ci1,u1,pms1,p1,iv1,c1,bl1), Case (ci2,u2,pms2,p2,iv2,c2,bl2) ->
    (** FIXME: what are we doing with u1 = u2 ? *)
    Ind.CanOrd.equal ci1.ci_ind ci2.ci_ind && leq_universes (Some (GlobRef.IndRef ci1.ci_ind, 0)) u1 u2 &&
    Array.equal (eq 0) pms1 pms2 && eq_under_context (eq 0) p1 p2 &&
    eq_invert (eq 0) iv1 iv2 &&
    eq 0 c1 c2 && Array.equal (eq_under_context (eq 0)) bl1 bl2
  | Fix ((ln1, i1),(_,tl1,bl1)), Fix ((ln2, i2),(_,tl2,bl2)) ->
    Int.equal i1 i2 && Array.equal Int.equal ln1 ln2
    && Array.equal_norefl (eq 0) tl1 tl2 && Array.equal_norefl (eq 0) bl1 bl2
  | CoFix(ln1,(_,tl1,bl1)), CoFix(ln2,(_,tl2,bl2)) ->
    Int.equal ln1 ln2 && Array.equal_norefl (eq 0) tl1 tl2 && Array.equal_norefl (eq 0) bl1 bl2
  | Array(u1,t1,def1,ty1), Array(u2,t2,def2,ty2) ->
    leq_universes None u1 u2 &&
    Array.equal_norefl (eq 0) t1 t2 &&
    eq 0 def1 def2 && eq 0 ty1 ty2
  | (Rel _ | Meta _ | Var _ | Sort _ | Prod _ | Lambda _ | LetIn _ | App _
    | Proj _ | Evar _ | Const _ | Ind _ | Construct _ | Case _ | Fix _
    | CoFix _ | Int _ | Float _| Array _), _ -> false

(* [compare_head_gen_leq u s eq leq c1 c2] compare [c1] and [c2] using [eq] to compare
   the immediate subterms of [c1] of [c2] for conversion if needed, [leq] for cumulativity,
   [u] to compare universe instances and [s] to compare sorts; Cast's,
   application associativity, binders name and Cases annotations are
   not taken into account *)

let compare_head_gen_leq leq_universes leq_sorts eq leq t1 t2 =
  compare_head_gen_leq_with kind kind leq_universes leq_sorts eq leq t1 t2

(* [compare_head_gen u s f c1 c2] compare [c1] and [c2] using [f] to
   compare the immediate subterms of [c1] of [c2] if needed, [u] to
   compare universe instances and [s] to compare sorts; Cast's,
   application associativity, binders name and Cases annotations are
   not taken into account.

   [compare_head_gen_with] is a variant taking kind-of-term functions,
   to expose subterms of [c1] and [c2], as arguments. *)

let compare_head_gen_with kind1 kind2 eq_universes eq_sorts eq t1 t2 =
  compare_head_gen_leq_with kind1 kind2 eq_universes eq_sorts eq eq t1 t2

let compare_head_gen eq_universes eq_sorts eq t1 t2 =
  compare_head_gen_leq eq_universes eq_sorts eq eq t1 t2

let compare_head = compare_head_gen (fun _ -> Univ.Instance.equal) Sorts.equal

(*******************************)
(*  alpha conversion functions *)
(*******************************)

(* alpha conversion : ignore print names and casts *)

let rec eq_constr nargs m n =
  (m == n) || compare_head_gen (fun _ -> Instance.equal) Sorts.equal eq_constr nargs m n

let equal n m = eq_constr 0 m n (* to avoid tracing a recursive fun *)

let eq_constr_univs univs m n =
  if m == n then true
  else
    let eq_universes _ = UGraph.check_eq_instances univs in
    let eq_sorts s1 s2 = s1 == s2 || UGraph.check_eq univs (Sorts.univ_of_sort s1) (Sorts.univ_of_sort s2) in
    let rec eq_constr' nargs m n =
      m == n ||	compare_head_gen eq_universes eq_sorts eq_constr' nargs m n
    in compare_head_gen eq_universes eq_sorts eq_constr' 0 m n

let leq_constr_univs univs m n =
  if m == n then true
  else
    let eq_universes _ = UGraph.check_eq_instances univs in
    let eq_sorts s1 s2 = s1 == s2 ||
      UGraph.check_eq univs (Sorts.univ_of_sort s1) (Sorts.univ_of_sort s2) in
    let leq_sorts s1 s2 = s1 == s2 ||
      UGraph.check_leq univs (Sorts.univ_of_sort s1) (Sorts.univ_of_sort s2) in
    let rec eq_constr' nargs m n =
      m == n || compare_head_gen eq_universes eq_sorts eq_constr' nargs m n
    in
    let rec compare_leq nargs m n =
      compare_head_gen_leq eq_universes leq_sorts eq_constr' leq_constr' nargs m n
    and leq_constr' nargs m n = m == n || compare_leq nargs m n in
    compare_leq 0 m n

let eq_constr_univs_infer univs m n =
  if m == n then true, Constraints.empty
  else
    let cstrs = ref Constraints.empty in
    let eq_universes _ = UGraph.check_eq_instances univs in
    let eq_sorts s1 s2 =
      if Sorts.equal s1 s2 then true
      else
        let u1 = Sorts.univ_of_sort s1 and u2 = Sorts.univ_of_sort s2 in
        if UGraph.check_eq univs u1 u2 then true
        else
          (cstrs := Univ.enforce_eq u1 u2 !cstrs;
           true)
    in
    let rec eq_constr' nargs m n =
      m == n || compare_head_gen eq_universes eq_sorts eq_constr' nargs m n
    in
    let res = compare_head_gen eq_universes eq_sorts eq_constr' 0 m n in
    res, !cstrs

let leq_constr_univs_infer univs m n =
  if m == n then true, Constraints.empty
  else
    let cstrs = ref Constraints.empty in
    let eq_universes _ l l' = UGraph.check_eq_instances univs l l' in
    let eq_sorts s1 s2 =
      if Sorts.equal s1 s2 then true
      else
        let u1 = Sorts.univ_of_sort s1 and u2 = Sorts.univ_of_sort s2 in
        if UGraph.check_eq univs u1 u2 then true
        else (cstrs := Univ.enforce_eq u1 u2 !cstrs;
              true)
    in
    let leq_sorts s1 s2 =
      if Sorts.equal s1 s2 then true
      else
        let u1 = Sorts.univ_of_sort s1 and u2 = Sorts.univ_of_sort s2 in
        if UGraph.check_leq univs u1 u2 then true
        else
          (try let c, _ = UGraph.enforce_leq_alg u1 u2 univs in
            cstrs := Univ.Constraints.union c !cstrs;
            true
          with Univ.UniverseInconsistency _ -> false)
    in
    let rec eq_constr' nargs m n =
      m == n || compare_head_gen eq_universes eq_sorts eq_constr' nargs m n
    in
    let rec compare_leq nargs m n =
      compare_head_gen_leq eq_universes leq_sorts eq_constr' leq_constr' nargs m n
    and leq_constr' nargs m n = m == n || compare_leq nargs m n in
    let res = compare_leq 0 m n in
    res, !cstrs

let rec eq_constr_nounivs m n =
  (m == n) || compare_head_gen (fun _ _ _ -> true) (fun _ _ -> true) (fun _ -> eq_constr_nounivs) 0 m n

let compare_invert f iv1 iv2 =
  match iv1, iv2 with
  | NoInvert, NoInvert -> 0
  | NoInvert, CaseInvert _ -> -1
  | CaseInvert _, NoInvert -> 1
  | CaseInvert iv1, CaseInvert iv2 ->
    Array.compare f iv1.indices iv2.indices

let constr_ord_int f t1 t2 =
  let (=?) f g i1 i2 j1 j2=
    let c = f i1 i2 in
    if Int.equal c 0 then g j1 j2 else c in
  let (==?) fg h i1 i2 j1 j2 k1 k2=
    let c=fg i1 i2 j1 j2 in
    if Int.equal c 0 then h k1 k2 else c in
  let fix_cmp (a1, i1) (a2, i2) =
    ((Array.compare Int.compare) =? Int.compare) a1 a2 i1 i2
  in
  let ctx_cmp f (_n1, p1) (_n2, p2) =
    f p1 p2
  in
  match kind t1, kind t2 with
    | Cast (c1,_,_), _ -> f c1 t2
    | _, Cast (c2,_,_) -> f t1 c2
    (* Why this special case? *)
    | App (Cast(c1,_,_),l1), _ -> f (mkApp (c1,l1)) t2
    | _, App (Cast(c2, _,_),l2) -> f t1 (mkApp (c2,l2))
    | Rel n1, Rel n2 -> Int.compare n1 n2
    | Rel _, _ -> -1 | _, Rel _ -> 1
    | Var id1, Var id2 -> Id.compare id1 id2
    | Var _, _ -> -1 | _, Var _ -> 1
    | Meta m1, Meta m2 -> Int.compare m1 m2
    | Meta _, _ -> -1 | _, Meta _ -> 1
    | Evar (e1,l1), Evar (e2,l2) ->
        (Evar.compare =? (List.compare f)) e1 e2 l1 l2
    | Evar _, _ -> -1 | _, Evar _ -> 1
    | Sort s1, Sort s2 -> Sorts.compare s1 s2
    | Sort _, _ -> -1 | _, Sort _ -> 1
    | Prod (_,t1,c1), Prod (_,t2,c2)
    | Lambda (_,t1,c1), Lambda (_,t2,c2) ->
        (f =? f) t1 t2 c1 c2
    | Prod _, _ -> -1 | _, Prod _ -> 1
    | Lambda _, _ -> -1 | _, Lambda _ -> 1
    | LetIn (_,b1,t1,c1), LetIn (_,b2,t2,c2) ->
        ((f =? f) ==? f) b1 b2 t1 t2 c1 c2
    | LetIn _, _ -> -1 | _, LetIn _ -> 1
    | App (c1,l1), App (c2,l2) -> (f =? (Array.compare f)) c1 c2 l1 l2
    | App _, _ -> -1 | _, App _ -> 1
    | Const (c1,_u1), Const (c2,_u2) -> Constant.CanOrd.compare c1 c2
    | Const _, _ -> -1 | _, Const _ -> 1
    | Ind (ind1, _u1), Ind (ind2, _u2) -> Ind.CanOrd.compare ind1 ind2
    | Ind _, _ -> -1 | _, Ind _ -> 1
    | Construct (ct1,_u1), Construct (ct2,_u2) -> Construct.CanOrd.compare ct1 ct2
    | Construct _, _ -> -1 | _, Construct _ -> 1
    | Case (_,_u1,pms1,p1,iv1,c1,bl1), Case (_,_u2,pms2,p2,iv2,c2,bl2) ->
      let c = Array.compare f pms1 pms2 in
      if Int.equal c 0 then let c = ctx_cmp f p1 p2 in
      if Int.equal c 0 then let c = compare_invert f iv1 iv2 in
      if Int.equal c 0 then let c = f c1 c2 in
      if Int.equal c 0 then Array.compare (ctx_cmp f) bl1 bl2
      else c else c else c else c
    | Case _, _ -> -1 | _, Case _ -> 1
    | Fix (ln1,(_,tl1,bl1)), Fix (ln2,(_,tl2,bl2)) ->
        ((fix_cmp =? (Array.compare f)) ==? (Array.compare f))
        ln1 ln2 tl1 tl2 bl1 bl2
    | Fix _, _ -> -1 | _, Fix _ -> 1
    | CoFix(ln1,(_,tl1,bl1)), CoFix(ln2,(_,tl2,bl2)) ->
        ((Int.compare =? (Array.compare f)) ==? (Array.compare f))
        ln1 ln2 tl1 tl2 bl1 bl2
    | CoFix _, _ -> -1 | _, CoFix _ -> 1
    | Proj (p1,c1), Proj (p2,c2) -> (Projection.CanOrd.compare =? f) p1 p2 c1 c2
    | Proj _, _ -> -1 | _, Proj _ -> 1
    | Int i1, Int i2 -> Uint63.compare i1 i2
    | Int _, _ -> -1 | _, Int _ -> 1
    | Float f1, Float f2 -> Float64.total_compare f1 f2
    | Array(_u1,t1,def1,ty1), Array(_u2,t2,def2,ty2) ->
      (((Array.compare f) =? f) ==? f) t1 t2 def1 def2 ty1 ty2
    | Array _, _ -> -1 | _, Array _ -> 1

let rec compare m n=
  constr_ord_int compare m n

(*******************)
(*  hash-consing   *)
(*******************)

(* Hash-consing of [constr] does not use the module [Hashcons] because
   [Hashcons] is not efficient on deep tree-like data
   structures. Indeed, [Hashcons] is based the (very efficient)
   generic hash function [Hashtbl.hash], which computes the hash key
   through a depth bounded traversal of the data structure to be
   hashed. As a consequence, for a deep [constr] like the natural
   number 1000 (S (S (... (S O)))), the same hash is assigned to all
   the sub [constr]s greater than the maximal depth handled by
   [Hashtbl.hash]. This entails a huge number of collisions in the
   hash table and leads to cubic hash-consing in this worst-case.

   In order to compute a hash key that is independent of the data
   structure depth while being constant-time, an incremental hashing
   function must be devised. A standard implementation creates a cache
   of the hashing function by decorating each node of the hash-consed
   data structure with its hash key. In that case, the hash function
   can deduce the hash key of a toplevel data structure by a local
   computation based on the cache held on its substructures.
   Unfortunately, this simple implementation introduces a space
   overhead that is damageable for the hash-consing of small [constr]s
   (the most common case). One can think of an heterogeneous
   distribution of caches on smartly chosen nodes, but this is forbidden
   by the use of generic equality in Coq source code. (Indeed, this forces
   each [constr] to have a unique canonical representation.)

   Given that hash-consing proceeds inductively, we can nonetheless
   computes the hash key incrementally during hash-consing by changing
   a little the signature of the hash-consing function: it now returns
   both the hash-consed term and its hash key. This simple solution is
   implemented in the following code: it does not introduce a space
   overhead in [constr], that's why the efficiency is unchanged for
   small [constr]s. Besides, it does handle deep [constr]s without
   introducing an unreasonable number of collisions in the hash table.
   Some benchmarks make us think that this implementation of
   hash-consing is linear in the size of the hash-consed data
   structure for our daily use of Coq.
*)

let array_eqeq t1 t2 =
  t1 == t2 ||
  (Int.equal (Array.length t1) (Array.length t2) &&
   let rec aux i =
     (Int.equal i (Array.length t1)) || (t1.(i) == t2.(i) && aux (i + 1))
   in aux 0)

let invert_eqeq iv1 iv2 =
  match iv1, iv2 with
  | NoInvert, NoInvert -> true
  | NoInvert, CaseInvert _ | CaseInvert _, NoInvert -> false
  | CaseInvert {indices=i1}, CaseInvert {indices=i2} ->
    i1 == i2

let hasheq_ctx (nas1, c1) (nas2, c2) =
  array_eqeq nas1 nas2 && c1 == c2

let hasheq t1 t2 =
  match t1, t2 with
    | Rel n1, Rel n2 -> n1 == n2
    | Meta m1, Meta m2 -> m1 == m2
    | Var id1, Var id2 -> id1 == id2
    | Sort s1, Sort s2 -> s1 == s2
    | Cast (c1,k1,t1), Cast (c2,k2,t2) -> c1 == c2 && k1 == k2 && t1 == t2
    | Prod (n1,t1,c1), Prod (n2,t2,c2) -> n1 == n2 && t1 == t2 && c1 == c2
    | Lambda (n1,t1,c1), Lambda (n2,t2,c2) -> n1 == n2 && t1 == t2 && c1 == c2
    | LetIn (n1,b1,t1,c1), LetIn (n2,b2,t2,c2) ->
      n1 == n2 && b1 == b2 && t1 == t2 && c1 == c2
    | App (c1,l1), App (c2,l2) -> c1 == c2 && array_eqeq l1 l2
    | Proj (p1,c1), Proj(p2,c2) -> p1 == p2 && c1 == c2
    | Evar (e1,l1), Evar (e2,l2) -> e1 == e2 && List.equal (==) l1 l2
    | Const (c1,u1), Const (c2,u2) -> c1 == c2 && u1 == u2
    | Ind (ind1,u1), Ind (ind2,u2) -> ind1 == ind2 && u1 == u2
    | Construct (cstr1,u1), Construct (cstr2,u2) -> cstr1 == cstr2 && u1 == u2
    | Case (ci1,u1,pms1,p1,iv1,c1,bl1), Case (ci2,u2,pms2,p2,iv2,c2,bl2) ->
      (** FIXME: use deeper equality for contexts *)
      u1 == u2 && array_eqeq pms1 pms2 &&
      ci1 == ci2 && hasheq_ctx p1 p2 &&
      invert_eqeq iv1 iv2 && c1 == c2 && Array.equal hasheq_ctx bl1 bl2
    | Fix ((ln1, i1),(lna1,tl1,bl1)), Fix ((ln2, i2),(lna2,tl2,bl2)) ->
      Int.equal i1 i2
      && Array.equal Int.equal ln1 ln2
      && array_eqeq lna1 lna2
      && array_eqeq tl1 tl2
      && array_eqeq bl1 bl2
    | CoFix(ln1,(lna1,tl1,bl1)), CoFix(ln2,(lna2,tl2,bl2)) ->
      Int.equal ln1 ln2
      && array_eqeq lna1 lna2
      && array_eqeq tl1 tl2
      && array_eqeq bl1 bl2
    | Int i1, Int i2 -> i1 == i2
    | Float f1, Float f2 -> Float64.equal f1 f2
    | Array(u1,t1,def1,ty1), Array(u2,t2,def2,ty2) ->
      u1 == u2 && def1 == def2 && ty1 == ty2 && array_eqeq t1 t2
    | (Rel _ | Meta _ | Var _ | Sort _ | Cast _ | Prod _ | Lambda _ | LetIn _
      | App _ | Proj _ | Evar _ | Const _ | Ind _ | Construct _ | Case _
      | Fix _ | CoFix _ | Int _ | Float _ | Array _), _ -> false

(** Note that the following Make has the side effect of creating
    once and for all the table we'll use for hash-consing all constr *)

module HashsetTerm =
  Hashset.Make(struct type t = constr let eq = hasheq end)

module HashsetTermArray =
  Hashset.Make(struct type t = constr array let eq = array_eqeq end)

let term_table = HashsetTerm.create 19991
(* The associative table to hashcons terms. *)

let term_array_table = HashsetTermArray.create 4999
(* The associative table to hashcons term arrays. *)

open Hashset.Combine

let hash_cast_kind = function
| VMcast -> 0
| NATIVEcast -> 1
| DEFAULTcast -> 2

let sh_instance = Univ.Instance.share

(* [hashcons hash_consing_functions constr] computes an hash-consed
   representation for [constr] using [hash_consing_functions] on
   leaves. *)
let hashcons (sh_sort,sh_ci,sh_construct,sh_ind,sh_con,sh_na,sh_id) =
  let rec hash_term (t : t) =
    match t with
      | Var i ->
        (Var (sh_id i), combinesmall 1 (Id.hash i))
      | Sort s ->
        (Sort (sh_sort s), combinesmall 2 (Sorts.hash s))
      | Cast (c, k, t) ->
        let c, hc = sh_rec c in
        let t, ht = sh_rec t in
        (Cast (c, k, t), combinesmall 3 (combine3 hc (hash_cast_kind k) ht))
      | Prod (na,t,c) ->
        let t, ht = sh_rec t
        and c, hc = sh_rec c in
        (Prod (sh_na na, t, c), combinesmall 4 (combine3 (hash_annot Name.hash na) ht hc))
      | Lambda (na,t,c) ->
        let t, ht = sh_rec t
        and c, hc = sh_rec c in
        (Lambda (sh_na na, t, c), combinesmall 5 (combine3 (hash_annot Name.hash na) ht hc))
      | LetIn (na,b,t,c) ->
        let b, hb = sh_rec b in
        let t, ht = sh_rec t in
        let c, hc = sh_rec c in
        (LetIn (sh_na na, b, t, c), combinesmall 6 (combine4 (hash_annot Name.hash na) hb ht hc))
      | App (c,l) ->
        let c, hc = sh_rec c in
        let l, hl = hash_term_array l in
        (App (c,l), combinesmall 7 (combine hl hc))
      | Evar (e,l) ->
        let l, hl = hash_list_array l in
        (Evar (e,l), combinesmall 8 (combine (Evar.hash e) hl))
      | Const (c,u) ->
        let c' = sh_con c in
        let u', hu = sh_instance u in
        (Const (c', u'), combinesmall 9 (combine (Constant.SyntacticOrd.hash c) hu))
      | Ind (ind,u) ->
        let u', hu = sh_instance u in
        (Ind (sh_ind ind, u'),
         combinesmall 10 (combine (Ind.SyntacticOrd.hash ind) hu))
      | Construct (c,u) ->
        let u', hu = sh_instance u in
        (Construct (sh_construct c, u'),
         combinesmall 11 (combine (Construct.SyntacticOrd.hash c) hu))
      | Case (ci,u,pms,p,iv,c,bl) ->
        (** FIXME: use a dedicated hashconsing structure *)
        let hcons_ctx (lna, c) =
          let () = Array.iteri (fun i x -> Array.unsafe_set lna i (sh_na x)) lna in
          let fold accu na = combine (hash_annot Name.hash na) accu in
          let hna = Array.fold_left fold 0 lna in
          let c, hc = sh_rec c in
          (lna, c), combine hna hc
        in
        let u, hu = sh_instance u in
        let pms,hpms = hash_term_array pms in
        let p, hp = hcons_ctx p in
        let iv, hiv = sh_invert iv in
        let c, hc = sh_rec c in
        let fold accu c =
          let c, h = hcons_ctx c in
          combine accu h, c
        in
        let hbl, bl = Array.fold_left_map fold 0 bl in
        let hbl = combine (combine hc (combine hiv (combine hpms (combine hu hp)))) hbl in
        (Case (sh_ci ci, u, pms, p, iv, c, bl), combinesmall 12 hbl)
      | Fix (ln,(lna,tl,bl)) ->
        let bl,hbl = hash_term_array bl in
        let tl,htl = hash_term_array tl in
        let () = Array.iteri (fun i x -> Array.unsafe_set lna i (sh_na x)) lna in
        let fold accu na = combine (hash_annot Name.hash na) accu in
        let hna = Array.fold_left fold 0 lna in
        let h = combine3 hna hbl htl in
        (Fix (ln,(lna,tl,bl)), combinesmall 13 h)
      | CoFix(ln,(lna,tl,bl)) ->
        let bl,hbl = hash_term_array bl in
        let tl,htl = hash_term_array tl in
        let () = Array.iteri (fun i x -> Array.unsafe_set lna i (sh_na x)) lna in
        let fold accu na = combine (hash_annot Name.hash na) accu in
        let hna = Array.fold_left fold 0 lna in
        let h = combine3 hna hbl htl in
        (CoFix (ln,(lna,tl,bl)), combinesmall 14 h)
      | Meta n ->
        (t, combinesmall 15 n)
      | Rel n ->
        (t, combinesmall 16 n)
      | Proj (p,c) ->
        let c, hc = sh_rec c in
        let p' = Projection.hcons p in
          (Proj (p', c), combinesmall 17 (combine (Projection.SyntacticOrd.hash p') hc))
      | Int i ->
        let (h,l) = Uint63.to_int2 i in
        (t, combinesmall 18 (combine h l))
      | Float f -> (t, combinesmall 19 (Float64.hash f))
      | Array (u,t,def,ty) ->
        let u, hu = sh_instance u in
        let t, ht = hash_term_array t in
        let def, hdef = sh_rec def in
        let ty, hty = sh_rec ty in
        let h = combine4 hu ht hdef hty in
        (Array(u,t,def,ty), combinesmall 20 h)

  and sh_invert = function
    | NoInvert -> NoInvert, 0
    | CaseInvert {indices;} ->
      let indices, ha = hash_term_array indices in
      CaseInvert {indices;}, combinesmall 1 ha

  and sh_rec t =
    let (y, h) = hash_term t in
    (* [h] must be positive. *)
    let h = h land 0x3FFFFFFF in
    (HashsetTerm.repr h y term_table, h)

  (* Note : During hash-cons of arrays, we modify them *in place* *)

  and hash_term_array t =
    let accu = ref 0 in
    for i = 0 to Array.length t - 1 do
      let x, h = sh_rec (Array.unsafe_get t i) in
      accu := combine !accu h;
      Array.unsafe_set t i x
    done;
    (* [h] must be positive. *)
    let h = !accu land 0x3FFFFFFF in
    (HashsetTermArray.repr h t term_array_table, h)

  and hash_list_array l =
    let fold accu c =
      let c, h = sh_rec c in
      (combine accu h, c)
    in
    let h, l = List.fold_left_map fold 0 l in
    (l, h land 0x3FFFFFFF)

  in
  (* Make sure our statically allocated Rels (1 to 16) are considered
     as canonical, and hence hash-consed to themselves *)
  ignore (hash_term_array rels);

  fun t -> fst (sh_rec t)

(* Exported hashing fonction on constr, used mainly in plugins.
   Slight differences from [snd (hash_term t)] above: it ignores binders
   and doesn't do [land  0x3FFFFFFF]. *)

let rec hash t =
  match kind t with
    | Var i -> combinesmall 1 (Id.hash i)
    | Sort s -> combinesmall 2 (Sorts.hash s)
    | Cast (c, k, t) ->
      let hc = hash c in
      let ht = hash t in
      combinesmall 3 (combine3 hc (hash_cast_kind k) ht)
    | Prod (_, t, c) -> combinesmall 4 (combine (hash t) (hash c))
    | Lambda (_, t, c) -> combinesmall 5 (combine (hash t) (hash c))
    | LetIn (_, b, t, c) ->
      combinesmall 6 (combine3 (hash b) (hash t) (hash c))
    | App (Cast(c, _, _),l) -> hash (mkApp (c,l))
    | App (c,l) ->
      combinesmall 7 (combine (hash_term_array l) (hash c))
    | Evar (e,l) ->
      combinesmall 8 (combine (Evar.hash e) (hash_term_list l))
    | Const (c,u) ->
      combinesmall 9 (combine (Constant.CanOrd.hash c) (Instance.hash u))
    | Ind (ind,u) ->
      combinesmall 10 (combine (Ind.CanOrd.hash ind) (Instance.hash u))
    | Construct (c,u) ->
      combinesmall 11 (combine (Construct.CanOrd.hash c) (Instance.hash u))
    | Case (_ , u, pms, p, iv, c, bl) ->
      combinesmall 12 (combine (combine (hash c) (combine (hash_invert iv) (combine (hash_term_array pms) (combine (Instance.hash u) (hash_under_context p))))) (hash_branches bl))
    | Fix (_ln ,(_, tl, bl)) ->
      combinesmall 13 (combine (hash_term_array bl) (hash_term_array tl))
    | CoFix(_ln, (_, tl, bl)) ->
       combinesmall 14 (combine (hash_term_array bl) (hash_term_array tl))
    | Meta n -> combinesmall 15 n
    | Rel n -> combinesmall 16 n
    | Proj (p,c) ->
      combinesmall 17 (combine (Projection.CanOrd.hash p) (hash c))
    | Int i -> combinesmall 18 (Uint63.hash i)
    | Float f -> combinesmall 19 (Float64.hash f)
    | Array(u,t,def,ty) ->
      combinesmall 20 (combine4 (Instance.hash u) (hash_term_array t) (hash def) (hash ty))

and hash_invert = function
  | NoInvert -> 0
  | CaseInvert {indices;} ->
    combinesmall 1 (hash_term_array indices)

and hash_term_array t =
  Array.fold_left (fun acc t -> combine acc (hash t)) 0 t

and hash_term_list t =
  List.fold_left (fun acc t -> combine (hash t) acc) 0 t

and hash_under_context (_, t) = hash t

and hash_branches bl =
  Array.fold_left (fun acc t -> combine acc (hash_under_context t)) 0 bl

module CaseinfoHash =
struct
  type t = case_info
  type u = inductive -> inductive
  let hashcons hind ci = { ci with ci_ind = hind ci.ci_ind }
  let pp_info_equal info1 info2 =
    List.equal (==) info1.ind_tags info2.ind_tags &&
    Array.equal (List.equal (==)) info1.cstr_tags info2.cstr_tags &&
    info1.style == info2.style
  let eq ci ci' =
    ci.ci_ind == ci'.ci_ind &&
    ci.ci_relevance == ci'.ci_relevance &&
    Int.equal ci.ci_npar ci'.ci_npar &&
    Array.equal Int.equal ci.ci_cstr_ndecls ci'.ci_cstr_ndecls && (* we use [Array.equal] on purpose *)
    Array.equal Int.equal ci.ci_cstr_nargs ci'.ci_cstr_nargs && (* we use [Array.equal] on purpose *)
    pp_info_equal ci.ci_pp_info ci'.ci_pp_info  (* we use (=) on purpose *)
  open Hashset.Combine
  let hash_bool b = if b then 0 else 1
  let hash_bool_list = List.fold_left (fun n b -> combine n (hash_bool b))
  let hash_pp_info info =
    let h1 = match info.style with
    | LetStyle -> 0
    | IfStyle -> 1
    | LetPatternStyle -> 2
    | MatchStyle -> 3
    | RegularStyle -> 4 in
    let h2 = hash_bool_list 0 info.ind_tags in
    let h3 = Array.fold_left hash_bool_list 0 info.cstr_tags in
    combine3 h1 h2 h3
  let hash ci =
    let h1 = Ind.CanOrd.hash ci.ci_ind in
    let h2 = Int.hash ci.ci_npar in
    let h3 = Array.fold_left combine 0 ci.ci_cstr_ndecls in
    let h4 = Array.fold_left combine 0 ci.ci_cstr_nargs in
    let h5 = hash_pp_info ci.ci_pp_info in
    combinesmall (Sorts.relevance_hash ci.ci_relevance) (combine5 h1 h2 h3 h4 h5)
end

module Hcaseinfo = Hashcons.Make(CaseinfoHash)

let case_info_hash = CaseinfoHash.hash

let hcons_caseinfo = Hashcons.simple_hcons Hcaseinfo.generate Hcaseinfo.hcons hcons_ind

module Hannotinfo = struct
    type t = Name.t binder_annot
    type u = Name.t -> Name.t
    let hash = hash_annot Name.hash
    let eq = eq_annot (fun na1 na2 -> na1 == na2)
    let hashcons h {binder_name=na;binder_relevance} =
      {binder_name=h na;binder_relevance}
  end
module Hannot = Hashcons.Make(Hannotinfo)

let hcons_annot = Hashcons.simple_hcons Hannot.generate Hannot.hcons Name.hcons

let hcons =
  hashcons
    (Sorts.hcons,
     hcons_caseinfo,
     hcons_construct,
     hcons_ind,
     hcons_con,
     hcons_annot,
     Id.hcons)

(* let hcons_types = hcons_constr *)

type rel_declaration = (constr, types) Context.Rel.Declaration.pt
type named_declaration = (constr, types) Context.Named.Declaration.pt
type compacted_declaration = (constr, types) Context.Compacted.Declaration.pt
type rel_context = rel_declaration list
type named_context = named_declaration list
type compacted_context = compacted_declaration list

(** Minimalistic constr printer, typically for debugging *)

let debug_print_fix pr_constr ((t,i),(lna,tl,bl)) =
  let open Pp in
  let fixl = Array.mapi (fun i na -> (na.binder_name,t.(i),tl.(i),bl.(i))) lna in
  hov 1
      (str"fix " ++ int i ++ spc() ++  str"{" ++
         v 0 (prlist_with_sep spc (fun (na,i,ty,bd) ->
           Name.print na ++ str"/" ++ int i ++ str":" ++ pr_constr ty ++
           cut() ++ str":=" ++ pr_constr bd) (Array.to_list fixl)) ++
         str"}")

let pr_puniverses p u =
  if Univ.Instance.is_empty u then p
  else Pp.(p ++ str"(*" ++ Univ.Instance.pr Univ.Level.pr u ++ str"*)")

let rec debug_print c =
  let open Pp in
  match kind c with
  | Rel n -> str "#"++int n
  | Meta n -> str "Meta(" ++ int n ++ str ")"
  | Var id -> Id.print id
  | Sort s -> Sorts.debug_print s
  | Cast (c,_, t) -> hov 1
      (str"(" ++ debug_print c ++ cut() ++
       str":" ++ debug_print t ++ str")")
  | Prod ({binder_name=Name id;_},t,c) -> hov 1
      (str"forall " ++ Id.print id ++ str":" ++ debug_print t ++ str"," ++
       spc() ++ debug_print c)
  | Prod ({binder_name=Anonymous;_},t,c) -> hov 0
      (str"(" ++ debug_print t ++ str " ->" ++ spc() ++
       debug_print c ++ str")")
  | Lambda (na,t,c) -> hov 1
      (str"fun " ++ Name.print na.binder_name ++ str":" ++
       debug_print t ++ str" =>" ++ spc() ++ debug_print c)
  | LetIn (na,b,t,c) -> hov 0
      (str"let " ++ Name.print na.binder_name ++ str":=" ++ debug_print b ++
       str":" ++ brk(1,2) ++ debug_print t ++ cut() ++
       debug_print c)
  | App (c,l) ->  hov 1
      (str"(" ++ debug_print c ++ spc() ++
       prlist_with_sep spc debug_print (Array.to_list l) ++ str")")
  | Evar (e,l) -> hov 1
      (str"Evar#" ++ int (Evar.repr e) ++ str"{" ++
       prlist_with_sep spc debug_print l ++str"}")
  | Const (c,u) -> str"Cst(" ++ pr_puniverses (Constant.debug_print c) u ++ str")"
  | Ind ((sp,i),u) -> str"Ind(" ++ pr_puniverses (MutInd.print sp ++ str"," ++ int i) u ++ str")"
  | Construct (((sp,i),j),u) ->
      str"Constr(" ++ pr_puniverses (MutInd.print sp ++ str"," ++ int i ++ str"," ++ int j) u ++ str")"
  | Proj (p,c) -> str"Proj(" ++ Constant.debug_print (Projection.constant p) ++ str"," ++ bool (Projection.unfolded p) ++ str"," ++ debug_print c ++ str")"
  | Case (_ci,_u,pms,p,iv,c,bl) ->
    let pr_ctx (nas, c) =
      prvect_with_sep spc (fun na -> Name.print na.binder_name) nas ++ spc () ++ str "|-" ++ spc () ++
        debug_print c
    in
    v 0 (hv 0 (str"Case " ++
             debug_print c ++ cut () ++ str "as" ++ cut () ++ prlist_with_sep cut debug_print (Array.to_list pms) ++
             cut () ++ str"return"++ cut () ++ pr_ctx p ++ debug_invert iv ++ cut () ++ str"with") ++ cut() ++
       prlist_with_sep (fun _ -> brk(1,2)) pr_ctx (Array.to_list bl) ++
      cut() ++ str"end")
  | Fix f -> debug_print_fix debug_print f
  | CoFix(i,(lna,tl,bl)) ->
      let fixl = Array.mapi (fun i na -> (na,tl.(i),bl.(i))) lna in
      hov 1
        (str"cofix " ++ int i ++ spc() ++  str"{" ++
         v 0 (prlist_with_sep spc (fun (na,ty,bd) ->
           Name.print na.binder_name ++ str":" ++ debug_print ty ++
           cut() ++ str":=" ++ debug_print bd) (Array.to_list fixl)) ++
         str"}")
  | Int i -> str"Int("++str (Uint63.to_string i) ++ str")"
  | Float i -> str"Float("++str (Float64.to_string i) ++ str")"
  | Array(u,t,def,ty) -> str"Array(" ++ prlist_with_sep pr_comma debug_print (Array.to_list t) ++ str" | "
      ++ debug_print def ++ str " : " ++ debug_print ty
      ++ str")@{" ++ Univ.Instance.pr Univ.Level.pr u ++ str"}"

and debug_invert = let open Pp in function
  | NoInvert -> mt()
  | CaseInvert {indices;} ->
    spc() ++ str"Invert {indices=" ++
    prlist_with_sep spc debug_print (Array.to_list indices) ++ str "} "
OCaml

Innovation. Community. Security.