-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcases.ml
2725 lines (2416 loc) · 111 KB
/
cases.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 Coq Proof Assistant / The Coq Development Team *)
(* v * INRIA, CNRS and contributors - Copyright 1999-2018 *)
(* <O___,, * (see CREDITS file for the list of authors) *)
(* \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 Nameops
open Constr
open Context
open Termops
open Environ
open EConstr
open Vars
open Namegen
open Declarations
open Inductiveops
open Reductionops
open Type_errors
open Glob_term
open Glob_ops
open Retyping
open Pretype_errors
open Evarutil
open Evardefine
open Evarsolve
open Evarconv
open Evd
open Context.Rel.Declaration
open GlobEnv
module RelDecl = Context.Rel.Declaration
module NamedDecl = Context.Named.Declaration
(* Pattern-matching errors *)
type pattern_matching_error =
| BadPattern of constructor * constr
| BadConstructor of constructor * inductive
| WrongNumargConstructor of constructor * int
| WrongNumargInductive of inductive * int
| UnusedClause of cases_pattern list
| NonExhaustive of cases_pattern list
| CannotInferPredicate of (constr * types) array
exception PatternMatchingError of env * evar_map * pattern_matching_error
let raise_pattern_matching_error ?loc (env,sigma,te) =
Loc.raise ?loc (PatternMatchingError(env,sigma,te))
let error_bad_pattern ?loc env sigma cstr ind =
raise_pattern_matching_error ?loc
(env, sigma, BadPattern (cstr,ind))
let error_bad_constructor ?loc env cstr ind =
raise_pattern_matching_error ?loc
(env, Evd.empty, BadConstructor (cstr,ind))
let error_wrong_numarg_constructor ?loc env c n =
raise_pattern_matching_error ?loc (env, Evd.empty, WrongNumargConstructor(c,n))
let error_wrong_numarg_inductive ?loc env c n =
raise_pattern_matching_error ?loc (env, Evd.empty, WrongNumargInductive(c,n))
let list_try_compile f l =
let rec aux errors = function
| [] -> if errors = [] then anomaly (str "try_find_f.") else iraise (List.last errors)
| h::t ->
try f h
with UserError _ | TypeError _ | PretypeError _ | PatternMatchingError _ as e ->
let e = CErrors.push e in
aux (e::errors) t in
aux [] l
let force_name =
let nx = Name default_dependent_ident in function Anonymous -> nx | na -> na
(************************************************************************)
(* Pattern-matching compilation (Cases) *)
(************************************************************************)
(************************************************************************)
(* Configuration, errors and warnings *)
open Pp
let msg_may_need_inversion () =
strbrk "Found a matching with no clauses on a term unknown to have an empty inductive type."
(* Utils *)
let make_anonymous_patvars n =
List.make n (DAst.make @@ PatVar Anonymous)
(* We have x1:t1...xn:tn,xi':ti,y1..yk |- c and re-generalize
over xi:ti to get x1:t1...xn:tn,xi':ti,y1..yk |- c[xi:=xi'] *)
let relocate_rel n1 n2 k j = if Int.equal j (n1 + k) then n2+k else j
let rec relocate_index sigma n1 n2 k t =
match EConstr.kind sigma t with
| Rel j when Int.equal j (n1 + k) -> mkRel (n2+k)
| Rel j when j < n1+k -> t
| Rel j when j > n1+k -> t
| _ -> EConstr.map_with_binders sigma succ (relocate_index sigma n1 n2) k t
(**********************************************************************)
(* Structures used in compiling pattern-matching *)
let (!!) env = GlobEnv.env env
type 'a rhs =
{ rhs_env : GlobEnv.t;
rhs_vars : Id.Set.t;
avoid_ids : Id.Set.t;
it : 'a option}
type 'a equation =
{ patterns : cases_pattern list;
rhs : 'a rhs;
alias_stack : Name.t list;
eqn_loc : Loc.t option;
used : bool ref }
type 'a matrix = 'a equation list
(* 1st argument of IsInd is the original ind before extracting the summary *)
type tomatch_type =
| IsInd of types * inductive_type * Name.t list
| NotInd of constr option * types
(* spiwack: The first argument of [Pushed] is [true] for initial
Pushed and [false] otherwise. Used to decide whether the term being
matched on must be aliased in the variable case (only initial
Pushed need to be aliased). The first argument of [Alias] is [true]
if the alias was introduced by an initial pushed and [false]
otherwise.*)
type tomatch_status =
| Pushed of (bool*((constr * tomatch_type) * int list * Name.t))
| Alias of (bool*(Name.t * constr * (constr * types)))
| NonDepAlias
| Abstract of int * rel_declaration
type tomatch_stack = tomatch_status list
(* We keep a constr for aliases and a cases_pattern for error message *)
type pattern_history =
| Top
| MakeConstructor of constructor * pattern_continuation
and pattern_continuation =
| Continuation of int * cases_pattern list * pattern_history
| Result of cases_pattern list
let start_history n = Continuation (n, [], Top)
let feed_history arg = function
| Continuation (n, l, h) when n>=1 ->
Continuation (n-1, arg :: l, h)
| Continuation (n, _, _) ->
anomaly (str "Bad number of expected remaining patterns: " ++ int n ++ str ".")
| Result _ ->
anomaly (Pp.str "Exhausted pattern history.")
(* This is for non exhaustive error message *)
let rec glob_pattern_of_partial_history args2 = function
| Continuation (n, args1, h) ->
let args3 = make_anonymous_patvars (n - (List.length args2)) in
build_glob_pattern (List.rev_append args1 (args2@args3)) h
| Result pl -> pl
and build_glob_pattern args = function
| Top -> args
| MakeConstructor (pci, rh) ->
glob_pattern_of_partial_history
[DAst.make @@ PatCstr (pci, args, Anonymous)] rh
let complete_history = glob_pattern_of_partial_history []
(* This is to build glued pattern-matching history and alias bodies *)
let pop_history_pattern = function
| Continuation (0, l, Top) ->
Result (List.rev l)
| Continuation (0, l, MakeConstructor (pci, rh)) ->
feed_history (DAst.make @@ PatCstr (pci,List.rev l,Anonymous)) rh
| _ ->
anomaly (Pp.str "Constructor not yet filled with its arguments.")
let pop_history h =
feed_history (DAst.make @@ PatVar Anonymous) h
(* Builds a continuation expecting [n] arguments and building [ci] applied
to this [n] arguments *)
let push_history_pattern n pci cont =
Continuation (n, [], MakeConstructor (pci, cont))
(* A pattern-matching problem has the following form:
env, evd |- match terms_to_tomatch return pred with mat end
where terms_to_match is some sequence of "instructions" (t1 ... tp)
and mat is some matrix
(p11 ... p1n -> rhs1)
( ... )
(pm1 ... pmn -> rhsm)
Terms to match: there are 3 kinds of instructions
- "Pushed" terms to match are typed in [env]; these are usually just
Rel(n) except for the initial terms given by user; in Pushed ((c,tm),deps,na),
[c] is the reference to the term (which is a Rel or an initial term), [tm] is
its type (telling whether we know if it is an inductive type or not),
[deps] is the list of terms to abstract before matching on [c] (these are
rels too)
- "Abstract" instructions mean that an abstraction has to be inserted in the
current branch to build (this means a pattern has been detected dependent
in another one and a generalization is necessary to ensure well-typing)
Abstract instructions extend the [env] in which the other instructions
are typed
- "Alias" instructions mean an alias has to be inserted (this alias
is usually removed at the end, except when its type is not the
same as the type of the matched term from which it comes -
typically because the inductive types are "real" parameters)
- "NonDepAlias" instructions mean the completion of a matching over
a term to match as for Alias but without inserting this alias
because there is no dependency in it
Right-hand sides:
They consist of a raw term to type in an environment specific to the
clause they belong to: the names of declarations are those of the
variables present in the patterns. Therefore, they come with their
own [rhs_env] (actually it is the same as [env] except for the names
of variables).
*)
type 'a pattern_matching_problem =
{ env : GlobEnv.t;
pred : constr;
tomatch : tomatch_stack;
history : pattern_continuation;
mat : 'a matrix;
caseloc : Loc.t option;
casestyle : case_style;
typing_function: type_constraint -> GlobEnv.t -> evar_map -> 'a option -> evar_map * unsafe_judgment }
(*--------------------------------------------------------------------------*
* A few functions to infer the inductive type from the patterns instead of *
* checking that the patterns correspond to the ind. type of the *
* destructurated object. Allows type inference of examples like *
* match n with O => true | _ => false end *
* match x in I with C => true | _ => false end *
*--------------------------------------------------------------------------*)
(* Computing the inductive type from the matrix of patterns *)
(* We use the "in I" clause to coerce the terms to match and otherwise
use the constructor to know in which type is the matching problem
Note that insertion of coercions inside nested patterns is done
each time the matrix is expanded *)
let rec find_row_ind = function
[] -> None
| p :: l ->
match DAst.get p with
| PatVar _ -> find_row_ind l
| PatCstr(c,_,_) -> Some (p.CAst.loc,c)
let inductive_template env sigma tmloc ind =
let sigma, indu = Evd.fresh_inductive_instance env sigma ind in
let arsign = inductive_alldecls env indu in
let indu = on_snd EInstance.make indu in
let hole_source i = match tmloc with
| Some loc -> Loc.tag ~loc @@ Evar_kinds.TomatchTypeParameter (ind,i)
| None -> Loc.tag @@ Evar_kinds.TomatchTypeParameter (ind,i) in
let (sigma, _, evarl, _) =
List.fold_right
(fun decl (sigma, subst, evarl, n) ->
match decl with
| LocalAssum (na,ty) ->
let ty = EConstr.of_constr ty in
let ty' = substl subst ty in
let sigma, e =
Evarutil.new_evar env ~src:(hole_source n) ~typeclass_candidate:false sigma ty'
in
(sigma, e::subst,e::evarl,n+1)
| LocalDef (na,b,ty) ->
let b = EConstr.of_constr b in
(sigma, substl subst b::subst,evarl,n+1))
arsign (sigma, [], [], 1) in
sigma, applist (mkIndU indu,List.rev evarl)
let try_find_ind env sigma typ realnames =
let (IndType(indf,realargs) as ind) = find_rectype env sigma typ in
let names =
match realnames with
| Some names -> names
| None ->
let ind = fst (fst (dest_ind_family indf)) in
List.make (inductive_nrealdecls env ind) Anonymous in
IsInd (typ,ind,names)
let inh_coerce_to_ind env sigma0 loc ty tyi =
let sigma, expected_typ = inductive_template env sigma0 loc tyi in
(* Try to refine the type with inductive information coming from the
constructor and renounce if not able to give more information *)
(* devrait être indifférent d'exiger leq ou pas puisque pour
un inductif cela doit être égal *)
match Evarconv.unify_leq_delay env sigma expected_typ ty with
| sigma -> sigma
| exception Evarconv.UnableToUnify _ -> sigma0
let binding_vars_of_inductive sigma = function
| NotInd _ -> []
| IsInd (_,IndType(_,realargs),_) -> List.filter (isRel sigma) realargs
let set_tomatch_realnames names = function
| NotInd _ as t -> t
| IsInd (typ,ind,_) -> IsInd (typ,ind,names)
let extract_inductive_data env sigma decl =
match decl with
| LocalAssum (_,t) ->
let tmtyp =
try try_find_ind env sigma t None
with Not_found -> NotInd (None,t) in
let tmtypvars = binding_vars_of_inductive sigma tmtyp in
(tmtyp,tmtypvars)
| LocalDef (_,_,t) ->
(NotInd (None, t), [])
let unify_tomatch_with_patterns env sigma loc typ pats realnames =
match find_row_ind pats with
| None -> sigma, NotInd (None,typ)
| Some (_,(ind,_)) ->
let sigma = inh_coerce_to_ind env sigma loc typ ind in
try sigma, try_find_ind env sigma typ realnames
with Not_found -> sigma, NotInd (None,typ)
let find_tomatch_tycon env sigma loc = function
(* Try if some 'in I ...' is present and can be used as a constraint *)
| Some {CAst.v=(ind,realnal)} ->
let sigma, tycon = inductive_template env sigma loc ind in
sigma, mk_tycon tycon, Some (List.rev realnal)
| None ->
sigma, empty_tycon, None
let make_return_predicate_ltac_lvar env sigma na tm c =
(* If we have an [x as x return ...] clause and [x] expands to [c],
we have to update the status of [x] in the substitution:
- if [c] is a variable [id'], then [x] should now become [id']
- otherwise, [x] should be hidden *)
match na, DAst.get tm with
| Name id, (GVar id' | GRef (Globnames.VarRef id', _)) when Id.equal id id' ->
let expansion = match kind sigma c with
| Var id' -> Name id'
| _ -> Anonymous in
GlobEnv.hide_variable env expansion id
| _ -> env
let is_patvar pat =
match DAst.get pat with
| PatVar _ -> true
| _ -> false
let coerce_row ~program_mode typing_fun env sigma pats (tomatch,(na,indopt)) =
let loc = loc_of_glob_constr tomatch in
let sigma, tycon, realnames = find_tomatch_tycon !!env sigma loc indopt in
let sigma, j = typing_fun tycon env sigma tomatch in
let sigma, j = Coercion.inh_coerce_to_base ?loc:(loc_of_glob_constr tomatch) ~program_mode !!env sigma j in
let typ = nf_evar sigma j.uj_type in
let env = make_return_predicate_ltac_lvar env sigma na tomatch j.uj_val in
let sigma, t =
if realnames = None && pats <> [] && List.for_all is_patvar pats then
sigma, NotInd (None,typ)
else
try sigma, try_find_ind !!env sigma typ realnames
with Not_found ->
unify_tomatch_with_patterns !!env sigma loc typ pats realnames
in
((env, sigma), (j.uj_val,t))
let coerce_to_indtype ~program_mode typing_fun env sigma matx tomatchl =
let pats = List.map (fun r -> r.patterns) matx in
let matx' = match matrix_transpose pats with
| [] -> List.map (fun _ -> []) tomatchl (* no patterns at all *)
| m -> m in
let (env, sigma), tms = List.fold_left2_map (fun (env, sigma) -> coerce_row ~program_mode typing_fun env sigma) (env, sigma) matx' tomatchl in
env, sigma, tms
(************************************************************************)
(* Utils *)
let mkExistential ?(src=(Loc.tag Evar_kinds.InternalHole)) env sigma =
let sigma, (e, u) = Evarutil.new_type_evar env sigma ~src:src univ_flexible_alg in
sigma, e
let adjust_tomatch_to_pattern ~program_mode sigma pb ((current,typ),deps,dep) =
(* Ideally, we could find a common inductive type to which both the
term to match and the patterns coerce *)
(* In practice, we coerce the term to match if it is not already an
inductive type and it is not dependent; moreover, we use only
the first pattern type and forget about the others *)
let typ,names =
match typ with IsInd(t,_,names) -> t,Some names | NotInd(_,t) -> t,None in
let tmtyp =
try try_find_ind !!(pb.env) sigma typ names
with Not_found -> NotInd (None,typ) in
match tmtyp with
| NotInd (None,typ) ->
let tm1 = List.map (fun eqn -> List.hd eqn.patterns) pb.mat in
(match find_row_ind tm1 with
| None -> sigma, (current, tmtyp)
| Some (loc,(ind,_)) ->
let sigma, indt = inductive_template !!(pb.env) sigma None ind in
let sigma, current =
if List.is_empty deps && isEvar sigma typ then
(* Don't insert coercions if dependent; only solve evars *)
match Evarconv.unify_leq_delay !!(pb.env) sigma indt typ with
| exception Evarconv.UnableToUnify _ -> sigma, current
| sigma -> sigma, current
else
let sigma, j = Coercion.inh_conv_coerce_to ?loc ~program_mode true !!(pb.env) sigma (make_judge current typ) indt in
sigma, j.uj_val
in
sigma, (current, try_find_ind !!(pb.env) sigma indt names))
| _ -> sigma, (current, tmtyp)
let type_of_tomatch = function
| IsInd (t,_,_) -> t
| NotInd (_,t) -> t
let map_tomatch_type f = function
| IsInd (t,ind,names) -> IsInd (f t,map_inductive_type f ind,names)
| NotInd (c,t) -> NotInd (Option.map f c, f t)
let liftn_tomatch_type n depth = map_tomatch_type (Vars.liftn n depth)
let lift_tomatch_type n = liftn_tomatch_type n 1
(**********************************************************************)
(* Utilities on patterns *)
let current_pattern eqn =
match eqn.patterns with
| pat::_ -> pat
| [] -> anomaly (Pp.str "Empty list of patterns.")
let remove_current_pattern eqn =
match eqn.patterns with
| pat::pats ->
{ eqn with
patterns = pats;
alias_stack = alias_of_pat pat :: eqn.alias_stack }
| [] -> anomaly (Pp.str "Empty list of patterns.")
let push_current_pattern ~program_mode sigma (cur,ty) eqn =
let hypnaming = if program_mode then ProgramNaming else KeepUserNameAndRenameExistingButSectionNames in
match eqn.patterns with
| pat::pats ->
let r = Sorts.Relevant in (* TODO relevance *)
let _,rhs_env = push_rel ~hypnaming sigma (LocalDef (make_annot (alias_of_pat pat) r,cur,ty)) eqn.rhs.rhs_env in
{ eqn with
rhs = { eqn.rhs with rhs_env = rhs_env };
patterns = pats }
| [] -> anomaly (Pp.str "Empty list of patterns.")
(* spiwack: like [push_current_pattern] but does not introduce an
alias in rhs_env. Aliasing binders are only useful for variables at
the root of a pattern matching problem (initial push), so we
distinguish the cases. *)
let push_noalias_current_pattern eqn =
match eqn.patterns with
| _::pats ->
{ eqn with patterns = pats }
| [] -> anomaly (Pp.str "push_noalias_current_pattern: Empty list of patterns.")
let prepend_pattern tms eqn = {eqn with patterns = [email protected] }
(**********************************************************************)
(* Well-formedness tests *)
(* Partial check on patterns *)
exception NotAdjustable
let rec adjust_local_defs ?loc = function
| (pat :: pats, LocalAssum _ :: decls) ->
pat :: adjust_local_defs ?loc (pats,decls)
| (pats, LocalDef _ :: decls) ->
(DAst.make ?loc @@ PatVar Anonymous) :: adjust_local_defs ?loc (pats,decls)
| [], [] -> []
| _ -> raise NotAdjustable
let check_and_adjust_constructor env ind cstrs pat = match DAst.get pat with
| PatVar _ -> pat
| PatCstr (((_,i) as cstr),args,alias) ->
let loc = pat.CAst.loc in
(* Check it is constructor of the right type *)
let ind' = inductive_of_constructor cstr in
if eq_ind ind' ind then
(* Check the constructor has the right number of args *)
let ci = cstrs.(i-1) in
let nb_args_constr = ci.cs_nargs in
if Int.equal (List.length args) nb_args_constr then pat
else
try
let args' = adjust_local_defs ?loc (args, List.rev ci.cs_args)
in DAst.make ?loc @@ PatCstr (cstr, args', alias)
with NotAdjustable ->
error_wrong_numarg_constructor ?loc env cstr nb_args_constr
else
(* Try to insert a coercion *)
try
Coercion.inh_pattern_coerce_to ?loc env pat ind' ind
with Not_found ->
error_bad_constructor ?loc env cstr ind
let check_all_variables env sigma typ mat =
List.iter
(fun eqn ->
let pat = current_pattern eqn in
match DAst.get pat with
| PatVar id -> ()
| PatCstr (cstr_sp,_,_) ->
let loc = pat.CAst.loc in
error_bad_pattern ?loc env sigma cstr_sp typ)
mat
let check_unused_pattern env eqn =
if not !(eqn.used) then
raise_pattern_matching_error ?loc:eqn.eqn_loc (env, Evd.empty, UnusedClause eqn.patterns)
let set_used_pattern eqn = eqn.used := true
let extract_rhs pb =
match pb.mat with
| [] -> user_err ~hdr:"build_leaf" (msg_may_need_inversion())
| eqn::_ ->
set_used_pattern eqn;
eqn.rhs
(**********************************************************************)
(* Functions to deal with matrix factorization *)
let occur_in_rhs na rhs =
match na with
| Anonymous -> false
| Name id -> Id.Set.mem id rhs.rhs_vars
let is_dep_patt_in eqn pat = match DAst.get pat with
| PatVar name -> occur_in_rhs name eqn.rhs
| PatCstr _ -> true
let mk_dep_patt_row ~program_mode (pats,_,eqn) =
if program_mode then List.map (fun _ -> true) pats
else List.map (is_dep_patt_in eqn) pats
let dependencies_in_pure_rhs ~program_mode nargs eqns =
if List.is_empty eqns then
List.make nargs (not program_mode) (* Only "_" patts *) else
let deps_rows = List.map (mk_dep_patt_row ~program_mode) eqns in
let deps_columns = matrix_transpose deps_rows in
List.map (List.exists (fun x -> x)) deps_columns
let dependent_decl sigma a =
function
| LocalAssum (na,t) -> dependent sigma a t
| LocalDef (na,c,t) -> dependent sigma a t || dependent sigma a c
let rec dep_in_tomatch sigma n = function
| (Pushed _ | Alias _ | NonDepAlias) :: l -> dep_in_tomatch sigma n l
| Abstract (_,d) :: l -> RelDecl.exists (fun c -> not (noccurn sigma n c)) d || dep_in_tomatch sigma (n+1) l
| [] -> false
let dependencies_in_rhs ~program_mode sigma nargs current tms eqns =
match EConstr.kind sigma current with
| Rel n when dep_in_tomatch sigma n tms -> List.make nargs true
| _ -> dependencies_in_pure_rhs ~program_mode nargs eqns
(* Computing the matrix of dependencies *)
(* [find_dependency_list tmi [d(i+1);...;dn]] computes in which
declarations [d(i+1);...;dn] the term [tmi] is dependent in.
[find_dependencies_signature (used1,...,usedn) ((tm1,d1),...,(tmn,dn))]
returns [(deps1,...,depsn)] where [depsi] is a subset of tm(i+1),..,tmn
denoting in which of the d(i+1)...dn, the term tmi is dependent.
*)
let rec find_dependency_list sigma tmblock = function
| [] -> []
| (used,tdeps,tm,d)::rest ->
let deps = find_dependency_list sigma tmblock rest in
if used && List.exists (fun x -> dependent_decl sigma x d) tmblock
then
match EConstr.kind sigma tm with
| Rel n -> List.add_set Int.equal n (List.union Int.equal deps tdeps)
| _ -> List.union Int.equal deps tdeps
else deps
let find_dependencies sigma is_dep_or_cstr_in_rhs (tm,(_,tmtypleaves),d) nextlist =
let deps = find_dependency_list sigma (tm::tmtypleaves) nextlist in
if is_dep_or_cstr_in_rhs || not (List.is_empty deps)
then ((true ,deps,tm,d)::nextlist)
else ((false,[] ,tm,d)::nextlist)
let find_dependencies_signature sigma deps_in_rhs typs =
let l = List.fold_right2 (find_dependencies sigma) deps_in_rhs typs [] in
List.map (fun (_,deps,_,_) -> deps) l
(* Assume we had terms t1..tq to match in a context xp:Tp,...,x1:T1 |-
and xn:Tn has just been regeneralized into x:Tn so that the terms
to match are now to be considered in the context xp:Tp,...,x1:T1,x:Tn |-.
[relocate_index_tomatch n 1 tomatch] updates t1..tq so that
former references to xn1 are now references to x. Note that t1..tq
are already adjusted to the context xp:Tp,...,x1:T1,x:Tn |-.
[relocate_index_tomatch 1 n tomatch] will go the way back.
*)
let relocate_index_tomatch sigma n1 n2 =
let rec genrec depth = function
| [] ->
[]
| Pushed (b,((c,tm),l,na)) :: rest ->
let c = relocate_index sigma n1 n2 depth c in
let tm = map_tomatch_type (relocate_index sigma n1 n2 depth) tm in
let l = List.map (relocate_rel n1 n2 depth) l in
Pushed (b,((c,tm),l,na)) :: genrec depth rest
| Alias (initial,(na,c,d)) :: rest ->
(* [c] is out of relocation scope *)
Alias (initial,(na,c,map_pair (relocate_index sigma n1 n2 depth) d)) :: genrec depth rest
| NonDepAlias :: rest ->
NonDepAlias :: genrec depth rest
| Abstract (i,d) :: rest ->
let i = relocate_rel n1 n2 depth i in
Abstract (i, RelDecl.map_constr (fun c -> relocate_index sigma n1 n2 depth c) d)
:: genrec (depth+1) rest in
genrec 0
(* [replace_tomatch n c tomatch] replaces [Rel n] by [c] in [tomatch] *)
let rec replace_term sigma n c k t =
if isRel sigma t && Int.equal (destRel sigma t) (n + k) then Vars.lift k c
else EConstr.map_with_binders sigma succ (replace_term sigma n c) k t
let length_of_tomatch_type_sign na t =
let l = match na with
| Anonymous -> 0
| Name _ -> 1
in
match t with
| NotInd _ -> l
| IsInd (_, _, names) -> List.length names + l
let replace_tomatch sigma n c =
let rec replrec depth = function
| [] -> []
| Pushed (initial,((b,tm),l,na)) :: rest ->
let b = replace_term sigma n c depth b in
let tm = map_tomatch_type (replace_term sigma n c depth) tm in
List.iter (fun i -> if Int.equal i (n + depth) then anomaly (Pp.str "replace_tomatch.")) l;
Pushed (initial,((b,tm),l,na)) :: replrec depth rest
| Alias (initial,(na,b,d)) :: rest ->
(* [b] is out of replacement scope *)
Alias (initial,(na,b,map_pair (replace_term sigma n c depth) d)) :: replrec depth rest
| NonDepAlias :: rest ->
NonDepAlias :: replrec depth rest
| Abstract (i,d) :: rest ->
Abstract (i, RelDecl.map_constr (fun t -> replace_term sigma n c depth t) d)
:: replrec (depth+1) rest in
replrec 0
(* [liftn_tomatch_stack]: a term to match has just been substituted by
some constructor t = (ci x1...xn) and the terms x1 ... xn have been
added to match; all pushed terms to match must be lifted by n
(knowing that [Abstract] introduces a binder in the list of pushed
terms to match).
*)
let rec liftn_tomatch_stack n depth = function
| [] -> []
| Pushed (initial,((c,tm),l,na))::rest ->
let c = liftn n depth c in
let tm = liftn_tomatch_type n depth tm in
let l = List.map (fun i -> if i<depth then i else i+n) l in
Pushed (initial,((c,tm),l,na))::(liftn_tomatch_stack n depth rest)
| Alias (initial,(na,c,d))::rest ->
Alias (initial,(na,liftn n depth c,map_pair (liftn n depth) d))
::(liftn_tomatch_stack n depth rest)
| NonDepAlias :: rest ->
NonDepAlias :: liftn_tomatch_stack n depth rest
| Abstract (i,d)::rest ->
let i = if i<depth then i else i+n in
Abstract (i, RelDecl.map_constr (liftn n depth) d)
::(liftn_tomatch_stack n (depth+1) rest)
let lift_tomatch_stack n = liftn_tomatch_stack n 1
(* if [current] has type [I(p1...pn u1...um)] and we consider the case
of constructor [ci] of type [I(p1...pn u'1...u'm)], then the
default variable [name] is expected to have which type?
Rem: [current] is [(Rel i)] except perhaps for initial terms to match *)
(************************************************************************)
(* Some heuristics to get names for variables pushed in pb environment *)
(* Typical requirement:
[match y with (S (S x)) => x | x => x end] should be compiled into
[match y with O => y | (S n) => match n with O => y | (S x) => x end end]
and [match y with (S (S n)) => n | n => n end] into
[match y with O => y | (S n0) => match n0 with O => y | (S n) => n end end]
i.e. user names should be preserved and created names should not
interfere with user names
The exact names here are not important for typing (because they are
put in pb.env and not in the rhs.rhs_env of branches. However,
whether a name is Anonymous or not may have an effect on whether a
generalization is done or not.
*)
let merge_name get_name obj = function
| Anonymous -> get_name obj
| na -> na
let merge_names get_name = List.map2 (merge_name get_name)
let get_names avoid env sigma sign eqns =
let names1 = List.make (Context.Rel.length sign) Anonymous in
(* If any, we prefer names used in pats, from top to bottom *)
let names2,aliasname =
List.fold_right
(fun (pats,pat_alias,eqn) (names,aliasname) ->
(merge_names alias_of_pat pats names,
merge_name (fun x -> x) pat_alias aliasname))
eqns (names1,Anonymous) in
(* Otherwise, we take names from the parameters of the constructor but
avoiding conflicts with user ids *)
let allvars =
List.fold_left (fun l (_,_,eqn) -> Id.Set.union l eqn.rhs.avoid_ids)
avoid eqns in
let names3,_ =
List.fold_left2
(fun (l,avoid) d na ->
let na =
merge_name
(fun decl ->
let na = get_name decl in
let t = get_type decl in
Name (next_name_away (named_hd env sigma t na) avoid))
d na
in
(na::l,Id.Set.add (Name.get_id na) avoid))
([],allvars) (List.rev sign) names2 in
names3,aliasname
(*****************************************************************)
(* Recovering names for variables pushed to the rhs' environment *)
(* We just factorized a match over a matrix of equations *)
(* "C xi1 .. xin as xi" as a single match over "C y1 .. yn as y" *)
(* We now replace the names y1 .. yn y by the actual names *)
(* xi1 .. xin xi to be found in the i-th clause of the matrix *)
let recover_initial_subpattern_names = List.map2 RelDecl.set_name
let recover_and_adjust_alias_names (_,avoid) names sign =
let rec aux = function
| [],[] ->
[]
| x::names, LocalAssum (x',t)::sign ->
(x, LocalAssum ({x' with binder_name=alias_of_pat x},t)) :: aux (names,sign)
| names, (LocalDef (na,_,_) as decl)::sign ->
(DAst.make @@ PatVar na.binder_name, decl) :: aux (names,sign)
| _ -> assert false
in
List.split (aux (names,sign))
let push_rels_eqn ~hypnaming sigma sign eqn =
{eqn with
rhs = {eqn.rhs with rhs_env = snd (push_rel_context ~hypnaming sigma sign eqn.rhs.rhs_env) } }
let push_rels_eqn_with_names sigma sign eqn =
let subpats = List.rev (List.firstn (List.length sign) eqn.patterns) in
let subpatnames = List.map alias_of_pat subpats in
let sign = recover_initial_subpattern_names subpatnames sign in
push_rels_eqn sigma sign eqn
let push_generalized_decl_eqn ~hypnaming env sigma n decl eqn =
match RelDecl.get_name decl with
| Anonymous ->
push_rels_eqn ~hypnaming sigma [decl] eqn
| Name _ ->
push_rels_eqn ~hypnaming sigma [RelDecl.set_name (RelDecl.get_name (Environ.lookup_rel n !!(eqn.rhs.rhs_env))) decl] eqn
let drop_alias_eqn eqn =
{ eqn with alias_stack = List.tl eqn.alias_stack }
let push_alias_eqn sigma alias eqn =
let aliasname = List.hd eqn.alias_stack in
let eqn = drop_alias_eqn eqn in
let alias = RelDecl.set_name aliasname alias in
push_rels_eqn sigma [alias] eqn
(**********************************************************************)
(* Functions to deal with elimination predicate *)
(* Infering the predicate *)
(*
The problem to solve is the following:
We match Gamma |- t : I(u01..u0q) against the following constructors:
Gamma, x11...x1p1 |- C1(x11..x1p1) : I(u11..u1q)
...
Gamma, xn1...xnpn |- Cn(xn1..xnp1) : I(un1..unq)
Assume the types in the branches are the following
Gamma, x11...x1p1 |- branch1 : T1
...
Gamma, xn1...xnpn |- branchn : Tn
Assume the type of the global case expression is Gamma |- T
The predicate has the form phi = [y1..yq][z:I(y1..yq)]psi and it has to
satisfy the following n+1 equations:
Gamma, x11...x1p1 |- (phi u11..u1q (C1 x11..x1p1)) = T1
...
Gamma, xn1...xnpn |- (phi un1..unq (Cn xn1..xnpn)) = Tn
Gamma |- (phi u01..u0q t) = T
Some hints:
- Clearly, if xij occurs in Ti, then, a "match z with (Ci xi1..xipi)
=> ... end" or a "psi(yk)", with psi extracting xij from uik, should be
inserted somewhere in Ti.
- If T is undefined, an easy solution is to insert a "match z with
(Ci xi1..xipi) => ... end" in front of each Ti
- Otherwise, T1..Tn and T must be step by step unified, if some of them
diverge, then try to replace the diverging subterm by one of y1..yq or z.
- The main problem is what to do when an existential variables is encountered
*)
(* Propagation of user-provided predicate through compilation steps *)
let rec map_predicate f k ccl = function
| [] -> f k ccl
| Pushed (_,((_,tm),_,na)) :: rest ->
let k' = length_of_tomatch_type_sign na tm in
map_predicate f (k+k') ccl rest
| (Alias _ | NonDepAlias) :: rest ->
map_predicate f k ccl rest
| Abstract _ :: rest ->
map_predicate f (k+1) ccl rest
let noccur_predicate_between sigma n = map_predicate (noccur_between sigma n)
let liftn_predicate n = map_predicate (liftn n)
let lift_predicate n = liftn_predicate n 1
let regeneralize_index_predicate sigma n = map_predicate (relocate_index sigma n 1) 0
let substnl_predicate sigma = map_predicate (substnl sigma)
(* This is parallel bindings *)
let subst_predicate (subst,copt) ccl tms =
let sigma = match copt with
| None -> subst
| Some c -> c::subst in
substnl_predicate sigma 0 ccl tms
let specialize_predicate_var (cur,typ,dep) env tms ccl =
let c = match dep with
| Anonymous -> None
| Name _ -> Some cur
in
let l =
match typ with
| IsInd (_, IndType (_, _), []) -> []
| IsInd (_, IndType (indf, realargs), names) ->
let arsign,_ = get_arity env indf in
let arsign = List.map EConstr.of_rel_decl arsign in
subst_of_rel_context_instance arsign realargs
| NotInd _ -> [] in
subst_predicate (l,c) ccl tms
(*****************************************************************************)
(* We have pred = [X:=realargs;x:=c]P typed in Gamma1, x:I(realargs), Gamma2 *)
(* and we want to abstract P over y:t(x) typed in the same context to get *)
(* *)
(* pred' = [X:=realargs;x':=c](y':t(x'))P[y:=y'] *)
(* *)
(* We first need to lift t(x) s.t. it is typed in Gamma, X:=rargs, x' *)
(* then we have to replace x by x' in t(x) and y by y' in P *)
(*****************************************************************************)
let generalize_predicate sigma (names,na) ny d tms ccl =
let () = match na with
| Anonymous -> anomaly (Pp.str "Undetected dependency.")
| _ -> () in
let p = List.length names + 1 in
let ccl = lift_predicate 1 ccl tms in
regeneralize_index_predicate sigma (ny+p+1) ccl tms
(*****************************************************************************)
(* We just matched over cur:ind(realargs) in the following matching problem *)
(* *)
(* env |- match cur tms return ccl with ... end *)
(* *)
(* and we want to build the predicate corresponding to the individual *)
(* matching over cur *)
(* *)
(* pred = fun X:realargstyps x:ind(X)] PI tms.ccl *)
(* *)
(* where pred is computed by abstract_predicate and PI tms.ccl by *)
(* extract_predicate *)
(*****************************************************************************)
let rec extract_predicate ccl = function
| (Alias _ | NonDepAlias)::tms ->
(* substitution already done in build_branch *)
extract_predicate ccl tms
| Abstract (i,d)::tms ->
mkProd_wo_LetIn d (extract_predicate ccl tms)
| Pushed (_,((cur,NotInd _),_,na))::tms ->
begin match na with
| Anonymous -> extract_predicate ccl tms
| Name _ ->
let tms = lift_tomatch_stack 1 tms in
let pred = extract_predicate ccl tms in
subst1 cur pred
end
| Pushed (_,((cur,IsInd (_,IndType(_,realargs),_)),_,na))::tms ->
let realargs = List.rev realargs in
let k, nrealargs = match na with
| Anonymous -> 0, realargs
| Name _ -> 1, (cur :: realargs)
in
let tms = lift_tomatch_stack (List.length realargs + k) tms in
let pred = extract_predicate ccl tms in
substl nrealargs pred
| [] ->
ccl
let abstract_predicate env sigma indf cur realargs (names,na) tms ccl =
let sign = make_arity_signature !!env sigma true indf in
(* n is the number of real args + 1 (+ possible let-ins in sign) *)
let n = List.length sign in
(* Before abstracting we generalize over cur and on those realargs *)
(* that are rels, consistently with the specialization made in *)
(* build_branch *)
let tms = List.fold_right2 (fun par arg tomatch ->
match EConstr.kind sigma par with
| Rel i -> relocate_index_tomatch sigma (i+n) (destRel sigma arg) tomatch
| _ -> tomatch) (realargs@[cur]) (Context.Rel.to_extended_list EConstr.mkRel 0 sign)
(lift_tomatch_stack n tms) in
(* Pred is already dependent in the current term to match (if *)
(* (na<>Anonymous) and its realargs; we just need to adjust it to *)
(* full sign if dep in cur is not taken into account *)
let ccl = match na with
| Anonymous -> lift_predicate 1 ccl tms
| Name _ -> ccl
in
let pred = extract_predicate ccl tms in
(* Build the predicate properly speaking *)
let sign = List.map2 set_name (na::names) sign in
it_mkLambda_or_LetIn_name !!env sigma pred sign
(* [expand_arg] is used by [specialize_predicate]
if Yk denotes [Xk;xk] or [Xk],
it replaces gamma, x1...xn, x1...xk Yk+1...Yn |- pred
by gamma, x1...xn, x1...xk-1 [Xk;xk] Yk+1...Yn |- pred (if dep) or
by gamma, x1...xn, x1...xk-1 [Xk] Yk+1...Yn |- pred (if not dep) *)
let expand_arg tms (p,ccl) ((_,t),_,na) =
let k = length_of_tomatch_type_sign na t in