]> matita.cs.unibo.it Git - helm.git/blob - matitaB/components/ng_tactics/nDestructTac.ml
dcd77499427218fa0487fbd504b8667325875132
[helm.git] / matitaB / components / ng_tactics / nDestructTac.ml
1 (* Copyright (C) 2002, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 (* $Id: destructTactic.ml 9774 2009-05-15 19:37:08Z sacerdot $ *)
27
28 open NTacStatus
29 open Continuationals.Stack
30
31 let debug = false
32 let pp = 
33   if debug then (fun x -> prerr_endline (Lazy.force x)) else (fun _ -> ())
34
35 let fresh_name =
36  let i = ref 0 in
37  function () ->
38   incr i;
39   "z" ^ string_of_int !i
40 ;;
41
42 let mk_id id =
43  let id = if id = "_" then fresh_name () else id in
44   NotationPt.Ident (id,`Ambiguous)
45 ;;
46
47 let mk_sym s = NotationPt.Symbol (s,None);;
48
49 let rec mk_prods l t =
50   match l with
51     [] -> t
52   | hd::tl -> NotationPt.Binder (`Forall, (mk_id hd, None), mk_prods tl t)
53 ;;
54
55 let mk_appl =
56  function
57     [] -> assert false
58   | [x] -> x
59   | l -> NotationPt.Appl l
60 ;;
61
62 let rec iter f n acc =
63   if n < 0 then acc
64   else iter f (n-1) (f n acc)
65 ;;
66
67 let subst_metasenv_and_fix_names status =
68   let u,h,metasenv, subst,o = status#obj in
69   let o = 
70     NCicUntrusted.map_obj_kind ~skip_body:true 
71      (NCicUntrusted.apply_subst status subst []) o
72   in
73    status#set_obj(u,h,NCicUntrusted.apply_subst_metasenv status subst metasenv,subst,o)
74 ;;
75
76 (* needed to workaround a weakness of the refiner? *)
77 let rec generalize0_tac tl s =
78   match tl with
79   | [] -> s
80   | t0::tl0 -> NTactics.generalize0_tac [t0] (generalize0_tac tl0 s)
81 ;;
82
83
84 (* input: nome della variabile riscritta
85  * output: lista dei nomi delle variabili il cui tipo dipende dall'input *)
86 let cascade_select_in_ctx status ~subst ctx skip iname =
87   let lctx, rctx = HExtlib.split_nth (iname - 1) ctx in
88   let lctx = List.rev lctx in
89   let rec rm_last = function
90       [] | [_] -> []
91     | hd::tl -> hd::(rm_last tl)
92   in
93
94   let indices,_ = List.fold_left
95        (fun (acc,context) item -> 
96           match item with
97             | n,(NCic.Decl s | NCic.Def (s,_)) 
98                   when (not (List.for_all (fun x -> NCicTypeChecker.does_not_occur status ~subst context (x-1) x s) acc)
99                    && not (List.mem n skip)) ->
100                 List.iter (fun m -> pp (lazy ("acc has " ^ (string_of_int m)))) acc;
101                 pp (lazy ("acc occurs in the type of " ^ n));
102                 (1::List.map ((+) 1) acc, item::context)
103             | _ -> (List.map ((+) 1) acc, item::context))
104        ([1], rctx) lctx in
105     let indices = rm_last indices in
106     let res = List.map (fun n -> let s,_ = List.nth ctx (n-1) in s) indices in
107     List.iter (fun n -> pp (lazy n)) res;
108     pp (lazy (status#ppcontext ~metasenv:[] ~subst ctx));
109     res, indices
110 ;;
111
112 let rec mk_fresh_name ctx firstch n =
113   let candidate = (String.make 1 firstch) ^ (string_of_int n) in
114   if (List.for_all (fun (s,_) -> s <> candidate) ctx) then candidate
115   else mk_fresh_name ctx firstch (n+1)
116 ;;
117
118 let arg_list nleft t =
119   let rec drop_prods n t =
120     if n <= 0 then t
121     else match t with
122       | NCic.Prod (_,_,ta) -> drop_prods (n-1) ta
123       | _ -> raise (Failure "drop_prods")
124   in
125   let rec aux = function
126     | NCic.Prod (_,so,ta) -> so::aux ta
127     | _ -> []
128   in aux (drop_prods nleft t)
129 ;;
130
131 let nargs it nleft consno =
132   pp (lazy (Printf.sprintf "nargs %d %d" nleft consno));
133   let _,indname,_,cl = it in
134   let _,_,t_k = List.nth cl consno in
135   List.length (arg_list nleft t_k) ;;
136
137 let default_pattern = "",0,(None,[],Some NotationPt.UserInput);;
138 let prod_pattern = 
139   "",0,(None,[],Some NotationPt.Binder 
140     (`Pi, (mk_id "_",Some (NotationPt.Appl
141       [ NotationPt.Implicit `JustOne
142       ; NotationPt.Implicit `JustOne
143       ; NotationPt.UserInput
144       ; NotationPt.Implicit `JustOne ])), 
145   NotationPt.Implicit `JustOne));;
146
147 let prod_pattern_jm = 
148   "",0,(None,[],Some NotationPt.Binder 
149     (`Pi, (mk_id "_",Some (NotationPt.Appl
150       [ NotationPt.Implicit `JustOne
151       ; NotationPt.Implicit `JustOne
152       ; NotationPt.UserInput
153       ; NotationPt.Implicit `JustOne
154       ; NotationPt.Implicit `JustOne ])),
155   NotationPt.Implicit `JustOne));;
156
157 let hp_pattern n = 
158   "",0,(None,[n, NotationPt.Appl
159       [ NotationPt.Implicit `JustOne
160       ; NotationPt.Implicit `JustOne
161       ; NotationPt.UserInput
162       ; NotationPt.Implicit `JustOne ] ], 
163   None);;
164
165 let hp_pattern_jm n = 
166   "",0,(None,[n, NotationPt.Appl
167       [ NotationPt.Implicit `JustOne
168       ; NotationPt.Implicit `JustOne
169       ; NotationPt.UserInput
170       ; NotationPt.Implicit `JustOne
171       ; NotationPt.Implicit `JustOne ] ], 
172   None);;
173
174 exception ConstructorTooBig of string;;
175
176 (* returns the discrimination = injection+contradiction principle *)
177
178 let mk_discriminator ~use_jmeq name it leftno status baseuri =
179   let itnargs = 
180     let _,_,arity,_ = it in 
181     List.length (arg_list 0 arity) in
182   let _,itname,_,_ = it in
183   let params = List.map (fun x -> "a" ^ string_of_int x) (HExtlib.list_seq 1 (itnargs+1)) in
184   let xyty = mk_appl (List.map mk_id (itname::params)) in
185
186   (* PHASE 1: derive the type of the discriminator (we'll name it "principle") *)
187
188
189   let mk_eq tys ts us es n =
190     if use_jmeq then
191       mk_appl [mk_id "jmeq";
192                NotationPt.Implicit `JustOne; List.nth ts n;
193                NotationPt.Implicit `JustOne; List.nth us n] 
194     else
195     (* eqty = Tn u0 e0...un-1 en-1 *)
196     let eqty = mk_appl 
197                  (List.nth tys n :: iter (fun i acc -> 
198                                            List.nth us i::
199                                            List.nth es i:: acc) 
200                                      (n-1) []) in
201
202     (* params = [T0;t0;...;Tn;tn;u0;e0;un-1;en-1] *)
203     let params = iter (fun i acc -> 
204                          List.nth tys i ::
205                          List.nth ts i :: acc) n
206                      (iter (fun i acc ->
207                             List.nth us i::
208                             List.nth es i:: acc) (n-1) []) in
209     mk_appl [mk_id "eq"; eqty;
210                         mk_appl (mk_id ("R" ^ string_of_int n) :: params);
211                         List.nth us n]
212
213   in
214     
215   let _,_,_,cl = it in
216
217   let kname (*it*) j =
218     let _,name,_ = List.nth cl j in
219     name
220   in
221
222   let branch i j ts us = 
223     let nargs = nargs it leftno i in
224     let es = List.map (fun x -> mk_id ("e" ^ string_of_int x)) (HExtlib.list_seq 0 nargs) in
225     let tys = List.map 
226                 (fun x -> iter 
227                   (fun i acc -> 
228                     NotationPt.Binder (`Lambda, (mk_id ("x" ^ string_of_int i), None),
229                     NotationPt.Binder (`Lambda, (mk_id ("p" ^ string_of_int i), None),
230                     acc))) (x-1) 
231                  (NotationPt.Implicit (`Tagged ("T" ^ (string_of_int x)))))
232                (HExtlib.list_seq 0 nargs) in
233     let tys = tys @ 
234       [iter (fun i acc -> 
235         NotationPt.Binder (`Lambda, (mk_id ("x" ^ string_of_int i), None),
236         NotationPt.Binder (`Lambda, (mk_id ("p" ^ string_of_int i), None),
237         acc))) (nargs-1)
238         (mk_appl [mk_id "eq"; NotationPt.Implicit `JustOne;
239           mk_appl (mk_id (kname i)::
240            List.map (fun x -> mk_id ("x" ^string_of_int x))
241               (HExtlib.list_seq 0 (List.length ts)));
242               mk_appl (mk_id (kname j)::us)])]
243     in
244     (** NotationPt.Binder (`Lambda, (mk_id "e", 
245       Some (mk_appl 
246         [mk_id "eq";
247          NotationPt.Implicit `JustOne;
248          mk_appl (mk_id (kname it i)::ts);
249          mk_appl (mk_id (kname it j)::us)])),
250     let ts = ts @ [mk_id "e"] in 
251     let refl2 = mk_appl
252                   [mk_id "refl";
253                    NotationPt.Implicit `JustOne;
254                    mk_appl (mk_id (kname it j)::us)] in
255     let us = us @ [refl2] in *)
256     NotationPt.Binder (`Forall, (mk_id "P", Some (NotationPt.Sort (`NType "1") )),
257       if i = j then 
258        NotationPt.Binder (`Forall, (mk_id "_",
259         Some (iter (fun i acc -> 
260               NotationPt.Binder (`Forall, (List.nth es i, Some (mk_eq tys ts us es i)), acc))
261               (nargs-1) 
262               (** (NotationPt.Binder (`Forall, (mk_id "_", 
263                 Some (mk_eq tys ts us es nargs)),*)
264                 (mk_id "P"))), mk_id "P")
265       else mk_id "P")
266   in
267
268   let inner i ts = NotationPt.Case 
269               (mk_id "y",None,
270                (*Some (NotationPt.Binder (`Lambda, (mk_id "y",None), 
271                  NotationPt.Binder (`Forall, (mk_id "_", Some
272                  (mk_appl [mk_id "eq";NotationPt.Implicit
273                  `JustOne;(*NotationPt.Implicit `JustOne*)
274                   mk_appl (mk_id (kname it i)::ts);mk_id "y"])),
275                  NotationPt.Implicit `JustOne )))*)
276                   None,
277                   List.map
278                   (fun j -> 
279                      let nargs_kty = nargs it leftno j in
280                      let us = iter (fun m acc -> mk_id ("u" ^ (string_of_int m))::acc) 
281                                 (nargs_kty - 1) [] in
282                      let nones = 
283                        iter (fun _ acc -> None::acc) (nargs_kty - 1) [] in
284                      NotationPt.Pattern (kname j,
285                                             None,
286                                             List.combine us nones), 
287                                 branch i j ts us)
288                   (HExtlib.list_seq 0 (List.length cl)))
289   in
290   let outer = NotationPt.Case
291                 (mk_id "x",None,
292                  None ,
293                  List.map
294                    (fun i -> 
295                       let nargs_kty = nargs it leftno i in
296                       if (nargs_kty > 5 && not use_jmeq) then raise (ConstructorTooBig (kname i)); 
297                       let ts = iter (fun m acc -> mk_id ("t" ^ (string_of_int m))::acc)
298                                  (nargs_kty - 1) [] in
299                      let nones = 
300                        iter (fun _ acc -> None::acc) (nargs_kty - 1) [] in
301                       NotationPt.Pattern (kname i,
302                                              None,
303                                              List.combine ts nones),
304                                 inner i ts)
305                    (HExtlib.list_seq 0 (List.length cl))) in
306   let principle = 
307     mk_prods params (NotationPt.Binder (`Forall, (mk_id "x",
308                                Some xyty),
309                            NotationPt.Binder (`Forall, (mk_id "y", Some xyty),
310                             (if use_jmeq then
311                              NotationPt.Binder (`Forall, (mk_id "e",
312                               Some (mk_appl
313                                [mk_sym "jmsimeq"; NotationPt.Implicit `JustOne; mk_id "x";
314                                                   NotationPt.Implicit `JustOne; mk_id "y"])),
315                                                   outer)
316                             else 
317                               NotationPt.Binder (`Forall, (mk_id "e",
318                               Some (mk_appl [mk_sym "eq";NotationPt.Implicit `JustOne; mk_id "x"; mk_id "y"])),
319                              outer)))))
320   in
321   pp (lazy ("discriminator = " ^ (NotationPp.pp_term status principle)));
322
323   (* PHASE 2: create the object for the proof of the principle: we'll name it
324    * "theorem" *)
325   let status, theorem =
326    GrafiteDisambiguate.disambiguate_nobj status ~baseuri 
327     (baseuri ^ name ^ ".def",0,
328       NotationPt.Theorem
329        (`Theorem,name,principle,
330          Some (NotationPt.Implicit (`Tagged "inv")),`DiscriminationPrinciple))
331   in 
332   let uri,height,nmenv,nsubst,nobj = theorem in
333   let ninitial_stack = Continuationals.Stack.of_nmetasenv nmenv in
334   let status = status#set_obj theorem in
335   let status = status#set_stack ninitial_stack in
336   let status = subst_metasenv_and_fix_names status in
337
338   (* PHASE 3: we finally prove the discrimination principle *)
339   let dbranch it ~use_jmeq leftno consno =
340     let refl_id = mk_sym "refl" in
341     pp (lazy (Printf.sprintf "dbranch %d %d" leftno consno));
342     let nlist = HExtlib.list_seq 0 (nargs it leftno consno) in
343     (* (\forall ...\forall P.\forall DH : ( ... = ... -> P). P) *)
344     let params = List.map (fun x -> NTactics.intro_tac ("a" ^ string_of_int x)) nlist in
345         (* NTactics.reduce_tac ~reduction:(`Normalize true)
346          * ~where:default_pattern::*)
347         params @ [
348         NTactics.intro_tac "P";
349         NTactics.intro_tac "DH";
350         NTactics.apply_tac ("",0,mk_id "DH");
351         NTactics.apply_tac ("",0,refl_id); (* well, it works even if no goal is selected after applying DH... *)
352     ] in
353   let dbranches it ~use_jmeq leftno =
354     pp (lazy (Printf.sprintf "dbranches %d" leftno));
355     let nbranches = List.length cl in 
356     let branches = iter (fun n acc -> 
357       let m = nbranches - n - 1 in
358       if m = 0 then acc @ (dbranch it ~use_jmeq leftno m)
359       else acc @ NTactics.shift_tac :: (dbranch it ~use_jmeq
360       leftno m))
361       (nbranches-1) [] in
362     if nbranches > 1 then
363          NTactics.branch_tac ~force:false:: branches @ [NTactics.merge_tac]
364     else branches
365   in
366   let print_tac s status = pp s ; status in 
367
368   let status =
369    NTactics.block_tac (
370     [print_tac (lazy "ci sono") (*;
371      NTactics.reduce_tac ~reduction:(`Normalize true) ~where:default_pattern *)
372     ]
373   @ List.map (fun x -> NTactics.intro_tac x) params @
374     [NTactics.intro_tac "x";
375      NTactics.intro_tac "y";
376      NTactics.intro_tac "Deq";
377     print_tac (lazy "ci sono 2");
378      NTactics.rewrite_tac ~dir:`RightToLeft ~what:("",0,mk_id "Deq") ~where:default_pattern;
379      NTactics.cases_tac ~what:("",0,mk_id "x") ~where:default_pattern]
380   @ dbranches it ~use_jmeq leftno) status
381   in status, status#obj
382 ;;
383
384 let hd_of_term status t =
385   match (snd (term_of_cic_term status  
386       (snd (whd status (ctx_of t) t)) (ctx_of t))) with
387   | NCic.Appl (hd::_) -> hd
388   | t -> t
389 ;;
390
391 let name_of_rel ~context rel =
392   let s, _ = List.nth context (rel-1) in s
393 ;;
394
395 (* let lookup_in_ctx ~context n =
396   List.nth context ((List.length context) - n - 1)
397 ;;*)
398
399 let discriminate_tac ~context cur_eq status =
400   pp (lazy (Printf.sprintf "discriminate: equation %s" (name_of_rel ~context cur_eq)));
401
402   
403   let eq_name,(NCic.Decl s | NCic.Def (s,_)) = List.nth context (cur_eq-1) in
404   let _,ctx' = HExtlib.split_nth cur_eq context in
405   let status, s = NTacStatus.whd status ctx' (mk_cic_term ctx' s) in
406   let status, s = term_of_cic_term status s ctx' in
407   let status,it,use_jmeq = 
408     let it, use_jmeq = match s with
409       | NCic.Appl [_;it;_;_] -> it,false
410       | NCic.Appl [_;it;_;_;_] -> it,true
411       | _ -> assert false in
412     (* XXX: serve? ho già fatto whd *)
413     let status, it = whd status ctx' (mk_cic_term ctx' it) in
414     let status, it = term_of_cic_term status it ctx' in
415     let _uri,indtyno,its = match it with
416       | NCic.Const (NReference.Ref (uri, NReference.Ind (_,indtyno,_)) as r) 
417       | NCic.Appl (NCic.Const 
418           (NReference.Ref (uri, NReference.Ind (_,indtyno,_)) as r)::_) -> 
419         uri, indtyno, NCicEnvironment.get_checked_indtys status r
420       | _ -> pp (lazy ("discriminate: indty ="  ^ status#ppterm
421                   ~metasenv:[] ~subst:[] ~context:[] it)) ; assert false in
422     let _,_,its,_,_ = its in
423     status,List.nth its indtyno, use_jmeq
424   in
425   
426   let itnargs = 
427     let _,_,arity,_ = it in 
428     List.length (arg_list 0 arity) in
429   let _,itname,_,_ = it in
430   let params = List.map (fun x -> "a" ^ string_of_int x) (HExtlib.list_seq 1 (itnargs+1)) in
431   let principle_name = 
432     if use_jmeq then itname ^ "_jmdiscr"
433     else itname ^ "_discr"
434   in
435   pp (lazy ("apply (" ^ principle_name ^ " " ^
436             (String.concat "" (HExtlib.mk_list "?" (List.length params + 2))) ^
437             " " ^ eq_name ^ ")"));
438   NTactics.apply_tac ("",0,mk_appl ([mk_id principle_name]@
439                                 HExtlib.mk_list (NotationPt.Implicit `JustOne) (List.length params + 2) @
440                                 [mk_id eq_name ])) status
441 ;;
442
443 let saturate_skip status context skip =
444   HExtlib.list_uniq
445     (List.fold_left
446       (fun acc x -> 
447          let ix = HExtlib.list_index ((=) x) (List.map fst context)
448          in match ix with
449          | None -> acc
450          | Some (i,_) -> 
451             fst (cascade_select_in_ctx status ~subst:(get_subst status) context [] (i+1)) @ acc) skip skip)
452 ;;
453       
454 let subst_tac ~context ~dir skip cur_eq =
455   fun status as oldstatus ->
456   let eq_name,(NCic.Decl s | NCic.Def (s,_)) = List.nth context (cur_eq-1) in
457   let _,ctx' = HExtlib.split_nth cur_eq context in
458   let status, s = NTacStatus.whd status ctx' (mk_cic_term ctx' s) in
459   let status, s = term_of_cic_term status s ctx' in
460   let skip = saturate_skip status context skip in
461   pp (lazy (Printf.sprintf "subst: equation %s" eq_name));
462     let l, r = match s with
463       | NCic.Appl [_;_;t1;t2] | NCic.Appl [_;_;t1;_;t2] -> t1,t2
464       | _ -> assert false in
465     let var = match dir with
466       | `LeftToRight -> l
467       | `RightToLeft -> r in
468     (* let var = match var with
469       | NCic.Rel i -> i
470       | _ -> assert false in *)
471     let names_to_gen, _ = 
472       match var with 
473       | NCic.Rel var ->
474         cascade_select_in_ctx status ~subst:(get_subst status) context skip (var+cur_eq)
475       | _ -> cascade_select_in_ctx status ~subst:(get_subst status) context skip cur_eq in
476     let varname = match var with
477       | NCic.Rel var -> 
478           let name,_ = List.nth context (var+cur_eq-1) in
479           HLog.warn (Printf.sprintf "destruct: trying to remove variable: %s" name);
480           [name]
481       | _ -> []
482     in      
483     let names_to_gen = List.filter (fun n -> n <> eq_name) names_to_gen in
484     if (List.exists (fun x -> List.mem x skip) names_to_gen)
485       then oldstatus
486     else 
487     let gen_tac x =
488       (fun s -> 
489       let x' = String.concat " " x in
490       let x = List.map mk_id x in
491       (* let s = NTactics.print_tac false ("@generalize " ^ x') s in *)
492       generalize0_tac x s) in
493     NTactics.block_tac (
494                 (* (List.map gen_tac names_to_gen)@ *)
495             [gen_tac (List.rev names_to_gen);
496                         NTactics.clear_tac names_to_gen;
497                  NTactics.rewrite_tac ~dir 
498                    ~what:("",0,mk_id eq_name) ~where:default_pattern;
499 (*                 NTactics.reduce_tac ~reduction:(`Normalize true)
500                    ~where:default_pattern;*)
501                  (* XXX: temo che la clear multipla funzioni bene soltanto se
502                   * gli identificatori sono nell'ordine giusto.
503                   * Per non saper né leggere né scrivere, usiamo due clear
504                   * invece di una *)
505                  NTactics.try_tac (NTactics.clear_tac [eq_name]);
506                  NTactics.try_tac (NTactics.clear_tac varname);
507 ]@
508                  (List.map NTactics.intro_tac (List.rev names_to_gen))) status
509 ;;
510
511 let clearid_tac ~context skip cur_eq =
512   fun status ->
513   let eq_name,(NCic.Decl s | NCic.Def (s,_)) = List.nth context (cur_eq-1) in
514   let _,ctx' = HExtlib.split_nth cur_eq context in
515   let status, s = NTacStatus.whd status ctx' (mk_cic_term ctx' s) in
516   let status, s = term_of_cic_term status s ctx' in
517   let skip = saturate_skip status context skip in
518
519   pp (lazy (Printf.sprintf "clearid: equation %s" eq_name));
520   let streicher_id = mk_id "streicherK" in
521   let names_to_gen, _ = 
522     cascade_select_in_ctx status ~subst:(get_subst status) context skip cur_eq in
523   let gen_tac x = generalize0_tac (List.map mk_id x) in
524   
525   match s with
526   (* jmeq *)
527   | NCic.Appl [_;_;_;_;_] ->
528       let names_to_gen = List.rev names_to_gen in
529       (*let gen_eq = NTactics.generalize_tac
530        ~where:("",0,(Some (mk_appl [mk_id "jmeq_to_eq";
531                                     NotationPt.Implicit `JustOne; 
532                                     NotationPt.Implicit `JustOne; 
533                                     NotationPt.Implicit `JustOne; 
534                                     mk_id eq_name]),[], Some
535                                     NotationPt.UserInput)) in*)
536       let gen_eq = generalize0_tac 
537                           [mk_appl [mk_id "jmeq_to_eq";
538                                     NotationPt.Implicit `JustOne; 
539                                     NotationPt.Implicit `JustOne; 
540                                     NotationPt.Implicit `JustOne; 
541                                     mk_id eq_name]] in
542       NTactics.block_tac ((gen_tac (List.rev names_to_gen))::gen_eq::
543                   [NTactics.clear_tac names_to_gen;
544                    NTactics.try_tac (NTactics.clear_tac [eq_name]);
545                    NTactics.apply_tac ("",0, mk_appl [streicher_id;
546                                                     NotationPt.Implicit `JustOne;
547                                                     NotationPt.Implicit `JustOne;
548                                                     NotationPt.Implicit `JustOne;
549                                                     NotationPt.Implicit `JustOne]);
550                    ] @
551                    (List.map NTactics.intro_tac names_to_gen)) status
552
553     (* leibniz *)
554   | NCic.Appl [_;_;_;_] ->
555       begin
556        let names_to_gen, _ = 
557          cascade_select_in_ctx status ~subst:(get_subst status) context skip cur_eq in
558        let names_to_gen = eq_name :: (List.rev names_to_gen) in
559        NTactics.block_tac ((gen_tac names_to_gen)::
560                    [NTactics.clear_tac names_to_gen;
561                     NTactics.apply_tac ("",0, mk_appl [streicher_id;
562                                                     NotationPt.Implicit `JustOne;
563                                                     NotationPt.Implicit `JustOne;
564                                                     NotationPt.Implicit `JustOne;
565                                                     NotationPt.Implicit `JustOne])
566    (*                 NTactics.reduce_tac ~reduction:(`Normalize true) 
567                       ~where:default_pattern *)
568                     ] @
569                     let names_to_intro = List.tl names_to_gen in
570                     (List.map NTactics.intro_tac names_to_intro)) status
571      end
572   | _ -> assert false
573
574 ;;
575
576 let get_ctx st goal =
577     ctx_of (get_goalty st goal)
578 ;;
579
580 (* = select + classify *)
581 let select_eq ctx acc domain status goal =
582   let classify ~use_jmeq ~subst ctx' l r =
583     (* FIXME: metasenv *)
584     if NCicReduction.are_convertible status ~metasenv:[] ~subst ctx' l r 
585       then status, `Identity
586       else status, (match hd_of_term status (mk_cic_term ctx' l),
587                           hd_of_term status (mk_cic_term ctx' r) with
588         | NCic.Const (NReference.Ref (_,NReference.Con (_,ki,nleft)) as kref),
589           NCic.Const (NReference.Ref (_,NReference.Con (_,kj,_))) -> 
590             if ki != kj then `Discriminate (0,true, use_jmeq)
591             else
592               let rit = NReference.mk_indty true kref in
593               let _,_,its,_,itno = NCicEnvironment.get_checked_indtys status rit in 
594               let it = List.nth its itno in
595               let newprods = nargs it nleft (ki-1) in
596               `Discriminate (newprods, false, use_jmeq) 
597         | NCic.Rel j, _  
598             when NCicTypeChecker.does_not_occur status ~subst ctx' (j-1) j r
599               && l = NCic.Rel j -> `Subst `LeftToRight
600         | _, NCic.Rel j 
601             when NCicTypeChecker.does_not_occur status ~subst ctx' (j-1) j l 
602               && r = NCic.Rel j -> `Subst `RightToLeft
603         | (NCic.Rel _, _ | _, NCic.Rel _ ) -> `Cycle (* could be a blob too... *)
604         | _ -> `Blob) in
605   let rec aux i =
606     try
607       let index = List.length ctx - i in
608       pp (lazy ("provo classify di index = " ^string_of_int index));
609       match (List.nth ctx (index - 1)) with
610       | n, (NCic.Decl ty | NCic.Def (ty,_)) ->
611           (let _,ctx_ty = HExtlib.split_nth index ctx in 
612            let status, ty = NTacStatus.whd status ctx_ty (mk_cic_term ctx_ty ty) in
613            let status, ty = term_of_cic_term status ty ctx_ty in
614            pp (lazy (Printf.sprintf "select_eq tries %s" (status#ppterm ~context:ctx_ty ~subst:[] ~metasenv:[] ty)));
615            let status, kind = match ty with
616            | NCic.Appl [NCic.Const (NReference.Ref (u,_)) ;_;l;r] 
617                when NUri.name_of_uri u = "eq" ->
618                classify ~use_jmeq:false ~subst:(get_subst status) ctx_ty l r
619            | NCic.Appl [NCic.Const (NReference.Ref (u,_)) ;lty;l;rty;r]
620                when NUri.name_of_uri u = "jmeq" && 
621                  NCicReduction.are_convertible status ~metasenv:[] 
622                    ~subst:(get_subst status) ctx_ty lty rty
623                -> classify ~use_jmeq:true ~subst:(get_subst status) ctx_ty l r
624            | _ -> status, `NonEq 
625            in match kind with
626               | `Identity ->
627                   let status, goalty = term_of_cic_term status (get_goalty status goal) ctx in
628                      status, Some (List.length ctx - i), kind
629               | `Cycle | `Blob | `NonEq -> aux (i+1) (* XXX: skip cyclic/blob equations for now *)
630               | _ -> 
631                  if (List.for_all (fun x -> x <> n) acc) && 
632                     (List.exists (fun x -> x = n) domain) 
633                  then status, Some (List.length ctx - i), kind
634                  else aux (i+1))
635     with Failure _ | Invalid_argument _ -> status, None, `Blob
636   in aux 0
637 ;;
638
639 let tagged_intro_tac curtag name =
640   match curtag with
641   | _ -> NTactics.intro_tac name
642 (*  | `Eq use_jmeq ->
643       NTactics.block_tac
644         [ NTactics.intro_tac name 
645         ; NTactics.reduce_tac 
646             ~reduction:(`Whd true) ~where:((if use_jmeq then hp_pattern_jm else
647                     hp_pattern) name) ] *)
648         
649 (*        status in
650       distribute_tac (fun s g ->
651         let eq_name,(NCic.Decl s | NCic.Def (s,_)) = List.nth context (cur_eq-1) in
652         let _,ctx' = HExtlib.split_nth cur_eq context in
653         let status, s = NTacStatus.whd status ctx' (mk_cic_term ctx' s) in
654         let status, s = term_of_cic_term status s ctx' in
655         let use_jmeq =
656           match s with
657           | NCic.Appl [_;it;t1;t2] -> false
658           | NCic.Appl [_;it;t1;_;t2] -> true
659           | _ -> assert false in
660       ) status
661     let it, t1, t2, use_jmeq = match s with
662       | NCic.Appl [_;it;t1;t2] -> it,t1,t2,false
663       | NCic.Appl [_;it;t1;_;t2] -> it,t1,t2,true
664       | _ -> assert false in
665            [ NTactics.intro_tac name
666            ; NTactics.reduce_tac ~reduction:(`Whd true) ~where:prod_pattern ]*)
667 ;;
668
669 let rec destruct_tac0 tags acc domain skip status goal =
670   let pptag = function
671     | `Eq false -> "eq"
672     | `Eq true -> "jmeq"
673     | `Notag -> "reg"
674   in
675   let pptags tags = String.concat ", " (List.map pptag tags) in
676   let ctx = get_ctx status goal in
677   let subst = get_subst status in
678   let get_newgoal os ns ogoal =
679     let go, gc = NTactics.compare_statuses ~past:os ~present:ns in
680     let go' = ([ogoal] @- gc) @+ go in
681       match go' with [] -> assert false | g::_ -> g
682   in
683   let status, selection, kind  = select_eq ctx acc domain status goal in
684   pp (lazy ("destruct: acc is " ^ String.concat "," acc ));
685   match selection, kind with
686   | None, _ -> 
687     pp (lazy (Printf.sprintf 
688        "destruct: no selection, context is %s, stack is %s" 
689        (status#ppcontext ~metasenv:[] ~subst ctx) (pptags tags)));
690      (match tags with 
691       | [] -> status
692       | curtag::tags' ->
693         let fresh = mk_fresh_name ctx 'e' 0 in 
694         let status' = NTactics.exec (tagged_intro_tac curtag fresh) status goal in
695         destruct_tac0 tags' acc (fresh::domain) skip status' 
696           (get_newgoal status status' goal))
697   | Some cur_eq, `Discriminate (newprods,conflict,use_jmeq) -> 
698     pp (lazy (Printf.sprintf 
699       "destruct: discriminate - nselection is %d, context is %s,stack is %s" 
700        cur_eq (status#ppcontext ~metasenv:[] ~subst ctx) (pptags tags)));
701       let status' = NTactics.exec (discriminate_tac ~context:ctx cur_eq) status goal in
702       if conflict then status'
703       else 
704         let newtags = HExtlib.mk_list (`Eq use_jmeq) newprods in
705         destruct_tac0 (newtags@tags) 
706              (name_of_rel ~context:ctx cur_eq::acc) 
707              (List.filter (fun x -> x <> name_of_rel ~context:ctx cur_eq) domain)
708              skip 
709              status' (get_newgoal status status' goal)
710   | Some cur_eq, `Subst dir ->
711     pp (lazy (Printf.sprintf 
712       "destruct: subst - selection is %d, context is %s, stack is %s" 
713         cur_eq (status#ppcontext ~metasenv:[] ~subst ctx) (pptags tags)));
714     let status' = NTactics.exec (subst_tac ~context:ctx ~dir skip cur_eq) status goal in
715       pp (lazy (Printf.sprintf " ctx after subst = %s" (status#ppcontext ~metasenv:[] ~subst (get_ctx status' (get_newgoal status status' goal)))));
716     let eq_name,_ = List.nth ctx (cur_eq-1) in
717     let newgoal = get_newgoal status status' goal in
718     let has_cleared = 
719      try 
720        let _ = NTactics.find_in_context eq_name (get_ctx status' newgoal) in false
721      with _ -> true in
722     let rm_eq b l = if b then List.filter (fun x -> x <> eq_name) l else l in
723     let acc = rm_eq has_cleared acc in
724     let skip = rm_eq has_cleared skip in
725     let domain = rm_eq has_cleared domain in
726       destruct_tac0 tags acc domain skip status' newgoal
727  | Some cur_eq, `Identity ->
728     pp (lazy (Printf.sprintf 
729       "destruct: identity - selection is %d, context is %s, stack is %s" 
730         cur_eq (status#ppcontext ~metasenv:[] ~subst ctx) (pptags tags)));
731       let eq_name,_ = List.nth ctx (cur_eq-1) in
732       let status' = NTactics.exec (clearid_tac ~context:ctx skip cur_eq) status goal in
733       let newgoal = get_newgoal status status' goal in
734       let has_cleared = 
735        try 
736          let _ = NTactics.find_in_context eq_name (get_ctx status' newgoal) in false
737        with _ -> true in
738       let rm_eq b l = if b then List.filter (fun x -> x <> eq_name) l else l in
739       let acc = rm_eq has_cleared acc in
740       let skip = rm_eq has_cleared skip in
741       let domain = rm_eq has_cleared domain in
742         destruct_tac0 tags acc domain skip status' newgoal
743   | Some cur_eq, `Cycle -> (* TODO, should never happen *)
744     pp (lazy (Printf.sprintf 
745       "destruct: cycle - selection is %d, context is %s, stack is %s" 
746         cur_eq (status#ppcontext ~metasenv:[] ~subst ctx) (pptags tags)));
747       assert false
748   | Some cur_eq, `Blob ->
749     pp (lazy (Printf.sprintf 
750       "destruct: blob - selection is %d, context is %s, stack is %s"
751       cur_eq (status#ppcontext ~metasenv:[] ~subst ctx) (pptags tags)));
752       assert false
753   | _ -> assert false
754 ;;
755
756 let destruct_tac dom skip s = 
757   NTactics.distribute_tac 
758     (fun s' g -> 
759      let ctx = get_ctx s' g in
760      let domain = match dom with
761        | None -> List.map (fun (n,_) -> n) ctx
762        | Some l -> l 
763      in
764      destruct_tac0 [] [] domain skip s' g) s;;