-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevarconv.ml
1796 lines (1666 loc) · 74.8 KB
/
evarconv.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 Util
open Names
open Constr
open Termops
open Environ
open EConstr
open Context
open Vars
open Reduction
open Reductionops
open Recordops
open Evarutil
open Evardefine
open Evarsolve
open Evd
open Pretype_errors
module RelDecl = Context.Rel.Declaration
module NamedDecl = Context.Named.Declaration
type unify_flags = Evarsolve.unify_flags
type unify_fun = unify_flags ->
env -> evar_map -> conv_pb -> EConstr.constr -> EConstr.constr -> Evarsolve.unification_result
let default_transparent_state env = TransparentState.full
(* Conv_oracle.get_transp_state (Environ.oracle env) *)
let default_flags_of ?(subterm_ts=TransparentState.empty) ts =
{ modulo_betaiota = true;
open_ts = ts; closed_ts = ts; subterm_ts;
frozen_evars = Evar.Set.empty; with_cs = true;
allow_K_at_toplevel = true }
let default_flags env =
let ts = default_transparent_state env in
default_flags_of ts
let debug_unification = ref (false)
let () = Goptions.(declare_bool_option {
optdepr = false;
optname =
"Print states sent to Evarconv unification";
optkey = ["Debug";"Unification"];
optread = (fun () -> !debug_unification);
optwrite = (fun a -> debug_unification:=a);
})
let debug_ho_unification = ref (false)
let () = Goptions.(declare_bool_option {
optdepr = false;
optname =
"Print higher-order unification debug information";
optkey = ["Debug";"HO";"Unification"];
optread = (fun () -> !debug_ho_unification);
optwrite = (fun a -> debug_ho_unification:=a);
})
(*******************************************)
(* Functions to deal with impossible cases *)
(*******************************************)
let impossible_default_case env =
let type_of_id = Coqlib.lib_ref "core.IDProp.type" in
let c, ctx = UnivGen.fresh_global_instance env (Coqlib.(lib_ref "core.IDProp.idProp")) in
let (_, u) = Constr.destRef c in
Some (c, Constr.mkRef (type_of_id, u), ctx)
let coq_unit_judge =
let open Environ in
let make_judge c t = make_judge (EConstr.of_constr c) (EConstr.of_constr t) in
let na1 = make_annot (Name (Id.of_string "A")) Sorts.Relevant in
let na2 = make_annot (Name (Id.of_string "H")) Sorts.Relevant in
fun env ->
match impossible_default_case env with
| Some (id, type_of_id, ctx) ->
make_judge id type_of_id, ctx
| None ->
(* In case the constants id/ID are not defined *)
Environ.make_judge (mkLambda (na1,mkProp,mkLambda(na2,mkRel 1,mkRel 1)))
(mkProd (na1,mkProp,mkArrow (mkRel 1) Sorts.Relevant (mkRel 2))),
Univ.ContextSet.empty
let unfold_projection env evd ts p c =
let cst = Projection.constant p in
if TransparentState.is_transparent_constant ts cst then
Some (mkProj (Projection.unfold p, c))
else None
let eval_flexible_term ts env evd c =
match EConstr.kind evd c with
| Const (c, u) ->
if TransparentState.is_transparent_constant ts c
then Option.map EConstr.of_constr (constant_opt_value_in env (c, EInstance.kind evd u))
else None
| Rel n ->
(try match lookup_rel n env with
| RelDecl.LocalAssum _ -> None
| RelDecl.LocalDef (_,v,_) -> Some (lift n v)
with Not_found -> None)
| Var id ->
(try
if TransparentState.is_transparent_variable ts id then
env |> lookup_named id |> NamedDecl.get_value
else None
with Not_found -> None)
| LetIn (_,b,_,c) -> Some (subst1 b c)
| Lambda _ -> Some c
| Proj (p, c) ->
if Projection.unfolded p then assert false
else unfold_projection env evd ts p c
| _ -> assert false
type flex_kind_of_term =
| Rigid
| MaybeFlexible of EConstr.t (* reducible but not necessarily reduced *)
| Flexible of EConstr.existential
let is_frozen flags (evk, _) = Evar.Set.mem evk flags.frozen_evars
let flex_kind_of_term flags env evd c sk =
match EConstr.kind evd c with
| LetIn _ | Rel _ | Const _ | Var _ | Proj _ ->
Option.cata (fun x -> MaybeFlexible x) Rigid (eval_flexible_term flags.open_ts env evd c)
| Lambda _ when not (Option.is_empty (Stack.decomp sk)) ->
if flags.modulo_betaiota then MaybeFlexible c
else Rigid
| Evar ev ->
if is_frozen flags ev then Rigid
else Flexible ev
| Lambda _ | Prod _ | Sort _ | Ind _ | Construct _ | CoFix _ | Int _ -> Rigid
| Meta _ -> Rigid
| Fix _ -> Rigid (* happens when the fixpoint is partially applied *)
| Cast _ | App _ | Case _ -> assert false
let apprec_nohdbeta flags env evd c =
let (t,sk as appr) = Reductionops.whd_nored_state evd (c, []) in
if flags.modulo_betaiota && Stack.not_purely_applicative sk
then Stack.zip evd (fst (whd_betaiota_deltazeta_for_iota_state
flags.open_ts env evd Cst_stack.empty appr))
else c
let position_problem l2r = function
| CONV -> None
| CUMUL -> Some l2r
(* [occur_rigidly ev evd t] tests if the evar ev occurs in a rigid
context in t. Precondition: t has a rigid head and is not reducible.
That function is an under approximation of occur-check, it can return
false even if the occur-check would succeed on the normal form. This
means we might postpone unsolvable constraints which will ultimately
result in an occur-check after reductions. If it returns true, we
know that the occur-check would also return true on the normal form.
[t] is assumed to have a rigid head, which can
appear under a elimination context (e.g. application, match or projection).
In the inner recursive function, the result indicates if the term is
rigid (irreducible), normal (succession of constructors) or
potentially reducible. For applications, this means than an
occurrence of the evar in arguments should be looked at to find an
occur-check if the head is rigid or normal. For inductive
eliminations, only an occurrence in a rigid context of the
discriminee counts as a rigid occurrence overall, not a normal
occurrence which might disappear after reduction. *)
type result = Rigid of bool | Normal of bool | Reducible
let rigid_normal_occ = function Rigid b -> b | Normal b -> b | _ -> false
let occur_rigidly flags env evd (evk,_) t =
let rec aux t =
match EConstr.kind evd t with
| App (f, c) ->
(match aux f with
| Rigid b -> Rigid (b || Array.exists (fun x -> rigid_normal_occ (aux x)) c)
| Normal b -> Normal (b || Array.exists (fun x -> rigid_normal_occ (aux x)) c)
| Reducible -> Reducible)
| Construct _ -> Normal false
| Ind _ | Sort _ -> Rigid false
| Proj (p, c) ->
let cst = Projection.constant p in
let rigid = not (TransparentState.is_transparent_constant flags.open_ts cst) in
if rigid then aux c
else (* if the evar appears rigidly in c then this elimination
cannot reduce and we have a rigid occurrence, otherwise
we don't know. *)
(match aux c with
| Rigid _ as res -> res
| Normal b -> Reducible
| Reducible -> Reducible)
| Evar (evk',l as ev) ->
if Evar.equal evk evk' then Rigid true
else if is_frozen flags ev then
Rigid (Array.exists (fun x -> rigid_normal_occ (aux x)) l)
else Reducible
| Cast (p, _, _) -> aux p
| Lambda (na, t, b) -> aux b
| LetIn (na, _, _, b) -> aux b
| Const (c,_) ->
if TransparentState.is_transparent_constant flags.open_ts c then Reducible
else Rigid false
| Prod (_, b, t) ->
let b' = aux b and t' = aux t in
if rigid_normal_occ b' || rigid_normal_occ t' then Rigid true
else Reducible
| Rel _ | Var _ -> Reducible
| Case (_,_,c,_) ->
(match aux c with
| Rigid b -> Rigid b
| _ -> Reducible)
| Meta _ | Fix _ | CoFix _ | Int _ -> Reducible
in
match aux t with
| Rigid b -> b
| Normal b -> b
| Reducible -> false
(* [check_conv_record env sigma (t1,stack1) (t2,stack2)] tries to decompose
the problem (t1 stack1) = (t2 stack2) into a problem
stack1 = params1@[c1]@extra_args1
stack2 = us2@extra_args2
t1 params1 c1 = proji params (c xs)
t2 us2 = head us
extra_args1 = extra_args2
by finding a record R and an object c := [xs:bs](Build_R params v1..vn)
with vi = (head us), for which we know that the i-th projection proji
satisfies
proji params (c xs) = head us
Rem: such objects, usable for conversion, are defined in the objdef
table; practically, it amounts to "canonically" equip t2 into a
object c in structure R (since, if c1 were not an evar, the
projection would have been reduced) *)
let check_conv_record env sigma (t1,sk1) (t2,sk2) =
let (proji, u), arg = Termops.global_app_of_constr sigma t1 in
let canon_s,sk2_effective =
try
match EConstr.kind sigma t2 with
Prod (_,a,b) -> (* assert (l2=[]); *)
let _, a, b = destProd sigma t2 in
if noccurn sigma 1 b then
lookup_canonical_conversion (proji, Prod_cs),
(Stack.append_app [|a;pop b|] Stack.empty)
else raise Not_found
| Sort s ->
let s = ESorts.kind sigma s in
lookup_canonical_conversion
(proji, Sort_cs (Sorts.family s)),[]
| Proj (p, c) ->
let c2 = Globnames.ConstRef (Projection.constant p) in
let c = Retyping.expand_projection env sigma p c [] in
let _, args = destApp sigma c in
let sk2 = Stack.append_app args sk2 in
lookup_canonical_conversion (proji, Const_cs c2), sk2
| _ ->
let (c2, _) = Termops.global_of_constr sigma t2 in
lookup_canonical_conversion (proji, Const_cs c2),sk2
with Not_found ->
let (c, cs) = lookup_canonical_conversion (proji,Default_cs) in
(c,cs),[]
in
let t', { o_DEF = c; o_CTX = ctx; o_INJ=n; o_TABS = bs;
o_TPARAMS = params; o_NPARAMS = nparams; o_TCOMPS = us } = canon_s in
let us = List.map EConstr.of_constr us in
let params = List.map EConstr.of_constr params in
let params1, c1, extra_args1 =
match arg with
| Some c -> (* A primitive projection applied to c *)
let ty = Retyping.get_type_of ~lax:true env sigma c in
let (i,u), ind_args =
try Inductiveops.find_mrectype env sigma ty
with _ -> raise Not_found
in Stack.append_app_list ind_args Stack.empty, c, sk1
| None ->
match Stack.strip_n_app nparams sk1 with
| Some (params1, c1, extra_args1) -> params1, c1, extra_args1
| _ -> raise Not_found in
let us2,extra_args2 =
let l_us = List.length us in
if Int.equal l_us 0 then Stack.empty,sk2_effective
else match (Stack.strip_n_app (l_us-1) sk2_effective) with
| None -> raise Not_found
| Some (l',el,s') -> (l'@Stack.append_app [|el|] Stack.empty,s') in
let u, ctx' = UnivGen.fresh_instance_from ctx None in
let subst = Univ.make_inverse_instance_subst u in
let c = EConstr.of_constr c in
let c' = subst_univs_level_constr subst c in
let t' = EConstr.of_constr t' in
let t' = subst_univs_level_constr subst t' in
let bs' = List.map (EConstr.of_constr %> subst_univs_level_constr subst) bs in
let params = List.map (fun c -> subst_univs_level_constr subst c) params in
let us = List.map (fun c -> subst_univs_level_constr subst c) us in
let h, _ = decompose_app_vect sigma t' in
ctx',(h, t2),c',bs',(Stack.append_app_list params Stack.empty,params1),
(Stack.append_app_list us Stack.empty,us2),(extra_args1,extra_args2),c1,
(n, Stack.zip sigma (t2,sk2))
(* Precondition: one of the terms of the pb is an uninstantiated evar,
* possibly applied to arguments. *)
let join_failures evd1 evd2 e1 e2 =
match e1, e2 with
| _, CannotSolveConstraint (_,ProblemBeyondCapabilities) -> (evd1,e1)
| _ -> (evd2,e2)
let rec ise_try evd = function
[] -> assert false
| [f] -> f evd
| f1::l ->
match f1 evd with
| Success _ as x -> x
| UnifFailure (evd1,e1) ->
match ise_try evd l with
| Success _ as x -> x
| UnifFailure (evd2,e2) ->
let evd,e = join_failures evd1 evd2 e1 e2 in
UnifFailure (evd,e)
let ise_and evd l =
let rec ise_and i = function
[] -> assert false
| [f] -> f i
| f1::l ->
match f1 i with
| Success i' -> ise_and i' l
| UnifFailure _ as x -> x in
ise_and evd l
let ise_exact ise x1 x2 =
match ise x1 x2 with
| None, out -> out
| _, (UnifFailure _ as out) -> out
| Some _, Success i -> UnifFailure (i,NotSameArgSize)
let ise_array2 evd f v1 v2 =
let rec allrec i = function
| -1 -> Success i
| n ->
match f i v1.(n) v2.(n) with
| Success i' -> allrec i' (n-1)
| UnifFailure _ as x -> x in
let lv1 = Array.length v1 in
if Int.equal lv1 (Array.length v2) then allrec evd (pred lv1)
else UnifFailure (evd,NotSameArgSize)
(* Applicative node of stack are read from the outermost to the innermost
but are unified the other way. *)
let rec ise_app_stack2 env f evd sk1 sk2 =
match sk1,sk2 with
| Stack.App node1 :: q1, Stack.App node2 :: q2 ->
let (t1,l1) = Stack.decomp_node_last node1 q1 in
let (t2,l2) = Stack.decomp_node_last node2 q2 in
begin match ise_app_stack2 env f evd l1 l2 with
|(_,UnifFailure _) as x -> x
|x,Success i' -> x,f env i' CONV t1 t2
end
| _, _ -> (sk1,sk2), Success evd
(* This function tries to unify 2 stacks element by element. It works
from the end to the beginning. If it unifies a non empty suffix of
stacks but not the entire stacks, the first part of the answer is
Some(the remaining prefixes to tackle)) *)
let ise_stack2 no_app env evd f sk1 sk2 =
let rec ise_stack2 deep i sk1 sk2 =
let fail x = if deep then Some (List.rev sk1, List.rev sk2), Success i
else None, x in
match sk1, sk2 with
| [], [] -> None, Success i
| Stack.Case (_,t1,c1,_)::q1, Stack.Case (_,t2,c2,_)::q2 ->
(match f env i CONV t1 t2 with
| Success i' ->
(match ise_array2 i' (fun ii -> f env ii CONV) c1 c2 with
| Success i'' -> ise_stack2 true i'' q1 q2
| UnifFailure _ as x -> fail x)
| UnifFailure _ as x -> fail x)
| Stack.Proj (p1,_)::q1, Stack.Proj (p2,_)::q2 ->
if Projection.Repr.equal (Projection.repr p1) (Projection.repr p2)
then ise_stack2 true i q1 q2
else fail (UnifFailure (i, NotSameHead))
| Stack.Fix (((li1, i1),(_,tys1,bds1 as recdef1)),a1,_)::q1,
Stack.Fix (((li2, i2),(_,tys2,bds2)),a2,_)::q2 ->
if Int.equal i1 i2 && Array.equal Int.equal li1 li2 then
match ise_and i [
(fun i -> ise_array2 i (fun ii -> f env ii CONV) tys1 tys2);
(fun i -> ise_array2 i (fun ii -> f (push_rec_types recdef1 env) ii CONV) bds1 bds2);
(fun i -> ise_exact (ise_stack2 false i) a1 a2)] with
| Success i' -> ise_stack2 true i' q1 q2
| UnifFailure _ as x -> fail x
else fail (UnifFailure (i,NotSameHead))
| Stack.App _ :: _, Stack.App _ :: _ ->
if no_app && deep then fail ((*dummy*)UnifFailure(i,NotSameHead)) else
begin match ise_app_stack2 env f i sk1 sk2 with
|_,(UnifFailure _ as x) -> fail x
|(l1, l2), Success i' -> ise_stack2 true i' l1 l2
end
|_, _ -> fail (UnifFailure (i,(* Maybe improve: *) NotSameHead))
in ise_stack2 false evd (List.rev sk1) (List.rev sk2)
(* Make sure that the matching suffix is the all stack *)
let exact_ise_stack2 env evd f sk1 sk2 =
let rec ise_stack2 i sk1 sk2 =
match sk1, sk2 with
| [], [] -> Success i
| Stack.Case (_,t1,c1,_)::q1, Stack.Case (_,t2,c2,_)::q2 ->
ise_and i [
(fun i -> ise_stack2 i q1 q2);
(fun i -> ise_array2 i (fun ii -> f env ii CONV) c1 c2);
(fun i -> f env i CONV t1 t2)]
| Stack.Fix (((li1, i1),(_,tys1,bds1 as recdef1)),a1,_)::q1,
Stack.Fix (((li2, i2),(_,tys2,bds2)),a2,_)::q2 ->
if Int.equal i1 i2 && Array.equal Int.equal li1 li2 then
ise_and i [
(fun i -> ise_stack2 i q1 q2);
(fun i -> ise_array2 i (fun ii -> f env ii CONV) tys1 tys2);
(fun i -> ise_array2 i (fun ii -> f (push_rec_types recdef1 env) ii CONV) bds1 bds2);
(fun i -> ise_stack2 i a1 a2)]
else UnifFailure (i,NotSameHead)
| Stack.Proj (p1,_)::q1, Stack.Proj (p2,_)::q2 ->
if Projection.Repr.equal (Projection.repr p1) (Projection.repr p2)
then ise_stack2 i q1 q2
else (UnifFailure (i, NotSameHead))
| Stack.App _ :: _, Stack.App _ :: _ ->
begin match ise_app_stack2 env f i sk1 sk2 with
|_,(UnifFailure _ as x) -> x
|(l1, l2), Success i' -> ise_stack2 i' l1 l2
end
|_, _ -> UnifFailure (i,(* Maybe improve: *) NotSameHead)
in
if Reductionops.Stack.compare_shape sk1 sk2 then
ise_stack2 evd (List.rev sk1) (List.rev sk2)
else UnifFailure (evd, (* Dummy *) NotSameHead)
(* Add equality constraints for covariant/invariant positions. For
irrelevant positions, unify universes when flexible. *)
let compare_cumulative_instances evd variances u u' =
match Evarutil.compare_cumulative_instances CONV variances u u' evd with
| Inl evd ->
Success evd
| Inr p -> UnifFailure (evd, UnifUnivInconsistency p)
let conv_fun f flags on_types =
let typefn env evd pbty term1 term2 =
let flags = { (default_flags env) with
with_cs = flags.with_cs;
frozen_evars = flags.frozen_evars }
in f flags env evd pbty term1 term2
in
let termfn env evd pbty term1 term2 =
f flags env evd pbty term1 term2
in
match on_types with
| TypeUnification -> typefn
| TermUnification -> termfn
let rec evar_conv_x flags env evd pbty term1 term2 =
let term1 = whd_head_evar evd term1 in
let term2 = whd_head_evar evd term2 in
(* Maybe convertible but since reducing can erase evars which [evar_apprec]
could have found, we do it only if the terms are free of evar.
Note: incomplete heuristic... *)
let ground_test =
if is_ground_term evd term1 && is_ground_term evd term2 then (
let e =
match infer_conv ~catch_incon:false ~pb:pbty ~ts:flags.closed_ts env evd term1 term2 with
| Some evd -> Success evd
| None -> UnifFailure (evd, ConversionFailed (env,term1,term2))
| exception Univ.UniverseInconsistency e -> UnifFailure (evd, UnifUnivInconsistency e)
in
match e with
| UnifFailure (evd, e) when not (is_ground_env evd env) -> None
| _ -> Some e)
else None
in
match ground_test with
| Some result -> result
| None ->
(* Until pattern-unification is used consistently, use nohdbeta to not
destroy beta-redexes that can be used for 1st-order unification *)
let term1 = apprec_nohdbeta flags env evd term1 in
let term2 = apprec_nohdbeta flags env evd term2 in
let default () =
evar_eqappr_x flags env evd pbty
(whd_nored_state evd (term1,Stack.empty), Cst_stack.empty)
(whd_nored_state evd (term2,Stack.empty), Cst_stack.empty)
in
begin match EConstr.kind evd term1, EConstr.kind evd term2 with
| Evar ev, _ when Evd.is_undefined evd (fst ev) && not (is_frozen flags ev) ->
(match solve_simple_eqn (conv_fun evar_conv_x) flags env evd
(position_problem true pbty,ev,term2) with
| UnifFailure (_,(OccurCheck _ | NotClean _)) ->
(* Eta-expansion might apply *)
(* OccurCheck: eta-expansion could solve
?X = {| foo := ?X.(foo) |}
NotClean: pruning in solve_simple_eqn is incomplete wrt
Miller patterns *)
default ()
| x -> x)
| _, Evar ev when Evd.is_undefined evd (fst ev) && not (is_frozen flags ev) ->
(match solve_simple_eqn (conv_fun evar_conv_x) flags env evd
(position_problem false pbty,ev,term1) with
| UnifFailure (_, (OccurCheck _ | NotClean _)) ->
(* OccurCheck: eta-expansion could solve
?X = {| foo := ?X.(foo) |}
NotClean: pruning in solve_simple_eqn is incomplete wrt
Miller patterns *)
default ()
| x -> x)
| _ -> default ()
end
and evar_eqappr_x ?(rhs_is_already_stuck = false) flags env evd pbty
((term1,sk1 as appr1),csts1) ((term2,sk2 as appr2),csts2) =
let quick_fail i = (* not costly, loses info *)
UnifFailure (i, NotSameHead)
in
let miller_pfenning on_left fallback ev lF tM evd =
match is_unification_pattern_evar env evd ev lF tM with
| None -> fallback ()
| Some l1' -> (* Miller-Pfenning's patterns unification *)
let t2 = tM in
let t2 = solve_pattern_eqn env evd l1' t2 in
solve_simple_eqn (conv_fun evar_conv_x) flags env evd
(position_problem on_left pbty,ev,t2)
in
let consume_stack on_left (termF,skF) (termO,skO) evd =
let switch f a b = if on_left then f a b else f b a in
let not_only_app = Stack.not_purely_applicative skO in
match switch (ise_stack2 not_only_app env evd (evar_conv_x flags)) skF skO with
|Some (l,r), Success i' when on_left && (not_only_app || List.is_empty l) ->
switch (evar_conv_x flags env i' pbty) (Stack.zip evd (termF,l)) (Stack.zip evd (termO,r))
|Some (r,l), Success i' when not on_left && (not_only_app || List.is_empty l) ->
switch (evar_conv_x flags env i' pbty) (Stack.zip evd (termF,l)) (Stack.zip evd (termO,r))
|None, Success i' -> switch (evar_conv_x flags env i' pbty) termF termO
|_, (UnifFailure _ as x) -> x
|Some _, _ -> UnifFailure (evd,NotSameArgSize) in
let eta env evd onleft sk term sk' term' =
assert (match sk with [] -> true | _ -> false);
let (na,c1,c'1) = destLambda evd term in
let c = nf_evar evd c1 in
let env' = push_rel (RelDecl.LocalAssum (na,c)) env in
let out1 = whd_betaiota_deltazeta_for_iota_state
flags.open_ts env' evd Cst_stack.empty (c'1, Stack.empty) in
let out2 = whd_nored_state evd
(lift 1 (Stack.zip evd (term', sk')), Stack.append_app [|EConstr.mkRel 1|] Stack.empty),
Cst_stack.empty in
if onleft then evar_eqappr_x flags env' evd CONV out1 out2
else evar_eqappr_x flags env' evd CONV out2 out1
in
let rigids env evd sk term sk' term' =
let check_strict evd u u' =
let cstrs = Univ.enforce_eq_instances u u' Univ.Constraint.empty in
try Success (Evd.add_constraints evd cstrs)
with Univ.UniverseInconsistency p -> UnifFailure (evd, UnifUnivInconsistency p)
in
let compare_heads evd =
match EConstr.kind evd term, EConstr.kind evd term' with
| Const (c, u), Const (c', u') when Constant.equal c c' ->
let u = EInstance.kind evd u and u' = EInstance.kind evd u' in
check_strict evd u u'
| Const _, Const _ -> UnifFailure (evd, NotSameHead)
| Ind ((mi,i) as ind , u), Ind (ind', u') when Names.eq_ind ind ind' ->
if EInstance.is_empty u && EInstance.is_empty u' then Success evd
else
let u = EInstance.kind evd u and u' = EInstance.kind evd u' in
let mind = Environ.lookup_mind mi env in
let open Declarations in
begin match mind.mind_variance with
| None -> check_strict evd u u'
| Some variances ->
let nparamsaplied = Stack.args_size sk in
let nparamsaplied' = Stack.args_size sk' in
let needed = Reduction.inductive_cumulativity_arguments (mind,i) in
if not (Int.equal nparamsaplied needed && Int.equal nparamsaplied' needed)
then check_strict evd u u'
else
compare_cumulative_instances evd variances u u'
end
| Ind _, Ind _ -> UnifFailure (evd, NotSameHead)
| Construct (((mi,ind),ctor as cons), u), Construct (cons', u')
when Names.eq_constructor cons cons' ->
if EInstance.is_empty u && EInstance.is_empty u' then Success evd
else
let u = EInstance.kind evd u and u' = EInstance.kind evd u' in
let mind = Environ.lookup_mind mi env in
let open Declarations in
begin match mind.mind_variance with
| None -> check_strict evd u u'
| Some variances ->
let nparamsaplied = Stack.args_size sk in
let nparamsaplied' = Stack.args_size sk' in
let needed = Reduction.constructor_cumulativity_arguments (mind,ind,ctor) in
if not (Int.equal nparamsaplied needed && Int.equal nparamsaplied' needed)
then check_strict evd u u'
else
Success (compare_constructor_instances evd u u')
end
| Construct _, Construct _ -> UnifFailure (evd, NotSameHead)
| _, _ -> anomaly (Pp.str "")
in
ise_and evd [(fun i ->
try compare_heads i
with Univ.UniverseInconsistency p -> UnifFailure (i, UnifUnivInconsistency p));
(fun i -> exact_ise_stack2 env i (evar_conv_x flags) sk sk')]
in
let consume on_left (_, skF as apprF) (_,skM as apprM) i =
if not (Stack.is_empty skF && Stack.is_empty skM) then
consume_stack on_left apprF apprM i
else quick_fail i
in
let miller on_left ev (termF,skF as apprF) (termM, skM as apprM) i =
let switch f a b = if on_left then f a b else f b a in
let not_only_app = Stack.not_purely_applicative skM in
match Stack.list_of_app_stack skF with
| None -> quick_fail evd
| Some lF ->
let tM = Stack.zip evd apprM in
miller_pfenning on_left
(fun () -> if not_only_app then (* Postpone the use of an heuristic *)
switch (fun x y -> Success (Evarutil.add_unification_pb (pbty,env,x,y) i)) (Stack.zip evd apprF) tM
else quick_fail i)
ev lF tM i
in
let flex_maybeflex on_left ev ((termF,skF as apprF),cstsF) ((termM, skM as apprM),cstsM) vM =
let switch f a b = if on_left then f a b else f b a in
let delta i =
switch (evar_eqappr_x flags env i pbty) (apprF,cstsF)
(whd_betaiota_deltazeta_for_iota_state flags.open_ts env i cstsM (vM,skM))
in
let default i = ise_try i [miller on_left ev apprF apprM;
consume on_left apprF apprM;
delta]
in
match EConstr.kind evd termM with
| Proj (p, c) when not (Stack.is_empty skF) ->
(* Might be ?X args = p.c args', and we have to eta-expand the
primitive projection if |args| >= |args'|+1. *)
let nargsF = Stack.args_size skF and nargsM = Stack.args_size skM in
begin
(* ?X argsF' ~= (p.c ..) argsM' -> ?X ~= (p.c ..), no need to expand *)
if nargsF <= nargsM then default evd
else
let f =
try
let termM' = Retyping.expand_projection env evd p c [] in
let apprM', cstsM' =
whd_betaiota_deltazeta_for_iota_state flags.open_ts env evd cstsM (termM',skM)
in
let delta' i =
switch (evar_eqappr_x flags env i pbty) (apprF,cstsF) (apprM',cstsM')
in
fun i -> ise_try i [miller on_left ev apprF apprM';
consume on_left apprF apprM'; delta']
with Retyping.RetypeError _ ->
(* Happens thanks to w_unify building ill-typed terms *)
default
in f evd
end
| _ -> default evd
in
let flex_rigid on_left ev (termF, skF as apprF) (termR, skR as apprR) =
let switch f a b = if on_left then f a b else f b a in
let eta evd =
match EConstr.kind evd termR with
| Lambda _ when (* if ever problem is ill-typed: *) List.is_empty skR ->
eta env evd false skR termR skF termF
| Construct u -> eta_constructor flags env evd skR u skF termF
| _ -> UnifFailure (evd,NotSameHead)
in
match Stack.list_of_app_stack skF with
| None ->
ise_try evd [consume_stack on_left apprF apprR; eta]
| Some lF ->
let tR = Stack.zip evd apprR in
miller_pfenning on_left
(fun () ->
ise_try evd
[eta;(* Postpone the use of an heuristic *)
(fun i ->
if not (occur_rigidly flags env i ev tR) then
let i,tF =
if isRel i tR || isVar i tR then
(* Optimization so as to generate candidates *)
let i,ev = evar_absorb_arguments env i ev lF in
i,mkEvar ev
else
i,Stack.zip evd apprF in
switch (fun x y -> Success (Evarutil.add_unification_pb (pbty,env,x,y) i))
tF tR
else
UnifFailure (evd,OccurCheck (fst ev,tR)))])
ev lF tR evd
in
let first_order env i t1 t2 sk1 sk2 =
(* Try first-order unification *)
match ise_stack2 false env i (evar_conv_x flags) sk1 sk2 with
| None, Success i' ->
(* We do have sk1[] = sk2[]: we now unify ?ev1 and ?ev2 *)
(* Note that ?ev1 and ?ev2, may have been instantiated in the meantime *)
let ev1' = whd_evar i' t1 in
if isEvar i' ev1' then
solve_simple_eqn (conv_fun evar_conv_x) flags env i'
(position_problem true pbty,destEvar i' ev1',term2)
else
evar_eqappr_x flags env evd pbty
((ev1', sk1), csts1) ((term2, sk2), csts2)
| Some (r,[]), Success i' ->
(* We have sk1'[] = sk2[] for some sk1' s.t. sk1[]=sk1'[r[]] *)
(* we now unify r[?ev1] and ?ev2 *)
let ev2' = whd_evar i' t2 in
if isEvar i' ev2' then
solve_simple_eqn (conv_fun evar_conv_x) flags env i'
(position_problem false pbty,destEvar i' ev2',Stack.zip i' (term1,r))
else
evar_eqappr_x flags env evd pbty
((ev2', sk1), csts1) ((term2, sk2), csts2)
| Some ([],r), Success i' ->
(* Symmetrically *)
(* We have sk1[] = sk2'[] for some sk2' s.t. sk2[]=sk2'[r[]] *)
(* we now unify ?ev1 and r[?ev2] *)
let ev1' = whd_evar i' t1 in
if isEvar i' ev1' then
solve_simple_eqn (conv_fun evar_conv_x) flags env i'
(position_problem true pbty,destEvar i' ev1',Stack.zip i' (term2,r))
else evar_eqappr_x flags env evd pbty
((ev1', sk1), csts1) ((term2, sk2), csts2)
| None, (UnifFailure _ as x) ->
(* sk1 and sk2 have no common outer part *)
if Stack.not_purely_applicative sk2 then
(* Ad hoc compatibility with 8.4 which treated non-app as rigid *)
flex_rigid true (destEvar evd t1) appr1 appr2
else
if Stack.not_purely_applicative sk1 then
(* Ad hoc compatibility with 8.4 which treated non-app as rigid *)
flex_rigid false (destEvar evd t2) appr2 appr1
else
(* We could instead try Miller unification, then
postpone to see if other equations help, as in:
[Check fun a b : unit => (eqᵣefl : _ a = _ a b)] *)
x
| Some _, Success _ ->
(* sk1 and sk2 have a common outer part *)
if Stack.not_purely_applicative sk2 then
(* Ad hoc compatibility with 8.4 which treated non-app as rigid *)
flex_rigid true (destEvar evd t1) appr1 appr2
else
if Stack.not_purely_applicative sk1 then
(* Ad hoc compatibility with 8.4 which treated non-app as rigid *)
flex_rigid false (destEvar evd t2) appr2 appr1
else
(* We could instead try Miller unification, then
postpone to see if other equations help, as in:
[Check fun a b c : unit => (eqᵣefl : _ a b = _ c a b)] *)
UnifFailure (i,NotSameArgSize)
| _, _ -> anomaly (Pp.str "Unexpected result from ise_stack2.")
in
let app_empty = match sk1, sk2 with [], [] -> true | _ -> false in
(* Evar must be undefined since we have flushed evars *)
let () = if !debug_unification then
let open Pp in
Feedback.msg_notice (v 0 (pr_state env evd appr1 ++ cut () ++ pr_state env evd appr2 ++ cut ())) in
match (flex_kind_of_term flags env evd term1 sk1,
flex_kind_of_term flags env evd term2 sk2) with
| Flexible (sp1,al1), Flexible (sp2,al2) ->
(* sk1[?ev1] =? sk2[?ev2] *)
let f1 i = first_order env i term1 term2 sk1 sk2
and f2 i =
if Evar.equal sp1 sp2 then
match ise_stack2 false env i (evar_conv_x flags) sk1 sk2 with
|None, Success i' ->
Success (solve_refl (fun flags p env i pbty a1 a2 ->
let flags =
match p with
| TypeUnification -> default_flags env
| TermUnification -> flags
in
is_success (evar_conv_x flags env i pbty a1 a2)) flags
env i' (position_problem true pbty) sp1 al1 al2)
|_, (UnifFailure _ as x) -> x
|Some _, _ -> UnifFailure (i,NotSameArgSize)
else UnifFailure (i,NotSameHead)
and f3 i = miller true (sp1,al1) appr1 appr2 i
and f4 i = miller false (sp2,al2) appr2 appr1 i
and f5 i =
(* We ensure failure of consuming the stacks does not
propagate an error about unification of the stacks while
the heads themselves cannot be unified, so we return
NotSameHead. *)
match consume true appr1 appr2 i with
| Success _ as x -> x
| UnifFailure _ -> quick_fail i
in
ise_try evd [f1; f2; f3; f4; f5]
| Flexible ev1, MaybeFlexible v2 ->
flex_maybeflex true ev1 (appr1,csts1) (appr2,csts2) v2
| MaybeFlexible v1, Flexible ev2 ->
flex_maybeflex false ev2 (appr2,csts2) (appr1,csts1) v1
| MaybeFlexible v1, MaybeFlexible v2 -> begin
match EConstr.kind evd term1, EConstr.kind evd term2 with
| LetIn (na1,b1,t1,c'1), LetIn (na2,b2,t2,c'2) ->
let f1 i = (* FO *)
ise_and i
[(fun i -> ise_try i
[(fun i -> evar_conv_x flags env i CUMUL t1 t2);
(fun i -> evar_conv_x flags env i CUMUL t2 t1)]);
(fun i -> evar_conv_x flags env i CONV b1 b2);
(fun i ->
let b = nf_evar i b1 in
let t = nf_evar i t1 in
let na = Nameops.Name.pick_annot na1 na2 in
evar_conv_x flags (push_rel (RelDecl.LocalDef (na,b,t)) env) i pbty c'1 c'2);
(fun i -> exact_ise_stack2 env i (evar_conv_x flags) sk1 sk2)]
and f2 i =
let out1 = whd_betaiota_deltazeta_for_iota_state flags.open_ts env i csts1 (v1,sk1)
and out2 = whd_betaiota_deltazeta_for_iota_state flags.open_ts env i csts2 (v2,sk2)
in evar_eqappr_x flags env i pbty out1 out2
in
ise_try evd [f1; f2]
| Proj (p, c), Proj (p', c') when Projection.repr_equal p p' ->
let f1 i =
ise_and i
[(fun i -> evar_conv_x flags env i CONV c c');
(fun i -> exact_ise_stack2 env i (evar_conv_x flags) sk1 sk2)]
and f2 i =
let out1 = whd_betaiota_deltazeta_for_iota_state flags.open_ts env i csts1 (v1,sk1)
and out2 = whd_betaiota_deltazeta_for_iota_state flags.open_ts env i csts2 (v2,sk2)
in evar_eqappr_x flags env i pbty out1 out2
in
ise_try evd [f1; f2]
(* Catch the p.c ~= p c' cases *)
| Proj (p,c), Const (p',u) when Constant.equal (Projection.constant p) p' ->
let res =
try Some (destApp evd (Retyping.expand_projection env evd p c []))
with Retyping.RetypeError _ -> None
in
(match res with
| Some (f1,args1) ->
evar_eqappr_x flags env evd pbty ((f1,Stack.append_app args1 sk1),csts1)
(appr2,csts2)
| None -> UnifFailure (evd,NotSameHead))
| Const (p,u), Proj (p',c') when Constant.equal p (Projection.constant p') ->
let res =
try Some (destApp evd (Retyping.expand_projection env evd p' c' []))
with Retyping.RetypeError _ -> None
in
(match res with
| Some (f2,args2) ->
evar_eqappr_x flags env evd pbty (appr1,csts1) ((f2,Stack.append_app args2 sk2),csts2)
| None -> UnifFailure (evd,NotSameHead))
| _, _ ->
let f1 i =
(* Gather the universe constraints that would make term1 and term2 equal.
If these only involve unifications of flexible universes to other universes,
allow this identification (first-order unification of universes). Otherwise
fallback to unfolding.
*)
let univs = EConstr.eq_constr_universes env evd term1 term2 in
match univs with
| Some univs ->
ise_and i [(fun i ->
try Success (Evd.add_universe_constraints i univs)
with UniversesDiffer -> UnifFailure (i,NotSameHead)
| Univ.UniverseInconsistency p -> UnifFailure (i, UnifUnivInconsistency p));
(fun i -> exact_ise_stack2 env i (evar_conv_x flags) sk1 sk2)]
| None ->
UnifFailure (i,NotSameHead)
and f2 i =
(try
if not flags.with_cs then raise Not_found
else conv_record flags env i
(try check_conv_record env i appr1 appr2
with Not_found -> check_conv_record env i appr2 appr1)
with Not_found -> UnifFailure (i,NoCanonicalStructure))
and f3 i =
(* heuristic: unfold second argument first, exception made
if the first argument is a beta-redex (expand a constant
only if necessary) or the second argument is potentially
usable as a canonical projection or canonical value *)
let rec is_unnamed (hd, args) = match EConstr.kind i hd with
| (Var _|Construct _|Ind _|Const _|Prod _|Sort _|Int _) ->
Stack.not_purely_applicative args
| (CoFix _|Meta _|Rel _)-> true
| Evar _ -> Stack.not_purely_applicative args
(* false (* immediate solution without Canon Struct *)*)
| Lambda _ -> assert (match args with [] -> true | _ -> false); true
| LetIn (_,b,_,c) -> is_unnamed
(fst (whd_betaiota_deltazeta_for_iota_state
flags.open_ts env i Cst_stack.empty (subst1 b c, args)))
| Fix _ -> true (* Partially applied fix can be the result of a whd call *)
| Proj (p, _) -> Projection.unfolded p || Stack.not_purely_applicative args
| Case _ | App _| Cast _ -> assert false in
let rhs_is_stuck_and_unnamed () =
let applicative_stack = fst (Stack.strip_app sk2) in
is_unnamed
(fst (whd_betaiota_deltazeta_for_iota_state
flags.open_ts env i Cst_stack.empty (v2, applicative_stack))) in
let rhs_is_already_stuck =
rhs_is_already_stuck || rhs_is_stuck_and_unnamed () in
if (EConstr.isLambda i term1 || rhs_is_already_stuck)
&& (not (Stack.not_purely_applicative sk1)) then
evar_eqappr_x ~rhs_is_already_stuck flags env i pbty
(whd_betaiota_deltazeta_for_iota_state
flags.open_ts env i (Cst_stack.add_cst term1 csts1) (v1,sk1))
(appr2,csts2)
else
evar_eqappr_x flags env i pbty (appr1,csts1)
(whd_betaiota_deltazeta_for_iota_state
flags.open_ts env i (Cst_stack.add_cst term2 csts2) (v2,sk2))
in
ise_try evd [f1; f2; f3]
end
| Rigid, Rigid when EConstr.isLambda evd term1 && EConstr.isLambda evd term2 ->
let (na1,c1,c'1) = EConstr.destLambda evd term1 in
let (na2,c2,c'2) = EConstr.destLambda evd term2 in
ise_and evd
[(fun i -> evar_conv_x flags env i CONV c1 c2);
(fun i ->
let c = nf_evar i c1 in
let na = Nameops.Name.pick_annot na1 na2 in
evar_conv_x flags (push_rel (RelDecl.LocalAssum (na,c)) env) i CONV c'1 c'2);
(* When in modulo_betaiota = false case, lambda's are not reduced *)
(fun i -> exact_ise_stack2 env i (evar_conv_x flags) sk1 sk2)]
| Flexible ev1, Rigid -> flex_rigid true ev1 appr1 appr2
| Rigid, Flexible ev2 -> flex_rigid false ev2 appr2 appr1
| MaybeFlexible v1, Rigid ->
let f3 i =
(try
if not flags.with_cs then raise Not_found
else conv_record flags env i (check_conv_record env i appr1 appr2)
with Not_found -> UnifFailure (i,NoCanonicalStructure))
and f4 i =
evar_eqappr_x flags env i pbty
(whd_betaiota_deltazeta_for_iota_state
flags.open_ts env i (Cst_stack.add_cst term1 csts1) (v1,sk1))
(appr2,csts2)
in
ise_try evd [f3; f4]
| Rigid, MaybeFlexible v2 ->
let f3 i =
(try
if not flags.with_cs then raise Not_found
else conv_record flags env i (check_conv_record env i appr2 appr1)
with Not_found -> UnifFailure (i,NoCanonicalStructure))
and f4 i =
evar_eqappr_x flags env i pbty (appr1,csts1)
(whd_betaiota_deltazeta_for_iota_state
flags.open_ts env i (Cst_stack.add_cst term2 csts2) (v2,sk2))
in
ise_try evd [f3; f4]
(* Eta-expansion *)
| Rigid, _ when isLambda evd term1 && (* if ever ill-typed: *) List.is_empty sk1 ->
eta env evd true sk1 term1 sk2 term2
| _, Rigid when isLambda evd term2 && (* if ever ill-typed: *) List.is_empty sk2 ->
eta env evd false sk2 term2 sk1 term1
| Rigid, Rigid -> begin
match EConstr.kind evd term1, EConstr.kind evd term2 with
| Sort s1, Sort s2 when app_empty ->
(try
let s1 = ESorts.kind evd s1 in
let s2 = ESorts.kind evd s2 in
let evd' =
if pbty == CONV
then Evd.set_eq_sort env evd s1 s2
else Evd.set_leq_sort env evd s1 s2
in Success evd'
with Univ.UniverseInconsistency p ->
UnifFailure (evd,UnifUnivInconsistency p)
| e when CErrors.noncritical e -> UnifFailure (evd,NotSameHead))