Source file inductive.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
open CErrors
open Util
open Names
open Univ
open Constr
open Vars
open Declarations
open Declareops
open Environ
open Reduction
open Type_errors
open Context.Rel.Declaration
type mind_specif = mutual_inductive_body * one_inductive_body
let lookup_mind_specif env (kn,tyi) =
let mib = Environ.lookup_mind kn env in
if tyi >= Array.length mib.mind_packets then
user_err Pp.(str "Inductive.lookup_mind_specif: invalid inductive index");
(mib, mib.mind_packets.(tyi))
let find_rectype env c =
let (t, l) = decompose_app (whd_all env c) in
match kind t with
| Ind ind -> (ind, l)
| _ -> raise Not_found
let find_inductive env c =
let (t, l) = decompose_app (whd_all env c) in
match kind t with
| Ind ind
when (fst (lookup_mind_specif env (out_punivs ind))).mind_finite <> CoFinite -> (ind, l)
| _ -> raise Not_found
let find_coinductive env c =
let (t, l) = decompose_app (whd_all env c) in
match kind t with
| Ind ind
when (fst (lookup_mind_specif env (out_punivs ind))).mind_finite == CoFinite -> (ind, l)
| _ -> raise Not_found
let inductive_params (mib,_) = mib.mind_nparams
let inductive_paramdecls (mib,u) =
Vars.subst_instance_context u mib.mind_params_ctxt
let instantiate_inductive_constraints mib u =
Univ.AbstractContext.instantiate u (Declareops.inductive_polymorphic_context mib)
let instantiate_params t u args sign =
let fail () =
anomaly ~label:"instantiate_params" (Pp.str "type, ctxt and args mismatch.") in
let (rem_args, subs, ty) =
Context.Rel.fold_outside
(fun decl (largs,subs,ty) ->
match (decl, largs, kind ty) with
| (LocalAssum _, a::args, Prod(_,_,t)) -> (args, a::subs, t)
| (LocalDef (_,b,_), _, LetIn(_,_,_,t)) ->
(largs, (substl subs (subst_instance_constr u b))::subs, t)
| _ -> fail ())
sign
~init:(args,[],t)
in
let () = if not (List.is_empty rem_args) then fail () in
substl subs ty
let full_inductive_instantiate mib u params sign =
let dummy = Sorts.prop in
let t = Term.mkArity (Vars.subst_instance_context u sign,dummy) in
fst (Term.destArity (instantiate_params t u params mib.mind_params_ctxt))
let full_constructor_instantiate (_,u,(mib,_),params) t =
let inst_ind = subst_instance_constr u t in
instantiate_params inst_ind u params mib.mind_params_ctxt
let cons_subst u su subst =
try
Univ.Level.Map.add u (Univ.sup (Univ.Level.Map.find u subst) su) subst
with Not_found -> Univ.Level.Map.add u su subst
let remember_subst u subst =
try
let su = Universe.make u in
Univ.Level.Map.add u (Univ.sup (Univ.Level.Map.find u subst) su) subst
with Not_found -> subst
type param_univs = (unit -> Universe.t) list
let make_param_univs env argtys =
Array.map_to_list (fun arg () ->
Sorts.univ_of_sort (snd (Reduction.dest_arity env arg)))
argtys
let make_subst =
let rec make subst = function
| LocalDef _ :: sign, exp, args ->
make subst (sign, exp, args)
| _d::sign, None::exp, args ->
let args = match args with _::args -> args | [] -> [] in
make subst (sign, exp, args)
| _d::sign, Some u::exp, a::args ->
let s = a () in
make (cons_subst u s subst) (sign, exp, args)
| LocalAssum (_na,_t) :: sign, Some u::exp, [] ->
make (remember_subst u subst) (sign, exp, [])
| _sign, [], _ ->
subst
| [], _, _ ->
assert false
in
make Univ.Level.Map.empty
exception SingletonInductiveBecomesProp of Id.t
let instantiate_universes ctx (templ, ar) args =
let subst = make_subst (ctx,templ.template_param_levels,args) in
let level = Univ.subst_univs_universe (Univ.make_subst subst) ar.template_level in
let ty =
if is_type0m_univ level then Sorts.prop
else if is_type0_univ level then Sorts.set
else Sorts.sort_of_univ level
in
(ctx, ty)
let relevance_of_inductive env ind =
let _, mip = lookup_mind_specif env ind in
mip.mind_relevance
let check_instance mib u =
if not (match mib.mind_universes with
| Monomorphic -> Instance.is_empty u
| Polymorphic uctx -> Instance.length u = AbstractContext.size uctx)
then CErrors.anomaly Pp.(str "bad instance length on mutind.")
let type_of_inductive_gen ?(polyprop=true) ((mib,mip),u) paramtyps =
check_instance mib u;
match mip.mind_arity with
| RegularArity a -> subst_instance_constr u a.mind_user_arity
| TemplateArity ar ->
let templ = match mib.mind_template with
| None -> assert false
| Some t -> t
in
let ctx = List.rev mip.mind_arity_ctxt in
let ctx,s = instantiate_universes ctx (templ, ar) paramtyps in
if not polyprop && not (is_type0m_univ ar.template_level) && Sorts.is_prop s
then raise (SingletonInductiveBecomesProp mip.mind_typename);
Term.mkArity (List.rev ctx,s)
let type_of_inductive pind =
type_of_inductive_gen pind []
let constrained_type_of_inductive ((mib,_mip),u as pind) =
let ty = type_of_inductive pind in
let cst = instantiate_inductive_constraints mib u in
(ty, cst)
let constrained_type_of_inductive_knowing_parameters ((mib,_mip),u as pind) args =
let ty = type_of_inductive_gen pind args in
let cst = instantiate_inductive_constraints mib u in
(ty, cst)
let type_of_inductive_knowing_parameters ?(polyprop=true) mip args =
type_of_inductive_gen ~polyprop mip args
let cumulate_constructor_univ u = let open Sorts in function
| SProp | Prop ->
u
| Set -> Universe.sup Universe.type0 u
| Type u' -> Universe.sup u u'
let max_inductive_sort =
Array.fold_left cumulate_constructor_univ Universe.type0m
let type_of_constructor (cstr, u) (mib,mip) =
check_instance mib u;
let i = index_of_constructor cstr in
let nconstr = Array.length mip.mind_consnames in
if i > nconstr then user_err Pp.(str "Not enough constructors in the type.");
subst_instance_constr u mip.mind_user_lc.(i-1)
let constrained_type_of_constructor (_cstr,u as cstru) (mib,_mip as ind) =
let ty = type_of_constructor cstru ind in
let cst = instantiate_inductive_constraints mib u in
(ty, cst)
let arities_of_constructors (_,u) (_,mip) =
let map (ctx, c) =
let cty = Term.it_mkProd_or_LetIn c ctx in
subst_instance_constr u cty
in
Array.map map mip.mind_nf_lc
let type_of_constructors (_,u) (_,mip) =
Array.map (subst_instance_constr u) mip.mind_user_lc
let abstract_constructor_type_relatively_to_inductive_types_context ntyps mind t =
let rec replace_ind k c =
let hd, args = decompose_appvect c in
match kind hd with
| Ind ((mind',i),_) when MutInd.CanOrd.equal mind mind' ->
mkApp (mkRel (ntyps+k-i), Array.map (replace_ind k) args)
| _ -> map_with_binders succ replace_ind k c
in
replace_ind 0 t
let inductive_sort_family mip =
match mip.mind_arity with
| RegularArity s -> Sorts.family s.mind_sort
| TemplateArity _ -> Sorts.InType
let mind_arity mip =
mip.mind_arity_ctxt, inductive_sort_family mip
let get_instantiated_arity (_ind,u) (mib,mip) params =
let sign, s = mind_arity mip in
full_inductive_instantiate mib u params sign, s
let elim_sort (_,mip) = mip.mind_kelim
let is_private (mib,_) = mib.mind_private = Some true
let is_primitive_record (mib,_) =
match mib.mind_record with
| PrimRecord _ -> true
| NotRecord | FakeRecord -> false
let build_dependent_inductive ind (_,mip) params =
let realargs,_ = List.chop mip.mind_nrealdecls mip.mind_arity_ctxt in
Term.applist
(mkIndU ind,
List.map (lift mip.mind_nrealdecls) params
@ Context.Rel.instance_list mkRel 0 realargs)
exception LocalArity of (Sorts.family * Sorts.family * Sorts.family * arity_error) option
let check_allowed_sort ksort specif =
if not (Sorts.family_leq ksort (elim_sort specif)) then
let s = inductive_sort_family (snd specif) in
raise (LocalArity (Some(elim_sort specif, ksort,s,error_elim_explain ksort s)))
let check_correct_arity env c pj ind specif params =
let arsign,_ = get_instantiated_arity ind specif params in
let rec srec env ar pt =
let pt' = whd_all env pt in
match ar, kind pt' with
| (LocalAssum (_,a1))::ar', Prod (na1,a1',t) ->
let () =
try conv_leq ~l2r:true env a1 a1'
with NotConvertible -> raise (LocalArity None) in
srec (push_rel (LocalAssum (na1,a1)) env) ar' t
| [], Prod (na1,a1',a2) ->
let env' = push_rel (LocalAssum (na1,a1')) env in
let ksort = match kind (whd_all env' a2) with
| Sort s -> Sorts.family s
| _ -> raise (LocalArity None)
in
let dep_ind = build_dependent_inductive ind specif params in
let () =
try conv_leq ~l2r:true env dep_ind a1'
with NotConvertible -> raise (LocalArity None)
in
let () = check_allowed_sort ksort specif in
let (pind, _args) = find_rectype env a1' in
pind
| (LocalDef _ as d)::ar', _ ->
srec (push_rel d env) ar' (lift 1 pt')
| _ ->
raise (LocalArity None)
in
try srec env (List.rev arsign) pj.uj_type
with LocalArity kinds ->
error_elim_arity env ind c pj kinds
(** {6 Changes of representation of Case nodes} *)
(** Provided:
- a universe instance [u]
- a term substitution [subst]
- name replacements [nas]
[instantiate_context u subst nas ctx] applies both [u] and [subst] to [ctx]
while replacing names using [nas] (order reversed)
*)
let instantiate_context u subst nas ctx =
let rec instantiate i ctx = match ctx with
| [] -> assert (Int.equal i (-1)); []
| LocalAssum (_, ty) :: ctx ->
let ctx = instantiate (pred i) ctx in
let ty = substnl subst i (subst_instance_constr u ty) in
LocalAssum (nas.(i), ty) :: ctx
| LocalDef (_, ty, bdy) :: ctx ->
let ctx = instantiate (pred i) ctx in
let ty = substnl subst i (subst_instance_constr u ty) in
let bdy = substnl subst i (subst_instance_constr u bdy) in
LocalDef (nas.(i), ty, bdy) :: ctx
in
instantiate (Array.length nas - 1) ctx
let expand_case_specif mib (ci, u, params, p, iv, c, br) =
let mip = mib.mind_packets.(snd ci.ci_ind) in
let paramdecl = Vars.subst_instance_context u mib.mind_params_ctxt in
let paramsubst = Vars.subst_of_rel_context_instance paramdecl params in
let ep =
let (nas, p) = p in
let realdecls, _ = List.chop mip.mind_nrealdecls mip.mind_arity_ctxt in
let self =
let args = Context.Rel.instance mkRel 0 mip.mind_arity_ctxt in
let inst = Instance.of_array (Array.init (Instance.length u) Level.var) in
mkApp (mkIndU (ci.ci_ind, inst), args)
in
let realdecls = LocalAssum (Context.anonR, self) :: realdecls in
let realdecls = instantiate_context u paramsubst nas realdecls in
Term.it_mkLambda_or_LetIn p realdecls
in
let ebr =
let build_one_branch i (nas, br) (ctx, _) =
let ctx, _ = List.chop mip.mind_consnrealdecls.(i) ctx in
let ctx = instantiate_context u paramsubst nas ctx in
Term.it_mkLambda_or_LetIn br ctx
in
Array.map2_i build_one_branch br mip.mind_nf_lc
in
(ci, ep, iv, c, ebr)
let expand_case env (ci, _, _, _, _, _, _ as case) =
let specif = Environ.lookup_mind (fst ci.ci_ind) env in
expand_case_specif specif case
let contract_case env (ci, p, iv, c, br) =
let (mib, mip) = lookup_mind_specif env ci.ci_ind in
let (arity, p) = Term.decompose_lam_n_decls (mip.mind_nrealdecls + 1) p in
let (u, pms) = match arity with
| LocalAssum (_, ty) :: _ ->
(** Last binder is the self binder for the term being eliminated *)
let (ind, args) = decompose_appvect ty in
let (ind, u) = destInd ind in
let () = assert (Ind.CanOrd.equal ind ci.ci_ind) in
let pms = Array.sub args 0 mib.mind_nparams in
(** Unlift the parameters from under the index binders *)
let dummy = List.make mip.mind_nrealdecls mkProp in
let pms = Array.map (fun c -> Vars.substl dummy c) pms in
(u, pms)
| _ -> assert false
in
let p =
let nas = Array.of_list (List.rev_map get_annot arity) in
(nas, p)
in
let map i br =
let (ctx, br) = Term.decompose_lam_n_decls mip.mind_consnrealdecls.(i) br in
let nas = Array.of_list (List.rev_map get_annot ctx) in
(nas, br)
in
(ci, u, pms, p, iv, c, Array.mapi map br)
let build_branches_type (ind,u) (_,mip as specif) params p =
let build_one_branch i (ctx, c) =
let cty = Term.it_mkProd_or_LetIn c ctx in
let typi = full_constructor_instantiate (ind,u,specif,params) cty in
let (cstrsign,ccl) = Term.decompose_prod_assum typi in
let nargs = Context.Rel.length cstrsign in
let (_,allargs) = decompose_app ccl in
let (lparams,vargs) = List.chop (inductive_params specif) allargs in
let cargs =
let cstr = ith_constructor_of_inductive ind (i+1) in
let dep_cstr = Term.applist (mkConstructU (cstr,u),lparams@(Context.Rel.instance_list mkRel 0 cstrsign)) in
vargs @ [dep_cstr] in
let base = Term.lambda_appvect_assum (mip.mind_nrealdecls+1) (lift nargs p) (Array.of_list cargs) in
Term.it_mkProd_or_LetIn base cstrsign in
Array.mapi build_one_branch mip.mind_nf_lc
let build_case_type env n p c realargs =
whd_betaiota env (Term.lambda_appvect_assum (n+1) p (Array.of_list (realargs@[c])))
let type_case_branches env ((ind, _ as pind),largs) pj c =
let specif = lookup_mind_specif env ind in
let nparams = inductive_params specif in
let (params,realargs) = List.chop nparams largs in
let p = pj.uj_val in
let pind = check_correct_arity env c pj pind specif params in
let lc = build_branches_type pind specif params p in
let ty = build_case_type env (snd specif).mind_nrealdecls p c realargs in
(lc, ty)
let check_case_info env (indsp,u) r ci =
let (mib,mip as spec) = lookup_mind_specif env indsp in
if
not (Ind.CanOrd.equal indsp ci.ci_ind) ||
not (Int.equal mib.mind_nparams ci.ci_npar) ||
not (Array.equal Int.equal mip.mind_consnrealdecls ci.ci_cstr_ndecls) ||
not (Array.equal Int.equal mip.mind_consnrealargs ci.ci_cstr_nargs) ||
not (ci.ci_relevance == r) ||
is_primitive_record spec
then raise (TypeError(env,WrongCaseInfo((indsp,u),ci)))
type size = Large | Strict
let size_glb s1 s2 =
match s1,s2 with
Strict, Strict -> Strict
| _ -> Large
type subterm_spec =
Subterm of (size * wf_paths)
| Dead_code
| Not_subterm
let eq_wf_paths = Rtree.equal Declareops.eq_recarg
let inter_recarg r1 r2 = match r1, r2 with
| Norec, Norec -> Some r1
| Norec, _ -> None
| Mrec i1, Mrec i2
| Nested (NestedInd i1), Nested (NestedInd i2)
| Mrec i1, (Nested (NestedInd i2)) -> if Names.Ind.CanOrd.equal i1 i2 then Some r1 else None
| Mrec _, _ -> None
| Nested (NestedInd i1), Mrec i2 -> if Names.Ind.CanOrd.equal i1 i2 then Some r2 else None
| Nested (NestedInd _), _ -> None
| Nested (NestedPrimitive c1), Nested (NestedPrimitive c2) ->
if Names.Constant.CanOrd.equal c1 c2 then Some r1 else None
| Nested (NestedPrimitive _), _ -> None
let inter_wf_paths = Rtree.inter Declareops.eq_recarg inter_recarg Norec
let incl_wf_paths = Rtree.incl Declareops.eq_recarg inter_recarg Norec
let spec_of_tree t =
if eq_wf_paths t mk_norec
then Not_subterm
else Subterm (Strict, t)
let inter_spec s1 s2 =
match s1, s2 with
| _, Dead_code -> s1
| Dead_code, _ -> s2
| Not_subterm, _ -> s1
| _, Not_subterm -> s2
| Subterm (a1,t1), Subterm (a2,t2) ->
Subterm (size_glb a1 a2, inter_wf_paths t1 t2)
let subterm_spec_glb =
Array.fold_left inter_spec Dead_code
type guard_env =
{ env : env;
rel_min : int;
genv : subterm_spec Lazy.t list;
}
let make_renv env recarg tree =
{ env = env;
rel_min = recarg+2;
genv = [Lazy.from_val(Subterm(Large,tree))] }
let push_var renv (x,ty,spec) =
{ env = push_rel (LocalAssum (x,ty)) renv.env;
rel_min = renv.rel_min+1;
genv = spec:: renv.genv }
let assign_var_spec renv (i,spec) =
{ renv with genv = List.assign renv.genv (i-1) spec }
let push_var_renv renv (x,ty) =
push_var renv (x,ty,lazy Not_subterm)
let subterm_var p renv =
try Lazy.force (List.nth renv.genv (p-1))
with Failure _ | Invalid_argument _ -> Not_subterm
let push_ctxt_renv renv ctxt =
let n = Context.Rel.length ctxt in
{ env = push_rel_context ctxt renv.env;
rel_min = renv.rel_min+n;
genv = iterate (fun ge -> lazy Not_subterm::ge) n renv.genv }
let push_fix_renv renv (_,v,_ as recdef) =
let n = Array.length v in
{ env = push_rec_types recdef renv.env;
rel_min = renv.rel_min+n;
genv = iterate (fun ge -> lazy Not_subterm::ge) n renv.genv }
type stack_element = |SClosure of guard_env*constr |SArg of subterm_spec Lazy.t
let push_stack_closures renv l stack =
List.fold_right (fun h b -> (SClosure (renv,h))::b) l stack
let push_stack_args l stack =
List.fold_right (fun h b -> (SArg h)::b) l stack
let lookup_subterms env ind =
let (_,mip) = lookup_mind_specif env ind in
mip.mind_recargs
let match_inductive ind ra =
match ra with
| Mrec i | Nested (NestedInd i) -> Ind.CanOrd.equal ind i
| Norec | Nested (NestedPrimitive _) -> false
let branches_specif renv c_spec ci =
let car =
let (_,mip) = lookup_mind_specif renv.env ci.ci_ind in
let v = dest_subterms mip.mind_recargs in
Array.map List.length v in
Array.mapi
(fun i nca ->
let lvra = lazy
(match Lazy.force c_spec with
Subterm (_,t) when match_inductive ci.ci_ind (dest_recarg t) ->
let vra = Array.of_list (dest_subterms t).(i) in
assert (Int.equal nca (Array.length vra));
Array.map spec_of_tree vra
| Dead_code -> Array.make nca Dead_code
| _ -> Array.make nca Not_subterm) in
List.init nca (fun j -> lazy (Lazy.force lvra).(j)))
car
let check_inductive_codomain env p =
let absctx, ar = dest_lam_assum env p in
let env = push_rel_context absctx env in
let arctx, s = dest_prod_assum env ar in
let env = push_rel_context arctx env in
let i,_l' = decompose_app (whd_all env s) in
isInd i
let ienv_push_var (env, lra) (x,a,ra) =
(push_rel (LocalAssum (x,a)) env, (Norec,ra)::lra)
let ienv_push_inductive (env, ra_env) ((mind,u),lpar) =
let mib = Environ.lookup_mind mind env in
let ntypes = mib.mind_ntypes in
let push_ind mip env =
let r = mip.mind_relevance in
let anon = Context.make_annot Anonymous r in
let decl = LocalAssum (anon, hnf_prod_applist env (type_of_inductive ((mib,mip),u)) lpar) in
push_rel decl env
in
let env = Array.fold_right push_ind mib.mind_packets env in
let rc = Array.mapi (fun j t -> (Nested (NestedInd (mind,j)),t)) (Rtree.mk_rec_calls ntypes) in
let lra_ind = Array.rev_to_list rc in
let ra_env = List.map (fun (r,t) -> (r,Rtree.lift ntypes t)) ra_env in
(env, lra_ind @ ra_env)
let rec ienv_decompose_prod (env,_ as ienv) n c =
if Int.equal n 0 then (ienv,c) else
let c' = whd_all env c in
match kind c' with
Prod(na,a,b) ->
let ienv' = ienv_push_var ienv (na,a,mk_norec) in
ienv_decompose_prod ienv' (n-1) b
| _ -> assert false
let dummy_univ = Level.(make (UGlobal.make (DirPath.make [Id.of_string "implicit"]) "" 0))
let dummy_implicit_sort = mkType (Universe.make dummy_univ)
let lambda_implicit n a =
let anon = Context.make_annot Anonymous Sorts.Relevant in
let lambda_implicit a = mkLambda (anon, dummy_implicit_sort, a) in
iterate lambda_implicit n a
let abstract_mind_lc ntyps npars mind lc =
let lc = Array.map (fun (ctx, c) -> Term.it_mkProd_or_LetIn c ctx) lc in
let rec replace_ind k c =
let hd, args = decompose_app c in
match kind hd with
| Ind ((mind',i),_) when MutInd.CanOrd.equal mind mind' ->
let rec drop_params n = function
| _ :: args when n > 0 -> drop_params (n-1) args
| args -> lambda_implicit n (Term.applist (mkRel (ntyps+n+k-i), List.Smart.map (replace_ind (n+k)) args))
in
drop_params npars args
| _ -> map_with_binders succ replace_ind k c
in
Array.map (replace_ind 0) lc
let is_primitive_positive_container env c =
match env.retroknowledge.Retroknowledge.retro_array with
| Some c' when QConstant.equal env c c' -> true
| _ -> false
let get_recargs_approx env tree ind args =
let rec build_recargs (env, ra_env as ienv) tree c =
let x,largs = decompose_app (whd_all env c) in
match kind x with
| Prod (na,b,d) ->
assert (List.is_empty largs);
build_recargs (ienv_push_var ienv (na, b, mk_norec)) tree d
| Rel k ->
(try snd (List.nth ra_env (k-1))
with Failure _ | Invalid_argument _ -> mk_norec)
| Ind ind_kn ->
begin match dest_recarg tree with
| Nested (NestedInd kn') | Mrec kn' when Ind.CanOrd.equal (fst ind_kn) kn' ->
build_recargs_nested ienv tree (ind_kn, largs)
| _ -> mk_norec
end
| Const (c,_) when is_primitive_positive_container env c ->
begin match dest_recarg tree with
| Nested (NestedPrimitive c') when QConstant.equal env c c' ->
build_recargs_nested_primitive ienv tree (c, largs)
| _ -> mk_norec
end
| _err ->
mk_norec
and build_recargs_nested (env,_ra_env as ienv) tree (((mind,i),u), largs) =
if eq_wf_paths tree mk_norec then tree
else
let mib = Environ.lookup_mind mind env in
let auxnpar = mib.mind_nparams_rec in
let nonrecpar = mib.mind_nparams - auxnpar in
let (lpar,_) = List.chop auxnpar largs in
let auxntyp = mib.mind_ntypes in
let (env',_ as ienv') = ienv_push_inductive ienv ((mind,u),lpar) in
let lpar' = List.map (lift auxntyp) lpar in
let trees =
if Int.equal auxntyp 1 then [|dest_subterms tree|]
else Array.map (fun mip -> dest_subterms mip.mind_recargs) mib.mind_packets
in
let mk_irecargs j mip =
let auxlcvect = abstract_mind_lc auxntyp auxnpar mind mip.mind_nf_lc in
let paths = Array.mapi
(fun k c ->
let c' = hnf_prod_applist env' c lpar' in
let (ienv',c') = ienv_decompose_prod ienv' nonrecpar c' in
build_recargs_constructors ienv' trees.(j).(k) c')
auxlcvect
in
mk_paths (Nested (NestedInd (mind,j))) paths
in
let irecargs = Array.mapi mk_irecargs mib.mind_packets in
(Rtree.mk_rec irecargs).(i)
and build_recargs_nested_primitive (env, ra_env) tree (c, largs) =
if eq_wf_paths tree mk_norec then tree
else
let ntypes = 1 in
let ra_env = List.map (fun (r,t) -> (r,Rtree.lift ntypes t)) ra_env in
let ienv = (env, ra_env) in
let paths = List.map2 (build_recargs ienv) (dest_subterms tree).(0) largs in
let recargs = [| mk_paths (Nested (NestedPrimitive c)) [| paths |] |] in
(Rtree.mk_rec recargs).(0)
and build_recargs_constructors ienv trees c =
let rec recargs_constr_rec (env,_ra_env as ienv) trees lrec c =
let x,largs = decompose_app (whd_all env c) in
match kind x with
| Prod (na,b,d) ->
let () = assert (List.is_empty largs) in
let recarg = build_recargs ienv (List.hd trees) b in
let ienv' = ienv_push_var ienv (na,b,mk_norec) in
recargs_constr_rec ienv' (List.tl trees) (recarg::lrec) d
| _hd ->
List.rev lrec
in
recargs_constr_rec ienv trees [] c
in
build_recargs_nested (env,[]) tree (ind, args)
let restrict_spec env spec p =
if spec = Not_subterm then spec
else let absctx, ar = dest_lam_assum env p in
if noccur_with_meta 1 (Context.Rel.length absctx) ar then spec
else
let env = push_rel_context absctx env in
let arctx, s = dest_prod_assum env ar in
let env = push_rel_context arctx env in
let i,args = decompose_app (whd_all env s) in
match kind i with
| Ind i ->
begin match spec with
| Dead_code -> spec
| Subterm(st,tree) ->
let recargs = get_recargs_approx env tree i args in
let recargs = inter_wf_paths tree recargs in
Subterm(st,recargs)
| _ -> assert false
end
| _ -> Not_subterm
let rec subterm_specif renv stack t =
let f,l = decompose_app (whd_all renv.env t) in
match kind f with
| Rel k -> subterm_var k renv
| Case (ci, u, pms, p, iv, c, lbr) ->
let (ci, p, _iv, c, lbr) = expand_case renv.env (ci, u, pms, p, iv, c, lbr) in
let stack' = push_stack_closures renv l stack in
let cases_spec =
branches_specif renv (lazy_subterm_specif renv [] c) ci
in
let stl =
Array.mapi (fun i br' ->
let stack_br = push_stack_args (cases_spec.(i)) stack' in
subterm_specif renv stack_br br')
lbr in
let spec = subterm_spec_glb stl in
restrict_spec renv.env spec p
| Fix ((recindxs,i),(_,typarray,bodies as recdef)) ->
if not (check_inductive_codomain renv.env typarray.(i)) then Not_subterm
else
let (ctxt,clfix) = dest_prod renv.env typarray.(i) in
let oind =
let env' = push_rel_context ctxt renv.env in
try Some(fst(find_inductive env' clfix))
with Not_found -> None in
(match oind with
None -> Not_subterm
| Some (ind, _) ->
let nbfix = Array.length typarray in
let recargs = lookup_subterms renv.env ind in
let renv' = push_fix_renv renv recdef in
let renv' =
assign_var_spec renv'
(nbfix-i, lazy (Subterm(Strict,recargs))) in
let decrArg = recindxs.(i) in
let theBody = bodies.(i) in
let nbOfAbst = decrArg+1 in
let sign,strippedBody = Term.decompose_lam_n_assum nbOfAbst theBody in
let stack' = push_stack_closures renv l stack in
let renv'' = push_ctxt_renv renv' sign in
let renv'' =
if List.length stack' < nbOfAbst then renv''
else
let decrArg = List.nth stack' decrArg in
let arg_spec = stack_element_specif decrArg in
assign_var_spec renv'' (1, arg_spec) in
subterm_specif renv'' [] strippedBody)
| Lambda (x,a,b) ->
let () = assert (List.is_empty l) in
let spec,stack' = extract_stack stack in
subterm_specif (push_var renv (x,a,spec)) stack' b
| (Meta _|Evar _) -> Dead_code
| Proj (p, c) ->
let subt = subterm_specif renv stack c in
(match subt with
| Subterm (_s, wf) ->
let wf_args = (dest_subterms wf).(0) in
let n = Projection.arg p in
spec_of_tree (List.nth wf_args n)
| Dead_code -> Dead_code
| Not_subterm -> Not_subterm)
| Const c ->
begin try
let _ = Environ.constant_value_in renv.env c in Not_subterm
with
| NotEvaluableConst (IsPrimitive (_u,op)) when List.length l >= CPrimitives.arity op ->
primitive_specif renv op l
| NotEvaluableConst _ -> Not_subterm
end
| Var _ | Sort _ | Cast _ | Prod _ | LetIn _ | App _ | Ind _
| Construct _ | CoFix _ | Int _ | Float _ | Array _ -> Not_subterm
and lazy_subterm_specif renv stack t =
lazy (subterm_specif renv stack t)
and stack_element_specif = function
|SClosure (h_renv,h) -> lazy_subterm_specif h_renv [] h
|SArg x -> x
and = function
| [] -> Lazy.from_val Not_subterm , []
| h::t -> stack_element_specif h, t
and primitive_specif renv op args =
let open CPrimitives in
match op with
| Arrayget | Arraydefault ->
let arg = List.nth args 1 in
let subt = subterm_specif renv [] arg in
begin match subt with
| Subterm (_s, wf) ->
let wf_args = (dest_subterms wf).(0) in
spec_of_tree (List.nth wf_args 0)
| Dead_code -> Dead_code
| Not_subterm -> Not_subterm
end
| _ -> Not_subterm
let check_is_subterm x tree =
match Lazy.force x with
| Subterm (Strict,tree') -> incl_wf_paths tree tree'
| Dead_code -> true
| _ -> false
exception FixGuardError of env * guard_error
let error_illegal_rec_call renv fx (arg_renv,arg) =
let (_,le_vars,lt_vars) =
List.fold_left
(fun (i,le,lt) sbt ->
match Lazy.force sbt with
(Subterm(Strict,_) | Dead_code) -> (i+1, le, i::lt)
| (Subterm(Large,_)) -> (i+1, i::le, lt)
| _ -> (i+1, le ,lt))
(1,[],[]) renv.genv in
raise (FixGuardError (renv.env,
RecursionOnIllegalTerm(fx,(arg_renv.env, arg),
le_vars,lt_vars)))
let error_partial_apply renv fx =
raise (FixGuardError (renv.env,NotEnoughArgumentsForFixCall fx))
let filter_stack_domain env p stack =
let absctx, ar = dest_lam_assum env p in
if noccur_with_meta 1 (Context.Rel.length absctx) ar then stack
else let env = push_rel_context absctx env in
let rec filter_stack env ar stack =
let t = whd_all env ar in
match stack, kind t with
| elt :: stack', Prod (n,a,c0) ->
let d = LocalAssum (n,a) in
let ctx, a = dest_prod_assum env a in
let env = push_rel_context ctx env in
let ty, args = decompose_app (whd_all env a) in
let elt = match kind ty with
| Ind ind ->
let spec' = stack_element_specif elt in
(match (Lazy.force spec') with
| Not_subterm | Dead_code -> elt
| Subterm(s,path) ->
let recargs = get_recargs_approx env path ind args in
let path = inter_wf_paths path recargs in
SArg (lazy (Subterm(s,path))))
| _ -> (SArg (lazy Not_subterm))
in
elt :: filter_stack (push_rel d env) c0 stack'
| _,_ -> List.fold_right (fun _ l -> SArg (lazy Not_subterm) :: l) stack []
in
filter_stack env ar stack
let judgment_of_fixpoint (_, types, bodies) =
Array.map2 (fun typ body -> { uj_val = body ; uj_type = typ }) types bodies
let check_one_fix renv recpos trees def =
let nfi = Array.length recpos in
let rec check_rec_call renv stack t =
if noccur_with_meta renv.rel_min nfi t then ()
else
let (f,l) = decompose_app (whd_betaiotazeta renv.env t) in
match kind f with
| Rel p ->
if renv.rel_min <= p && p < renv.rel_min+nfi then
begin
List.iter (check_rec_call renv []) l;
let glob = renv.rel_min+nfi-1-p in
let np = recpos.(glob) in
let stack' = push_stack_closures renv l stack in
if List.length stack' <= np then error_partial_apply renv glob
else
let z = List.nth stack' np in
if not (check_is_subterm (stack_element_specif z) trees.(glob)) then
begin match z with
|SClosure (z,z') -> error_illegal_rec_call renv glob (z,z')
|SArg _ -> error_partial_apply renv glob
end
end
else
begin
match lookup_rel p renv.env with
| LocalAssum _ ->
List.iter (check_rec_call renv []) l
| LocalDef (_,c,_) ->
try List.iter (check_rec_call renv []) l
with FixGuardError _ ->
check_rec_call renv stack (Term.applist(lift p c,l))
end
| Case (ci, u, pms, ret, iv, c_0, br) ->
let (ci, p, _iv, c_0, lrest) = expand_case renv.env (ci, u, pms, ret, iv, c_0, br) in
begin try
List.iter (check_rec_call renv []) (c_0::p::l);
let case_spec =
branches_specif renv (lazy_subterm_specif renv [] c_0) ci in
let stack' = push_stack_closures renv l stack in
let stack' = filter_stack_domain renv.env p stack' in
lrest |> Array.iteri (fun k br' ->
let stack_br = push_stack_args case_spec.(k) stack' in
check_rec_call renv stack_br br')
with (FixGuardError _ as exn) ->
let exn = Exninfo.capture exn in
let c_0 = whd_all renv.env c_0 in
let hd, _ = decompose_app c_0 in
match kind hd with
| Construct _ | CoFix _ ->
check_rec_call renv []
(Term.applist (mkCase (ci, u, pms, ret, iv, c_0, br), l))
| Rel _ | Var _ | Const _ | App _ | Lambda _ | Prod _ | LetIn _
| Ind _ | Case _ | Fix _ | Proj _ | Sort _ | Cast _
| Int _ | Float _ | Array _ | Meta _ | Evar _ -> Exninfo.iraise exn
end
| Fix ((recindxs,i),(_,typarray,bodies as recdef)) ->
let decrArg = recindxs.(i) in
begin try
List.iter (check_rec_call renv []) l;
Array.iter (check_rec_call renv []) typarray;
let renv' = push_fix_renv renv recdef in
let stack' = push_stack_closures renv l stack in
bodies |> Array.iteri (fun j body ->
if Int.equal i j && (List.length stack' > decrArg) then
let recArg = List.nth stack' decrArg in
let arg_sp = stack_element_specif recArg in
let illformed () =
error_ill_formed_rec_body renv.env NotEnoughAbstractionInFixBody
(pi1 recdef) i (push_rec_types recdef renv.env)
(judgment_of_fixpoint recdef)
in
check_nested_fix_body illformed renv' (decrArg+1) arg_sp body
else check_rec_call renv' [] body)
with (FixGuardError _ as exn) ->
let exn = Exninfo.capture exn in
if List.length l <= decrArg then Exninfo.iraise exn;
let recArg = List.nth l decrArg in
let recArg = whd_all renv.env recArg in
let hd, _ = decompose_app recArg in
match kind hd with
| Construct _ ->
let before, after = CList.(firstn decrArg l, skipn (decrArg+1) l) in
check_rec_call renv []
(Term.applist (mkFix ((recindxs,i),recdef), (before @ recArg :: after)))
| Rel _ | Var _ | Const _ | App _ | Lambda _ | Prod _ | LetIn _
| Ind _ | Case _ | Fix _ | CoFix _ | Proj _ | Sort _ | Cast _
| Int _ | Float _ | Array _ | Meta _ | Evar _ -> Exninfo.iraise exn
end
| Const (kn,_u as cu) ->
if evaluable_constant kn renv.env then
try List.iter (check_rec_call renv []) l
with (FixGuardError _ ) ->
let value = (Term.applist(constant_value_in renv.env cu, l)) in
check_rec_call renv stack value
else List.iter (check_rec_call renv []) l
| Lambda (x,a,b) ->
let () = assert (List.is_empty l) in
check_rec_call renv [] a ;
let spec, stack' = extract_stack stack in
check_rec_call (push_var renv (x,a,spec)) stack' b
| Prod (x,a,b) ->
let () = assert (List.is_empty l && List.is_empty stack) in
check_rec_call renv [] a;
check_rec_call (push_var_renv renv (x,a)) [] b
| CoFix (_i,(_,typarray,bodies as recdef)) ->
List.iter (check_rec_call renv []) l;
Array.iter (check_rec_call renv []) typarray;
let renv' = push_fix_renv renv recdef in
Array.iter (check_rec_call renv' []) bodies
| (Ind _ | Construct _) ->
List.iter (check_rec_call renv []) l
| Proj (p, c) ->
begin try
List.iter (check_rec_call renv []) l;
check_rec_call renv [] c
with (FixGuardError _ as exn) ->
let exn = Exninfo.capture exn in
let c = whd_all renv.env c in
let hd, _ = decompose_app c in
match kind hd with
| Construct _ | CoFix _ ->
check_rec_call renv stack
(Term.applist (mkProj(Projection.unfold p,c), l))
| Rel _ | Var _ | Const _ | App _ | Lambda _ | Prod _ | LetIn _
| Ind _ | Case _ | Fix _ | Proj _ | Sort _ | Cast _
| Int _ | Float _ | Array _ | Meta _ | Evar _ -> Exninfo.iraise exn
end
| Var id ->
begin
let open! Context.Named.Declaration in
match lookup_named id renv.env with
| LocalAssum _ ->
List.iter (check_rec_call renv []) l
| LocalDef (_,c,_) ->
try List.iter (check_rec_call renv []) l
with (FixGuardError _) ->
check_rec_call renv stack (Term.applist(c,l))
end
| Sort _ | Int _ | Float _ ->
assert (List.is_empty l)
| Array (_u, t,def,ty) ->
assert (List.is_empty l);
Array.iter (check_rec_call renv []) t;
check_rec_call renv [] def;
check_rec_call renv [] ty
| (Evar _ | Meta _) -> ()
| (App _ | LetIn _ | Cast _) -> assert false
and check_nested_fix_body illformed renv decr recArgsDecrArg body =
if Int.equal decr 0 then
check_rec_call (assign_var_spec renv (1,recArgsDecrArg)) [] body
else
match kind (whd_all renv.env body) with
| Lambda (x,a,b) ->
check_rec_call renv [] a;
let renv' = push_var_renv renv (x,a) in
check_nested_fix_body illformed renv' (decr-1) recArgsDecrArg b
| _ -> illformed ()
in
check_rec_call renv [] def
let inductive_of_mutfix env ((nvect,bodynum),(names,types,bodies as recdef)) =
let nbfix = Array.length bodies in
if Int.equal nbfix 0
|| not (Int.equal (Array.length nvect) nbfix)
|| not (Int.equal (Array.length types) nbfix)
|| not (Int.equal (Array.length names) nbfix)
|| bodynum < 0
|| bodynum >= nbfix
then anomaly (Pp.str "Ill-formed fix term.");
let fixenv = push_rec_types recdef env in
let vdefj = judgment_of_fixpoint recdef in
let raise_err env i err =
error_ill_formed_rec_body env err names i fixenv vdefj in
let find_ind i k def =
let rec check_occur env n def =
match kind (whd_all env def) with
| Lambda (x,a,b) ->
if noccur_with_meta n nbfix a then
let env' = push_rel (LocalAssum (x,a)) env in
if Int.equal n (k + 1) then
let (mind, _) =
try find_inductive env a
with Not_found ->
raise_err env i (RecursionNotOnInductiveType a) in
let mib,_ = lookup_mind_specif env (out_punivs mind) in
if mib.mind_finite != Finite then
raise_err env i (RecursionNotOnInductiveType a);
(mind, (env', b))
else check_occur env' (n+1) b
else anomaly ~label:"check_one_fix" (Pp.str "Bad occurrence of recursive call.")
| _ -> raise_err env i NotEnoughAbstractionInFixBody
in
let ((ind, _), _) as res = check_occur fixenv 1 def in
let _, mip = lookup_mind_specif env ind in
if mip.mind_relevance == Sorts.Irrelevant &&
not (Environ.is_type_in_type env (GlobRef.IndRef ind))
then
begin
if names.(i).Context.binder_relevance == Sorts.Relevant
then raise_err env i FixpointOnIrrelevantInductive
end;
res
in
let rv = Array.map2_i find_ind nvect bodies in
(Array.map fst rv, Array.map snd rv)
let check_fix env ((nvect,_),(names,_,bodies as recdef) as fix) =
let flags = Environ.typing_flags env in
if flags.check_guarded then
let (minds, rdef) = inductive_of_mutfix env fix in
let get_tree (kn,i) =
let mib = Environ.lookup_mind kn env in
mib.mind_packets.(i).mind_recargs
in
let trees = Array.map (fun (mind,_) -> get_tree mind) minds in
for i = 0 to Array.length bodies - 1 do
let (fenv,body) = rdef.(i) in
let renv = make_renv fenv nvect.(i) trees.(i) in
try check_one_fix renv nvect trees body
with FixGuardError (fixenv,err) ->
error_ill_formed_rec_body fixenv err names i
(push_rec_types recdef env) (judgment_of_fixpoint recdef)
done
else
()
exception CoFixGuardError of env * guard_error
let anomaly_ill_typed () =
anomaly ~label:"check_one_cofix" (Pp.str "too many arguments applied to constructor.")
let rec codomain_is_coind env c =
let b = whd_all env c in
match kind b with
| Prod (x,a,b) ->
codomain_is_coind (push_rel (LocalAssum (x,a)) env) b
| _ ->
(try find_coinductive env b
with Not_found ->
raise (CoFixGuardError (env, CodomainNotInductiveType b)))
let check_one_cofix env nbfix def deftype =
let rec check_rec_call env alreadygrd n tree vlra t =
if not (noccur_with_meta n nbfix t) then
let c,args = decompose_app (whd_all env t) in
match kind c with
| Rel p when n <= p && p < n+nbfix ->
if not alreadygrd then
raise (CoFixGuardError (env,UnguardedRecursiveCall t))
else if not(List.for_all (noccur_with_meta n nbfix) args) then
raise (CoFixGuardError (env,NestedRecursiveOccurrences))
| Construct ((_,i as cstr_kn),_u) ->
let lra = vlra.(i-1) in
let mI = inductive_of_constructor cstr_kn in
let (mib,_mip) = lookup_mind_specif env mI in
let realargs = List.skipn mib.mind_nparams args in
let rec process_args_of_constr = function
| (t::lr), (rar::lrar) ->
if eq_wf_paths rar mk_norec then
if noccur_with_meta n nbfix t
then process_args_of_constr (lr, lrar)
else raise (CoFixGuardError
(env,RecCallInNonRecArgOfConstructor t))
else begin
check_rec_call env true n rar (dest_subterms rar) t;
process_args_of_constr (lr, lrar)
end
| [],_ -> ()
| _ -> anomaly_ill_typed ()
in process_args_of_constr (realargs, lra)
| Lambda (x,a,b) ->
let () = assert (List.is_empty args) in
if noccur_with_meta n nbfix a then
let env' = push_rel (LocalAssum (x,a)) env in
check_rec_call env' alreadygrd (n+1) tree vlra b
else
raise (CoFixGuardError (env,RecCallInTypeOfAbstraction a))
| CoFix (_j,(_,varit,vdefs as recdef)) ->
if List.for_all (noccur_with_meta n nbfix) args
then
if Array.for_all (noccur_with_meta n nbfix) varit then
let nbfix = Array.length vdefs in
let env' = push_rec_types recdef env in
(Array.iter (check_rec_call env' alreadygrd (n+nbfix) tree vlra) vdefs;
List.iter (check_rec_call env alreadygrd n tree vlra) args)
else
raise (CoFixGuardError (env,RecCallInTypeOfDef c))
else
raise (CoFixGuardError (env,UnguardedRecursiveCall c))
| Case (ci, u, pms, p, iv, tm, br) ->
begin
let (_, p, _iv, tm, vrest) = expand_case env (ci, u, pms, p, iv, tm, br) in
let tree = match restrict_spec env (Subterm (Strict, tree)) p with
| Dead_code -> assert false
| Subterm (_, tree') -> tree'
| _ -> raise (CoFixGuardError (env, ReturnPredicateNotCoInductive c))
in
if (noccur_with_meta n nbfix p) then
if (noccur_with_meta n nbfix tm) then
if (List.for_all (noccur_with_meta n nbfix) args) then
let vlra = dest_subterms tree in
Array.iter (check_rec_call env alreadygrd n tree vlra) vrest
else
raise (CoFixGuardError (env,RecCallInCaseFun c))
else
raise (CoFixGuardError (env,RecCallInCaseArg c))
else
raise (CoFixGuardError (env,RecCallInCasePred c))
end
| Meta _ -> ()
| Evar _ ->
List.iter (check_rec_call env alreadygrd n tree vlra) args
| Rel _ | Var _ | Sort _ | Cast _ | Prod _ | LetIn _ | App _ | Const _
| Ind _ | Fix _ | Proj _ | Int _ | Float _ | Array _ ->
raise (CoFixGuardError (env,NotGuardedForm t)) in
let ((mind, _),_) = codomain_is_coind env deftype in
let vlra = lookup_subterms env mind in
check_rec_call env false 1 vlra (dest_subterms vlra) def
let check_cofix env (_bodynum,(names,types,bodies as recdef)) =
let flags = Environ.typing_flags env in
if flags.check_guarded then
let nbfix = Array.length bodies in
for i = 0 to nbfix-1 do
let fixenv = push_rec_types recdef env in
try check_one_cofix fixenv nbfix bodies.(i) types.(i)
with CoFixGuardError (errenv,err) ->
error_ill_formed_rec_body errenv err names i
fixenv (judgment_of_fixpoint recdef)
done
else
()