aboutsummaryrefslogtreecommitdiffhomepage
path: root/tactics/eqschemes.ml
blob: 0d16e49312b86215ee9ef1ad47d81026c5c75821 (plain)
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
(************************************************************************)
(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)
(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)
(*   \VV/  **************************************************************)
(*    //   *      This file is distributed under the terms of the       *)
(*         *       GNU Lesser General Public License Version 2.1        *)
(************************************************************************)

(* File created by Hugo Herbelin, Nov 2009 *)

(* This file builds schemes related to equality inductive types,
   especially for dependent rewrite, rewriting on arbitrary equality
   types and congruence on arbitrary equality types *)

(* However, the choices made lack uniformity, as we have to make a
   compromise between several constraints and ideal requirements:

   - Having the extended schemes working conservatively over the
     existing non-dependent schemes eq_rect and eq_rect_r. There is in
     particular a problem with the dependent rewriting schemes in
     hypotheses for which the inductive types cannot be in last
     position of the scheme as it is the general rule in Coq. This has
     an effect on the order of generated goals (side-conditions of the
     lemma after or before the main goal). The non-dependent case can be
     fixed but to the price of a lost of uniformity wrt side-conditions
     in the dependent and non-dependent cases.

   - Having schemes general enough to support non-symmetric equality
     type like eq_true.

   - Having schemes that avoid introducing beta-expansions blocked by
     "match" so as to please the guard condition, but this introduces
     some tricky things involving involutivity of symmetry that I
     don't how to avoid. The result below is a compromise with
     dependent left-to-right rewriting in conclusion (l2r_dep) using
     the tricky involutivity of symmetry and dependent left-to-right
     rewriting in hypotheses (r2l_forward_dep), that one wants to be
     used for non-symmetric equality and that introduces blocked
     beta-expansions.

   One may wonder whether these extensions are worth to be done
   regarding the price we have to pay and regarding the rare
   situations where they are needed. However, I believe it meets a 
   natural expectation of the user.
*)

open Errors
open Util
open Names
open Term
open Declarations
open Environ
open Inductive
open Termops
open Namegen
open Inductiveops
open Ind_tables
open Indrec

let hid = id_of_string "H"
let xid = id_of_string "X"
let default_id_of_sort = function InProp | InSet -> hid | InType -> xid
let fresh env id = next_global_ident_away id []

let build_dependent_inductive ind (mib,mip) =
  let realargs,_ = list_chop mip.mind_nrealargs_ctxt mip.mind_arity_ctxt in
  applist
    (mkInd ind,
       extended_rel_list mip.mind_nrealargs_ctxt mib.mind_params_ctxt
       @ extended_rel_list 0 realargs)

let my_it_mkLambda_or_LetIn s c = it_mkLambda_or_LetIn c s
let my_it_mkProd_or_LetIn s c = it_mkProd_or_LetIn c s
let my_it_mkLambda_or_LetIn_name s c =
  it_mkLambda_or_LetIn_name (Global.env()) c s

let get_coq_eq () =
  try
    let eq = Globnames.destIndRef Coqlib.glob_eq in
    let _ = Global.lookup_inductive eq in
    (* Do not force the lazy if they are not defined *)
    mkInd eq, Coqlib.build_coq_eq_refl ()
  with Not_found ->
    error "eq not found."

(**********************************************************************)
(* Check if an inductive type [ind] has the form                      *)
(*                                                                    *)
(*   I q1..qm,p1..pn a1..an with one constructor                      *)
(*   C : I q1..qm,p1..pn p1..pn                                       *)
(*                                                                    *)
(* in which case, a symmetry lemma is definable                       *)
(**********************************************************************)

let get_sym_eq_data env ind =
  let (mib,mip as specif) = lookup_mind_specif env ind in
  if Array.length mib.mind_packets <> 1 or Array.length mip.mind_nf_lc <> 1 then
    error "Not an inductive type with a single constructor.";
  let realsign,_ = list_chop mip.mind_nrealargs_ctxt mip.mind_arity_ctxt in
  if List.exists (fun (_,b,_) -> b <> None) realsign then
    error "Inductive equalities with local definitions in arity not supported.";
  let constrsign,ccl = decompose_prod_assum mip.mind_nf_lc.(0) in
  let _,constrargs = decompose_app ccl in
  if rel_context_length constrsign<>rel_context_length mib.mind_params_ctxt then
    error "Constructor must have no arguments"; (* This can be relaxed... *)
  let params,constrargs = list_chop mib.mind_nparams constrargs in
  if mip.mind_nrealargs > mib.mind_nparams then
    error "Constructors arguments must repeat the parameters.";
  let _,params2 = list_chop (mib.mind_nparams-mip.mind_nrealargs) params in
  let paramsctxt1,_ =
    list_chop (mib.mind_nparams-mip.mind_nrealargs) mib.mind_params_ctxt in
  if not (list_equal eq_constr params2 constrargs) then
    error "Constructors arguments must repeat the parameters.";
  (* nrealargs_ctxt and nrealargs are the same here *)
  (specif,mip.mind_nrealargs,realsign,mib.mind_params_ctxt,paramsctxt1)

(**********************************************************************)
(* Check if an inductive type [ind] has the form                      *)
(*                                                                    *)
(*   I q1..qm a1..an with one constructor                             *)
(*   C : I q1..qm b1..bn                                              *)
(*                                                                    *)
(* in which case it expresses the equalities ai=bi, but not in a way  *)
(* such that symmetry is a priori definable                           *)
(**********************************************************************)

let get_non_sym_eq_data env ind =
  let (mib,mip as specif) = lookup_mind_specif env ind in
  if Array.length mib.mind_packets <> 1 or Array.length mip.mind_nf_lc <> 1 then
    error "Not an inductive type with a single constructor.";
  let realsign,_ = list_chop mip.mind_nrealargs_ctxt mip.mind_arity_ctxt in
  if List.exists (fun (_,b,_) -> b <> None) realsign then
    error "Inductive equalities with local definitions in arity not supported";
  let constrsign,ccl = decompose_prod_assum mip.mind_nf_lc.(0) in
  let _,constrargs = decompose_app ccl in
  if rel_context_length constrsign<>rel_context_length mib.mind_params_ctxt then
    error "Constructor must have no arguments";
  let _,constrargs = list_chop mib.mind_nparams constrargs in
  (specif,constrargs,realsign,mip.mind_nrealargs)

(**********************************************************************)
(* Build the symmetry lemma associated to an inductive type           *)
(* I q1..qm,p1..pn a1..an with one constructor                        *)
(* C : I q1..qm,p1..pn p1..pn                                         *)
(*                                                                    *)
(* sym := fun q1..qn p1..pn a1..an (H:I q1..qm p1..pn a1..an) =>      *)
(*        match H in I _.._ a1..an return I q1..qm a1..an p1..pn with *)
(*            C => C                                                  *)
(*        end                                                         *)
(*      : forall q1..qm p1..pn a1..an I q1..qm p1..pn a1..an ->       *)
(*          I q1..qm a1..an p1..pn                                    *)
(*                                                                    *)
(**********************************************************************)

let build_sym_scheme env ind =
  let (mib,mip as specif),nrealargs,realsign,paramsctxt,paramsctxt1 =
    get_sym_eq_data env ind in
  let cstr n =
    mkApp (mkConstruct(ind,1),extended_rel_vect n mib.mind_params_ctxt) in
  let varH = fresh env (default_id_of_sort (snd (mind_arity mip))) in
  let applied_ind = build_dependent_inductive ind specif in
  let realsign_ind =
    name_context env ((Name varH,None,applied_ind)::realsign) in
  let ci = make_case_info (Global.env()) ind RegularStyle in
  (my_it_mkLambda_or_LetIn mib.mind_params_ctxt
  (my_it_mkLambda_or_LetIn_name realsign_ind
  (mkCase (ci,
     my_it_mkLambda_or_LetIn_name
       (lift_rel_context (nrealargs+1) realsign_ind)
       (mkApp (mkInd ind,Array.concat
	  [extended_rel_vect (3*nrealargs+2) paramsctxt1;
	   rel_vect 1 nrealargs;
	   rel_vect (2*nrealargs+2) nrealargs])),
     mkRel 1 (* varH *),
       [|cstr (nrealargs+1)|]))))

let sym_scheme_kind =
  declare_individual_scheme_object "_sym_internal"
  (fun ind -> build_sym_scheme (Global.env() (* side-effect! *)) ind)

(**********************************************************************)
(* Build the involutivity of symmetry for an inductive type           *)
(* I q1..qm,p1..pn a1..an with one constructor                        *)
(* C : I q1..qm,p1..pn p1..pn                                         *)
(*                                                                    *)
(* inv := fun q1..qn p1..pn a1..an (H:I q1..qm p1..pn a1..an) =>      *)
(*        match H in I _.._ a1..an return                             *)
(*          sym q1..qm p1..pn a1..an (sym q1..qm a1..an p1..pn H) = H *)
(*        with                                                        *)
(*          C => refl_equal C                                         *)
(*        end                                                         *)
(*      : forall q1..qm p1..pn a1..an (H:I q1..qm a1..an p1..pn),     *)
(*          sym q1..qm p1..pn a1..an (sym q1..qm a1..an p1..pn H) = H *)
(*                                                                    *)
(**********************************************************************)

let build_sym_involutive_scheme env ind =
  let (mib,mip as specif),nrealargs,realsign,paramsctxt,paramsctxt1 =
    get_sym_eq_data env ind in
  let sym = mkConst (find_scheme sym_scheme_kind ind) in
  let (eq,eqrefl) = get_coq_eq () in
  let cstr n = mkApp (mkConstruct(ind,1),extended_rel_vect n paramsctxt) in
  let varH = fresh env (default_id_of_sort (snd (mind_arity mip))) in
  let applied_ind = build_dependent_inductive ind specif in
  let applied_ind_C =
    mkApp
      (mkInd ind, Array.append
         (extended_rel_vect (nrealargs+1) mib.mind_params_ctxt)
         (rel_vect (nrealargs+1) nrealargs)) in
  let realsign_ind =
    name_context env ((Name varH,None,applied_ind)::realsign) in
  let ci = make_case_info (Global.env()) ind RegularStyle in
  (my_it_mkLambda_or_LetIn paramsctxt
  (my_it_mkLambda_or_LetIn_name realsign_ind
  (mkCase (ci,
     my_it_mkLambda_or_LetIn_name
       (lift_rel_context (nrealargs+1) realsign_ind)
       (mkApp (eq,[|
	 mkApp
	   (mkInd ind, Array.concat
	     [extended_rel_vect (3*nrealargs+2) paramsctxt1;
	      rel_vect (2*nrealargs+2) nrealargs;
	      rel_vect 1 nrealargs]);
         mkApp (sym,Array.concat
	   [extended_rel_vect (3*nrealargs+2) paramsctxt1;
            rel_vect 1 nrealargs;
            rel_vect (2*nrealargs+2) nrealargs;
            [|mkApp (sym,Array.concat
	      [extended_rel_vect (3*nrealargs+2) paramsctxt1;
	       rel_vect (2*nrealargs+2) nrealargs;
	       rel_vect 1 nrealargs;
	       [|mkRel 1|]])|]]);
	 mkRel 1|])),
     mkRel 1 (* varH *),
       [|mkApp(eqrefl,[|applied_ind_C;cstr (nrealargs+1)|])|]))))

let sym_involutive_scheme_kind =
  declare_individual_scheme_object "_sym_involutive"
  (fun ind -> build_sym_involutive_scheme (Global.env() (* side-effect! *)) ind)

(**********************************************************************)
(* Build the left-to-right rewriting lemma for conclusion associated  *)
(* to an inductive type I q1..qm,p1..pn a1..an with one constructor   *)
(* C : I q1..qm,p1..pn p1..pn                                         *)
(* (symmetric equality in non-dependent and dependent cases)          *)
(*                                                                    *)
(* We could have defined the scheme in one match over a generalized   *)
(* type but this behaves badly wrt the guard condition, so we use     *)
(* symmetry instead; with commutative-cuts-aware guard condition a    *)
(* proof in the style of l2r_forward is also possible (see below)     *)
(*                                                                    *)
(* rew := fun q1..qm p1..pn a1..an                                    *)
(*          (P:forall p1..pn, I q1..qm p1..pn a1..an -> kind)         *)
(*          (HC:P a1..an C)                                           *)
(*          (H:I q1..qm p1..pn a1..an)  =>                            *)
(*          match sym_involutive q1..qm p1..pn a1..an H as Heq        *)
(*                in _ = H return P p1..pn H                          *)
(*          with                                                      *)
(*            refl =>                                                 *)
(*              match sym q1..qm p1..pn a1..an H as H                 *)
(*                     in I _.._ p1..pn                               *)
(*                    return P p1..pn (sym q1..qm a1..an p1..pn H)    *)
(*              with                                                  *)
(*                C => HC                                             *)
(*              end                                                   *)
(*          end                                                       *)
(*      : forall q1..qn p1..pn a1..an                                 *)
(*          (P:forall p1..pn, I q1..qm p1..pn a1..an -> kind),        *)
(*          P a1..an C ->                                             *)
(*          forall (H:I q1..qm p1..pn a1..an), P p1..pn H             *)
(*                                                                    *)
(* where A1..An are the common types of p1..pn and a1..an             *)
(*                                                                    *)
(* Note: the symmetry is needed in the dependent case since the       *)
(* dependency is on the inner arguments (the indices in C) and these  *)
(* inner arguments need to be visible as parameters to be able to     *)
(* abstract over them in P.                                           *)
(**********************************************************************)

(**********************************************************************)
(* For information, the alternative proof of dependent l2r_rew scheme *)
(* that would use commutative cuts is the following                   *)
(*                                                                    *)
(* rew := fun q1..qm p1..pn a1..an                                    *)
(*          (P:forall p1..pn, I q1..qm p1..pn a1..an -> kind)         *)
(*          (HC:P a1..an C)                                           *)
(*          (H:I q1..qm p1..pn a1..an)  =>                            *)
(*          match H in I .._.. a1..an return                          *)
(*             forall p1..pn, I q1..qm p1..pn a1..an -> kind),        *)
(*             P a1..an C -> P p1..pn H                               *)
(*          with                                                      *)
(*            C => fun P HC => HC                                     *)
(*          end P HC                                                  *)
(*      : forall q1..qn p1..pn a1..an                                 *)
(*          (P:forall p1..pn, I q1..qm p1..pn a1..an -> kind),        *)
(*          P a1..an C ->                                             *)
(*          forall (H:I q1..qm p1..pn a1..an), P p1..pn H             *)
(*                                                                    *)
(**********************************************************************)

