-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunification.ml
2039 lines (1836 loc) · 77.9 KB
/
unification.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) *)
(************************************************************************)
open CErrors
open Pp
open Util
open Names
open Constr
open Context
open Termops
open Environ
open EConstr
open Vars
open Namegen
open Evd
open Reduction
open Reductionops
open Evarutil
open Evardefine
open Evarsolve
open Pretype_errors
open Retyping
open Coercion
open Recordops
open Locus
open Locusops
open Find_subterm
type metabinding = (metavariable * EConstr.constr * (instance_constraint * instance_typing_status))
type subst0 =
(evar_map *
metabinding list *
(Environ.env * EConstr.existential * EConstr.t) list)
module RelDecl = Context.Rel.Declaration
module NamedDecl = Context.Named.Declaration
let keyed_unification = ref (false)
let () = Goptions.(declare_bool_option {
optdepr = false;
optname = "Unification is keyed";
optkey = ["Keyed";"Unification"];
optread = (fun () -> !keyed_unification);
optwrite = (fun a -> keyed_unification:=a);
})
let is_keyed_unification () = !keyed_unification
let debug_unification = ref (false)
let () = Goptions.(declare_bool_option {
optdepr = false;
optname =
"Print states sent to tactic unification";
optkey = ["Debug";"Tactic";"Unification"];
optread = (fun () -> !debug_unification);
optwrite = (fun a -> debug_unification:=a);
})
(** Making this unification algorithm correct w.r.t. the evar-map abstraction
breaks too much stuff. So we redefine incorrect functions here. *)
let unsafe_occur_meta_or_existential c =
let c = EConstr.Unsafe.to_constr c in
let rec occrec c = match Constr.kind c with
| Evar _ -> raise Occur
| Meta _ -> raise Occur
| _ -> Constr.iter occrec c
in try occrec c; false with Occur -> true
let occur_meta_or_undefined_evar evd c =
(* This is performance-critical. Using the evar-insensitive API changes the
resulting heuristic. *)
let c = EConstr.Unsafe.to_constr c in
let rec occrec c = match Constr.kind c with
| Meta _ -> raise Occur
| Evar (ev,args) ->
(match evar_body (Evd.find evd ev) with
| Evar_defined c ->
occrec (EConstr.Unsafe.to_constr c); Array.iter occrec args
| Evar_empty -> raise Occur)
| _ -> Constr.iter occrec c
in try occrec c; false with Occur | Not_found -> true
let occur_meta_evd sigma mv c =
let rec occrec c =
(* Note: evars are not instantiated by terms with metas *)
let c = whd_meta sigma c in
match EConstr.kind sigma c with
| Meta mv' when Int.equal mv mv' -> raise Occur
| _ -> EConstr.iter sigma occrec c
in try occrec c; false with Occur -> true
(* if lname_typ is [xn,An;..;x1,A1] and l is a list of terms,
gives [x1:A1]..[xn:An]c' such that c converts to ([x1:A1]..[xn:An]c' l) *)
let abstract_scheme env evd c l lname_typ =
let mkLambda_name env (n,a,b) =
mkLambda (map_annot (named_hd env evd a) n, a, b)
in
List.fold_left2
(fun (t,evd) (locc,a) decl ->
let na = RelDecl.get_annot decl in
let ta = RelDecl.get_type decl in
let na = match EConstr.kind evd a with Var id -> {na with binder_name=Name id} | _ -> na in
(* [occur_meta ta] test removed for support of eelim/ecase but consequences
are unclear...
if occur_meta ta then error "cannot find a type for the generalisation"
else *)
if occur_meta evd a then mkLambda_name env (na,ta,t), evd
else
let t', evd' = Find_subterm.subst_closed_term_occ env evd locc a t in
mkLambda_name env (na,ta,t'), evd')
(c,evd)
(List.rev l)
lname_typ
(* Precondition: resulting abstraction is expected to be of type [typ] *)
let abstract_list_all env evd typ c l =
let ctxt,_ = splay_prod_n env evd (List.length l) typ in
let l_with_all_occs = List.map (function a -> (LikeFirst,a)) l in
let p,evd = abstract_scheme env evd c l_with_all_occs ctxt in
let evd,typp =
try Typing.type_of env evd p
with
| UserError _ ->
error_cannot_find_well_typed_abstraction env evd p l None
| Type_errors.TypeError (env',x) ->
(* FIXME: plug back the typing information *)
error_cannot_find_well_typed_abstraction env evd p l None
| Pretype_errors.PretypeError (env',evd,TypingError x) ->
error_cannot_find_well_typed_abstraction env evd p l (Some (env',x)) in
evd,(p,typp)
let set_occurrences_of_last_arg args =
Evarconv.AtOccurrences AllOccurrences ::
List.tl (Array.map_to_list (fun _ -> Evarconv.Unspecified Abstraction.Abstract) args)
let occurrence_test _ _ _ env sigma _ c1 c2 =
match EConstr.eq_constr_universes env sigma c1 c2 with
| None -> false, sigma
| Some cstr ->
try true, Evd.add_universe_constraints sigma cstr
with UniversesDiffer -> false, sigma
let abstract_list_all_with_dependencies env evd typ c l =
let (evd, ev) = new_evar env evd typ in
let evd,ev' = evar_absorb_arguments env evd (destEvar evd ev) l in
let n = List.length l in
let argoccs = set_occurrences_of_last_arg (Array.sub (snd ev') 0 n) in
let evd,b =
Evarconv.second_order_matching
(Evarconv.default_flags_of TransparentState.empty)
env evd ev' (occurrence_test, argoccs) c in
if b then
let p = nf_evar evd ev in
evd, p
else error_cannot_find_well_typed_abstraction env evd
c l None
(* A refinement of [conv_pb]: the integers tells how many arguments
were applied in the context of the conversion problem; if the number
is non zero, steps of eta-expansion will be allowed
*)
let opp_status = function
| IsSuperType -> IsSubType
| IsSubType -> IsSuperType
| Conv -> Conv
let add_type_status (x,y) = ((x,TypeNotProcessed),(y,TypeNotProcessed))
let extract_instance_status = function
| CUMUL -> add_type_status (IsSubType, IsSuperType)
| CONV -> add_type_status (Conv, Conv)
let rec subst_meta_instances sigma bl c =
match EConstr.kind sigma c with
| Meta i ->
let select (j,_,_) = Int.equal i j in
(try pi2 (List.find select bl) with Not_found -> c)
| _ -> EConstr.map sigma (subst_meta_instances sigma bl) c
(** [env] should be the context in which the metas live *)
let pose_all_metas_as_evars env evd t =
let evdref = ref evd in
let rec aux t = match EConstr.kind !evdref t with
| Meta mv ->
(match Evd.meta_opt_fvalue !evdref mv with
| Some ({rebus=c},_) -> c
| None ->
let {rebus=ty;freemetas=mvs} = Evd.meta_ftype evd mv in
let ty = if Evd.Metaset.is_empty mvs then ty else aux ty in
let ty = nf_betaiota env evd ty in
let src = Evd.evar_source_of_meta mv !evdref in
let evd, ev = Evarutil.new_evar env !evdref ~src ty in
evdref := meta_assign mv (ev,(Conv,TypeNotProcessed)) evd;
ev)
| _ ->
EConstr.map !evdref aux t in
let c = aux t in
(* side-effect *)
(!evdref, c)
let solve_pattern_eqn_array (env,nb) f l c (sigma,metasubst,evarsubst : subst0) =
match EConstr.kind sigma f with
| Meta k ->
(* We enforce that the Meta does not depend on the [nb]
extra assumptions added by unification to the context *)
let env' = pop_rel_context nb env in
let sigma,c = pose_all_metas_as_evars env' sigma c in
let c = solve_pattern_eqn env sigma l c in
let pb = (Conv,TypeNotProcessed) in
if noccur_between sigma 1 nb c then
sigma,(k,lift (-nb) c,pb)::metasubst,evarsubst
else
let l = List.map of_alias l in
error_cannot_unify_local env sigma (applist (f, l),c,c)
| Evar ev ->
let env' = pop_rel_context nb env in
let sigma,c = pose_all_metas_as_evars env' sigma c in
sigma,metasubst,(env,ev,solve_pattern_eqn env sigma l c)::evarsubst
| _ -> assert false
let push d (env,n) = (push_rel_assum d env,n+1)
(*******************************)
(* Unification à l'ordre 0 de m et n: [unify_0 env sigma cv_pb m n]
renvoie deux listes:
metasubst:(int*constr)list récolte les instances des (Meta k)
evarsubst:(constr*constr)list récolte les instances des (Const "?k")
Attention : pas d'unification entre les différences instances d'une
même meta ou evar, il peut rester des doublons *)
(* Unification order: *)
(* Left to right: unifies first argument and then the other arguments *)
(*let unify_l2r x = List.rev x
(* Right to left: unifies last argument and then the other arguments *)
let unify_r2l x = x
let sort_eqns = unify_r2l
*)
type core_unify_flags = {
modulo_conv_on_closed_terms : TransparentState.t option;
(* What this flag controls was activated with all constants transparent, *)
(* even for auto, since Coq V5.10 *)
use_metas_eagerly_in_conv_on_closed_terms : bool;
(* This refinement of the conversion on closed terms is activable *)
(* (and activated for apply, rewrite but not auto since Feb 2008 for 8.2) *)
use_evars_eagerly_in_conv_on_closed_terms : bool;
modulo_delta : TransparentState.t;
(* This controls which constants are unfoldable; this is on for apply *)
(* (but not simple apply) since Feb 2008 for 8.2 *)
modulo_delta_types : TransparentState.t;
check_applied_meta_types : bool;
(* This controls whether meta's applied to arguments have their *)
(* type unified with the type of their instance *)
use_pattern_unification : bool;
(* This solves pattern "?n x1 ... xn = t" when the xi are distinct rels *)
(* This says if pattern unification is tried *)
use_meta_bound_pattern_unification : bool;
(* This is implied by use_pattern_unification; has no particular *)
(* reasons to be set differently than use_pattern_unification *)
(* except for compatibility of "auto". *)
(* This was on for all tactics, including auto, since Sep 2006 for 8.1 *)
(* This allowed for instance to unify "forall x:?A, ?B x" with "A' -> B'" *)
(* when ?B is a Meta. *)
frozen_evars : Evar.Set.t;
(* Evars of this set are considered axioms and never instantiated *)
(* Useful e.g. for autorewrite *)
restrict_conv_on_strict_subterms : bool;
(* No conversion at the root of the term; potentially useful for rewrite *)
modulo_betaiota : bool;
(* Support betaiota in the reduction *)
(* Note that zeta is always used *)
modulo_eta : bool;
(* Support eta in the reduction *)
}
type unify_flags = {
core_unify_flags : core_unify_flags;
(* Governs unification of problems of the form "t(?x) = u(?x)" in apply *)
merge_unify_flags : core_unify_flags;
(* These are the flags to be used when trying to unify *)
(* several instances of the same metavariable *)
(* Typical situation is when we give a pattern to be matched *)
(* syntactically against a subterm but we want the metas of the *)
(* pattern to be modulo convertibility *)
subterm_unify_flags : core_unify_flags;
(* Governs unification of problems of the form "?X a1..an = u" in apply, *)
(* hence in rewrite and elim *)
allow_K_in_toplevel_higher_order_unification : bool;
(* Tells in second-order abstraction over subterms which have not *)
(* been found in term are allowed (used for rewrite, elim, or *)
(* apply with a lemma whose type has the form "?X a1 ... an") *)
resolve_evars : bool
(* This says if type classes instances resolution must be used to infer *)
(* the remaining evars *)
}
(* Default flag for unifying a type against a type (e.g. apply) *)
(* We set all conversion flags (no flag should be modified anymore) *)
let default_core_unify_flags () =
let ts = TransparentState.full in {
modulo_conv_on_closed_terms = Some ts;
use_metas_eagerly_in_conv_on_closed_terms = true;
use_evars_eagerly_in_conv_on_closed_terms = false;
modulo_delta = ts;
modulo_delta_types = ts;
check_applied_meta_types = true;
use_pattern_unification = true;
use_meta_bound_pattern_unification = true;
frozen_evars = Evar.Set.empty;
restrict_conv_on_strict_subterms = false;
modulo_betaiota = true;
modulo_eta = true;
}
(* Default flag for first-order or second-order unification of a type *)
(* against another type (e.g. apply) *)
(* We set all conversion flags (no flag should be modified anymore) *)
let default_unify_flags () =
let flags = default_core_unify_flags () in {
core_unify_flags = flags;
merge_unify_flags = flags;
subterm_unify_flags = { flags with modulo_delta = TransparentState.var_full };
allow_K_in_toplevel_higher_order_unification = false; (* Why not? *)
resolve_evars = false
}
let set_no_delta_core_flags flags = { flags with
modulo_conv_on_closed_terms = None;
modulo_delta = TransparentState.empty;
check_applied_meta_types = false;
use_pattern_unification = false;
use_meta_bound_pattern_unification = true;
modulo_betaiota = false
}
let set_no_delta_flags flags = {
core_unify_flags = set_no_delta_core_flags flags.core_unify_flags;
merge_unify_flags = set_no_delta_core_flags flags.merge_unify_flags;
subterm_unify_flags = set_no_delta_core_flags flags.subterm_unify_flags;
allow_K_in_toplevel_higher_order_unification =
flags.allow_K_in_toplevel_higher_order_unification;
resolve_evars = flags.resolve_evars
}
(* For the first phase of keyed unification, restrict
to conversion (including beta-iota) only on closed terms *)
let set_no_delta_open_core_flags flags = { flags with
modulo_delta = TransparentState.empty;
modulo_betaiota = false;
}
let set_no_delta_open_flags flags = {
core_unify_flags = set_no_delta_open_core_flags flags.core_unify_flags;
merge_unify_flags = set_no_delta_open_core_flags flags.merge_unify_flags;
subterm_unify_flags = set_no_delta_open_core_flags flags.subterm_unify_flags;
allow_K_in_toplevel_higher_order_unification =
flags.allow_K_in_toplevel_higher_order_unification;
resolve_evars = flags.resolve_evars
}
(* Default flag for the "simple apply" version of unification of a *)
(* type against a type (e.g. apply) *)
(* We set only the flags available at the time the new "apply" extended *)
(* out of "simple apply" *)
let default_no_delta_core_unify_flags () = { (default_core_unify_flags ()) with
modulo_delta = TransparentState.empty;
check_applied_meta_types = false;
use_pattern_unification = false;
use_meta_bound_pattern_unification = true;
modulo_betaiota = false;
}
let default_no_delta_unify_flags ts =
let flags = default_no_delta_core_unify_flags () in
let flags = { flags with
modulo_conv_on_closed_terms = Some ts;
modulo_delta_types = ts
} in
{
core_unify_flags = flags;
merge_unify_flags = flags;
subterm_unify_flags = flags;
allow_K_in_toplevel_higher_order_unification = false;
resolve_evars = false
}
(* Default flags for looking for subterms in elimination tactics *)
(* Not used in practice at the current date, to the exception of *)
(* allow_K) because only closed terms are involved in *)
(* induction/destruct/case/elim and w_unify_to_subterm_list does not *)
(* call w_unify for induction/destruct/case/elim (13/6/2011) *)
let elim_core_flags sigma = { (default_core_unify_flags ()) with
modulo_betaiota = false;
frozen_evars =
fold_undefined (fun evk _ evars -> Evar.Set.add evk evars)
sigma Evar.Set.empty;
}
let elim_flags_evars sigma =
let flags = elim_core_flags sigma in {
core_unify_flags = flags;
merge_unify_flags = flags;
subterm_unify_flags = { flags with modulo_delta = TransparentState.empty };
allow_K_in_toplevel_higher_order_unification = true;
resolve_evars = false
}
let elim_flags () = elim_flags_evars Evd.empty
let elim_no_delta_core_flags () = { (elim_core_flags Evd.empty) with
modulo_delta = TransparentState.empty;
check_applied_meta_types = false;
use_pattern_unification = false;
modulo_betaiota = false;
}
let elim_no_delta_flags () =
let flags = elim_no_delta_core_flags () in {
core_unify_flags = flags;
merge_unify_flags = flags;
subterm_unify_flags = flags;
allow_K_in_toplevel_higher_order_unification = true;
resolve_evars = false
}
(* On types, we don't restrict unification, but possibly for delta *)
let set_flags_for_type flags = { flags with
modulo_delta = flags.modulo_delta_types;
modulo_conv_on_closed_terms = Some flags.modulo_delta_types;
use_pattern_unification = true;
modulo_betaiota = true;
modulo_eta = true;
}
let use_evars_pattern_unification flags =
flags.use_pattern_unification
let use_metas_pattern_unification sigma flags nb l =
flags.use_pattern_unification
|| flags.use_meta_bound_pattern_unification &&
Array.for_all (fun c -> isRel sigma c && destRel sigma c <= nb) l
type key =
| IsKey of CClosure.table_key
| IsProj of Projection.t * EConstr.constr
let expand_table_key env = function
| ConstKey cst -> constant_opt_value_in env cst
| VarKey id -> (try named_body id env with Not_found -> None)
| RelKey _ -> None
let unfold_projection env p stk =
let s = Stack.Proj (p, Cst_stack.empty) in
s :: stk
let expand_key ts env sigma = function
| Some (IsKey k) -> Option.map EConstr.of_constr (expand_table_key env k)
| Some (IsProj (p, c)) ->
let red = Stack.zip sigma (fst (whd_betaiota_deltazeta_for_iota_state ts env sigma
Cst_stack.empty (c, unfold_projection env p [])))
in if EConstr.eq_constr sigma (EConstr.mkProj (p, c)) red then None else Some red
| None -> None
let isApp_or_Proj sigma c =
match kind sigma c with
| App _ | Proj _ -> true
| _ -> false
type unirec_flags = {
at_top: bool;
with_types: bool;
with_cs : bool;
}
let subterm_restriction opt flags =
not opt.at_top && flags.restrict_conv_on_strict_subterms
let key_of env sigma b flags f =
if subterm_restriction b flags then None else
match EConstr.kind sigma f with
| Const (cst, u) when is_transparent env (ConstKey cst) &&
(TransparentState.is_transparent_constant flags.modulo_delta cst
|| Recordops.is_primitive_projection cst) ->
let u = EInstance.kind sigma u in
Some (IsKey (ConstKey (cst, u)))
| Var id when is_transparent env (VarKey id) &&
TransparentState.is_transparent_variable flags.modulo_delta id ->
Some (IsKey (VarKey id))
| Proj (p, c) when Projection.unfolded p
|| (is_transparent env (ConstKey (Projection.constant p)) &&
(TransparentState.is_transparent_constant flags.modulo_delta (Projection.constant p))) ->
Some (IsProj (p, c))
| _ -> None
let translate_key = function
| ConstKey (cst,u) -> ConstKey cst
| VarKey id -> VarKey id
| RelKey n -> RelKey n
let translate_key = function
| IsKey k -> translate_key k
| IsProj (c, _) -> ConstKey (Projection.constant c)
let oracle_order env cf1 cf2 =
match cf1 with
| None ->
(match cf2 with
| None -> None
| Some k2 -> Some false)
| Some k1 ->
match cf2 with
| None -> Some true
| Some k2 ->
match k1, k2 with
| IsProj (p, _), IsKey (ConstKey (p',_))
when Constant.equal (Projection.constant p) p' ->
Some (not (Projection.unfolded p))
| IsKey (ConstKey (p,_)), IsProj (p', _)
when Constant.equal p (Projection.constant p') ->
Some (Projection.unfolded p')
| _ ->
Some (Conv_oracle.oracle_order (fun x -> x)
(Environ.oracle env) false (translate_key k1) (translate_key k2))
let is_rigid_head sigma flags t =
match EConstr.kind sigma t with
| Const (cst,u) -> not (TransparentState.is_transparent_constant flags.modulo_delta cst)
| Ind (i,u) -> true
| Construct _ | Int _ -> true
| Fix _ | CoFix _ -> true
| Rel _ | Var _ | Meta _ | Evar _ | Sort _ | Cast (_, _, _) | Prod _
| Lambda _ | LetIn _ | App (_, _) | Case (_, _, _, _)
| Proj (_, _) -> false (* Why aren't Prod, Sort rigid heads ? *)
let force_eqs c =
let open UnivProblem in
Set.fold
(fun c acc ->
let c' = match c with
(* Should we be forcing weak constraints? *)
| ULub (l, r) | UWeak (l, r) -> UEq (Univ.Universe.make l,Univ.Universe.make r)
| ULe _ | UEq _ -> c
in
Set.add c' acc)
c Set.empty
let constr_cmp pb env sigma flags t u =
let cstrs =
if pb == Reduction.CONV then EConstr.eq_constr_universes env sigma t u
else EConstr.leq_constr_universes env sigma t u
in
match cstrs with
| Some cstrs ->
begin try Some (Evd.add_universe_constraints sigma cstrs)
with Univ.UniverseInconsistency _ -> None
| Evd.UniversesDiffer ->
if is_rigid_head sigma flags t then
try Some (Evd.add_universe_constraints sigma (force_eqs cstrs))
with Univ.UniverseInconsistency _ -> None
else None
end
| None ->
None
let do_reduce ts (env, nb) sigma c =
Stack.zip sigma (fst (whd_betaiota_deltazeta_for_iota_state
ts env sigma Cst_stack.empty (c, Stack.empty)))
let isAllowedEvar sigma flags c = match EConstr.kind sigma c with
| Evar (evk,_) -> not (Evar.Set.mem evk flags.frozen_evars)
| _ -> false
let subst_defined_metas_evars sigma (bl,el) c =
(* This seems to be performance-critical, and using the
evar-insensitive primitives blow up the time passed in this
function. *)
let c = EConstr.Unsafe.to_constr c in
let rec substrec c = match Constr.kind c with
| Meta i ->
let select (j,_,_) = Int.equal i j in
substrec (EConstr.Unsafe.to_constr (pi2 (List.find select bl)))
| Evar (evk,args) ->
let eq c1 c2 = Constr.equal c1 (EConstr.Unsafe.to_constr c2) in
let select (_,(evk',args'),_) = Evar.equal evk evk' && Array.for_all2 eq args args' in
(try substrec (EConstr.Unsafe.to_constr (pi3 (List.find select el)))
with Not_found -> Constr.map substrec c)
| _ -> Constr.map substrec c
in try Some (EConstr.of_constr (substrec c)) with Not_found -> None
let check_compatibility env pbty flags (sigma,metasubst,evarsubst : subst0) tyM tyN =
match subst_defined_metas_evars sigma (metasubst,[]) tyM with
| None -> sigma
| Some m ->
match subst_defined_metas_evars sigma (metasubst,[]) tyN with
| None -> sigma
| Some n ->
if is_ground_term sigma m && is_ground_term sigma n then
match infer_conv ~pb:pbty ~ts:flags.modulo_delta_types env sigma m n with
| Some sigma -> sigma
| None -> error_cannot_unify env sigma (m,n)
else sigma
let rec is_neutral env sigma ts t =
let (f, l) = decompose_app_vect sigma t in
match EConstr.kind sigma f with
| Const (c, u) ->
not (Environ.evaluable_constant c env) ||
not (is_transparent env (ConstKey c)) ||
not (TransparentState.is_transparent_constant ts c)
| Var id ->
not (Environ.evaluable_named id env) ||
not (is_transparent env (VarKey id)) ||
not (TransparentState.is_transparent_variable ts id)
| Rel n -> true
| Evar _ | Meta _ -> true
| Case (_, p, c, cl) -> is_neutral env sigma ts c
| Proj (p, c) -> is_neutral env sigma ts c
| Lambda _ | LetIn _ | Construct _ | CoFix _ | Int _ -> false
| Sort _ | Cast (_, _, _) | Prod (_, _, _) | Ind _ -> false (* Really? *)
| Fix _ -> false (* This is an approximation *)
| App _ -> assert false
let is_eta_constructor_app env sigma ts f l1 term =
match EConstr.kind sigma f with
| Construct (((_, i as ind), j), u) when j == 1 ->
let open Declarations in
let mib = lookup_mind (fst ind) env in
(match mib.Declarations.mind_record with
| PrimRecord info when mib.Declarations.mind_finite == Declarations.BiFinite &&
let (_, projs, _, _) = info.(i) in
Array.length projs == Array.length l1 - mib.Declarations.mind_nparams ->
(* Check that the other term is neutral *)
is_neutral env sigma ts term
| _ -> false)
| _ -> false
let eta_constructor_app env sigma f l1 term =
match EConstr.kind sigma f with
| Construct (((_, i as ind), j), u) ->
let mib = lookup_mind (fst ind) env in
(match get_projections env ind with
| Some projs ->
let npars = mib.Declarations.mind_nparams in
let pars, l1' = Array.chop npars l1 in
let arg = Array.append pars [|term|] in
let l2 = Array.map (fun p -> mkApp (mkConstU (Projection.Repr.constant p,u), arg)) projs in
l1', l2
| _ -> assert false)
| _ -> assert false
let rec unify_0_with_initial_metas (sigma,ms,es as subst : subst0) conv_at_top env cv_pb flags m n =
let rec unirec_rec (curenv,nb as curenvnb) pb opt ((sigma,metasubst,evarsubst) as substn : subst0) curm curn =
let cM = Evarutil.whd_head_evar sigma curm
and cN = Evarutil.whd_head_evar sigma curn in
let () =
if !debug_unification then
Feedback.msg_debug (
Termops.Internal.print_constr_env curenv sigma cM ++ str" ~= " ++
Termops.Internal.print_constr_env curenv sigma cN)
in
match (EConstr.kind sigma cM, EConstr.kind sigma cN) with
| Meta k1, Meta k2 ->
if Int.equal k1 k2 then substn else
let stM,stN = extract_instance_status pb in
let sigma =
if opt.with_types && flags.check_applied_meta_types then
let tyM = Typing.meta_type sigma k1 in
let tyN = Typing.meta_type sigma k2 in
let l, r = if k2 < k1 then tyN, tyM else tyM, tyN in
check_compatibility curenv CUMUL flags substn l r
else sigma
in
if k2 < k1 then sigma,(k1,cN,stN)::metasubst,evarsubst
else sigma,(k2,cM,stM)::metasubst,evarsubst
| Meta k, _
when not (occur_metavariable sigma k cN) (* helps early trying alternatives *) ->
let sigma =
if opt.with_types && flags.check_applied_meta_types then
(try
let tyM = Typing.meta_type sigma k in
let tyN = get_type_of curenv ~lax:true sigma cN in
check_compatibility curenv CUMUL flags substn tyN tyM
with RetypeError _ ->
(* Renounce, maybe metas/evars prevents typing *) sigma)
else sigma
in
(* Here we check that [cN] does not contain any local variables *)
if Int.equal nb 0 then
sigma,(k,cN,snd (extract_instance_status pb))::metasubst,evarsubst
else if noccur_between sigma 1 nb cN then
(sigma,
(k,lift (-nb) cN,snd (extract_instance_status pb))::metasubst,
evarsubst)
else error_cannot_unify_local curenv sigma (m,n,cN)
| _, Meta k
when not (occur_metavariable sigma k cM) (* helps early trying alternatives *) ->
let sigma =
if opt.with_types && flags.check_applied_meta_types then
(try
let tyM = get_type_of curenv ~lax:true sigma cM in
let tyN = Typing.meta_type sigma k in
check_compatibility curenv CUMUL flags substn tyM tyN
with RetypeError _ ->
(* Renounce, maybe metas/evars prevents typing *) sigma)
else sigma
in
(* Here we check that [cM] does not contain any local variables *)
if Int.equal nb 0 then
(sigma,(k,cM,fst (extract_instance_status pb))::metasubst,evarsubst)
else if noccur_between sigma 1 nb cM
then
(sigma,(k,lift (-nb) cM,fst (extract_instance_status pb))::metasubst,
evarsubst)
else error_cannot_unify_local curenv sigma (m,n,cM)
| Evar (evk,_ as ev), Evar (evk',_)
when not (Evar.Set.mem evk flags.frozen_evars)
&& Evar.equal evk evk' ->
begin match constr_cmp cv_pb env sigma flags cM cN with
| Some sigma ->
sigma, metasubst, evarsubst
| None ->
sigma,metasubst,((curenv,ev,cN)::evarsubst)
end
| Evar (evk,_ as ev), _
when not (Evar.Set.mem evk flags.frozen_evars)
&& not (occur_evar sigma evk cN) ->
let cmvars = free_rels sigma cM and cnvars = free_rels sigma cN in
if Int.Set.subset cnvars cmvars then
sigma,metasubst,((curenv,ev,cN)::evarsubst)
else error_cannot_unify_local curenv sigma (m,n,cN)
| _, Evar (evk,_ as ev)
when not (Evar.Set.mem evk flags.frozen_evars)
&& not (occur_evar sigma evk cM) ->
let cmvars = free_rels sigma cM and cnvars = free_rels sigma cN in
if Int.Set.subset cmvars cnvars then
sigma,metasubst,((curenv,ev,cM)::evarsubst)
else error_cannot_unify_local curenv sigma (m,n,cN)
| Sort s1, Sort s2 ->
(try
let s1 = ESorts.kind sigma s1 in
let s2 = ESorts.kind sigma s2 in
let sigma' =
if pb == CUMUL
then Evd.set_leq_sort curenv sigma s1 s2
else Evd.set_eq_sort curenv sigma s1 s2
in (sigma', metasubst, evarsubst)
with e when CErrors.noncritical e ->
error_cannot_unify curenv sigma (m,n))
| Lambda (na,t1,c1), Lambda (__,t2,c2) ->
unirec_rec (push (na,t1) curenvnb) CONV {opt with at_top = true}
(unirec_rec curenvnb CONV {opt with at_top = true; with_types = false} substn t1 t2) c1 c2
| Prod (na,t1,c1), Prod (_,t2,c2) ->
unirec_rec (push (na,t1) curenvnb) pb {opt with at_top = true}
(unirec_rec curenvnb CONV {opt with at_top = true; with_types = false} substn t1 t2) c1 c2
| LetIn (_,a,_,c), _ -> unirec_rec curenvnb pb opt substn (subst1 a c) cN
| _, LetIn (_,a,_,c) -> unirec_rec curenvnb pb opt substn cM (subst1 a c)
(* Fast path for projections. *)
| Proj (p1,c1), Proj (p2,c2) when Constant.equal
(Projection.constant p1) (Projection.constant p2) ->
(try unify_same_proj curenvnb cv_pb {opt with at_top = true}
substn c1 c2
with ex when precatchable_exception ex ->
unify_not_same_head curenvnb pb opt substn cM cN)
(* eta-expansion *)
| Lambda (na,t1,c1), _ when flags.modulo_eta ->
unirec_rec (push (na,t1) curenvnb) CONV {opt with at_top = true} substn
c1 (mkApp (lift 1 cN,[|mkRel 1|]))
| _, Lambda (na,t2,c2) when flags.modulo_eta ->
unirec_rec (push (na,t2) curenvnb) CONV {opt with at_top = true} substn
(mkApp (lift 1 cM,[|mkRel 1|])) c2
(* For records *)
| App (f1, l1), _ when flags.modulo_eta &&
(* This ensures cN is an evar, meta or irreducible constant/variable
and not a constructor. *)
is_eta_constructor_app curenv sigma flags.modulo_delta f1 l1 cN ->
(try
let l1', l2' = eta_constructor_app curenv sigma f1 l1 cN in
let opt' = {opt with at_top = true; with_cs = false} in
Array.fold_left2 (unirec_rec curenvnb CONV opt') substn l1' l2'
with ex when precatchable_exception ex ->
match EConstr.kind sigma cN with
| App(f2,l2) when
(isMeta sigma f2 && use_metas_pattern_unification sigma flags nb l2
|| use_evars_pattern_unification flags && isAllowedEvar sigma flags f2) ->
unify_app_pattern false curenvnb pb opt substn cM f1 l1 cN f2 l2
| _ -> raise ex)
| _, App (f2, l2) when flags.modulo_eta &&
is_eta_constructor_app curenv sigma flags.modulo_delta f2 l2 cM ->
(try
let l2', l1' = eta_constructor_app curenv sigma f2 l2 cM in
let opt' = {opt with at_top = true; with_cs = false} in
Array.fold_left2 (unirec_rec curenvnb CONV opt') substn l1' l2'
with ex when precatchable_exception ex ->
match EConstr.kind sigma cM with
| App(f1,l1) when
(isMeta sigma f1 && use_metas_pattern_unification sigma flags nb l1
|| use_evars_pattern_unification flags && isAllowedEvar sigma flags f1) ->
unify_app_pattern true curenvnb pb opt substn cM f1 l1 cN f2 l2
| _ -> raise ex)
| Case (_,p1,c1,cl1), Case (_,p2,c2,cl2) ->
(try
let opt' = {opt with at_top = true; with_types = false} in
Array.fold_left2 (unirec_rec curenvnb CONV {opt with at_top = true})
(unirec_rec curenvnb CONV opt'
(unirec_rec curenvnb CONV opt' substn p1 p2) c1 c2)
cl1 cl2
with ex when precatchable_exception ex ->
reduce curenvnb pb opt substn cM cN)
| Fix ((ln1,i1),(lna1,tl1,bl1)), Fix ((ln2,i2),(_,tl2,bl2)) when
Int.equal i1 i2 && Array.equal Int.equal ln1 ln2 ->
(try
let opt' = {opt with at_top = true; with_types = false} in
let curenvnb' = Array.fold_right2 (fun na t -> push (na,t)) lna1 tl1 curenvnb in
Array.fold_left2 (unirec_rec curenvnb' CONV opt')
(Array.fold_left2 (unirec_rec curenvnb CONV opt') substn tl1 tl2) bl1 bl2
with ex when precatchable_exception ex ->
reduce curenvnb pb opt substn cM cN)
| CoFix (i1,(lna1,tl1,bl1)), CoFix (i2,(_,tl2,bl2)) when
Int.equal i1 i2 ->
(try
let opt' = {opt with at_top = true; with_types = false} in
let curenvnb' = Array.fold_right2 (fun na t -> push (na,t)) lna1 tl1 curenvnb in
Array.fold_left2 (unirec_rec curenvnb' CONV opt')
(Array.fold_left2 (unirec_rec curenvnb CONV opt') substn tl1 tl2) bl1 bl2
with ex when precatchable_exception ex ->
reduce curenvnb pb opt substn cM cN)
| App (f1,l1), _ when
(isMeta sigma f1 && use_metas_pattern_unification sigma flags nb l1
|| use_evars_pattern_unification flags && isAllowedEvar sigma flags f1) ->
unify_app_pattern true curenvnb pb opt substn cM f1 l1 cN cN [||]
| _, App (f2,l2) when
(isMeta sigma f2 && use_metas_pattern_unification sigma flags nb l2
|| use_evars_pattern_unification flags && isAllowedEvar sigma flags f2) ->
unify_app_pattern false curenvnb pb opt substn cM cM [||] cN f2 l2
| App (f1,l1), App (f2,l2) ->
unify_app curenvnb pb opt substn cM f1 l1 cN f2 l2
| App (f1,l1), Proj(p2,c2) ->
unify_app curenvnb pb opt substn cM f1 l1 cN cN [||]
| Proj (p1,c1), App(f2,l2) ->
unify_app curenvnb pb opt substn cM cM [||] cN f2 l2
| _ ->
unify_not_same_head curenvnb pb opt substn cM cN
and unify_app_pattern dir curenvnb pb opt (sigma, _, _ as substn) cM f1 l1 cN f2 l2 =
let f, l, t = if dir then f1, l1, cN else f2, l2, cM in
match is_unification_pattern curenvnb sigma f (Array.to_list l) t with
| None ->
(match EConstr.kind sigma t with
| App (f',l') ->
if dir then unify_app curenvnb pb opt substn cM f1 l1 t f' l'
else unify_app curenvnb pb opt substn t f' l' cN f2 l2
| Proj _ -> unify_app curenvnb pb opt substn cM f1 l1 cN f2 l2
| _ -> unify_not_same_head curenvnb pb opt substn cM cN)
| Some l ->
solve_pattern_eqn_array curenvnb f l t substn
and unify_app (curenv, nb as curenvnb) pb opt (sigma, metas, evars as substn : subst0) cM f1 l1 cN f2 l2 =
try
let needs_expansion p c' =
match EConstr.kind sigma c' with
| Meta _ -> true
| Evar _ -> true
| Const (c, u) -> Constant.equal c (Projection.constant p)
| _ -> false
in
let expand_proj c c' l =
match EConstr.kind sigma c with
| Proj (p, t) when not (Projection.unfolded p) && needs_expansion p c' ->
(try destApp sigma (Retyping.expand_projection curenv sigma p t (Array.to_list l))
with RetypeError _ -> (* Unification can be called on ill-typed terms, due
to FO and eta in particular, fail gracefully in that case *)
(c, l))
| _ -> (c, l)
in
let f1, l1 = expand_proj f1 f2 l1 in
let f2, l2 = expand_proj f2 f1 l2 in
let opta = {opt with at_top = true; with_types = false} in
let optf = {opt with at_top = true; with_types = true} in
let (f1,l1,f2,l2) = adjust_app_array_size f1 l1 f2 l2 in
if Array.length l1 == 0 then error_cannot_unify (fst curenvnb) sigma (cM,cN)
else
Array.fold_left2 (unirec_rec curenvnb CONV opta)
(unirec_rec curenvnb CONV optf substn f1 f2) l1 l2
with ex when precatchable_exception ex ->
try reduce curenvnb pb {opt with with_types = false} substn cM cN
with ex when precatchable_exception ex ->
try canonical_projections curenvnb pb opt cM cN substn
with ex when precatchable_exception ex ->
expand curenvnb pb {opt with with_types = false} substn cM f1 l1 cN f2 l2
and unify_same_proj (curenv, nb as curenvnb) cv_pb opt substn c1 c2 =
let substn = unirec_rec curenvnb CONV opt substn c1 c2 in
try (* Force unification of the types to fill in parameters *)
let ty1 = get_type_of curenv ~lax:true sigma c1 in
let ty2 = get_type_of curenv ~lax:true sigma c2 in
unify_0_with_initial_metas substn true curenv cv_pb
{ flags with modulo_conv_on_closed_terms = Some TransparentState.full;
modulo_delta = TransparentState.full;
modulo_eta = true;
modulo_betaiota = true }
ty1 ty2
with RetypeError _ -> substn
and unify_not_same_head curenvnb pb opt (sigma, metas, evars as substn : subst0) cM cN =
try canonical_projections curenvnb pb opt cM cN substn
with ex when precatchable_exception ex ->
match constr_cmp cv_pb env sigma flags cM cN with
| Some sigma -> (sigma, metas, evars)
| None ->
try reduce curenvnb pb opt substn cM cN
with ex when precatchable_exception ex ->
let (f1,l1) =
match EConstr.kind sigma cM with App (f,l) -> (f,l) | _ -> (cM,[||]) in
let (f2,l2) =
match EConstr.kind sigma cN with App (f,l) -> (f,l) | _ -> (cN,[||]) in
expand curenvnb pb opt substn cM f1 l1 cN f2 l2
and reduce curenvnb pb opt (sigma, metas, evars as substn) cM cN =
if flags.modulo_betaiota && not (subterm_restriction opt flags) then
let cM' = do_reduce flags.modulo_delta curenvnb sigma cM in
if not (EConstr.eq_constr sigma cM cM') then
unirec_rec curenvnb pb opt substn cM' cN
else
let cN' = do_reduce flags.modulo_delta curenvnb sigma cN in
if not (EConstr.eq_constr sigma cN cN') then
unirec_rec curenvnb pb opt substn cM cN'
else error_cannot_unify (fst curenvnb) sigma (cM,cN)
else error_cannot_unify (fst curenvnb) sigma (cM,cN)
and expand (curenv,_ as curenvnb) pb opt (sigma,metasubst,evarsubst as substn : subst0) cM f1 l1 cN f2 l2 =
let res =
(* Try full conversion on meta-free terms. *)
(* Back to 1995 (later on called trivial_unify in 2002), the
heuristic was to apply conversion on meta-free (but not
evar-free!) terms in all cases (i.e. for apply but also for
auto and rewrite, even though auto and rewrite did not use
modulo conversion in the rest of the unification
algorithm). By compatibility we need to support this
separately from the main unification algorithm *)
(* The exploitation of known metas has been added in May 2007
(it is used by apply and rewrite); it might now be redundant
with the support for delta-expansion (which is used
essentially for apply)... *)
if subterm_restriction opt flags then None else
match flags.modulo_conv_on_closed_terms with
| None -> None
| Some convflags ->
let subst = ((if flags.use_metas_eagerly_in_conv_on_closed_terms then metasubst else ms), (if flags.use_evars_eagerly_in_conv_on_closed_terms then evarsubst else es)) in
match subst_defined_metas_evars sigma subst cM with
| None -> (* some undefined Metas in cM *) None