forked from coq/coq
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdetyping.ml
1319 lines (1197 loc) · 50.5 KB
/
detyping.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
(************************************************************************)
(* * The Rocq Prover / The Rocq 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) *)
(************************************************************************)
module CVars = Vars
open Pp
open CErrors
open Util
open Names
open Constr
open Context
open Term
open EConstr
open Vars
open Inductiveops
open Glob_term
open Glob_ops
open Termops
open Namegen
open Libnames
open Globnames
open Mod_subst
open Context.Rel.Declaration
open Ltac_pretype
type detyping_flags = {
flg_isgoal : bool;
}
let nongoal (_:detyping_flags) = { flg_isgoal = false }
(** Reimplementation of kernel case expansion functions in more lenient way *)
module RobustExpand :
sig
val return_clause : Environ.env -> Evd.evar_map -> Ind.t ->
EInstance.t -> EConstr.t array -> EConstr.case_return -> rel_context * EConstr.t
val branch : Environ.env -> Evd.evar_map -> Construct.t ->
EInstance.t -> EConstr.t array -> EConstr.case_branch -> rel_context * EConstr.t
end =
struct
open CVars
open Declarations
open UVars
open Constr
let instantiate_context u subst nas ctx =
let rec instantiate i ctx = match ctx with
| [] -> []
| 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
let () = if not (Int.equal (Array.length nas) (List.length ctx)) then raise_notrace Exit in
instantiate (Array.length nas - 1) ctx
let return_clause env sigma ind u params ((nas, p),_) =
let nas : Name.t EConstr.binder_annot array = nas in
try
let u = EConstr.Unsafe.to_instance u in
let params = EConstr.Unsafe.to_constr_array params in
let nas : Name.t Constr.binder_annot array =
match EConstr.Unsafe.relevance_eq with Refl -> nas
in
let () = if not @@ Environ.mem_mind (fst ind) env then raise_notrace Exit in
let mib = Environ.lookup_mind (fst ind) env in
let mip = mib.mind_packets.(snd ind) in
let paramdecl = subst_instance_context u mib.mind_params_ctxt in
let paramsubst = subst_of_rel_context_instance paramdecl params 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.(abstract_instance (length u)) in
mkApp (mkIndU (ind, inst), args)
in
let na = Context.make_annot Anonymous mip.mind_relevance in
let realdecls = LocalAssum (na, self) :: realdecls in
let realdecls = instantiate_context u paramsubst nas realdecls in
List.map EConstr.of_rel_decl realdecls, p
with e when CErrors.noncritical e ->
let dummy na = LocalAssum (na, EConstr.mkProp) in
List.rev (Array.map_to_list dummy nas), p
let branch env sigma (ind, i) u params (nas, br) =
let nas : Name.t EConstr.binder_annot array = nas in
try
let u = EConstr.Unsafe.to_instance u in
let params = EConstr.Unsafe.to_constr_array params in
let nas : Name.t Constr.binder_annot array =
match EConstr.Unsafe.relevance_eq with Refl -> nas
in
let () = if not @@ Environ.mem_mind (fst ind) env then raise_notrace Exit in
let mib = Environ.lookup_mind (fst ind) env in
let mip = mib.mind_packets.(snd ind) in
let paramdecl = subst_instance_context u mib.mind_params_ctxt in
let paramsubst = subst_of_rel_context_instance paramdecl params in
let (ctx, _) = mip.mind_nf_lc.(i - 1) in
let ctx, _ = List.chop mip.mind_consnrealdecls.(i - 1) ctx in
let ctx = instantiate_context u paramsubst nas ctx in
List.map EConstr.of_rel_decl ctx, br
with e when CErrors.noncritical e ->
let dummy na = LocalAssum (na, EConstr.mkProp) in
List.rev (Array.map_to_list dummy nas), br
end
let genset = Generator.idset
let next_name_away0 na (gen, avoid) =
let (id, avoid) = Namegen.Generator.next_name_away gen na avoid in
(id, (gen, avoid))
module Avoid :
sig
type t
val make : fast:bool -> 'a Generator.input option -> t
val compute_name : Evd.evar_map -> let_in:bool -> pattern:bool ->
detyping_flags -> t -> Name.t list * 'a -> Name.t ->
EConstr.constr -> Name.t * t
val next_name_away : detyping_flags -> Name.t -> t -> Id.t * t
end =
struct
open Nameops
type t =
| Nice : 'a Generator.t * 'a -> t
| Fast of Subscript.t Id.Map.t
(** Overapproximation of the set of names to avoid. If [(id ↦ s) ∈ m] then for
all subscript [s'] smaller than [s], [add_subscript id s'] needs to be
avoided. *)
let make0 ~fast gen ids =
if fast then Fast (Generator.max_map gen ids)
else Nice (gen, ids)
let make ~fast = function
| None -> make0 ~fast Generator.fresh Fresh.empty
| Some (gen, avoid) -> make0 ~fast gen avoid
let fresh_id_in id avoid =
let id, _ = get_subscript id in
(* Find the first free subscript for that identifier *)
let ss = try Subscript.succ (Id.Map.find id avoid) with Not_found -> Subscript.zero in
let avoid = Id.Map.add id ss avoid in
(add_subscript id ss, avoid)
let compute_name sigma ~let_in ~pattern flags avoid env na c =
match avoid with
| Nice (gen, avoid) ->
let flags =
if flags.flg_isgoal then RenamingForGoal
else if pattern then RenamingForCasesPattern (fst env, c)
else RenamingElsewhereFor (fst env, c)
in
let na, avoid =
if let_in then compute_displayed_let_name_in gen (Global.env ()) sigma flags avoid na
else compute_displayed_name_in gen (Global.env ()) sigma flags avoid na c
in
na, Nice (gen, avoid)
| Fast avoid ->
(* In fast mode, we use a dumber algorithm but algorithmically more
efficient algorithm that doesn't iterate through the term to find the
used constants and variables. *)
let id = match na with
| Name id -> id
| Anonymous ->
if flags.flg_isgoal then default_non_dependent_ident
else if pattern then default_dependent_ident
else default_non_dependent_ident
in
let id, avoid = fresh_id_in id avoid in
(Name id, Fast avoid)
let next_name_away flags na avoid = match avoid with
| Nice (gen, avoid) ->
let id, (gen, avoid) = next_name_away0 na (gen, avoid) in
id, Nice (gen, avoid)
| Fast avoid ->
let id = match na with
| Anonymous -> default_non_dependent_ident
| Name id -> id
in
let id, avoid = fresh_id_in id avoid in
(id, Fast avoid)
end
let compute_name = Avoid.compute_name
let next_name_away = Avoid.next_name_away
type _ delay =
| Now : 'a delay
| Later : [ `thunk ] delay
(** Should we keep details of universes during detyping ? *)
let print_universes = ref false
(** Should we print hidden sort quality variables? *)
let { Goptions.get = print_sort_quality } =
Goptions.declare_bool_option_and_ref
~key:["Printing";"Sort";"Qualities"]
~value:true
()
(** If true, prints local context of evars, whatever print_arguments *)
let print_evar_arguments = ref false
let () =
let open Goptions in
declare_bool_option
{ optstage = Summary.Stage.Interp;
optdepr = None;
optkey = ["Printing";"Existential";"Instances"];
optread = (fun () -> !print_evar_arguments);
optwrite = (:=) print_evar_arguments }
let add_name decl (nenv, env) =
add_name (get_name decl) nenv, push_rel decl env
(****************************************************************************)
(* Tools for printing of Cases *)
let encode_inductive env r =
let indsp = Nametab.global_inductive r in
let constr_lengths = constructors_nrealargs env indsp in
(indsp,constr_lengths)
(* Parameterization of the translation from constr to ast *)
(* Tables for Cases printing under a "if" form, a "let" form, *)
let has_two_constructors lc =
Int.equal (Array.length lc) 2 (* & lc.(0) = 0 & lc.(1) = 0 *)
let isomorphic_to_tuple lc = Int.equal (Array.length lc) 1
let encode_bool env ({CAst.loc} as r) =
let (x,lc) = encode_inductive env r in
if not (has_two_constructors lc) then
user_err ?loc
(str "This type has not exactly two constructors.");
x
let encode_tuple env ({CAst.loc} as r) =
let (x,lc) = encode_inductive env r in
if not (isomorphic_to_tuple lc) then
user_err ?loc
(str "This type cannot be seen as a tuple type.");
x
module PrintingInductiveMake =
functor (Test : sig
val encode : Environ.env -> qualid -> inductive
val member_message : Pp.t -> bool -> Pp.t
val field : string
val title : string
end) ->
struct
type t = inductive
module Set = Indset
let encode = Test.encode
let subst subst obj = subst_ind subst obj
let check_local _ _ = ()
let discharge (i:t) = i
let printer ind = Nametab.pr_global_env Id.Set.empty (GlobRef.IndRef ind)
let key = ["Printing";Test.field]
let title = Test.title
let member_message x = Test.member_message (printer x)
end
module PrintingCasesIf =
PrintingInductiveMake (struct
let encode = encode_bool
let field = "If"
let title = "Types leading to pretty-printing of Cases using a `if' form:"
let member_message s b =
str "Cases on elements of " ++ s ++
str
(if b then " are printed using a `if' form"
else " are not printed using a `if' form")
end)
module PrintingCasesLet =
PrintingInductiveMake (struct
let encode = encode_tuple
let field = "Let"
let title =
"Types leading to a pretty-printing of Cases using a `let' form:"
let member_message s b =
str "Cases on elements of " ++ s ++
str
(if b then " are printed using a `let' form"
else " are not printed using a `let' form")
end)
module PrintingIf = Goptions.MakeRefTable(PrintingCasesIf)
module PrintingLet = Goptions.MakeRefTable(PrintingCasesLet)
(* Flags.for printing or not wildcard and synthetisable types *)
let { Goptions.get = force_wildcard } =
Goptions.declare_bool_option_and_ref
~key:["Printing";"Wildcard"]
~value:true
()
let { Goptions.get = fast_name_generation } =
Goptions.declare_bool_option_and_ref
~key:["Fast";"Name";"Printing"]
~value:false
()
let { Goptions.get = synthetize_type } =
Goptions.declare_bool_option_and_ref
~key:["Printing";"Synth"]
~value:true
()
let { Goptions.get = reverse_matching } =
Goptions.declare_bool_option_and_ref
~key:["Printing";"Matching"]
~value:true
()
let { Goptions.get = print_primproj_params } =
Goptions.declare_bool_option_and_ref
~key:["Printing";"Primitive";"Projection";"Parameters"]
~value:false
()
let { Goptions.get = print_unfolded_primproj_asmatch } =
Goptions.declare_bool_option_and_ref
~key:["Printing";"Unfolded";"Projection";"As";"Match"]
~value:false
()
let { Goptions.get = print_match_paramunivs } =
Goptions.declare_bool_option_and_ref
~key:["Printing";"Match";"All";"Subterms"]
~value:false
()
let { Goptions.get = print_relevances } =
Goptions.declare_bool_option_and_ref
~key:["Printing";"Relevance";"Marks"]
~value:false
()
(** univ and sort detyping *)
let detype_level_name sigma l =
if Univ.Level.is_set l then GSet else
match UState.id_of_level (Evd.ustate sigma) l with
| Some id -> GLocalUniv (CAst.make id)
| None -> GUniv l
let detype_level sigma l =
UNamed (detype_level_name sigma l)
let detype_qvar sigma q =
match UState.id_of_qvar (Evd.ustate sigma) q with
| Some id -> GLocalQVar (CAst.make (Name id))
| None -> GQVar q
let detype_quality sigma q =
let open Sorts.Quality in
match q with
| QConstant q -> GQConstant q
| QVar q -> GQualVar (detype_qvar sigma q)
let detype_universe sigma u =
UNamed (List.map (on_fst (detype_level_name sigma)) (Univ.Universe.repr u))
let detype_sort sigma = function
| SProp -> glob_SProp_sort
| Prop -> glob_Prop_sort
| Set -> glob_Set_sort
| Type u ->
(if !print_universes
then None, detype_universe sigma u
else glob_Type_sort)
| QSort (q, u) ->
if !print_universes then
let q = if print_sort_quality () then Some (detype_qvar sigma q) else None in
q, detype_universe sigma u
else glob_Type_sort
let detype_relevance_info sigma na =
if not (print_relevances ()) then None
else match ERelevance.kind sigma na.binder_relevance with
| Relevant -> Some GRelevant
| Irrelevant -> Some GIrrelevant
| RelevanceVar q -> Some (GRelevanceVar (detype_qvar sigma q))
(* Auxiliary function for MutCase printing *)
(* [computable] tries to tell if the predicate typing the result is inferable*)
let computable sigma (nas, ccl) =
(* We first remove as many lambda as the arity, then we look
if it remains a lambda for a dependent elimination.
Lorsque le prédicat est dépendant de manière certaine, on
ne déclare pas le prédicat synthétisable (même si la
variable dépendante ne l'est pas effectivement) parce que
sinon on perd la réciprocité de la synthèse (qui, lui,
engendrera un prédicat non dépendant) *)
noccur_between sigma 1 (Array.length nas) ccl
let lookup_name_as_displayed env sigma t s =
let rec lookup avoid n c = match EConstr.kind sigma c with
| Prod (name,_,c') ->
(match compute_displayed_name_in genset (Global.env ()) sigma RenamingForGoal avoid name.binder_name c' with
| (Name id,avoid') -> if Id.equal id s then Some n else lookup avoid' (n+1) c'
| (Anonymous,avoid') -> lookup avoid' (n+1) (pop c'))
| LetIn (name,_,_,c') ->
(match Namegen.compute_displayed_name_in genset (Global.env ()) sigma RenamingForGoal avoid name.binder_name c' with
| (Name id,avoid') -> if Id.equal id s then Some n else lookup avoid' (n+1) c'
| (Anonymous,avoid') -> lookup avoid' (n+1) (pop c'))
| Cast (c,_,_) -> lookup avoid n c
| _ -> None
in lookup (Environ.ids_of_named_context_val (Environ.named_context_val env)) 1 t
let lookup_index_as_renamed env sigma t n =
let rec lookup n d c = match EConstr.kind sigma c with
| Prod (name,_,c') ->
(match Namegen.compute_displayed_name_in genset (Global.env ()) sigma RenamingForGoal Id.Set.empty name.binder_name c' with
(Name _,_) -> lookup n (d+1) c'
| (Anonymous,_) ->
if Int.equal n 0 then
Some (d-1)
else if Int.equal n 1 then
Some d
else
lookup (n-1) (d+1) c')
| LetIn (name,_,_,c') ->
(match Namegen.compute_displayed_name_in genset (Global.env ()) sigma RenamingForGoal Id.Set.empty name.binder_name c' with
| (Name _,_) -> lookup n (d+1) c'
| (Anonymous,_) ->
if Int.equal n 0 then
Some (d-1)
else if Int.equal n 1 then
Some d
else
lookup (n-1) (d+1) c'
)
| Cast (c,_,_) -> lookup n d c
| _ -> if Int.equal n 0 then Some (d-1) else None
in lookup n 1 t
(**********************************************************************)
(* Factorization of match patterns *)
let { Goptions.get = print_factorize_match_patterns } =
Goptions.declare_bool_option_and_ref
~key:["Printing";"Factorizable";"Match";"Patterns"]
~value:true
()
let print_allow_match_default_opt_name =
["Printing";"Allow";"Match";"Default";"Clause"]
let { Goptions.get = print_allow_match_default_clause } =
Goptions.declare_bool_option_and_ref
~key:print_allow_match_default_opt_name
~value:true
()
let rec join_eqns (ids,rhs as x) patll = function
| ({CAst.loc; v=(ids',patl',rhs')} as eqn')::rest ->
if not !Flags.raw_print && print_factorize_match_patterns () &&
List.eq_set Id.equal ids ids' && glob_constr_eq rhs rhs'
then
join_eqns x (patl'::patll) rest
else
let eqn,rest = join_eqns x patll rest in
eqn, eqn'::rest
| [] ->
patll, []
let number_of_patterns {CAst.v=(_ids,patll,_rhs)} = List.length patll
let is_default_candidate {CAst.v=(ids,_patll,_rhs)} = ids = []
let rec move_more_factorized_default_candidate_to_end eqn n = function
| eqn' :: eqns ->
let set,get = set_temporary_memory () in
if is_default_candidate eqn' && set (number_of_patterns eqn') >= n then
let isbest, dft, eqns = move_more_factorized_default_candidate_to_end eqn' (get ()) eqns in
if isbest then false, dft, eqns else false, dft, eqn' :: eqns
else
let isbest, dft, eqns = move_more_factorized_default_candidate_to_end eqn n eqns in
isbest, dft, eqn' :: eqns
| [] -> true, Some eqn, []
let rec select_default_clause = function
| eqn :: eqns ->
let set,get = set_temporary_memory () in
if is_default_candidate eqn && set (number_of_patterns eqn) > 1 then
let isbest, dft, eqns = move_more_factorized_default_candidate_to_end eqn (get ()) eqns in
if isbest then dft, eqns else dft, eqn :: eqns
else
let dft, eqns = select_default_clause eqns in dft, eqn :: eqns
| [] -> None, []
let factorize_eqns eqns =
let open CAst in
let rec aux found = function
| {loc;v=(ids,patl,rhs)}::rest ->
let patll,rest = join_eqns (ids,rhs) [patl] rest in
aux (CAst.make ?loc (ids,patll,rhs)::found) rest
| [] ->
found in
let eqns = aux [] (List.rev eqns) in
let mk_anon patl = List.map (fun _ -> DAst.make @@ PatVar Anonymous) patl in
let open CAst in
if not !Flags.raw_print && print_allow_match_default_clause () && eqns <> [] then
match select_default_clause eqns with
(* At least two clauses and the last one is disjunctive with no variables *)
| Some {loc=gloc;v=([],patl::_::_,rhs)}, (_::_ as eqns) ->
eqns@[CAst.make ?loc:gloc ([],[mk_anon patl],rhs)]
(* Only one clause which is disjunctive with no variables: we keep at least one constructor *)
(* so that it is not interpreted as a dummy "match" *)
| Some {loc=gloc;v=([],patl::patl'::_,rhs)}, [] ->
[CAst.make ?loc:gloc ([],[patl;mk_anon patl'],rhs)]
| Some {v=((_::_,_,_ | _,([]|[_]),_))}, _ -> assert false
| None, eqns -> eqns
else
eqns
(**********************************************************************)
(* Fragile algorithm to reverse pattern-matching compilation *)
let update_name sigma na ((_,(e,_)),c) =
match na with
| Name _ when force_wildcard () && noccurn sigma (List.index Name.equal na e) c ->
Anonymous
| _ ->
na
let decomp_branch flags e sigma (ctx, c) =
let n = List.length ctx in
let rec aux i nal (avoid, env as e) c =
if Int.equal i 0 then (List.rev nal,(e,c))
else
let decl, c, let_in =
match EConstr.kind sigma c with
| Lambda (na,t,c) -> LocalAssum (na,t), c, true
| LetIn (na,b,t,c) -> LocalDef (na,b,t), c, false
| _ -> assert false
in
let na',avoid' = compute_name sigma ~let_in ~pattern:true flags avoid env (get_name decl) c in
aux (i - 1) (na'::nal) (avoid', add_name (set_name na' decl) env) c
in
aux n [] e (EConstr.it_mkLambda_or_LetIn c ctx)
let rec build_tree na isgoal e sigma (ci, u, pms, cl) =
let map i br =
RobustExpand.branch (snd (snd e)) sigma (ci.ci_ind, i + 1) u pms br
in
let cl = Array.mapi map cl in
let mkpat n rhs pl =
let na = update_name sigma na rhs in
na, DAst.make @@ PatCstr((ci.ci_ind,n+1),pl,na) in
List.flatten
(List.init (Array.length cl)
(fun i -> contract_branch isgoal e sigma (mkpat i,cl.(i))))
and align_tree nal isgoal (e,c as rhs) sigma = match nal with
| [] -> [Id.Set.empty,[],rhs]
| na::nal ->
match EConstr.kind sigma c with
| Case (ci,u,pms,(p,_),iv,c,cl) when
eq_constr (snd (snd e)) sigma c (mkRel (List.index Name.equal na (fst (snd e))))
&& not (Int.equal (Array.length cl) 0)
&& (* don't contract if p dependent *)
computable sigma p (* FIXME: can do better *) ->
let clauses = build_tree na isgoal e sigma (ci, u, pms, cl) in
List.flatten
(List.map (fun (ids,pat,rhs) ->
let lines = align_tree nal isgoal rhs sigma in
List.map (fun (ids',hd,rest) -> Id.Set.fold Id.Set.add ids ids',pat::hd,rest) lines)
clauses)
| _ ->
let na = update_name sigma na rhs in
let pat = DAst.make @@ PatVar na in
let mat = align_tree nal isgoal rhs sigma in
List.map (fun (ids,hd,rest) -> Nameops.Name.fold_right Id.Set.add na ids,pat::hd,rest) mat
and contract_branch isgoal e sigma (mkpat,rhs) =
let nal,rhs = decomp_branch isgoal e sigma rhs in
let mat = align_tree nal isgoal rhs sigma in
List.map (fun (ids,hd,rhs) ->
let na, pat = mkpat rhs hd in
(Nameops.Name.fold_right Id.Set.add na ids, pat, rhs)) mat
(**********************************************************************)
(* Transform internal representation of pattern-matching into list of *)
(* clauses *)
let is_nondep_branch sigma (nas, ccl) =
noccur_between sigma 1 (Array.length nas) ccl
let extract_nondep_branches b l =
let rec strip l r =
match DAst.get r, l with
| r', [] -> r
| GLambda (_,_,_,_,t), false::l -> strip l t
| GLetIn (_,_,_,_,t), true::l -> strip l t
(* FIXME: do we need adjustment? *)
| _,_ -> assert false in
strip l b
let it_destRLambda_or_LetIn_names l c =
let rec aux l nal c =
match DAst.get c, l with
| _, [] -> (List.rev nal,c)
| GLambda (na,_,_,_,c), false::l -> aux l (na::nal) c
| GLetIn (na,_,_,_,c), true::l -> aux l (na::nal) c
| _, true::l -> (* let-expansion *) aux l (Anonymous :: nal) c
| _, false::l ->
(* eta-expansion *)
let next l =
let x = next_ident_away default_dependent_ident l in
(* Not efficient but unusual and no function to get free glob_vars *)
(* if occur_glob_constr x c then next (x::l) else x in *)
x
in
let x = next (free_glob_vars c) in
let a = DAst.make @@ GVar x in
aux l (Name x :: nal)
(match DAst.get c with
| GApp (p,l) -> DAst.make ?loc:c.CAst.loc @@ GApp (p,l@[a])
| _ -> DAst.make @@ GApp (c,[a]))
in aux l [] c
let get_ind_tag env ind p =
if Environ.mem_mind (fst ind) env then
let (mib, mip) = Inductive.lookup_mind_specif env ind in
Context.Rel.to_tags (List.firstn mip.mind_nrealdecls mip.mind_arity_ctxt)
else
let (nas, _), _ = p in
Array.map_to_list (fun _ -> false) nas
let get_cstr_tags env ind bl =
if Environ.mem_mind (fst ind) env then
let (mib, mip) = Inductive.lookup_mind_specif env ind in
Array.map2 (fun (d, _) n -> Context.Rel.to_tags (List.firstn n d))
mip.mind_nf_lc mip.mind_consnrealdecls
else
let map (nas, _) = Array.map_to_list (fun _ -> false) nas in
Array.map map bl
let detype_case computable detype detype_eqns avoid env sigma (ci, univs, params, p, iv, c, bl) =
let synth_type = synthetize_type () in
let tomatch = detype c in
let tomatch =
if not (print_match_paramunivs ()) then tomatch
else match iv with
| NoInvert ->
if Array.is_empty params && EInstance.is_empty univs
then tomatch
else if !Flags.in_debugger then
let t = mkApp (mkIndU (ci.ci_ind,univs), params) in
DAst.make @@ GCast (tomatch, None, detype t)
else
let _, mip = Global.lookup_inductive ci.ci_ind in
let hole = DAst.make @@ GHole (GInternalHole) in
let indices = List.make mip.mind_nrealargs hole in
let t = mkApp (mkIndU (ci.ci_ind,univs), params) in
DAst.make @@ GCast (tomatch, None, mkGApp (detype t) indices)
| CaseInvert {indices} ->
let t = mkApp (mkIndU (ci.ci_ind,univs), Array.append params indices) in
DAst.make @@ GCast (tomatch, None, detype t)
in
let alias, aliastyp, pred =
if (not !Flags.raw_print) && synth_type && computable && not (Int.equal (Array.length bl) 0)
then
Anonymous, None, None
else
let ind_tags = get_ind_tag (snd env) ci.ci_ind p in
let (ctx, p) = RobustExpand.return_clause (snd env) sigma ci.ci_ind univs params p in
let p = EConstr.it_mkLambda_or_LetIn p ctx in
let p = detype p in
let nl,typ = it_destRLambda_or_LetIn_names ind_tags p in
let n,typ = match DAst.get typ with
| GLambda (x,_,_,t,c) -> x, c
| _ -> Anonymous, typ in
let aliastyp =
if List.for_all (Name.equal Anonymous) nl then None
else Some (CAst.make (ci.ci_ind,nl)) in
n, aliastyp, Some typ
in
let constructs = Array.init (Array.length bl) (fun i -> (ci.ci_ind,i+1)) in
let tag = let st = ci.ci_pp_info.style in
try
if !Flags.raw_print then
RegularStyle
else if st == LetPatternStyle then
st
else if PrintingLet.active ci.ci_ind then
LetStyle
else if PrintingIf.active ci.ci_ind then
IfStyle
else
st
with Not_found -> st
in
match tag, aliastyp with
| LetStyle, None ->
let map i br =
let (ctx, body) = RobustExpand.branch (snd env) sigma (ci.ci_ind, i + 1) univs params br in
EConstr.it_mkLambda_or_LetIn body ctx
in
let constagsl = get_cstr_tags (snd env) ci.ci_ind bl in
let bl = Array.mapi map bl in
let bl' = Array.map detype bl in
let (nal,d) = it_destRLambda_or_LetIn_names constagsl.(0) bl'.(0) in
GLetTuple (nal,(alias,pred),tomatch,d)
| IfStyle, None ->
if Array.for_all (fun br -> is_nondep_branch sigma br) bl then
let map i br =
let ctx, body = RobustExpand.branch (snd env) sigma (ci.ci_ind, i + 1) univs params br in
EConstr.it_mkLambda_or_LetIn body ctx
in
let constagsl = get_cstr_tags (snd env) ci.ci_ind bl in
let bl = Array.mapi map bl in
let bl' = Array.map detype bl in
let nondepbrs = Array.map2 extract_nondep_branches bl' constagsl in
GIf (tomatch,(alias,pred), nondepbrs.(0), nondepbrs.(1))
else
let eqnl = detype_eqns constructs (ci, univs, params, bl) in
GCases (tag,pred,[tomatch,(alias,aliastyp)],eqnl)
| _ ->
let eqnl = detype_eqns constructs (ci, univs, params, bl) in
GCases (tag,pred,[tomatch,(alias,aliastyp)],eqnl)
let rec share_names detype flags n l avoid env sigma c t =
match EConstr.kind sigma c, EConstr.kind sigma t with
(* factorize even when not necessary to have better presentation *)
| Lambda (na,t,c), Prod (na',t',c') ->
let decl = LocalAssum (na,t) in
let na = Nameops.Name.pick_annot na na' in
let t' = detype flags avoid env sigma t in
let id, avoid = next_name_away flags na.binder_name avoid in
let env = add_name (set_name (Name id) decl) env in
share_names detype flags (n-1) ((Name id,detype_relevance_info sigma na, Explicit,None,t')::l) avoid env sigma c c'
(* May occur for fix built interactively *)
| LetIn (na,b,t',c), _ when n > 0 ->
let decl = LocalDef (na,b,t') in
let t'' = detype flags avoid env sigma t' in
let b' = detype flags avoid env sigma b in
let id, avoid = next_name_away flags na.binder_name avoid in
let env = add_name (set_name (Name id) decl) env in
share_names detype flags n ((Name id,detype_relevance_info sigma na, Explicit,Some b',t'')::l) avoid env sigma c (lift 1 t)
(* Only if built with the f/n notation or w/o let-expansion in types *)
| _, LetIn (_,b,_,t) when n > 0 ->
share_names detype flags n l avoid env sigma c (subst1 b t)
(* If it is an open proof: we cheat and eta-expand *)
| _, Prod (na',t',c') when n > 0 ->
let decl = LocalAssum (na',t') in
let t'' = detype flags avoid env sigma t' in
let id, avoid = next_name_away flags na'.binder_name avoid in
let env = add_name (set_name (Name id) decl) env in
let appc = mkApp (lift 1 c,[|mkRel 1|]) in
share_names detype flags (n-1) ((Name id,detype_relevance_info sigma na',Explicit,None,t'')::l) avoid env sigma appc c'
(* If built with the f/n notation: we renounce to share names *)
| _ ->
if n>0 then Feedback.msg_debug (strbrk "Detyping.detype: cannot factorize fix enough");
let c = detype flags avoid env sigma c in
let t = detype flags avoid env sigma t in
(List.rev l,c,t)
let rec share_pattern_names detype n l avoid env sigma c t =
let open Pattern in
if n = 0 then
let c = detype avoid env sigma c in
let t = detype avoid env sigma t in
(List.rev l,c,t)
else match c, t with
| PLambda (na,t,c), PProd (na',t',c') ->
let na = match (na,na') with
Name _, _ -> na
| _, Name _ -> na'
| _ -> na in
let t' = detype avoid env sigma t in
let id, avoid = next_name_away0 na avoid in
let env = Name id :: env in
share_pattern_names detype (n-1) ((Name id,None,Explicit,None,t')::l) avoid env sigma c c'
| _ ->
if n>0 then Feedback.msg_debug (strbrk "Detyping.detype: cannot factorize fix enough");
let c = detype avoid env sigma c in
let t = detype avoid env sigma t in
(List.rev l,c,t)
let detype_fix detype flags avoid env sigma (vn,_ as nvn) (names,tys,bodies) =
let def_avoid, def_env, lfi =
Array.fold_left2
(fun (avoid, env, l) na ty ->
let id, avoid = next_name_away flags na.binder_name avoid in
(avoid, add_name (set_name (Name id) (LocalAssum (na,ty))) env, id::l))
(avoid, env, []) names tys in
let n = Array.length tys in
let v = Array.map3
(fun c t i -> share_names detype flags (i+1) [] def_avoid def_env sigma c (lift n t))
bodies tys vn in
GRec(GFix (Array.map (fun i -> Some i) (fst nvn), snd nvn),Array.of_list (List.rev lfi),
Array.map (fun (bl,_,_) -> bl) v,
Array.map (fun (_,_,ty) -> ty) v,
Array.map (fun (_,bd,_) -> bd) v)
let detype_cofix detype flags avoid env sigma n (names,tys,bodies) =
let def_avoid, def_env, lfi =
Array.fold_left2
(fun (avoid, env, l) na ty ->
let id, avoid = next_name_away flags na.binder_name avoid in
(avoid, add_name (set_name (Name id) (LocalAssum (na,ty))) env, id::l))
(avoid, env, []) names tys in
let ntys = Array.length tys in
let v = Array.map2
(fun c t -> share_names detype flags 0 [] def_avoid def_env sigma c (lift ntys t))
bodies tys in
GRec(GCoFix n,Array.of_list (List.rev lfi),
Array.map (fun (bl,_,_) -> bl) v,
Array.map (fun (_,_,ty) -> ty) v,
Array.map (fun (_,bd,_) -> bd) v)
type binder_kind = BProd | BLambda | BLetIn
(**********************************************************************)
(* Main detyping function *)
let detype_instance sigma l =
if not !print_universes then None
else
let l = EInstance.kind sigma l in
if UVars.Instance.is_empty l then None
else
let qs, us = UVars.Instance.to_array l in
let qs = List.map (detype_quality sigma) (Array.to_list qs) in
let us = List.map (detype_level sigma) (Array.to_list us) in
Some (qs, us)
let delay (type a) (d : a delay) (f : a delay -> _ -> _ -> _ -> _ -> _ -> a glob_constr_r) flags env avoid sigma t : a glob_constr_g =
match d with
| Now -> DAst.make (f d flags env avoid sigma t)
| Later -> DAst.delay (fun () -> f d flags env avoid sigma t)
let rec detype d flags avoid env sigma t =
delay d detype_r flags avoid env sigma t
and detype_r d flags avoid env sigma t =
match EConstr.kind sigma t with
| Rel n ->
(try match lookup_name_of_rel n (fst env) with
| Name id -> GVar id
| Anonymous ->
let s = "_ANONYMOUS_REL_"^(string_of_int n) in
GVar (Id.of_string s)
with Not_found ->
let s = "_UNBOUND_REL_"^(string_of_int n)
in GVar (Id.of_string s))
| Meta n ->
(* Meta in constr are not user-parsable and are mapped to Evar *)
if n = Constr_matching.special_meta then
(* Using a dash to be unparsable *)
GEvar (CAst.make @@ Id.of_string_soft "CONTEXT-HOLE", [])
else
GEvar (CAst.make @@ Id.of_string_soft ("M" ^ string_of_int n), [])
| Var id ->
(* Discriminate between section variable and non-section variable *)
(try let _ = Global.lookup_named id in GRef (GlobRef.VarRef id, None)
with Not_found -> GVar id)
| Sort s -> GSort (detype_sort sigma (ESorts.kind sigma s))
| Cast (c1,k,c2) ->
let d1 = detype d flags avoid env sigma c1 in
let d2 = detype d flags avoid env sigma c2 in
GCast(d1,Some k,d2)
| Prod (na,ty,c) -> detype_binder d flags BProd avoid env sigma (LocalAssum (na,ty)) c
| Lambda (na,ty,c) -> detype_binder d flags BLambda avoid env sigma (LocalAssum (na,ty)) c
| LetIn (na,b,ty,c) -> detype_binder d flags BLetIn avoid env sigma (LocalDef (na,b,ty)) c
| App (f,args) ->
let mkapp f' args' =
match DAst.get f' with
| GApp (f',args'') ->
GApp (f',args''@args')
| _ -> GApp (f',args')
in
mkapp (detype d flags avoid env sigma f)
(Array.map_to_list (detype d flags avoid env sigma) args)
| Const (sp,u) -> GRef (GlobRef.ConstRef sp, detype_instance sigma u)
| Proj (p,_,c) ->
if Projection.unfolded p && print_unfolded_primproj_asmatch () then
let c = detype d flags avoid env sigma c in
let id = Label.to_id @@ Projection.label p in
let nargs, parg =
try
let _, mip = Global.lookup_inductive (Projection.inductive p) in
mip.mind_consnrealargs.(0), Projection.arg p
with e when !Flags.in_debugger ->
(* kinda weird printing but the name should be enough to
indicate which projection it is *)
1, 0
in
let pathole = DAst.make @@ PatVar Anonymous in
let patargs = List.init nargs (fun i ->
if Int.equal i parg
then DAst.make @@ PatVar (Name id)
else pathole)
in
let pat = DAst.make @@ PatCstr ((Projection.inductive p, 1), patargs, Anonymous) in
let br = ([id], [pat], DAst.make @@ GVar id) in
(* MatchStyle looks relatively heavy *)
GCases (LetPatternStyle, None, [c, (Anonymous, None)], [CAst.make br])
else
let noparams () =
let pars = Projection.npars p in
let hole = DAst.make @@ GHole (GInternalHole) in
let args = List.make pars hole in
GApp (DAst.make @@ GRef (GlobRef.ConstRef (Projection.constant p), None),
(args @ [detype d flags avoid env sigma c]))
in
if !Flags.in_debugger || !Flags.in_ml_toplevel
|| not (print_primproj_params ())
then noparams ()
else begin
try
let c = Retyping.expand_projection (snd env) sigma p c [] in
DAst.get (detype d flags avoid env sigma c)
with Retyping.RetypeError _ -> noparams ()
end
| Evar (evk,cl) ->
let open Context.Named.Declaration in
let bound_to_itself_or_letin decl c =
match decl with
| LocalDef _ -> true
| LocalAssum (id,_) ->
try let n = List.index Name.equal (Name id.binder_name) (fst env) in
isRelN sigma n c
with Not_found -> isVarId sigma id.binder_name c
in
let id,l =
try
let id = match Evd.evar_ident evk sigma with
| None -> Termops.evar_suggested_name (snd env) sigma evk
| Some id -> id
in
let info = Evd.find_undefined sigma evk in
let cl = Evd.expand_existential sigma (evk, cl) in
let ctx = Evd.evar_filtered_context info in
let get_instance f =
let fold d c acc = if f d c then acc else (get_id d, c) :: acc in
List.fold_right2 fold ctx cl []
in
let l = get_instance bound_to_itself_or_letin in
(* If the instance is {x:=y; y:=y; z:=z} we print {x:=y; y:=y}
ie the non-identity part + the variables which also instantiate other variables
NB if the instance is {x:=f y; y:=y} we only print {x:=f y}
*)
let fvs,rels = List.fold_left
(fun (fvs,rels) (_,c) -> match EConstr.kind sigma c with
| Rel n -> (fvs,Int.Set.add n rels)
| Var id -> (Id.Set.add id fvs,rels)
| _ -> (fvs,rels))
(Id.Set.empty,Int.Set.empty)
l
in
let l = get_instance (fun d c ->
not !print_evar_arguments
&& bound_to_itself_or_letin d c
&& not (match EConstr.kind sigma c with
| Rel n -> Int.Set.mem n rels
| Var id -> Id.Set.mem id fvs
| _ -> false))
in
id,List.map (fun (id,c) -> (CAst.make id,c)) l
with Not_found ->
let map = function None -> mkMeta 0 | Some c -> c in (* FIXME? *)
let cl = List.map map @@ SList.to_list cl in
Id.of_string ("X" ^ string_of_int (Evar.repr evk)),
(List.map (fun c -> (CAst.make @@ Id.of_string "__",c)) cl)
in
GEvar (CAst.make id,
List.map (on_snd (detype d flags avoid env sigma)) l)
| Ind (ind_sp,u) ->
GRef (GlobRef.IndRef ind_sp, detype_instance sigma u)
| Construct (cstr_sp,u) ->