-
Notifications
You must be signed in to change notification settings - Fork 631
/
equality.ml
1987 lines (1735 loc) · 76.4 KB
/
equality.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 * Copyright INRIA, CNRS and contributors *)
(* <O___,, * (see version control and CREDITS file for authors & dates) *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
module CVars = Vars
open Pp
open CErrors
open Util
open Names
open Nameops
open Term
open Constr
open Context
open Termops
open EConstr
open Vars
open Namegen
open Inductive
open Inductiveops
open Libnames
open Globnames
open Reductionops
open Typing
open Retyping
open Tacmach
open Logic
open Hipattern
open Tacticals
open Tactics
open Tacred
open Coqlib
open Declarations
open Indrec
open Ind_tables
open Eqschemes
open Locus
open Locusops
open Tactypes
open Proofview.Notations
open Unification
open Context.Named.Declaration
module NamedDecl = Context.Named.Declaration
(* Options *)
type inj_flags = {
keep_proof_equalities : bool;
injection_pattern_l2r_order : bool;
}
open Goptions
let use_injection_pattern_l2r_order = function
| None -> true
| Some flags -> flags.injection_pattern_l2r_order
let { Goptions.get = injection_in_context_flag } =
declare_bool_option_and_ref
~key:["Structural";"Injection"]
~value:false
()
(* Rewriting tactics *)
type dep_proof_flag = bool (* true = support rewriting dependent proofs *)
type freeze_evars_flag = bool (* true = don't instantiate existing evars *)
type orientation = bool
type conditions =
| Naive (* Only try the first occurrence of the lemma (default) *)
| FirstSolved (* Use the first match whose side-conditions are solved *)
| AllMatches (* Rewrite all matches whose side-conditions are solved *)
(* Warning : rewriting from left to right only works
if there exists in the context a theorem named <eqname>_<suffsort>_r
with type (A:<sort>)(x:A)(P:A->Prop)(P x)->(y:A)(eqname A y x)->(P y).
If another equality myeq is introduced, then corresponding theorems
myeq_ind_r, myeq_rec_r and myeq_rect_r have to be proven. See below.
-- Eduardo (19/8/97)
*)
let rewrite_core_unif_flags = {
modulo_conv_on_closed_terms = None;
use_metas_eagerly_in_conv_on_closed_terms = true;
use_evars_eagerly_in_conv_on_closed_terms = false;
modulo_delta = TransparentState.empty;
modulo_delta_types = TransparentState.empty;
check_applied_meta_types = true;
use_pattern_unification = true;
use_meta_bound_pattern_unification = true;
allowed_evars = Evarsolve.AllowedEvars.all;
restrict_conv_on_strict_subterms = false;
modulo_betaiota = false;
modulo_eta = true;
}
let rewrite_unif_flags = {
core_unify_flags = rewrite_core_unif_flags;
merge_unify_flags = rewrite_core_unif_flags;
subterm_unify_flags = rewrite_core_unif_flags;
allow_K_in_toplevel_higher_order_unification = false;
(* allow_K does not matter in practice because calls w_typed_unify *)
resolve_evars = true
}
let freeze_initial_evars sigma flags newevars =
let initial = Evd.undefined_map sigma in
let allowed evk =
if Evar.Map.mem evk initial then false
else Evar.Set.mem evk (Lazy.force newevars)
in
let allowed_evars = Evarsolve.AllowedEvars.from_pred allowed in
{flags with
core_unify_flags = {flags.core_unify_flags with allowed_evars};
merge_unify_flags = {flags.merge_unify_flags with allowed_evars};
subterm_unify_flags = {flags.subterm_unify_flags with allowed_evars}}
let make_flags frzevars sigma flags newevars =
if frzevars then freeze_initial_evars sigma flags newevars else flags
let side_tac tac sidetac =
match sidetac with
| None -> tac
| Some sidetac -> tclTHENSFIRSTn tac [|Proofview.tclUNIT ()|] sidetac
let instantiate_lemma_all env flags eqclause l2r concl =
let (_, args) = decompose_app (Clenv.clenv_evd eqclause) (Clenv.clenv_type eqclause) in
let arglen = Array.length args in
let () = if arglen < 2 then user_err Pp.(str "The term provided is not an applied relation.") in
let c1 = args.(arglen - 2) in
let c2 = args.(arglen - 1) in
w_unify_to_subterm_all ~flags env (Clenv.clenv_evd eqclause)
((if l2r then c1 else c2),concl)
let rewrite_conv_closed_core_unif_flags = {
modulo_conv_on_closed_terms = Some TransparentState.full;
(* We have this flag for historical reasons, it has e.g. the consequence *)
(* to rewrite "?x+2" in "y+(1+1)=0" or to rewrite "?x+?x" in "2+(1+1)=0" *)
use_metas_eagerly_in_conv_on_closed_terms = true;
use_evars_eagerly_in_conv_on_closed_terms = false;
(* Combined with modulo_conv_on_closed_terms, this flag allows since 8.2 *)
(* to rewrite e.g. "?x+(2+?x)" in "1+(1+2)=0" *)
modulo_delta = TransparentState.empty;
modulo_delta_types = TransparentState.full;
check_applied_meta_types = true;
use_pattern_unification = true;
(* To rewrite "?n x y" in "y+x=0" when ?n is *)
(* a preexisting evar of the goal*)
use_meta_bound_pattern_unification = true;
allowed_evars = Evarsolve.AllowedEvars.all;
restrict_conv_on_strict_subterms = false;
modulo_betaiota = false;
modulo_eta = true;
}
let rewrite_conv_closed_unif_flags = {
core_unify_flags = rewrite_conv_closed_core_unif_flags;
merge_unify_flags = rewrite_conv_closed_core_unif_flags;
subterm_unify_flags = rewrite_conv_closed_core_unif_flags;
allow_K_in_toplevel_higher_order_unification = false;
resolve_evars = false
}
let rewrite_keyed_core_unif_flags = {
modulo_conv_on_closed_terms = Some TransparentState.full;
(* We have this flag for historical reasons, it has e.g. the consequence *)
(* to rewrite "?x+2" in "y+(1+1)=0" or to rewrite "?x+?x" in "2+(1+1)=0" *)
use_metas_eagerly_in_conv_on_closed_terms = true;
use_evars_eagerly_in_conv_on_closed_terms = false;
(* Combined with modulo_conv_on_closed_terms, this flag allows since 8.2 *)
(* to rewrite e.g. "?x+(2+?x)" in "1+(1+2)=0" *)
modulo_delta = TransparentState.full;
modulo_delta_types = TransparentState.full;
check_applied_meta_types = true;
use_pattern_unification = true;
(* To rewrite "?n x y" in "y+x=0" when ?n is *)
(* a preexisting evar of the goal*)
use_meta_bound_pattern_unification = true;
allowed_evars = Evarsolve.AllowedEvars.all;
restrict_conv_on_strict_subterms = false;
modulo_betaiota = true;
modulo_eta = true;
}
let rewrite_keyed_unif_flags = {
core_unify_flags = rewrite_keyed_core_unif_flags;
merge_unify_flags = rewrite_keyed_core_unif_flags;
subterm_unify_flags = rewrite_keyed_core_unif_flags;
allow_K_in_toplevel_higher_order_unification = false;
resolve_evars = false
}
let tclNOTSAMEGOAL tac =
let goal gl = Proofview.Goal.goal gl in
Proofview.Goal.enter begin fun gl ->
let sigma = project gl in
let ev = goal gl in
tac >>= fun () ->
Proofview.Goal.goals >>= fun gls ->
let check accu gl' =
gl' >>= fun gl' ->
let accu = accu || Proofview.Progress.goal_equal
~evd:sigma ~extended_evd:(project gl') ev (goal gl')
in
Proofview.tclUNIT accu
in
Proofview.Monad.List.fold_left check false gls >>= fun has_same ->
if has_same then
tclZEROMSG (str"Tactic generated a subgoal identical to the original goal.")
else
Proofview.tclUNIT ()
end
let elim_wrapper cls rwtac =
let open Pretype_errors in
Proofview.tclORELSE
begin match cls with
| None ->
(* was tclWEAK_PROGRESS which only fails for tactics generating one
subgoal and did not fail for useless conditional rewritings generating
an extra condition *)
tclNOTSAMEGOAL rwtac
| Some _ -> rwtac
end
begin function (e, info) -> match e with
| PretypeError (env, evd, NoOccurrenceFound (c', _)) ->
Proofview.tclZERO ~info (PretypeError (env, evd, NoOccurrenceFound (c', cls)))
| e ->
Proofview.tclZERO ~info e
end
let general_elim_clause with_evars frzevars tac cls c (ctx, eqn, args) l l2r elim =
(* Ad hoc asymmetric general_elim_clause *)
let general_elim_clause0 rew =
let rewrite_elim =
Proofview.Goal.enter begin fun gl ->
let sigma = Proofview.Goal.sigma gl in
let flags = if Unification.is_keyed_unification ()
then rewrite_keyed_unif_flags else rewrite_conv_closed_unif_flags in
(* We take evars of the type: this may include old evars! For excluding *)
(* all old evars, including the ones occurring in the rewriting lemma, *)
(* we would have to take the clenv_value *)
let newevars = lazy (Evarutil.undefined_evars_of_term sigma (Clenv.clenv_type rew)) in
let flags = make_flags frzevars sigma flags newevars in
let metas = Evd.meta_list (Clenv.clenv_evd rew) in
let submetas = List.map (fun mv -> mv, Evd.Metamap.find mv metas) (Clenv.clenv_arguments rew) in
general_elim_clause with_evars flags cls (submetas, c, Clenv.clenv_type rew) elim
end
in
Proofview.Unsafe.tclEVARS (Evd.clear_metas (Clenv.clenv_evd rew)) <*>
elim_wrapper cls rewrite_elim
in
let strat, tac =
match tac with
| None -> Naive, None
| Some (tac, Naive) -> Naive, Some tac
| Some (tac, FirstSolved) -> FirstSolved, Some (tclCOMPLETE tac)
| Some (tac, AllMatches) -> AllMatches, Some (tclCOMPLETE tac)
in
Proofview.Goal.enter begin fun gl ->
let env = Proofview.Goal.env gl in
let sigma = Proofview.Goal.sigma gl in
let typ = match cls with
| None -> pf_concl gl
| Some id -> pf_get_hyp_typ id gl
in
let ty = it_mkProd_or_LetIn (applist (eqn, args)) ctx in
let eqclause = Clenv.make_clenv_binding env sigma (c, ty) l in
let try_clause evd' =
let clenv = Clenv.update_clenv_evd eqclause evd' in
let clenv = Clenv.clenv_pose_dependent_evars ~with_evars:true clenv in
side_tac (general_elim_clause0 clenv) tac
in
match strat with
| Naive ->
side_tac (general_elim_clause0 eqclause) tac
| FirstSolved ->
let flags = make_flags frzevars sigma rewrite_unif_flags (lazy Evar.Set.empty) in
let cs = instantiate_lemma_all env flags eqclause l2r typ in
tclFIRST (List.map try_clause cs)
| AllMatches ->
let flags = make_flags frzevars sigma rewrite_unif_flags (lazy Evar.Set.empty) in
let cs = instantiate_lemma_all env flags eqclause l2r typ in
tclMAP try_clause cs
end
(* The next function decides in particular whether to try a regular
rewrite or a generalized rewrite.
Approach is to break everything, if [eq] appears in head position
then regular rewrite else try general rewrite.
If occurrences are set, use general rewrite.
*)
let (forward_general_setoid_rewrite_clause, general_setoid_rewrite_clause) = Hook.make ()
(* Do we have a JMeq instance on twice the same domains ? *)
let jmeq_same_dom env sigma (rels, eq, args) =
let env = push_rel_context rels env in
match args with
| [dom1; _; dom2;_] -> is_conv env sigma dom1 dom2
| _ -> false
let eq_elimination_ref l2r sort =
let name =
if l2r then
match sort with
| InProp -> "core.eq.ind_r"
| InSProp -> "core.eq.sind_r"
| InSet | InType | InQSort -> "core.eq.rect_r"
else
match sort with
| InProp -> "core.eq.ind"
| InSProp -> "core.eq.sind"
| InSet | InType | InQSort -> "core.eq.rect"
in
Coqlib.lib_ref_opt name
(* find_elim determines which elimination principle is necessary to
eliminate lbeq on sort_of_gl. *)
let find_elim lft2rgt dep cls ((_, hdcncl, _) as t) =
Proofview.Goal.enter_one begin fun gl ->
let env = Proofview.Goal.env gl in
let sigma = project gl in
let is_global_exists gr c = match Coqlib.lib_ref_opt gr with
| Some gr -> isRefX env sigma gr c
| None -> false
in
let inccl = Option.is_empty cls in
let is_eq = is_global_exists "core.eq.type" hdcncl in
let is_jmeq = is_global_exists "core.JMeq.type" hdcncl && jmeq_same_dom env sigma t in
if (is_eq || is_jmeq) && not dep
then
let sort = elimination_sort_of_clause cls gl in
let c =
match EConstr.kind sigma hdcncl with
| Ind (ind_sp,u) ->
begin match lft2rgt, cls with
| Some true, None
| Some false, Some _ ->
begin match if is_eq then eq_elimination_ref true sort else None with
| Some r -> destConstRef r
| None ->
let c1 = destConstRef (lookup_eliminator env ind_sp sort) in
let mp,l = KerName.repr (Constant.canonical c1) in
let l' = Label.of_id (add_suffix (Label.to_id l) "_r") in
let c1' = Global.constant_of_delta_kn (KerName.make mp l') in
if not (Environ.mem_constant c1' (Global.env ())) then
user_err
(str "Cannot find rewrite principle " ++ Label.print l' ++ str ".");
c1'
end
| _ ->
begin match if is_eq then eq_elimination_ref false sort else None with
| Some r -> destConstRef r
| None -> destConstRef (lookup_eliminator env ind_sp sort)
end
end
| _ ->
(* cannot occur since we checked that we are in presence of
Logic.eq or Jmeq just before *)
assert false
in
Proofview.tclUNIT c
else
let scheme_name = match dep, lft2rgt, inccl with
(* Non dependent case *)
| false, Some true, true -> rew_l2r_scheme_kind
| false, Some true, false -> rew_r2l_scheme_kind
| false, _, false -> rew_l2r_scheme_kind
| false, _, true -> rew_r2l_scheme_kind
(* Dependent case *)
| true, Some true, true -> rew_l2r_dep_scheme_kind
| true, Some true, false -> rew_l2r_forward_dep_scheme_kind
| true, _, true -> rew_r2l_dep_scheme_kind
| true, _, false -> rew_r2l_forward_dep_scheme_kind
in
match EConstr.kind sigma hdcncl with
| Ind (ind,u) -> find_scheme scheme_name ind
| _ -> assert false
end
let type_of_clause cls gl = match cls with
| None -> Proofview.Goal.concl gl
| Some id -> pf_get_hyp_typ id gl
let leibniz_rewrite_ebindings_clause cls lft2rgt tac c ((_, hdcncl, _) as t) l with_evars frzevars dep_proof_ok =
Proofview.Goal.enter begin fun gl ->
let evd = Proofview.Goal.sigma gl in
let type_of_cls = type_of_clause cls gl in
let dep = dep_proof_ok && dependent_no_evar evd c type_of_cls in
find_elim lft2rgt dep cls t >>= fun elim ->
general_elim_clause with_evars frzevars tac cls c t l
(match lft2rgt with None -> false | Some b -> b) elim
end
let adjust_rewriting_direction args lft2rgt =
match args with
| [_] ->
(* equality to a constant, like in eq_true *)
(* more natural to see -> as the rewriting to the constant *)
if not lft2rgt then
user_err Pp.(str "Rewriting non-symmetric equality not allowed from right-to-left.");
None
| _ ->
(* other equality *)
Some lft2rgt
let rewrite_side_tac tac sidetac = side_tac tac (Option.map fst sidetac)
(* Main function for dispatching which kind of rewriting it is about *)
let general_rewrite ~where:cls ~l2r:lft2rgt occs ~freeze:frzevars ~dep:dep_proof_ok ~with_evars ?tac
((c,l) : constr with_bindings) =
if not (Locusops.is_all_occurrences occs) then (
rewrite_side_tac (Hook.get forward_general_setoid_rewrite_clause cls lft2rgt occs (c,l) ~new_goals:[]) tac)
else
Proofview.Goal.enter begin fun gl ->
let sigma = Tacmach.project gl in
let env = Proofview.Goal.env gl in
let ctype = get_type_of env sigma c in
let rels, t = decompose_prod_decls sigma (whd_betaiotazeta env sigma ctype) in
match match_with_equality_type env sigma t with
| Some (hdcncl,args) -> (* Fast path: direct leibniz-like rewrite *)
let lft2rgt = adjust_rewriting_direction args lft2rgt in
leibniz_rewrite_ebindings_clause cls lft2rgt tac c (rels, hdcncl, args)
l with_evars frzevars dep_proof_ok
| None ->
Proofview.tclORELSE
begin
rewrite_side_tac (Hook.get forward_general_setoid_rewrite_clause cls
lft2rgt occs (c,l) ~new_goals:[]) tac
end
begin function
| (e, info) ->
Proofview.tclEVARMAP >>= fun sigma ->
let env' = push_rel_context rels env in
let rels',t' = hnf_decompose_prod_decls env' sigma t in (* Search for underlying eq *)
match match_with_equality_type env' sigma t' with
| Some (hdcncl,args) ->
let lft2rgt = adjust_rewriting_direction args lft2rgt in
leibniz_rewrite_ebindings_clause cls lft2rgt tac c
(rels' @ rels, hdcncl, args) l with_evars frzevars dep_proof_ok
| None -> Proofview.tclZERO ~info e
(* error "The provided term does not end with an equality or a declared rewrite relation." *)
end
end
let clear_for_rewrite_in_hyps ids c =
let ids = Id.Set.of_list ids in
Proofview.Goal.enter begin fun gl ->
let env = Proofview.Goal.env gl in
let sigma = Proofview.Goal.sigma gl in
(* Is this the right err? *)
let err = (Evarutil.OccurHypInSimpleClause None) in
let sigma =
try Evarutil.check_and_clear_in_constr env sigma err ids c
with Evarutil.ClearDependencyError (id,err,inglobal) ->
CErrors.user_err Pp.(str "Cannot rewrite due to dependency on " ++ Id.print id ++ str ".")
in
Proofview.Unsafe.tclEVARS sigma
end
let general_rewrite_clause l2r with_evars ?tac c cl =
let occs_of = occurrences_map (List.fold_left
(fun acc ->
function ArgArg x -> x :: acc | ArgVar _ -> acc)
[])
in
match cl.onhyps with
| Some l ->
(* If a precise list of locations is given, success is mandatory for
each of these locations. *)
let rec do_hyps = function
| [] -> Proofview.tclUNIT ()
| ((occs,id),_) :: l ->
tclTHENFIRST
(general_rewrite ~where:(Some id) ~l2r (occs_of occs) ~freeze:false ~dep:true ~with_evars ?tac c)
(do_hyps l)
in
let tac =
if cl.concl_occs == NoOccurrences then do_hyps l
else
tclTHENFIRST
(general_rewrite ~where:None ~l2r (occs_of cl.concl_occs) ~freeze:false ~dep:true ~with_evars ?tac c)
(do_hyps l)
in
begin match l with
| [] | [_] ->
(* don't clear when rewriting in 1 hyp *)
tac
| _ ->
tclTHEN (clear_for_rewrite_in_hyps (List.map (fun ((_,id),_) -> id) l) (fst c)) tac
end
| None ->
(* Otherwise, if we are told to rewrite in all hypothesis via the
syntax "* |-", we fail iff all the different rewrites fail *)
let rec do_hyps_atleastonce = function
| [] -> tclZEROMSG (Pp.str"Nothing to rewrite.")
| id :: l ->
tclIFTHENFIRSTTRYELSEMUST
(tclTHEN (clear_for_rewrite_in_hyps [id] (fst c))
(general_rewrite ~where:(Some id) ~l2r AllOccurrences ~freeze:false ~dep:true ~with_evars ?tac c))
(do_hyps_atleastonce l)
in
let do_hyps =
Proofview.Goal.enter begin fun gl ->
do_hyps_atleastonce (pf_ids_of_hyps gl)
end
in
if cl.concl_occs == NoOccurrences then do_hyps else
tclIFTHENFIRSTTRYELSEMUST
(general_rewrite ~where:None ~l2r (occs_of cl.concl_occs) ~freeze:false ~dep:true ~with_evars ?tac c)
do_hyps
let apply_special_clear_request clear_flag f =
Proofview.Goal.enter begin fun gl ->
let sigma = Tacmach.project gl in
let env = Proofview.Goal.env gl in
try
let (sigma, (c, bl)) = f env sigma in
let c = try Some (destVar sigma c) with DestKO -> None in
apply_clear_request clear_flag (use_clear_hyp_by_default ()) c
with
e when noncritical e -> tclIDTAC
end
type multi =
| Precisely of int
| UpTo of int
| RepeatStar
| RepeatPlus
let general_multi_rewrite with_evars l cl tac =
let do1 l2r f =
Proofview.Goal.enter begin fun gl ->
let sigma = Tacmach.project gl in
let env = Proofview.Goal.env gl in
let (sigma, c) = f env sigma in
tclWITHHOLES with_evars
(general_rewrite_clause l2r with_evars ?tac c cl) sigma
end
in
let rec doN l2r c = function
| Precisely n when n <= 0 -> Proofview.tclUNIT ()
| Precisely 1 -> do1 l2r c
| Precisely n -> tclTHENFIRST (do1 l2r c) (doN l2r c (Precisely (n-1)))
| RepeatStar -> tclREPEAT_MAIN (do1 l2r c)
| RepeatPlus -> tclTHENFIRST (do1 l2r c) (doN l2r c RepeatStar)
| UpTo n when n<=0 -> Proofview.tclUNIT ()
| UpTo n -> tclTHENFIRST (tclTRY (do1 l2r c)) (doN l2r c (UpTo (n-1)))
in
let rec loop = function
| [] -> Proofview.tclUNIT ()
| (l2r,m,clear_flag,c)::l ->
tclTHENFIRST
(tclTHEN (doN l2r c m) (apply_special_clear_request clear_flag c)) (loop l)
in loop l
let rewriteLR c =
general_rewrite ~where:None ~l2r:true AllOccurrences ~freeze:true ~dep:true ~with_evars:false (c, NoBindings)
let rewriteRL c =
general_rewrite ~where:None ~l2r:false AllOccurrences ~freeze:true ~dep:true ~with_evars:false (c, NoBindings)
(* Replacing tactics *)
let classes_dirpath =
DirPath.make (List.map Id.of_string ["Classes";"Coq"])
let init_setoid () =
if is_dirpath_prefix_of classes_dirpath (Lib.cwd ()) then ()
else check_required_library ["Coq";"Setoids";"Setoid"]
let check_setoid cl =
let concloccs = Locusops.occurrences_map (fun x -> x) cl.concl_occs in
Option.fold_left
(List.fold_left
(fun b ((occ,_),_) ->
b||(not (Locusops.is_all_occurrences (Locusops.occurrences_map (fun x -> x) occ)))
)
)
(not (Locusops.is_all_occurrences concloccs) &&
(concloccs <> NoOccurrences))
cl.onhyps
let replace_core clause l2r eq =
if check_setoid clause
then init_setoid ();
tclTHENFIRST
(assert_after Anonymous eq)
(onLastHypId (fun id ->
tclTHEN
(tclTRY (general_rewrite_clause l2r false (mkVar id,NoBindings) clause))
(clear [id])))
(* eq,sym_eq : equality on Type and its symmetry theorem
c1 c2 : c1 is to be replaced by c2
unsafe : If true, do not check that c1 and c2 are convertible
tac : Used to prove the equality c1 = c2
gl : goal *)
let since_8_19 = Deprecation.make ~since:"8.19" ()
let {Goptions.get = replace_use_assum} =
Goptions.declare_bool_option_and_ref ~depr:since_8_19 ~key:["Replace";"Use";"Assumption"]
~value:false ()
let replace_using_leibniz clause c1 c2 l2r unsafe try_prove_eq_opt =
let try_prove_eq =
match try_prove_eq_opt with
| None -> Proofview.tclUNIT ()
| Some tac -> tclCOMPLETE tac
in
Proofview.Goal.enter begin fun gl ->
let get_type_of = pf_apply get_type_of gl in
let t1 = get_type_of c1
and t2 = get_type_of c2 in
let evd =
if unsafe then Some (Tacmach.project gl)
else
try Some (Evarconv.unify_delay (Proofview.Goal.env gl) (Tacmach.project gl) t1 t2)
with Evarconv.UnableToUnify _ -> None
in
match evd with
| None ->
tclFAIL (str"Terms do not have convertible types")
| Some evd ->
let e,sym =
try lib_ref "core.eq.type", lib_ref "core.eq.sym"
with NotFoundRef _ ->
try lib_ref "core.identity.type", lib_ref "core.identity.sym"
with NotFoundRef _ ->
user_err (strbrk "Need a registration for either core.eq.type and core.eq.sym or core.identity.type and core.identity.sym.") in
Tacticals.pf_constr_of_global sym >>= fun sym ->
Tacticals.pf_constr_of_global e >>= fun e ->
let eq = applist (e, [t1;c1;c2]) in
let solve_tac =
if replace_use_assum () then
tclFIRST
[assumption;
tclTHEN (apply sym) assumption;
try_prove_eq
]
else try_prove_eq
in
tclTHENLAST
(replace_core clause l2r eq)
solve_tac
end
let replace c1 c2 =
replace_using_leibniz onConcl c2 c1 false false None
let replace_by c1 c2 tac =
replace_using_leibniz onConcl c2 c1 false false (Some tac)
let replace_in_clause_maybe_by c1 c2 cl tac_opt =
replace_using_leibniz cl c2 c1 false false tac_opt
(* End of Eduardo's code. The rest of this file could be improved
using the functions match_with_equation, etc that I defined
in Pattern.ml.
-- Eduardo (19/8/97)
*)
(* Tactics for equality reasoning with the "eq" relation. This code
will work with any equivalence relation which is substitutive *)
(* [find_positions t1 t2]
will find the positions in the two terms which are suitable for
discrimination, or for injection. Obviously, if there is a
position which is suitable for discrimination, then we want to
exploit it, and not bother with injection. So when we find a
position which is suitable for discrimination, we will just raise
an exception with that position.
So the algorithm goes like this:
if [t1] and [t2] start with the same constructor, then we can
continue to try to find positions in the arguments of [t1] and
[t2].
if [t1] and [t2] do not start with the same constructor, then we
have found a discrimination position
if one [t1] or [t2] do not start with a constructor and the two
terms are not already convertible, then we have found an injection
position.
A discriminating position consists of a constructor-path and a pair
of operators. The constructor-path tells us how to get down to the
place where the two operators, which must differ, can be found.
An injecting position has two terms instead of the two operators,
since these terms are different, but not manifestly so.
A constructor-path is a list of pairs of (operator * int), where
the int (based at 0) tells us which argument of the operator we
descended into.
*)
exception DiscrFound of
(constructor * int) list * constructor * constructor
let keep_proof_equalities_for_injection = ref false
let () =
declare_bool_option
{ optstage = Summary.Stage.Interp;
optdepr = None;
optkey = ["Keep";"Proof";"Equalities"];
optread = (fun () -> !keep_proof_equalities_for_injection) ;
optwrite = (fun b -> keep_proof_equalities_for_injection := b) }
let keep_proof_equalities = function
| None -> !keep_proof_equalities_for_injection
| Some flags -> flags.keep_proof_equalities
module KeepEqualities =
struct
type t = inductive
module Set = Indset_env
let encode _env r = Nametab.global_inductive r
let subst subst obj = Mod_subst.subst_ind subst obj
let printer ind = Nametab.pr_global_env Id.Set.empty (GlobRef.IndRef ind)
let key = ["Keep"; "Equalities"]
let title = "Prop-valued inductive types for which injection keeps equality proofs"
let member_message ind b =
let b = if b then mt () else str "not " in
str "Equality proofs over " ++ (printer ind) ++
str " are " ++ b ++ str "kept by injection"
end
module KeepEqualitiesTable = Goptions.MakeRefTable(KeepEqualities)
let set_keep_equality = KeepEqualitiesTable.set
(* [keep_proofs] is relevant for types in Prop with elimination in Type *)
(* In particular, it is relevant for injection but not for discriminate *)
let keep_head_inductive sigma c =
(* Note that we do not weak-head normalize c before checking it is an
applied inductive, because [get_sort_family_of] did not use to either.
As a matter of fact, if it reduces to an applied template inductive
type but is not syntactically equal to it, it will fail to project. *)
let _, hd = EConstr.decompose_prod sigma c in
let hd, _ = EConstr.decompose_app sigma hd in
match EConstr.kind sigma hd with
| Ind (ind, _) -> KeepEqualitiesTable.active ind
| _ -> false
let find_positions env sigma ~keep_proofs ~no_discr t1 t2 =
let project env sorts posn t1 t2 =
let ty1 = get_type_of env sigma t1 in
let keep =
if keep_head_inductive sigma ty1 then true
else
let s = get_sort_family_of env sigma ty1 in
List.mem_f Sorts.family_equal s sorts
in
if keep then [(List.rev posn,t1,t2)] else []
in
let rec findrec sorts posn t1 t2 =
let hd1,args1 = whd_all_stack env sigma t1 in
let hd2,args2 = whd_all_stack env sigma t2 in
match (EConstr.kind sigma hd1, EConstr.kind sigma hd2) with
| Construct ((ind1,i1 as sp1),u1), Construct (sp2,_)
when Int.equal (List.length args1) (constructor_nallargs env sp1)
->
let sorts' =
CList.intersect Sorts.family_equal sorts (sorts_below (top_allowed_sort env (fst sp1)))
in
(* both sides are fully applied constructors, so either we descend,
or we can discriminate here. *)
if Environ.QConstruct.equal env sp1 sp2 then
let nparams = inductive_nparams env ind1 in
let params1,rargs1 = List.chop nparams args1 in
let _,rargs2 = List.chop nparams args2 in
let (mib,mip) = lookup_mind_specif env ind1 in
let params1 = List.map EConstr.Unsafe.to_constr params1 in
let u1 = EInstance.kind sigma u1 in
let ctxt = (get_constructor ((ind1,u1),mib,mip,params1) i1).cs_args in
let adjust i = CVars.adjust_rel_to_rel_context ctxt (i+1) - 1 in
List.flatten
(List.map2_i (fun i -> findrec sorts' ((sp1,adjust i)::posn))
0 rargs1 rargs2)
else if List.mem_f Sorts.family_equal InType sorts' && not no_discr
then (* see build_discriminator *)
raise (DiscrFound (List.rev posn,sp1,sp2))
else
(* if we cannot eliminate to Type, we cannot discriminate but we
may still try to project *)
project env sorts posn (applist (hd1,args1)) (applist (hd2,args2))
| _ ->
let t1_0 = applist (hd1,args1)
and t2_0 = applist (hd2,args2) in
if is_conv env sigma t1_0 t2_0 then
[]
else
project env sorts posn t1_0 t2_0
in
try
let sorts = if keep_proofs then [InSet;InType;InProp] else [InSet;InType] in
Inr (findrec sorts [] t1 t2)
with DiscrFound (path,c1,c2) ->
Inl (path,c1,c2)
let use_keep_proofs = function
| None -> !keep_proof_equalities_for_injection
| Some b -> b
(* Once we have found a position, we need to project down to it. If
we are discriminating, then we need to produce False on one of the
branches of the discriminator, and True on the other one. So the
result type of the case-expressions is always Prop.
If we are injecting, then we need to discover the result-type.
This can be difficult, since the type of the two terms at the
injection-position can be different, and we need to find a
dependent sigma-type which generalizes them both.
We can get an approximation to the right type to choose by:
(0) Before beginning, we reserve a patvar for the default
value of the match, to be used in all the bogus branches.
(1) perform the case-splits, down to the site of the injection. At
each step, we have a term which is the "head" of the next
case-split. At the point when we actually reach the end of our
path, the "head" is the term to return. We compute its type, and
then, backwards, make a sigma-type with every free debruijn
reference in that type. We can be finer, and first do a S(TRONG)NF
on the type, so that we get the fewest number of references
possible.
(2) This gives us a closed type for the head, which we use for the
types of all the case-splits.
(3) Now, we can compute the type of one of T1, T2, and then unify
it with the type of the last component of the result-type, and this
will give us the bindings for the other arguments of the tuple.
*)
(* The algorithm, then is to perform successive case-splits. We have
the result-type of the case-split, and also the type of that
result-type. We have a "direction" we want to follow, i.e. a
constructor-number, and in all other "directions", we want to juse
use the default-value.
After doing the case-split, we call the afterfun, with the updated
environment, to produce the term for the desired "direction".
The assumption is made here that the result-type is not manifestly
functional, so we can just use the length of the branch-type to
know how many lambda's to stick in.
*)
(* [descend_then env sigma head dirn]
returns the number of products introduced, and the environment
which is active, in the body of the case-branch given by [dirn],
along with a continuation, which expects to be fed:
(1) the value of the body of the branch given by [dirn]
(2) the default-value
(3) the type of the default-value, which must also be the type of
the body of the [dirn] branch
the continuation then constructs the case-split.
*)
let descend_then env sigma head dirn =
let IndType (indf,_) as indt =
try find_rectype env sigma (get_type_of env sigma head)
with Not_found ->
user_err Pp.(str "Cannot project on an inductive type derived from a dependency.")
in
let (ind, _),_ = (dest_ind_family indf) in
let () = check_privacy env ind in
let (mib,mip) = lookup_mind_specif env ind in
let cstr = get_constructors env indf in
let dirn_nlams = cstr.(dirn-1).cs_nargs in
let dirn_env = Environ.push_rel_context cstr.(dirn-1).cs_args env in
(dirn_nlams,
dirn_env,
(fun sigma dirnval (dfltval,resty) ->
let deparsign = make_arity_signature env sigma true indf in
let p =
it_mkLambda_or_LetIn (lift (mip.mind_nrealargs+1) resty) deparsign in
let build_branch i =
let result = if Int.equal i dirn then dirnval else dfltval in
let cs_args = List.map (fun d -> map_rel_decl EConstr.of_constr d) cstr.(i-1).cs_args in
let args = name_context env sigma cs_args in
it_mkLambda_or_LetIn result args in
let brl =
List.map build_branch
(List.interval 1 (Array.length mip.mind_consnames)) in
let rci = Sorts.Relevant in (* TODO relevance *)
let ci = make_case_info env ind rci RegularStyle in
Inductiveops.make_case_or_project env sigma indt ci p head (Array.of_list brl)))
(* Now we need to construct the discriminator, given a discriminable
position. This boils down to:
(1) If the position is directly beneath us, then we need to do a
case-split, with result-type Prop, and stick True and False into
the branches, as is convenient.
(2) If the position is not directly beneath us, then we need to
call descend_then, to descend one step, and then recursively
construct the discriminator.
*)
(* [construct_discriminator env sigma dirn c ind special default]]
constructs a case-split on [c] of type [ind], with the [dirn]-th
branch giving [special], and all the rest giving [default]. *)
let build_selector env sigma dirn c ind special default =
let IndType(indf,_) as indt =
try find_rectype env sigma ind
with Not_found ->
(* one can find Rel(k) in case of dependent constructors
like T := c : (A:Set)A->T and a discrimination
on (c bool true) = (c bool false)
CP : changed assert false in a more informative error
*)
user_err
(str "Cannot discriminate on inductive constructors with \
dependent types.") in
let (ind, _),_ = dest_ind_family indf in
let () = check_privacy env ind in
let typ = Retyping.get_type_of env sigma default in
let (mib,mip) = lookup_mind_specif env ind in
let deparsign = make_arity_signature env sigma true indf in
let p = it_mkLambda_or_LetIn typ deparsign in
let cstrs = get_constructors env indf in
let build_branch i =
let endpt = if Int.equal i dirn then special else default in
let args = List.map (fun d -> map_rel_decl EConstr.of_constr d) cstrs.(i-1).cs_args in
it_mkLambda_or_LetIn endpt args in
let brl =
List.map build_branch(List.interval 1 (Array.length mip.mind_consnames)) in
let rci = Sorts.Relevant in (* TODO relevance *)
let ci = make_case_info env ind rci RegularStyle in
let ans = Inductiveops.make_case_or_project env sigma indt ci p c (Array.of_list brl) in
ans
let build_coq_False () = pf_constr_of_global (lib_ref "core.False.type")
let build_coq_True () = pf_constr_of_global (lib_ref "core.True.type")
let build_coq_I () = pf_constr_of_global (lib_ref "core.True.I")
let rec build_discriminator env sigma true_0 false_0 dirn c = function
| [] ->
let ind = get_type_of env sigma c in
build_selector env sigma dirn c ind true_0 (fst false_0)
| ((sp,cnum),argnum)::l ->
let (cnum_nlams,cnum_env,kont) = descend_then env sigma c cnum in
let newc = mkRel(cnum_nlams-argnum) in
let subval = build_discriminator cnum_env sigma true_0 false_0 dirn newc l in
kont sigma subval false_0
(* Note: discrimination could be more clever: if some elimination is
not allowed because of a large impredicative constructor in the
path (see allowed_sorts in find_positions), the positions could
still be discrimated by projecting first instead of putting the
discrimination combinator inside the projecting combinator. Example
of relevant situation:
Inductive t:Set := c : forall A:Set, A -> nat -> t.
Goal ~ c _ 0 0 = c _ 0 1. intro. discriminate H.
*)
let gen_absurdity id =
Proofview.Goal.enter begin fun gl ->