forked from coq/coq
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathevarsolve.ml
1910 lines (1741 loc) · 77.3 KB
/
evarsolve.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) *)
(************************************************************************)
open Sorts
open Util
open CErrors
open Names
open Context
open Constr
open Environ
open Termops
open Evd
open EConstr
open Vars
open Namegen
open Retyping
open Reductionops
open Evarutil
open Pretype_errors
module AllowedEvars = struct
type t =
| AllowAll
| AllowFun of (Evar.t -> bool) * Evar.Set.t
let mem allowed evk =
match allowed with
| AllowAll -> true
| AllowFun (f,except) -> f evk && not (Evar.Set.mem evk except)
let remove evk = function
| AllowAll -> AllowFun ((fun _ -> true), Evar.Set.singleton evk)
| AllowFun (f,except) -> AllowFun (f, Evar.Set.add evk except)
let all = AllowAll
let except evars =
AllowFun ((fun _ -> true), evars)
let from_pred f =
AllowFun (f, Evar.Set.empty)
end
type unify_flags = {
modulo_betaiota: bool;
open_ts : TransparentState.t;
closed_ts : TransparentState.t;
subterm_ts : TransparentState.t;
allowed_evars : AllowedEvars.t;
with_cs : bool
}
let is_evar_allowed flags evk =
AllowedEvars.mem flags.allowed_evars evk
type unification_kind =
| TypeUnification
| TermUnification
(************************)
(* Unification results *)
(************************)
type unification_result =
| Success of evar_map
| UnifFailure of evar_map * unification_error
let is_success = function Success _ -> true | UnifFailure _ -> false
let test_success unify flags b env evd c c' rhs =
is_success (unify flags b env evd c c' rhs)
(** A unification function parameterized by:
- unification flags
- the kind of unification
- environment
- sigma
- conversion problem
- the two terms to unify. *)
type unifier = unify_flags -> unification_kind ->
env -> evar_map -> conv_pb -> constr -> constr -> unification_result
(** A conversion function: parameterized by the kind of unification,
environment, sigma, conversion problem and the two terms to convert.
Conversion is not allowed to instantiate evars contrary to unification. *)
type conversion_check = unify_flags -> unification_kind ->
env -> evar_map -> conv_pb -> constr -> constr -> bool
let normalize_evar evd ev =
match EConstr.kind evd (mkEvar ev) with
| Evar (evk,args) -> (evk,args)
| _ -> assert false
let get_polymorphic_positions env sigma f =
let open Declarations in
match EConstr.kind sigma f with
| Ind (ind, u) | Construct ((ind, _), u) ->
let mib,oib = Inductive.lookup_mind_specif env ind in
(match mib.mind_template with
| None -> assert false
| Some templ -> templ.template_param_arguments)
| _ -> assert false
let refresh_universes ?(status=univ_rigid) ?(onlyalg=false) ?(refreshset=false)
pbty env evd t =
let evdref = ref evd in
(* direction: true for fresh universes lower than the existing ones *)
let refresh_sort status ~direction s =
let sigma, l = new_univ_level_variable status !evdref in
let s' = match ESorts.kind sigma s with
| QSort (q, _) -> Sorts.qsort q (Univ.Universe.make l)
| _ -> Sorts.sort_of_univ @@ Univ.Universe.make l
in
let s' = ESorts.make s' in
evdref := sigma;
let evd =
if direction then set_leq_sort !evdref s' s
else set_leq_sort !evdref s s'
in evdref := evd; mkSort s'
in
let rec refresh ~onlyalg status ~direction t =
match EConstr.kind !evdref t with
| Sort s ->
begin match ESorts.kind !evdref s with
| Type u | QSort (_, u) ->
(* TODO: check if max(l,u) is not ok as well *)
(match Univ.Universe.level u with
| None -> refresh_sort status ~direction s
| Some l ->
(match Evd.universe_rigidity !evdref l with
| UnivRigid ->
if not onlyalg && (not (Univ.Level.is_set l) || (refreshset && not direction))
then refresh_sort status ~direction s
else t
| UnivFlexible alg ->
(if alg then
evdref := Evd.make_nonalgebraic_variable !evdref l);
t))
| Set when refreshset && not direction ->
(* Cannot make a universe "lower" than "Set",
only refreshing when we want higher universes. *)
refresh_sort status ~direction s
| Prop | SProp | Set -> t
end
| Prod (na,u,v) ->
let v' = refresh ~onlyalg status ~direction v in
if v' == v then t else mkProd (na, u, v')
| _ -> t
in
(* Refresh the types of evars under template polymorphic references *)
let rec refresh_term_evars ~onevars ~top t =
match EConstr.kind !evdref t with
| App (f, args) when Termops.is_template_polymorphic_ref env !evdref f ->
let pos = get_polymorphic_positions env !evdref f in
refresh_polymorphic_positions args pos; t
| App (f, args) when top && isEvar !evdref f ->
let f' = refresh_term_evars ~onevars:true ~top:false f in
let args' = Array.map (refresh_term_evars ~onevars ~top:false) args in
if f' == f && args' == args then t
else mkApp (f', args')
| Evar (ev, a) when onevars ->
let evi = Evd.find_undefined !evdref ev in
let ty = Evd.evar_concl evi in
let ty' = refresh ~onlyalg univ_flexible ~direction:true ty in
if ty == ty' then t
else (evdref := Evd.downcast ev ty' !evdref; t)
| Sort s ->
(match ESorts.kind !evdref s with
| Type u when not (Univ.Universe.is_levels u) ->
refresh_sort Evd.univ_flexible ~direction:false s
| _ -> t)
| _ -> EConstr.map !evdref (refresh_term_evars ~onevars ~top:false) t
and refresh_polymorphic_positions args pos =
let rec aux i = function
| true :: ls ->
if i < Array.length args then
ignore(refresh_term_evars ~onevars:true ~top:false args.(i));
aux (succ i) ls
| false :: ls ->
if i < Array.length args then
ignore(refresh_term_evars ~onevars:false ~top:false args.(i));
aux (succ i) ls
| [] -> ()
in aux 0 pos
in
let t' =
if isArity !evdref t then
match pbty with
| None ->
(* No cumulativity needed, but we still need to refresh the algebraics *)
refresh ~onlyalg:true univ_flexible ~direction:false t
| Some direction -> refresh ~onlyalg status ~direction t
else refresh_term_evars ~onevars:false ~top:true t
in !evdref, t'
let get_type_of_refresh ?(lax=false) env evars t =
let tty = Retyping.get_type_of env evars t in
let evars', tty = refresh_universes ~onlyalg:true
~status:(Evd.UnivFlexible false) (Some false) env evars tty in
evars', tty
let add_conv_oriented_pb ?(tail=true) (pbty,env,t1,t2) evd =
match pbty with
| Some true -> add_conv_pb ~tail (Conversion.CUMUL,env,t1,t2) evd
| Some false -> add_conv_pb ~tail (Conversion.CUMUL,env,t2,t1) evd
| None -> add_conv_pb ~tail (Conversion.CONV,env,t1,t2) evd
(* We retype applications to ensure the universe constraints are collected *)
exception IllTypedInstance of env * evar_map * EConstr.types * EConstr.types
exception IllTypedInstanceFun of env * evar_map * EConstr.constr * EConstr.types
let checked_appvect, checked_appvect_hook = Hook.make ()
let recheck_applications unify flags env evdref t =
let rec aux env t =
(* the order matters: if the sub-applications are incorrect, checked_appvect may fail badly *)
iter_with_full_binders env !evdref (fun d env -> push_rel d env) aux env t;
match EConstr.kind !evdref t with
| App (f, args) ->
let evd, _ = Hook.get checked_appvect env !evdref f args in
evdref := evd
| _ -> ()
in
try aux env t
with PretypeError (env,sigma,e) ->
match e with
| CantApplyBadTypeExplained (((_,expected,argty),_,_),_) ->
raise (IllTypedInstance (env,sigma,argty, expected))
| TypingError (CantApplyNonFunctional (fj,_)) ->
raise (IllTypedInstanceFun (env,sigma,fj.uj_val,fj.uj_type))
| _ -> assert false
(*------------------------------------*
* Restricting existing evars *
*------------------------------------*)
type 'a update =
| UpdateWith of 'a
| NoUpdate
let restrict_evar_key evd evk filter candidates =
match filter, candidates with
| None, NoUpdate -> evd, evk
| _ ->
let evi = Evd.find_undefined evd evk in
let oldfilter = evar_filter evi in
begin match filter, candidates with
| Some filter, NoUpdate when Filter.equal oldfilter filter ->
evd, evk
| _ ->
let filter = match filter with
| None -> evar_filter evi
| Some filter -> filter in
let candidates = match candidates with
| NoUpdate -> Evd.evar_candidates evi
| UpdateWith c -> Some c in
restrict_evar evd evk filter candidates
end
(* Restrict an applied evar and returns its restriction in the same context *)
(* (the filter is assumed to be at least stronger than the original one) *)
let restrict_applied_evar evd (evk,argsv) filter candidates =
let evd,newevk = restrict_evar_key evd evk filter candidates in
let newargsv = match filter with
| None -> (* optim *) argsv
| Some filter ->
let EvarInfo evi = Evd.find evd evk in
let subfilter = Filter.compose (evar_filter evi) filter in
Filter.filter_slist subfilter argsv in
evd,(newevk,newargsv)
(* Restrict an evar in the current evar_map *)
let restrict_evar evd evk filter candidates =
fst (restrict_evar_key evd evk filter candidates)
(* Restrict an evar in the current evar_map *)
let restrict_instance evd evk filter argsv =
match filter with None -> argsv | Some filter ->
let EvarInfo evi = Evd.find evd evk in
Filter.filter_slist (Filter.compose (evar_filter evi) filter) argsv
open Context.Rel.Declaration
let noccur_evar env evd evk c =
let cache = ref Int.Set.empty (* cache for let-ins *) in
let rec occur_rec check_types (k, env as acc) c =
match EConstr.kind evd c with
| Evar (evk',args' as ev') ->
if Evar.equal evk evk' then raise Occur
else (if check_types then
occur_rec false acc (existential_type evd ev');
SList.Skip.iter (occur_rec check_types acc) args')
| Rel i when i > k ->
if not (Int.Set.mem (i-k) !cache) then
let decl = Environ.lookup_rel i env in
if check_types then
(cache := Int.Set.add (i-k) !cache; occur_rec false acc (lift i (EConstr.of_constr (get_type decl))));
(match decl with
| LocalAssum _ -> ()
| LocalDef (_,b,_) -> cache := Int.Set.add (i-k) !cache; occur_rec false acc (lift i (EConstr.of_constr b)))
| Proj (p,_,c) -> occur_rec true acc c
| _ -> iter_with_full_binders env evd (fun rd (k,env) -> (succ k, push_rel rd env))
(occur_rec check_types) acc c
in
try occur_rec false (0,env) c; true with Occur -> false
(****************************************)
(* Managing chains of local definitions *)
(****************************************)
type alias =
| RelAlias of int
| VarAlias of Id.t
let of_alias = function
| RelAlias n -> mkRel n
| VarAlias id -> mkVar id
let to_alias sigma c = match EConstr.kind sigma c with
| Rel n -> Some (RelAlias n)
| Var id -> Some (VarAlias id)
| _ -> None
let is_alias sigma c alias = match EConstr.kind sigma c, alias with
| Var id, VarAlias id' -> Id.equal id id'
| Rel n, RelAlias n' -> Int.equal n n'
| _ -> false
let eq_alias a b = match a, b with
| RelAlias n, RelAlias m -> Int.equal m n
| VarAlias id1, VarAlias id2 -> Id.equal id1 id2
| _ -> false
let compare_alias a b = match a, b with
| RelAlias n, RelAlias m -> Int.compare n m
| VarAlias id1, VarAlias id2 -> Id.compare id1 id2
| RelAlias _, VarAlias _ -> -1
| VarAlias _, RelAlias _ -> 1
module AlsOrd = struct type t = alias let compare = compare_alias end
module AlsMap = Map.Make(AlsOrd)
(* A chain of let-in ended either by a declared variable or a non-variable term *)
(* e.g. [x:=t;y:=x;z:=y] binds [z] to [NonVarAliasChain ([y;x],t)] *)
(* and. [a:T;x:=a;y:=x;z:=y] binds [z] to [VarAliasChain ([y;x],a)] *)
type 'a alias_chain =
| VarAliasChain of alias list * alias
| NonVarAliasChain of alias list * 'a
let init_var_alias_chain x = VarAliasChain ([], x)
let init_term_alias_chain c = NonVarAliasChain ([], c)
let push_alias aliases_chain a =
(* most recent variables come first *)
match aliases_chain with
| VarAliasChain (l, last) -> VarAliasChain (a :: l, last)
| NonVarAliasChain (l, last) -> NonVarAliasChain (a :: l, last)
module Alias =
struct
type t = { mutable lift : int; mutable data : EConstr.t }
let make c = { lift = 0; data = c }
let lift n { lift; data } = { lift = lift + n; data }
let eval alias =
let c = EConstr.Vars.lift alias.lift alias.data in
let () = alias.lift <- 0 in
let () = alias.data <- c in
c
let repr sigma alias = match EConstr.kind sigma alias.data with
| Rel n -> Some (RelAlias (n + alias.lift))
| Var id -> Some (VarAlias id)
| _ -> None
end
let lift_alias_chain n alias_chain =
let map a = match a with
| VarAlias _ -> a
| RelAlias m -> RelAlias (m + n)
in
match alias_chain with
| VarAliasChain (l, alias) -> VarAliasChain (List.map map l, map alias)
| NonVarAliasChain (l, alias) -> NonVarAliasChain (List.map map l, Alias.lift n alias)
let cast_alias_chain = function
| VarAliasChain (l, v) -> VarAliasChain (l, v)
| NonVarAliasChain (l, c) -> NonVarAliasChain (l, Alias.make c)
type aliases = {
rel_aliases : Alias.t alias_chain Int.Map.t;
var_aliases : EConstr.t alias_chain Id.Map.t;
(** Only contains [VarAlias] *)
}
(* Expand rels and vars that are bound to other rels or vars so that
dependencies in variables are canonically associated to the most ancient
variable in its family of aliased variables *)
let compute_var_aliases sign sigma =
let open Context.Named.Declaration in
(* push from oldest to more recent variables *)
List.fold_right (fun decl aliases ->
let id = get_id decl in
match decl with
| LocalDef (_,t,_) ->
let aliases_of_id =
match EConstr.kind sigma t with
| Var id' ->
(try push_alias (Id.Map.find id' aliases) (VarAlias id')
with Not_found -> init_var_alias_chain (VarAlias id'))
| _ ->
init_term_alias_chain t in
Id.Map.add id aliases_of_id aliases
| LocalAssum _ -> aliases)
sign Id.Map.empty
let compute_rel_aliases var_aliases rels sigma =
(* push from oldest to more recent variables *)
snd (List.fold_right
(fun decl (n,aliases) ->
(n-1,
match decl with
| LocalDef (_,t,u) ->
let aliases_of_n =
match EConstr.kind sigma t with
| Var id' ->
(let alias = VarAlias id' in
try push_alias (cast_alias_chain (Id.Map.find id' var_aliases)) alias
with Not_found -> init_var_alias_chain alias)
| Rel p ->
(let alias = RelAlias (p+n) in
try push_alias (Int.Map.find (p+n) aliases) alias
with Not_found -> init_var_alias_chain alias)
| _ ->
init_term_alias_chain (Alias.lift n (Alias.make @@ mkCast(t,DEFAULTcast, u)))
in
Int.Map.add n aliases_of_n aliases
| LocalAssum _ -> aliases)
)
rels
(List.length rels,Int.Map.empty))
let make_alias_map env sigma =
(* We compute the chain of aliases for each var and rel *)
let var_aliases = compute_var_aliases (named_context env) sigma in
let rel_aliases = compute_rel_aliases var_aliases (rel_context env) sigma in
{ var_aliases; rel_aliases }
let lift_aliases n aliases =
if Int.equal n 0 then aliases else
let rel_aliases =
Int.Map.fold (fun p l -> Int.Map.add (p+n) (lift_alias_chain n l))
aliases.rel_aliases Int.Map.empty
in
{ aliases with rel_aliases }
let get_alias_chain_of aliases x = match x with
| RelAlias n -> (try Some (Int.Map.find n aliases.rel_aliases) with Not_found -> None)
| VarAlias id -> (try Some (cast_alias_chain (Id.Map.find id aliases.var_aliases)) with Not_found -> None)
(* Expand an alias as much as possible while remaining a variable *)
(* i.e. returns either a declared variable [y], or the last expansion
of [x] defined to be [c] and [c] is not a variable *)
let normalize_alias aliases x =
match get_alias_chain_of aliases x with
| None | Some (NonVarAliasChain ([], _)) -> x
| Some (NonVarAliasChain (l, _)) -> List.last l
| Some (VarAliasChain (_, a)) -> a
(* Idem, specifically for named variables *)
let normalize_alias_var var_aliases id =
let aliases = { var_aliases; rel_aliases = Int.Map.empty } in
match normalize_alias aliases (VarAlias id) with
| VarAlias id -> id
| RelAlias _ -> assert false (** var only aliases to variables *)
let extend_alias sigma decl { var_aliases; rel_aliases } =
let rel_aliases =
Int.Map.fold (fun n l -> Int.Map.add (n+1) (lift_alias_chain 1 l))
rel_aliases Int.Map.empty in
let rel_aliases =
match decl with
| LocalDef(_,t,_) ->
let aliases_of_binder =
match EConstr.kind sigma t with
| Var id' ->
let alias = VarAlias id' in
(try push_alias (cast_alias_chain (Id.Map.find id' var_aliases)) alias
with Not_found -> init_var_alias_chain alias)
| Rel p ->
let alias = RelAlias (p+1) in
(try push_alias (Int.Map.find (p+1) rel_aliases) alias
with Not_found -> init_var_alias_chain alias)
| _ ->
init_term_alias_chain (Alias.lift 1 (Alias.make t))
in
Int.Map.add 1 aliases_of_binder rel_aliases
| LocalAssum _ -> rel_aliases in
{ var_aliases; rel_aliases }
let expand_alias_once aliases x =
match get_alias_chain_of aliases x with
| None -> None
| Some (VarAliasChain (x :: _, _) | NonVarAliasChain (x :: _, _) | VarAliasChain ([], x)) -> Some (Alias.make (of_alias x))
| Some (NonVarAliasChain ([], a)) -> Some a
let expansions_of_var aliases x =
match get_alias_chain_of aliases x with
| None -> [x]
| Some (VarAliasChain (l, y)) -> x :: l @ [y]
| Some (NonVarAliasChain (l, _)) -> x :: l
let expansion_of_var sigma aliases x =
match get_alias_chain_of aliases x with
| None -> (false, Some x, [])
| Some (VarAliasChain (l, x)) -> (true, Some x, l)
| Some (NonVarAliasChain (l, a)) -> (true, Alias.repr sigma a, l)
let rec expand_vars_in_term_using env sigma aliases t = match EConstr.kind sigma t with
| Rel n -> of_alias (normalize_alias aliases (RelAlias n))
| Var id -> of_alias (normalize_alias aliases (VarAlias id))
| _ ->
let self aliases c = expand_vars_in_term_using env sigma aliases c in
map_constr_with_full_binders env sigma (extend_alias sigma) self aliases t
let expand_vars_in_term env sigma = expand_vars_in_term_using env sigma (make_alias_map env sigma)
let free_vars_and_rels_up_alias_expansion env sigma aliases c =
let fv_rels = ref Int.Set.empty and fv_ids = ref Id.Set.empty in
let let_rels = ref Int.Set.empty and let_ids = ref Id.Set.empty in
let cache_rel = ref Int.Set.empty and cache_var = ref Id.Set.empty in
let is_in_cache depth = function
| RelAlias n -> Int.Set.mem (n-depth) !cache_rel
| VarAlias s -> Id.Set.mem s !cache_var
in
let put_in_cache depth = function
| RelAlias n -> cache_rel := Int.Set.add (n-depth) !cache_rel
| VarAlias s -> cache_var := Id.Set.add s !cache_var
in
let rec frec (aliases,depth) c =
match EConstr.kind sigma c with
| Rel _ | Var _ as ck ->
let ck = match ck with
| Rel n -> RelAlias n
| Var id -> VarAlias id
| _ -> assert false
in
if is_in_cache depth ck then () else begin
put_in_cache depth ck;
let expanded, c', l = expansion_of_var sigma aliases ck in
(if expanded then (* expansion, hence a let-in *)
List.iter (function
| VarAlias id -> let_ids := Id.Set.add id !let_ids
| RelAlias n -> if n >= depth+1 then let_rels := Int.Set.add (n-depth) !let_rels)
(ck :: l));
match c' with
| Some (VarAlias id) -> fv_ids := Id.Set.add id !fv_ids
| Some (RelAlias n) -> if n >= depth+1 then fv_rels := Int.Set.add (n-depth) !fv_rels
| None -> frec (aliases,depth) c end
| Const _ | Ind _ | Construct _ ->
fv_ids := Id.Set.union (vars_of_global env (fst @@ EConstr.destRef sigma c)) !fv_ids
| _ ->
iter_with_full_binders env sigma
(fun d (aliases,depth) -> (extend_alias sigma d aliases,depth+1))
frec (aliases,depth) c
in
frec (aliases,0) c;
(!fv_rels,!fv_ids,!let_rels,!let_ids)
(********************************)
(* Managing pattern-unification *)
(********************************)
let expand_and_check_vars aliases l =
let map a = match get_alias_chain_of aliases a with
| None -> Some a
| Some (VarAliasChain (_, a)) -> Some a
| Some (NonVarAliasChain ([], c)) -> None
| Some (NonVarAliasChain (l, c)) -> Some (List.last l)
in
Option.List.map map l
let alias_distinct l =
let rec check (rels, vars) = function
| [] -> true
| RelAlias n :: l ->
not (Int.Set.mem n rels) && check (Int.Set.add n rels, vars) l
| VarAlias id :: l ->
not (Id.Set.mem id vars) && check (rels, Id.Set.add id vars) l
in
check (Int.Set.empty, Id.Set.empty) l
let distinct_actual_deps env evd aliases l t =
(* If the aliases are already unique, any subset will also be. *)
if alias_distinct l then true
(* The instance of a meta can virtually contains any variable of the context *)
else if occur_meta evd t then false
else
(* Probably strong restrictions coming from t being evar-closed *)
let (fv_rels,fv_ids,_,_) = free_vars_and_rels_up_alias_expansion env evd aliases t in
alias_distinct @@ List.filter (function
| VarAlias id -> Id.Set.mem id fv_ids
| RelAlias n -> Int.Set.mem n fv_rels
) l
open Context.Named.Declaration
let remove_instance_local_defs evd evk args =
let EvarInfo evi = Evd.find evd evk in
let rec aux sign args = match sign, args with
| [], [] -> []
| LocalAssum _ :: sign, c :: args -> c :: aux sign args
| LocalDef _ :: sign, _ :: args -> aux sign args
| _ -> assert false
in
aux (evar_filtered_context evi) args
(* Check if an applied evar "?X[args] l" is a Miller's pattern *)
let find_unification_pattern_args env evd l t =
let aliases = make_alias_map env evd in
match expand_and_check_vars aliases l with
| Some l as x when distinct_actual_deps env evd aliases l t -> x
| _ -> None
let is_unification_pattern_meta env evd nb m l t =
(* Variables from context and rels > nb are implicitly all there *)
(* so we need to be a rel <= nb *)
let map a = match EConstr.kind evd a with
| Rel n -> if n <= nb then Some (RelAlias n) else None
| _ -> None
in
match Option.List.map map l with
| Some l ->
begin match find_unification_pattern_args env evd l t with
| Some _ as x when not (occur_metavariable evd m t) -> x
| _ -> None
end
| None ->
None
let is_unification_pattern_evar env evd (evk,args) l t =
match Option.List.map (fun c -> to_alias evd c) l with
| Some l when noccur_evar env evd evk t ->
let args = Evd.expand_existential evd (evk, args) in
let args = remove_instance_local_defs evd evk args in
let args = Option.List.map (fun c -> to_alias evd c) args in
begin match args with
| None -> None
| Some args ->
let n = List.length args in
match find_unification_pattern_args env evd (args @ l) t with
| Some l -> Some (List.skipn n l)
| _ -> None
end
| _ -> None
let is_unification_pattern_pure_evar env evd (evk,args) t =
let is_ev = is_unification_pattern_evar env evd (evk,args) [] t in
match is_ev with
| None -> false
| Some _ -> true
let is_unification_pattern (env,nb) evd f l t =
match EConstr.kind evd f with
| Meta m -> is_unification_pattern_meta env evd nb m l t
| Evar ev -> is_unification_pattern_evar env evd ev l t
| _ -> None
(* From a unification problem "?X l = c", build "\x1...xn.(term1 l2)"
(pattern unification). It is assumed that l is made of rel's that
are distinct and not bound to aliases. *)
(* It is also assumed that c does not contain metas because metas
*implicitly* depend on Vars but lambda abstraction will not reflect this
dependency: ?X x = ?1 (?1 is a meta) will return \_.?1 while it should
return \y. ?1{x\y} (non constant function if ?1 depends on x) (BB) *)
let solve_pattern_eqn env sigma l c =
let c' = List.fold_right (fun a c ->
let c' = subst_term sigma (lift 1 (of_alias a)) (lift 1 c) in
match a with
(* Rem: if [a] links to a let-in, do as if it were an assumption *)
| RelAlias n ->
let open Context.Rel.Declaration in
let d = map_constr (lift n) (lookup_rel n env) in
mkLambda_or_LetIn d c'
| VarAlias id ->
let d = lookup_named id env in mkNamedLambda_or_LetIn sigma d c'
)
l c in
(* Warning: we may miss some opportunity to eta-reduce more since c'
is not in normal form *)
shrink_eta sigma c'
(*****************************************)
(* Refining/solving unification problems *)
(*****************************************)
(* Knowing that [Gamma |- ev : T] and that [ev] is applied to [args],
* [make_projectable_subst ev args] builds the substitution [Gamma:=args].
* If a variable and an alias of it are bound to the same instance, we skip
* the alias (we just use eq_constr -- instead of conv --, since anyway,
* only instances that are variables -- or evars -- are later considered;
* moreover, we can bet that similar instances came at some time from
* the very same substitution. The removal of aliased duplicates is
* useful to ensure the uniqueness of a projection.
*)
type esubst = {
ealias : (alias * Id.t) list Int.Map.t;
evalue : (existential * Id.t) Int.Map.t;
eindex : Int.Set.t AlsMap.t;
(** Reverse map of indices in [ealias] containing the corresponding alias *)
}
let make_constructor_subst sigma sign args =
let rec fold decls args accu = match decls, SList.view args with
| _ :: _, None | [], Some _ -> assert false
| [], None -> accu
| LocalAssum ({ binder_name = id }, _) :: decls, Some (Some a, args) ->
let accu = fold decls args accu in
let a', args = decompose_app sigma a in
begin match EConstr.kind sigma a' with
| Construct (cstr, _) ->
let l = try Constrmap.find cstr accu with Not_found -> [] in
Constrmap.add cstr ((args, id) :: l) accu
| _ -> accu
end
| LocalAssum _ :: decls, Some (None, args) -> fold decls args accu
| LocalDef _ :: decls, Some (_, args) -> fold decls args accu
in
fold sign args Constrmap.empty
let make_projectable_subst aliases sigma sign args =
let evar_aliases = compute_var_aliases sign sigma in
(* First compute aliasing equivalence classes *)
let rec fold accu args decls = match SList.view args, decls with
| None, _ :: _ | Some _, [] -> assert false
| None, [] -> accu
| Some (a, args), decl :: decls ->
let (i, all, vals, revmap) = fold accu args decls in
let id = get_id decl in
let a = match a with None -> mkVar id | Some a -> a in
let revmap = Id.Map.add id i revmap in
let oldbindings = match decl with
| LocalAssum _ -> None
| LocalDef (_, c, _) ->
match EConstr.kind sigma c with
| Var id' ->
let idc = normalize_alias_var evar_aliases id' in
let ic, sub = match Id.Map.find_opt idc revmap with
| Some ic ->
let bnd = match Int.Map.find_opt ic all with
| None -> []
| Some bnd -> bnd
in
ic, bnd
| None ->
(* [idc] is a filtered variable: treat [id] as an assumption *)
i, []
in
Some (ic, sub)
| _ -> None
in
let all, vals = match oldbindings with
| None ->
begin match to_alias sigma a with
| Some v -> Int.Map.add i [v, id] all, vals
| None ->
match destEvar sigma a with
| ev -> all, Int.Map.add i (ev, id) vals
| exception DestKO -> all, vals
end
| Some (ic, sub) ->
(* Necessarily a let-binding aliasing a variable *)
match to_alias sigma a with
| None -> all, vals
| Some v ->
if List.exists (fun (c, _) -> eq_alias v c) sub then all, vals
else Int.Map.add ic ((v, id) :: sub) all, vals
in
(i + 1, all, vals, revmap)
in
let (_, ealias, evalue, _) = fold (0, Int.Map.empty, Int.Map.empty, Id.Map.empty) args sign in
(* Then extract the backpointers. *)
let fold i bnd eindex =
let fold accu (a, _) = match AlsMap.find a accu with
| set -> AlsMap.add a (Int.Set.add i set) accu
| exception Not_found -> AlsMap.add a (Int.Set.singleton i) accu
in
List.fold_left fold eindex bnd
in
let eindex = Int.Map.fold fold ealias AlsMap.empty in
{ eindex; ealias; evalue }
(*------------------------------------*
* operations on the evar constraints *
*------------------------------------*)
(* We have a unification problem Σ; Γ |- ?e[u1..uq] = t : s where ?e is not yet
* declared in Σ but yet known to be declarable in some context x1:T1..xq:Tq.
* [define_evar_from_virtual_equation ... Γ Σ t (x1:T1..xq:Tq) .. (u1..uq) (x1..xq)]
* declares x1:T1..xq:Tq |- ?e : s such that ?e[u1..uq] = t holds.
*)
let define_evar_from_virtual_equation define_fun env evd src t_in_env ty_t_in_sign sign filter inst_in_env =
let (evd, evk) = new_pure_evar sign evd ty_t_in_sign ~filter ~src in
let t_in_env = whd_evar evd t_in_env in
let evd = define_fun env evd None (evk, inst_in_env) t_in_env in
let EvarInfo evi = Evd.find evd evk in
let inst_in_sign = evar_identity_subst evi in
let evar_in_sign = mkEvar (evk, inst_in_sign) in
(evd,whd_evar evd evar_in_sign)
(* We have x1..xq |- ?e1 : τ and had to solve something like
* Σ; Γ |- ?e1[u1..uq] = (...\y1 ... \yk ... c), where c is typically some
* ?e2[v1..vn], hence flexible. We had to go through k binders and now
* virtually have x1..xq, y1'..yk' | ?e1' : τ' and the equation
* Γ, y1..yk |- ?e1'[u1..uq y1..yk] = c.
* [materialize_evar Γ evd k (?e1[u1..uq]) τ'] extends Σ with the declaration
* of ?e1' and returns both its instance ?e1'[x1..xq y1..yk] in an extension
* of the context of e1 so that e1 can be instantiated by
* (...\y1' ... \yk' ... ?e1'[x1..xq y1'..yk']),
* and the instance ?e1'[u1..uq y1..yk] so that the remaining equation
* ?e1'[u1..uq y1..yk] = c can be registered
*
* Note that, because invert_definition does not check types, we need to
* guess the types of y1'..yn' by inverting the types of y1..yn along the
* substitution u1..uq.
*)
exception MorePreciseOccurCheckNeeeded
let materialize_evar define_fun env evd k (evk1,args1) ty_in_env =
if Evd.is_defined evd evk1 then
(* Some circularity somewhere (see e.g. #3209) *)
raise MorePreciseOccurCheckNeeeded;
let (evk1,args1) = destEvar evd (mkEvar (evk1,args1)) in
let evi1 = Evd.find_undefined evd evk1 in
let env1,rel_sign = env_rel_context_chop k env in
let sign1 = evar_hyps evi1 in
let filter1 = evar_filter evi1 in
let src = subterm_source evk1 (Evd.evar_source evi1) in
let avoid = Environ.ids_of_named_context_val sign1 in
let inst_in_sign = evar_identity_subst evi1 in
let open Context.Rel.Declaration in
let (sign2,filter2,inst2_in_env,inst2_in_sign,_,evd,_) =
List.fold_right (fun d (sign,filter,inst_in_env,inst_in_sign,env,evd,avoid) ->
let LocalAssum (na,t_in_env) | LocalDef (na,_,t_in_env) = d in
let id = map_annot (fun na -> next_name_away na avoid) na in
let evd,t_in_sign =
let s = Retyping.get_sort_of env evd t_in_env in
let evd,ty_t_in_sign = refresh_universes
~status:univ_flexible (Some false) env evd (mkSort s) in
define_evar_from_virtual_equation define_fun env evd src t_in_env
ty_t_in_sign sign filter inst_in_env in
let evd,d' = match d with
| LocalAssum _ -> evd, Context.Named.Declaration.LocalAssum (id,t_in_sign)
| LocalDef (_,b,_) ->
let evd,b = define_evar_from_virtual_equation define_fun env evd src b
t_in_sign sign filter inst_in_env in
evd, Context.Named.Declaration.LocalDef (id,b,t_in_sign) in
(push_named_context_val d' sign, Filter.extend 1 filter,
SList.cons (mkRel 1) (SList.Skip.map (lift 1) inst_in_env),
SList.cons (mkRel 1) (SList.Skip.map (lift 1) inst_in_sign),
push_rel d env,evd,Id.Set.add id.binder_name avoid))
rel_sign
(sign1,filter1,args1,inst_in_sign,env1,evd,avoid)
in
let evd,ev2ty_in_sign =
let s = Retyping.get_sort_of env evd ty_in_env in
let evd,ty_t_in_sign = refresh_universes
~status:univ_flexible (Some false) env evd (mkSort s) in
define_evar_from_virtual_equation define_fun env evd src ty_in_env
ty_t_in_sign sign2 filter2 inst2_in_env in
let (evd, ev2_in_sign) =
new_pure_evar sign2 evd ev2ty_in_sign ~filter:filter2 ~src in
let ev2_in_env = (ev2_in_sign, inst2_in_env) in
(evd, mkEvar (ev2_in_sign, inst2_in_sign), ev2_in_env)
let restrict_upon_filter evd evk p args =
let oldfullfilter = evar_filter (Evd.find_undefined evd evk) in
let args = Array.of_list args in
let len = Array.length args in
Filter.restrict_upon oldfullfilter len (fun i -> p (Array.unsafe_get args i))
let check_evar_instance_evi unify flags env evd evi body =
let evenv = evar_env env evi in
(* FIXME: The body might be ill-typed when this is called from w_merge *)
(* This happens in practice, cf MathClasses build failure on 2013-3-15 *)
let ty =
try Retyping.get_type_of ~lax:true evenv evd body
with Retyping.RetypeError _ ->
let loc, _ = Evd.evar_source evi in user_err ?loc (Pp.(str "Ill-typed evar instance"))
in
match unify flags TypeUnification evenv evd Conversion.CUMUL ty (Evd.evar_concl evi) with
| Success evd -> evd
| UnifFailure _ -> raise (IllTypedInstance (evenv,evd,ty, Evd.evar_concl evi))
let check_evar_instance unify flags env evd evk body =
let evi = try Evd.find_undefined evd evk with Not_found -> assert false in
check_evar_instance_evi unify flags env evd evi body
(***************)
(* Unification *)
(* Inverting constructors in instances (common when inferring type of match) *)
let find_projectable_constructor env evd cstr k args cstr_subst =
try
let l = Constrmap.find cstr cstr_subst in
let args = Array.map (lift (-k)) args in
let l =
List.filter (fun (args',id) ->
(* is_conv is maybe too strong (and source of useless computation) *)
(* (at least expansion of aliases is needed) *)
Array.for_all2 (fun c1 c2 -> is_conv env evd c1 c2) args args') l in
List.map snd l
with Not_found ->
[]
(* [find_projectable_vars env sigma y subst] finds all vars of [subst]
* that project on [y]. It is able to find solutions to the following
* two kinds of problems:
*
* - ?n[...;x:=y;...] = y
* - ?n[...;x:=?m[args];...] = y with ?m[args] = y recursively solvable
*
* (see test-suite/success/Fixpoint.v for an example of application of
* the second kind of problem).
*
* The seek for [y] is up to variable aliasing. In case of solutions that
* differ only up to aliasing, the binding that requires the less
* steps of alias reduction is kept. At the end, only one solution up
* to aliasing is kept.
*
* [find_projectable_vars] also unifies against evars that themselves mention
* [y] and recursively.
*
* In short, the following situations give the following solutions:
*
* problem evar ctxt soluce remark
* z1; z2:=z1 |- ?ev[z1;z2] = z1 y1:A; y2:=y1 y1 \ thanks to defs kept in
* z1; z2:=z1 |- ?ev[z1;z2] = z2 y1:A; y2:=y1 y2 / subst and preferring =
* z1; z2:=z1 |- ?ev[z1] = z2 y1:A y1 thanks to expand_var
* z1; z2:=z1 |- ?ev[z2] = z1 y1:A y1 thanks to expand_var
* z3 |- ?ev[z3;z3] = z3 y1:A; y2:=y1 y2 see make_projectable_subst
*
* Remark: [find_projectable_vars] assumes that identical instances of
* variables in the same set of aliased variables are already removed (see
* [make_projectable_subst])
*)
type evar_projection =
| ProjectVar
| ProjectEvar of EConstr.existential * undefined evar_info * Id.t * evar_projection
exception NotUnique
exception NotUniqueInType of (Id.t * evar_projection) list
let rec assoc_up_to_alias sigma aliases y = function
| [] -> assert false
| (c, id)::l ->
if eq_alias c y then id
else assoc_up_to_alias sigma aliases y l
let rec find_projectable_vars aliases sigma y subst =
let indices = try AlsMap.find y subst.eindex with Not_found -> Int.Set.empty in
let is_projectable_var i subst1 =
(* First test if some [id] aliased to [idc] is bound to [y] in [subst] *)
let idcl = Int.Map.find i subst.ealias in
let id = assoc_up_to_alias sigma aliases y idcl in
(id, ProjectVar)::subst1
in
let is_projectable_evar i (c, id) subst2 =
(* Then test if [idc] is (indirectly) bound in [subst] to some evar *)
(* projectable on [y] *)
if Int.Set.mem i indices then subst2 (* already found by is_projectable_var *)
else if Evd.is_defined sigma (fst c) then subst2 (* already solved *)
else
let (evk,argsv as t) = c in
let evi = Evd.find_undefined sigma evk in
let subst = make_projectable_subst aliases sigma (evar_filtered_context evi) argsv in
let l = find_projectable_vars aliases sigma y subst in
match l with
| [id',p] -> (id, ProjectEvar (t, evi, id', p)) :: subst2
| _ -> subst2
in