let build_l2r_rew_scheme dep env ind kind =
  let (mib,mip as specif),nrealargs,realsign,paramsctxt,paramsctxt1 =
    get_sym_eq_data env ind in
  let sym = mkConst (find_scheme sym_scheme_kind ind) in
  let sym_involutive = mkConst (find_scheme sym_involutive_scheme_kind ind) in
  let (eq,eqrefl) = get_coq_eq () in
  let cstr n p =
    mkApp (mkConstruct(ind,1),
      Array.concat [extended_rel_vect n paramsctxt1;
                    rel_vect p nrealargs]) in
  let varH = fresh env (default_id_of_sort (snd (mind_arity mip))) in
  let varHC = fresh env (id_of_string "HC") in
  let varP = fresh env (id_of_string "P") in
  let applied_ind = build_dependent_inductive ind specif in
  let applied_ind_P =
    mkApp (mkInd ind, Array.concat
       [extended_rel_vect (3*nrealargs) paramsctxt1;
        rel_vect 0 nrealargs;
        rel_vect nrealargs nrealargs]) in
  let applied_ind_G =
    mkApp (mkInd ind, Array.concat
       [extended_rel_vect (3*nrealargs+3) paramsctxt1;
        rel_vect (nrealargs+3) nrealargs;
        rel_vect 0 nrealargs]) in
  let realsign_P = lift_rel_context nrealargs realsign in
  let realsign_ind_P =
    name_context env ((Name varH,None,applied_ind_P)::realsign_P) in
  let realsign_ind_G =
    name_context env ((Name varH,None,applied_ind_G)::
                      lift_rel_context (nrealargs+3) realsign) in
  let applied_sym_C n =
     mkApp(sym,
       Array.append (extended_rel_vect n mip.mind_arity_ctxt) [|mkVar varH|]) in
  let applied_sym_G =
     mkApp(sym,
       Array.concat [extended_rel_vect (nrealargs*3+4) paramsctxt1;
                     rel_vect (nrealargs+4) nrealargs;
                     rel_vect 1 nrealargs;
		     [|mkRel 1|]]) in
  let s = mkSort (new_sort_in_family kind) in
  let ci = make_case_info (Global.env()) ind RegularStyle in
  let cieq = make_case_info (Global.env()) (destInd eq) RegularStyle in
  let applied_PC =
    mkApp (mkVar varP,Array.append (extended_rel_vect 1 realsign)
           (if dep then [|cstr (2*nrealargs+1) 1|] else [||])) in
  let applied_PG =
    mkApp (mkVar varP,Array.append (rel_vect 1 nrealargs)
           (if dep then [|applied_sym_G|] else [||])) in
  let applied_PR =
    mkApp (mkVar varP,Array.append (rel_vect (nrealargs+5) nrealargs)
           (if dep then [|mkRel 2|] else [||])) in
  let applied_sym_sym =
         mkApp (sym,Array.concat
	   [extended_rel_vect (2*nrealargs+4) paramsctxt1;
            rel_vect 4 nrealargs;
            rel_vect (nrealargs+4) nrealargs;
            [|mkApp (sym,Array.concat
	      [extended_rel_vect (2*nrealargs+4) paramsctxt1;
	       rel_vect (nrealargs+4) nrealargs;
	       rel_vect 4 nrealargs;
	       [|mkRel 2|]])|]]) in
  let main_body =
    mkCase (ci,
      my_it_mkLambda_or_LetIn_name realsign_ind_G applied_PG,
      applied_sym_C 3,
      [|mkVar varHC|]) in
  (my_it_mkLambda_or_LetIn mib.mind_params_ctxt
  (my_it_mkLambda_or_LetIn_name realsign
  (mkNamedLambda varP
    (my_it_mkProd_or_LetIn (if dep then realsign_ind_P else realsign_P) s)
  (mkNamedLambda varHC applied_PC
  (mkNamedLambda varH (lift 2 applied_ind)
  (if dep then (* we need a coercion *)
     mkCase (cieq,
       mkLambda (Name varH,lift 3 applied_ind,
         mkLambda (Anonymous,
                   mkApp (eq,[|lift 4 applied_ind;applied_sym_sym;mkRel 1|]),
                   applied_PR)),
       mkApp (sym_involutive,
         Array.append (extended_rel_vect 3 mip.mind_arity_ctxt) [|mkVar varH|]),
       [|main_body|])
   else
     main_body))))))

(**********************************************************************)
(* Build the left-to-right rewriting lemma for hypotheses associated  *)
(* to an inductive type I q1..qm,p1..pn a1..an with one constructor   *)
(* C : I q1..qm,p1..pn p1..pn                                         *)
(* (symmetric equality in non dependent and dependent cases)          *)
(*                                                                    *)
(* rew := fun q1..qm p1..pn a1..an (H:I q1..qm p1..pn a1..an)         *)
(*          match H in I _.._ a1..an                                  *)
(*                 return forall                                      *)
(*                  (P:forall p1..pn, I q1..qm p1..pn a1..an -> kind) *)
(*                  (HC:P p1..pn H) =>                                *)
(*                  P a1..an C                                        *)
(*          with                                                      *)
(*             C => fun P HC => HC                                    *)
(*          end                                                       *)
(*      : forall q1..qm p1..pn a1..an                                 *)
(*          (H:I q1..qm p1..pn a1..an)                                *)
(*          (P:forall p1..pn, I q1..qm p1..pn a1..an ->kind),         *)
(*          P p1..pn H -> P a1..an C                                  *)
(*                                                                    *)
(* Note: the symmetry is needed in the dependent case since the       *)
(* dependency is on the inner arguments (the indices in C) and these  *)
(* inner arguments need to be visible as parameters to be able to     *)
(* abstract over them in P.                                           *)
(**********************************************************************)

let build_l2r_forward_rew_scheme dep env ind kind =
  let (mib,mip as specif),nrealargs,realsign,paramsctxt,paramsctxt1 =
    get_sym_eq_data env ind in
  let cstr n p =
    mkApp (mkConstruct(ind,1),
      Array.concat [extended_rel_vect n paramsctxt1;
                    rel_vect p nrealargs]) in
  let varH = fresh env (default_id_of_sort (snd (mind_arity mip))) in
  let varHC = fresh env (id_of_string "HC") in
  let varP = fresh env (id_of_string "P") in
  let applied_ind = build_dependent_inductive ind specif in
  let applied_ind_P =
    mkApp (mkInd ind, Array.concat
       [extended_rel_vect (4*nrealargs+2) paramsctxt1;
        rel_vect 0 nrealargs;
        rel_vect (nrealargs+1) nrealargs]) in
  let applied_ind_P' =
    mkApp (mkInd ind, Array.concat
       [extended_rel_vect (3*nrealargs+1) paramsctxt1;
        rel_vect 0 nrealargs;
        rel_vect (2*nrealargs+1) nrealargs]) in
  let realsign_P n = lift_rel_context (nrealargs*n+n) realsign in
  let realsign_ind =
    name_context env ((Name varH,None,applied_ind)::realsign) in
  let realsign_ind_P n aP =
    name_context env ((Name varH,None,aP)::realsign_P n) in
  let s = mkSort (new_sort_in_family kind) in
  let ci = make_case_info (Global.env()) ind RegularStyle in
  let applied_PC =
    mkApp (mkVar varP,Array.append
           (rel_vect (nrealargs*2+3) nrealargs)
           (if dep then [|mkRel 2|] else [||])) in
  let applied_PC' =
    mkApp (mkVar varP,Array.append
           (rel_vect (nrealargs+2) nrealargs)
           (if dep then [|cstr (2*nrealargs+2) (nrealargs+2)|]
	    else [||])) in
  let applied_PG =
    mkApp (mkVar varP,Array.append (rel_vect 3 nrealargs)
           (if dep then [|cstr (3*nrealargs+4) 3|] else [||])) in
  (my_it_mkLambda_or_LetIn mib.mind_params_ctxt
  (my_it_mkLambda_or_LetIn_name realsign
  (mkNamedLambda varH applied_ind
  (mkCase (ci,
     my_it_mkLambda_or_LetIn_name
       (lift_rel_context (nrealargs+1) realsign_ind)
       (mkNamedProd varP
         (my_it_mkProd_or_LetIn
	   (if dep then realsign_ind_P 2 applied_ind_P else realsign_P 2) s)
       (mkNamedProd varHC applied_PC applied_PG)),
     (mkVar varH),
     [|mkNamedLambda varP
        (my_it_mkProd_or_LetIn
	  (if dep then realsign_ind_P 1 applied_ind_P' else realsign_P 2) s)
      (mkNamedLambda varHC applied_PC'
	(mkVar varHC))|])))))

(**********************************************************************)
(* Build the right-to-left rewriting lemma for hypotheses associated  *)
(* to an inductive type I q1..qm a1..an with one constructor          *)
(* C : I q1..qm b1..bn                                                *)
(* (arbitrary equality in non-dependent and dependent cases)          *)
(*                                                                    *)
(* rew := fun q1..qm a1..an (H:I q1..qm a1..an)                       *)
(*          (P:forall a1..an, I q1..qm a1..an -> kind)                *)
(*          (HC:P a1..an H) =>                                        *)
(*          match H in I _.._ a1..an return P a1..an H -> P b1..bn C  *)
(*          with                                                      *)
(*            C => fun x => x                                         *)
(*          end HC                                                    *)
(*      : forall q1..pm a1..an (H:I q1..qm a1..an)                    *)
(*          (P:forall a1..an, I q1..qm a1..an -> kind),               *)
(*          P a1..an H -> P b1..bn C                                  *)
(*                                                                    *)
(* Note that the dependent elimination here is not a dependency       *)
(* in the conclusion of the scheme but a dependency in the premise of *)
(* the scheme. This is unfortunately incompatible with the standard   *)
(* pattern for schemes in Coq which expects that the eliminated       *)
(* object is the last premise of the scheme. We then have no choice   *)
(* than following the more liberal pattern of having the eliminated   *)
(* object coming before the premises.                                 *)
(*                                                                    *)
(* Note that in the non-dependent case, this scheme (up to the order  *)
(* of premises) generalizes the (backward) l2r scheme above: same     *)
(* statement but no need for symmetry of the equality.                *)
(**********************************************************************)

let build_r2l_forward_rew_scheme dep env ind kind =
  let ((mib,mip as specif),constrargs,realsign,nrealargs) =
    get_non_sym_eq_data env ind in
  let cstr n =
    mkApp (mkConstruct(ind,1),extended_rel_vect n mib.mind_params_ctxt) in
  let constrargs_cstr = constrargs@[cstr 0] in
  let varH = fresh env (default_id_of_sort (snd (mind_arity mip))) in
  let varHC = fresh env (id_of_string "HC") in
  let varP = fresh env (id_of_string "P") in
  let applied_ind = build_dependent_inductive ind specif in
  let realsign_ind =
    name_context env ((Name varH,None,applied_ind)::realsign) in
  let s = mkSort (new_sort_in_family kind) in
  let ci = make_case_info (Global.env()) ind RegularStyle in
  let applied_PC =
    applist (mkVar varP,if dep then constrargs_cstr else constrargs) in
  let applied_PG =
    mkApp (mkVar varP,
           if dep then extended_rel_vect 0 realsign_ind
	   else extended_rel_vect 1 realsign) in
  (my_it_mkLambda_or_LetIn mib.mind_params_ctxt
  (my_it_mkLambda_or_LetIn_name realsign_ind
  (mkNamedLambda varP
    (my_it_mkProd_or_LetIn (lift_rel_context (nrealargs+1)
                             (if dep then realsign_ind else realsign)) s)
  (mkNamedLambda varHC (lift 1 applied_PG)
  (mkApp
    (mkCase (ci,
       my_it_mkLambda_or_LetIn_name
         (lift_rel_context (nrealargs+3) realsign_ind)
         (mkArrow applied_PG (lift (2*nrealargs+5) applied_PC)),
       mkRel 3 (* varH *),
       [|mkLambda
          (Name varHC,
	   lift (nrealargs+3) applied_PC,
	   mkRel 1)|]),
    [|mkVar varHC|]))))))

(**********************************************************************)
(* This function "repairs" the non-dependent r2l forward rewriting    *)
(* scheme by making it comply with the standard pattern of schemes    *)
(* in Coq. Otherwise said, it turns a scheme of type                  *)
(*                                                                    *)
(*  forall q1..pm a1..an, I q1..qm a1..an ->                          *)
(*  forall (P: forall a1..an, kind),                                  *)
(*         P a1..an -> P b1..bn                                       *)
(*                                                                    *)
(* into a scheme of type                                              *)
(*                                                                    *)
(*  forall q1..pm (P:forall a1..an, kind),                            *)
(*         P a1..an -> forall a1..an, I q1..qm a1..an -> P b1..bn     *)
(*                                                                    *)
(**********************************************************************)

let fix_r2l_forward_rew_scheme c =
  let t = Retyping.get_type_of (Global.env()) Evd.empty c in
  let ctx,_ = decompose_prod_assum t in
  match ctx with
  | hp :: p :: ind :: indargs ->
      my_it_mkLambda_or_LetIn indargs
	(mkLambda_or_LetIn (map_rel_declaration (liftn (-1) 1) p)
	  (mkLambda_or_LetIn (map_rel_declaration (liftn (-1) 2) hp)
	    (mkLambda_or_LetIn (map_rel_declaration (lift 2) ind)
	      (Reductionops.whd_beta Evd.empty
		(applist (c,
	          extended_rel_list 3 indargs @ [mkRel 1;mkRel 3;mkRel 2]))))))
  | _ -> anomaly "Ill-formed non-dependent left-to-right rewriting scheme"

(**********************************************************************)
(* Build the right-to-left rewriting lemma for conclusion associated  *)
(* to an inductive type I q1..qm a1..an with one constructor          *)
(* C : I q1..qm b1..bn                                                *)
(* (arbitrary equality in non-dependent and dependent case)           *)
(*                                                                    *)
(* This is actually the standard case analysis scheme                 *)
(*                                                                    *)
(* rew := fun q1..qm a1..an                                           *)
(*          (P:forall a1..an, I q1..qm a1..an -> kind)                *)
(*          (H:I q1..qm a1..an)                                       *)
(*          (HC:P b1..bn C) =>                                        *)
(*          match H in I _.._ a1..an return P a1..an H with           *)
(*            C => HC                                                 *)
(*          end                                                       *)
(*      : forall q1..pm a1..an                                        *)
(*          (P:forall a1..an, I q1..qm a1..an -> kind)                *)
(*          (H:I q1..qm a1..an),                                      *)
(*          P b1..bn C -> P a1..an H                                  *)
(**********************************************************************)

let build_r2l_rew_scheme dep env ind k =
  build_case_analysis_scheme env Evd.empty ind dep k

(**********************************************************************)
(* Register the rewriting schemes                                     *)
(**********************************************************************)

(**********************************************************************)
(* Dependent rewrite from left-to-right in conclusion                 *)
(* (symmetrical equality type only)                                   *)
(* Gamma |- P p1..pn H   ==>   Gamma |- P a1..an C                    *)
(* with H:I p1..pn a1..an in Gamma                                    *)
(**********************************************************************)
let rew_l2r_dep_scheme_kind =
  declare_individual_scheme_object "_rew_r_dep"
  (fun ind -> build_l2r_rew_scheme true (Global.env()) ind InType)

(**********************************************************************)
(* Dependent rewrite from right-to-left in conclusion                 *)
(* Gamma |- P a1..an H   ==>   Gamma |- P b1..bn C                    *)
(* with H:I a1..an in Gamma (non symmetric case)                      *)
(* or   H:I b1..bn a1..an in Gamma (symmetric case)                   *)
(**********************************************************************)
let rew_r2l_dep_scheme_kind =
  declare_individual_scheme_object "_rew_dep"
  (fun ind -> build_r2l_rew_scheme true (Global.env()) ind InType)

(**********************************************************************)
(* Dependent rewrite from right-to-left in hypotheses                 *)
(* Gamma, P a1..an H |- D   ==>   Gamma, P b1..bn C |- D              *)
(* with H:I a1..an in Gamma (non symmetric case)                      *)
(* or   H:I b1..bn a1..an in Gamma (symmetric case)                   *)
(**********************************************************************)
let rew_r2l_forward_dep_scheme_kind =
  declare_individual_scheme_object "_rew_fwd_dep"
  (fun ind -> build_r2l_forward_rew_scheme true (Global.env()) ind InType)

(**********************************************************************)
(* Dependent rewrite from left-to-right in hypotheses                 *)
(* (symmetrical equality type only)                                   *)
(* Gamma, P p1..pn H |- D   ==>   Gamma, P a1..an C |- D              *)
(* with H:I p1..pn a1..an in Gamma                                    *)
(**********************************************************************)
let rew_l2r_forward_dep_scheme_kind =
  declare_individual_scheme_object "_rew_fwd_r_dep"
  (fun ind -> build_l2r_forward_rew_scheme true (Global.env()) ind InType)

(**********************************************************************)
(* Non-dependent rewrite from either left-to-right in conclusion or   *)
(* right-to-left in hypotheses: both l2r_rew and r2l_forward_rew are  *)
(* potential candidates. Since l2r_rew needs a symmetrical equality,  *)
(* we adopt r2l_forward_rew (this one introduces a blocked beta-      *)
(* expansion but since the guard condition supports commutative cuts  *)
(* this is not a problem; we need though a fix to adjust it to the    *)
(* standard form of schemes in Coq)                                   *)
(**********************************************************************)
let rew_l2r_scheme_kind =
  declare_individual_scheme_object "_rew_r"
  (fun ind -> fix_r2l_forward_rew_scheme
      (build_r2l_forward_rew_scheme false (Global.env()) ind InType))

(**********************************************************************)
(* Non-dependent rewrite from either right-to-left in conclusion or   *)
(* left-to-right in hypotheses: both r2l_rew and l2r_forward_rew but  *)
(* since r2l_rew works in the non-symmetric case as well as without   *)
(* introducing commutative cuts, we adopt it                          *)
(**********************************************************************)
let rew_r2l_scheme_kind =
  declare_individual_scheme_object "_rew"
  (fun ind -> build_r2l_rew_scheme false (Global.env()) ind InType)

(* End of rewriting schemes *)

(**********************************************************************)
(* Build the congruence lemma associated to an inductive type         *)
(* I p1..pn a with one constructor C : I q1..qn b                     *)
(*                                                                    *)
(* congr := fun p1..pn (B:Type) (f:A->B) a (H:I p1..pn a) =>          *)
(*          match H in I _.._ a' return f b = f a' with               *)
(*            C => eq_refl (f b)                                      *)
(*          end                                                       *)
(*       : forall p1..pn (B:Type) (f:A->B) a, I p1..pn a -> f b = f a *)
(*                                                                    *)
(* where A is the common type of a and b                              *)
(**********************************************************************)

(* TODO: extend it to types with more than one index *)

let build_congr env (eq,refl) ind =
  let (mib,mip) = lookup_mind_specif env ind in
  if Array.length mib.mind_packets <> 1 or Array.length mip.mind_nf_lc <> 1 then
    error "Not an inductive type with a single constructor.";
  if mip.mind_nrealargs <> 1 then
    error "Expect an inductive type with one predicate parameter.";
  let i = 1 in
  let realsign,_ = list_chop mip.mind_nrealargs_ctxt mip.mind_arity_ctxt in
  if List.exists (fun (_,b,_) -> b <> None) realsign then
    error "Inductive equalities with local definitions in arity not supported.";
  let env_with_arity = push_rel_context mip.mind_arity_ctxt env in
  let (_,_,ty) = lookup_rel (mip.mind_nrealargs - i + 1) env_with_arity in
  let constrsign,ccl = decompose_prod_assum mip.mind_nf_lc.(0) in
  let _,constrargs = decompose_app ccl in
  if rel_context_length constrsign<>rel_context_length mib.mind_params_ctxt then
    error "Constructor must have no arguments";
  let b = List.nth constrargs (i + mib.mind_nparams - 1) in
  let varB = fresh env (id_of_string "B") in
  let varH = fresh env (id_of_string "H") in
  let varf = fresh env (id_of_string "f") in
  let ci = make_case_info (Global.env()) ind RegularStyle in
  my_it_mkLambda_or_LetIn mib.mind_params_ctxt
     (mkNamedLambda varB (new_Type ())
     (mkNamedLambda varf (mkArrow (lift 1 ty) (mkVar varB))
     (my_it_mkLambda_or_LetIn_name (lift_rel_context 2 realsign)
     (mkNamedLambda varH
        (applist
           (mkInd ind,
	    extended_rel_list (mip.mind_nrealargs+2) mib.mind_params_ctxt @
	    extended_rel_list 0 realsign))
     (mkCase (ci,
       my_it_mkLambda_or_LetIn_name
	 (lift_rel_context (mip.mind_nrealargs+3) realsign)
         (mkLambda
           (Anonymous,
            applist
             (mkInd ind,
	        extended_rel_list (2*mip.mind_nrealargs_ctxt+3)
		  mib.mind_params_ctxt
	        @ extended_rel_list 0 realsign),
            mkApp (eq,
	      [|mkVar varB;
                mkApp (mkVar varf, [|lift (2*mip.mind_nrealargs_ctxt+4) b|]);
		mkApp (mkVar varf, [|mkRel (mip.mind_nrealargs - i + 2)|])|]))),
       mkVar varH,
       [|mkApp (refl,
          [|mkVar varB;
	    mkApp (mkVar varf, [|lift (mip.mind_nrealargs+3) b|])|])|]))))))

let congr_scheme_kind = declare_individual_scheme_object "_congr"
  (fun ind ->
    (* May fail if equality is not defined *)
    build_congr (Global.env()) (get_coq_eq ()) ind)