]> matita.cs.unibo.it Git - helm.git/blob - matita/components/ng_tactics/nDestructTac.ml
- now destruct tries to clear the replaced variables (from wilmer's
[helm.git] / matita / 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,None)
45 ;;
46
47 let mk_sym s = NotationPt.Symbol (s,0);;
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 (* creates the discrimination = injection+contradiction principle *)
175 exception ConstructorTooBig of string;;
176
177 let mk_discriminator ~use_jmeq name it leftno status baseuri =
178   let itnargs = 
179     let _,_,arity,_ = it in 
180     List.length (arg_list 0 arity) in
181   let _,itname,_,_ = it in
182   let params = List.map (fun x -> "a" ^ string_of_int x) (HExtlib.list_seq 1 (itnargs+1)) in
183   let xyty = mk_appl (List.map mk_id (itname::params)) in
184
185   (* PHASE 1: derive the type of the discriminator (we'll name it "principle") *)
186
187   let mk_eq tys ts us es n =
188     if use_jmeq then
189       mk_appl [mk_id "jmeq";
190                NotationPt.Implicit `JustOne; List.nth ts n;
191                NotationPt.Implicit `JustOne; List.nth us n] 
192     else
193     (* eqty = Tn u0 e0...un-1 en-1 *)
194     let eqty = mk_appl 
195                  (List.nth tys n :: iter (fun i acc -> 
196                                            List.nth us i::
197                                            List.nth es i:: acc) 
198                                      (n-1) []) in
199
200     (* params = [T0;t0;...;Tn;tn;u0;e0;un-1;en-1] *)
201     let params = iter (fun i acc -> 
202                          List.nth tys i ::
203                          List.nth ts i :: acc) n
204                      (iter (fun i acc ->
205                             List.nth us i::
206                             List.nth es i:: acc) (n-1) []) in
207     mk_appl [mk_id "eq"; eqty;
208                         mk_appl (mk_id ("R" ^ string_of_int n) :: params);
209                         List.nth us n]
210
211   in
212     
213   let _,_,_,cl = it in
214
215   let kname (*it*) j =
216     let _,name,_ = List.nth cl j in
217     name
218   in
219
220   let branch i j ts us = 
221     let nargs = nargs it leftno i in
222     let es = List.map (fun x -> mk_id ("e" ^ string_of_int x)) (HExtlib.list_seq 0 nargs) in
223     let tys = List.map 
224                 (fun x -> iter 
225                   (fun i acc -> 
226                     NotationPt.Binder (`Lambda, (mk_id ("x" ^ string_of_int i), None),
227                     NotationPt.Binder (`Lambda, (mk_id ("p" ^ string_of_int i), None),
228                     acc))) (x-1) 
229                  (NotationPt.Implicit (`Tagged ("T" ^ (string_of_int x)))))
230                (HExtlib.list_seq 0 nargs) in
231     let tys = tys @ 
232       [iter (fun i acc -> 
233         NotationPt.Binder (`Lambda, (mk_id ("x" ^ string_of_int i), None),
234         NotationPt.Binder (`Lambda, (mk_id ("p" ^ string_of_int i), None),
235         acc))) (nargs-1)
236         (mk_appl [mk_id "eq"; NotationPt.Implicit `JustOne;
237           mk_appl (mk_id (kname i)::
238            List.map (fun x -> mk_id ("x" ^string_of_int x))
239               (HExtlib.list_seq 0 (List.length ts)));
240               mk_appl (mk_id (kname j)::us)])]
241     in
242     (** NotationPt.Binder (`Lambda, (mk_id "e", 
243       Some (mk_appl 
244         [mk_id "eq";
245          NotationPt.Implicit `JustOne;
246          mk_appl (mk_id (kname it i)::ts);
247          mk_appl (mk_id (kname it j)::us)])),
248     let ts = ts @ [mk_id "e"] in 
249     let refl2 = mk_appl
250                   [mk_id "refl";
251                    NotationPt.Implicit `JustOne;
252                    mk_appl (mk_id (kname it j)::us)] in
253     let us = us @ [refl2] in *)
254     NotationPt.Binder (`Forall, (mk_id "P", Some (NotationPt.Sort (`NType "1") )),
255       if i = j then 
256        NotationPt.Binder (`Forall, (mk_id "_",
257         Some (iter (fun i acc -> 
258               NotationPt.Binder (`Forall, (List.nth es i, Some (mk_eq tys ts us es i)), acc))
259               (nargs-1) 
260               (** (NotationPt.Binder (`Forall, (mk_id "_", 
261                 Some (mk_eq tys ts us es nargs)),*)
262                 (mk_id "P"))), mk_id "P")
263       else mk_id "P")
264   in
265
266   let inner i ts = NotationPt.Case 
267               (mk_id "y",None,
268                (*Some (NotationPt.Binder (`Lambda, (mk_id "y",None), 
269                  NotationPt.Binder (`Forall, (mk_id "_", Some
270                  (mk_appl [mk_id "eq";NotationPt.Implicit
271                  `JustOne;(*NotationPt.Implicit `JustOne*)
272                   mk_appl (mk_id (kname it i)::ts);mk_id "y"])),
273                  NotationPt.Implicit `JustOne )))*)
274                   None,
275                   List.map
276                   (fun j -> 
277                      let nargs_kty = nargs it leftno j in
278                      let us = iter (fun m acc -> mk_id ("u" ^ (string_of_int m))::acc) 
279                                 (nargs_kty - 1) [] in
280                      let nones = 
281                        iter (fun _ acc -> None::acc) (nargs_kty - 1) [] in
282                      NotationPt.Pattern (kname j,
283                                             None,
284                                             List.combine us nones), 
285                                 branch i j ts us)
286                   (HExtlib.list_seq 0 (List.length cl)))
287   in
288   let outer = NotationPt.Case
289                 (mk_id "x",None,
290                  None ,
291                  List.map
292                    (fun i -> 
293                       let nargs_kty = nargs it leftno i in
294                       if (nargs_kty > 5 && not use_jmeq) then raise (ConstructorTooBig (kname i)); 
295                       let ts = iter (fun m acc -> mk_id ("t" ^ (string_of_int m))::acc)
296                                  (nargs_kty - 1) [] in
297                      let nones = 
298                        iter (fun _ acc -> None::acc) (nargs_kty - 1) [] in
299                       NotationPt.Pattern (kname i,
300                                              None,
301                                              List.combine ts nones),
302                                 inner i ts)
303                    (HExtlib.list_seq 0 (List.length cl))) in
304   let principle = 
305     mk_prods params (NotationPt.Binder (`Forall, (mk_id "x",
306                                Some xyty),
307                            NotationPt.Binder (`Forall, (mk_id "y", Some xyty),
308                             (if use_jmeq then
309                              NotationPt.Binder (`Forall, (mk_id "e",
310                               Some (mk_appl
311                                [mk_sym "jmsimeq"; NotationPt.Implicit `JustOne; mk_id "x";
312                                                   NotationPt.Implicit `JustOne; mk_id "y"])),
313                                                   outer)
314                             else 
315                               NotationPt.Binder (`Forall, (mk_id "e",
316                               Some (mk_appl [mk_sym "eq";NotationPt.Implicit `JustOne; mk_id "x"; mk_id "y"])),
317                              outer)))))
318   in
319   pp (lazy ("discriminator = " ^ (NotationPp.pp_term status principle)));
320
321   (* PHASE 2: create the object for the proof of the principle: we'll name it
322    * "theorem" *)
323   let status, theorem =
324    GrafiteDisambiguate.disambiguate_nobj status ~baseuri 
325     (baseuri ^ name ^ ".def",0,
326       NotationPt.Theorem
327        (`Theorem,name,principle,
328          Some (NotationPt.Implicit (`Tagged "inv")),`DiscriminationPrinciple))
329   in 
330   let uri,height,nmenv,nsubst,nobj = theorem in
331   let ninitial_stack = Continuationals.Stack.of_nmetasenv nmenv in
332   let status = status#set_obj theorem in
333   let status = status#set_stack ninitial_stack in
334   let status = subst_metasenv_and_fix_names status in
335
336   (* PHASE 3: we finally prove the discrimination principle *)
337   let dbranch it ~use_jmeq leftno consno =
338     let refl_id = mk_sym "refl" in
339     pp (lazy (Printf.sprintf "dbranch %d %d" leftno consno));
340     let nlist = HExtlib.list_seq 0 (nargs it leftno consno) in
341     (* (\forall ...\forall P.\forall DH : ( ... = ... -> P). P) *)
342     let params = List.map (fun x -> NTactics.intro_tac ("a" ^ string_of_int x)) nlist in
343         (* NTactics.reduce_tac ~reduction:(`Normalize true)
344          * ~where:default_pattern::*)
345         params @ [
346         NTactics.intro_tac "P";
347         NTactics.intro_tac "DH";
348         NTactics.apply_tac ("",0,mk_id "DH");
349         NTactics.apply_tac ("",0,refl_id); (* well, it works even if no goal is selected after applying DH... *)
350     ] in
351   let dbranches it ~use_jmeq leftno =
352     pp (lazy (Printf.sprintf "dbranches %d" leftno));
353     let nbranches = List.length cl in 
354     let branches = iter (fun n acc -> 
355       let m = nbranches - n - 1 in
356       if m = 0 then acc @ (dbranch it ~use_jmeq leftno m)
357       else acc @ NTactics.shift_tac :: (dbranch it ~use_jmeq
358       leftno m))
359       (nbranches-1) [] in
360     if nbranches > 1 then
361          NTactics.branch_tac ~force:false:: branches @ [NTactics.merge_tac]
362     else branches
363   in
364   let print_tac s status = pp s ; status in 
365
366   let status =
367    NTactics.block_tac (
368     [print_tac (lazy "ci sono") (*;
369      NTactics.reduce_tac ~reduction:(`Normalize true) ~where:default_pattern *)
370     ]
371   @ List.map (fun x -> NTactics.intro_tac x) params @
372     [NTactics.intro_tac "x";
373      NTactics.intro_tac "y";
374      NTactics.intro_tac "Deq";
375     print_tac (lazy "ci sono 2");
376      NTactics.rewrite_tac ~dir:`RightToLeft ~what:("",0,mk_id "Deq") ~where:default_pattern;
377      NTactics.cases_tac ~what:("",0,mk_id "x") ~where:default_pattern]
378   @ dbranches it ~use_jmeq leftno) status
379   in status, status#obj
380 ;;
381
382 let hd_of_term = function
383   | NCic.Appl (hd::_) -> hd
384   | t -> t
385 ;;
386
387 let name_of_rel ~context rel =
388   let s, _ = List.nth context (rel-1) in s
389 ;;
390
391 (* let lookup_in_ctx ~context n =
392   List.nth context ((List.length context) - n - 1)
393 ;;*)
394
395 let discriminate_tac ~context cur_eq status =
396   pp (lazy (Printf.sprintf "discriminate: equation %s" (name_of_rel ~context cur_eq)));
397
398   
399   let eq_name,(NCic.Decl s | NCic.Def (s,_)) = List.nth context (cur_eq-1) in
400   let _,ctx' = HExtlib.split_nth cur_eq context in
401   let status, s = NTacStatus.whd status ctx' (mk_cic_term ctx' s) in
402   let status, s = term_of_cic_term status s ctx' in
403   let status,it,use_jmeq = 
404     let it,use_jmeq = match s with
405       | NCic.Appl [_;it;_;_] -> it,false
406       | NCic.Appl [_;it;_;_;_] -> it,true
407       | _ -> assert false in
408     (* XXX: serve? ho già fatto whd *)
409     let status, it = whd status ctx' (mk_cic_term ctx' it) in
410     let status, it = term_of_cic_term status it ctx' in
411     let _uri,indtyno,its = match it with
412       | NCic.Const (NReference.Ref (uri, NReference.Ind (_,indtyno,_)) as r) 
413       | NCic.Appl (NCic.Const 
414           (NReference.Ref (uri, NReference.Ind (_,indtyno,_)) as r)::_) -> 
415         uri, indtyno, NCicEnvironment.get_checked_indtys status r
416       | _ -> pp (lazy ("discriminate: indty ="  ^ status#ppterm
417                   ~metasenv:[] ~subst:[] ~context:[] it)) ; assert false in
418     let _,_,its,_,_ = its in
419     status,List.nth its indtyno, use_jmeq
420   in
421   
422   let itnargs = 
423     let _,_,arity,_ = it in 
424     List.length (arg_list 0 arity) in
425   let _,itname,_,_ = it in
426   let params = List.map (fun x -> "a" ^ string_of_int x) (HExtlib.list_seq 1 (itnargs+1)) in
427   let principle_name = 
428     if use_jmeq then itname ^ "_jmdiscr"
429     else itname ^ "_discr"
430   in
431   pp (lazy ("apply (" ^ principle_name ^ " " ^
432             (String.concat "" (HExtlib.mk_list "?" (List.length params + 2))) ^
433             " " ^ eq_name ^ ")"));
434   NTactics.apply_tac ("",0,mk_appl ([mk_id principle_name]@
435                                 HExtlib.mk_list (NotationPt.Implicit `JustOne) (List.length params + 2) @
436                                 [mk_id eq_name ])) status
437 ;;
438
439 let saturate_skip status context skip =
440   HExtlib.list_uniq
441     (List.fold_left
442       (fun acc x -> 
443          let ix = HExtlib.list_index ((=) x) (List.map fst context)
444          in match ix with
445          | None -> acc
446          | Some (i,_) -> 
447             fst (cascade_select_in_ctx status ~subst:(get_subst status) context [] (i+1)) @ acc) skip skip)
448 ;;
449       
450 let subst_tac ~context ~dir skip cur_eq =
451   fun status as oldstatus ->
452   let eq_name,(NCic.Decl s | NCic.Def (s,_)) = List.nth context (cur_eq-1) in
453   let _,ctx' = HExtlib.split_nth cur_eq context in
454   let status, s = NTacStatus.whd status ctx' (mk_cic_term ctx' s) in
455   let status, s = term_of_cic_term status s ctx' in
456   let skip = saturate_skip status context skip in
457   pp (lazy (Printf.sprintf "subst: equation %s" eq_name));
458     let l, r = match s with
459       | NCic.Appl [_;_;t1;t2] | NCic.Appl [_;_;t1;_;t2] -> t1,t2
460       | _ -> assert false in
461     let var = match dir with
462       | `LeftToRight -> l
463       | `RightToLeft -> r in
464     (* let var = match var with
465       | NCic.Rel i -> i
466       | _ -> assert false in *)
467     let names_to_gen, _ = 
468       match var with 
469       | NCic.Rel var ->
470         cascade_select_in_ctx status ~subst:(get_subst status) context skip (var+cur_eq)
471       | _ -> cascade_select_in_ctx status ~subst:(get_subst status) context skip cur_eq in
472     let varname = match var with
473       | NCic.Rel var -> 
474           let name,_ = List.nth context var in [name]
475       | _ -> []
476     in      
477     let names_to_gen = List.filter (fun n -> n <> eq_name) names_to_gen in
478     if (List.exists (fun x -> List.mem x skip) names_to_gen)
479       then oldstatus
480     else 
481     let gen_tac x =
482       (fun s -> 
483       let x' = String.concat " " x in
484       let x = List.map mk_id x in
485       (* let s = NTactics.print_tac false ("@generalize " ^ x') s in *)
486       generalize0_tac x s) in
487     NTactics.block_tac (
488                 (* (List.map gen_tac names_to_gen)@ *)
489             [gen_tac (List.rev names_to_gen);
490                         NTactics.clear_tac names_to_gen;
491                  NTactics.rewrite_tac ~dir 
492                    ~what:("",0,mk_id eq_name) ~where:default_pattern;
493 (*                 NTactics.reduce_tac ~reduction:(`Normalize true)
494                    ~where:default_pattern;*)
495                  (* XXX: temo che la clear multipla funzioni bene soltanto se
496                   * gli identificatori sono nell'ordine giusto.
497                   * Per non saper né leggere né scrivere, usiamo due clear
498                   * invece di una *)               
499                  NTactics.try_tac (NTactics.clear_tac [eq_name]);
500                  NTactics.try_tac (NTactics.clear_tac varname);
501 ]@
502                  (List.map NTactics.intro_tac (List.rev names_to_gen))) status
503 ;;
504
505 let clearid_tac ~context skip cur_eq =
506   fun status ->
507   let eq_name,(NCic.Decl s | NCic.Def (s,_)) = List.nth context (cur_eq-1) in
508   let _,ctx' = HExtlib.split_nth cur_eq context in
509   let status, s = NTacStatus.whd status ctx' (mk_cic_term ctx' s) in
510   let status, s = term_of_cic_term status s ctx' in
511   let skip = saturate_skip status context skip in
512
513   pp (lazy (Printf.sprintf "clearid: equation %s" eq_name));
514   let streicher_id = mk_id "streicherK" in
515   let names_to_gen, _ = 
516     cascade_select_in_ctx status ~subst:(get_subst status) context skip cur_eq in
517   let gen_tac x = generalize0_tac (List.map mk_id x) in
518   
519   match s with
520   (* jmeq *)
521   | NCic.Appl [_;_;_;_;_] ->
522       let names_to_gen = List.rev names_to_gen in
523       (*let gen_eq = NTactics.generalize_tac
524        ~where:("",0,(Some (mk_appl [mk_id "jmeq_to_eq";
525                                     NotationPt.Implicit `JustOne; 
526                                     NotationPt.Implicit `JustOne; 
527                                     NotationPt.Implicit `JustOne; 
528                                     mk_id eq_name]),[], Some
529                                     NotationPt.UserInput)) in*)
530       let gen_eq = generalize0_tac 
531                           [mk_appl [mk_id "jmeq_to_eq";
532                                     NotationPt.Implicit `JustOne; 
533                                     NotationPt.Implicit `JustOne; 
534                                     NotationPt.Implicit `JustOne; 
535                                     mk_id eq_name]] in
536       NTactics.block_tac ((gen_tac (List.rev names_to_gen))::gen_eq::
537                   [NTactics.clear_tac names_to_gen;
538                    NTactics.try_tac (NTactics.clear_tac [eq_name]);
539                    NTactics.apply_tac ("",0, mk_appl [streicher_id;
540                                                     NotationPt.Implicit `JustOne;
541                                                     NotationPt.Implicit `JustOne;
542                                                     NotationPt.Implicit `JustOne;
543                                                     NotationPt.Implicit `JustOne]);
544                    ] @
545                    (List.map NTactics.intro_tac names_to_gen)) status
546
547     (* leibniz *)
548   | NCic.Appl [_;_;_;_] ->
549       begin
550        let names_to_gen, _ = 
551          cascade_select_in_ctx status ~subst:(get_subst status) context skip cur_eq in
552        let names_to_gen = eq_name :: (List.rev names_to_gen) in
553        NTactics.block_tac ((gen_tac names_to_gen)::
554                    [NTactics.clear_tac names_to_gen;
555                     NTactics.apply_tac ("",0, mk_appl [streicher_id;
556                                                     NotationPt.Implicit `JustOne;
557                                                     NotationPt.Implicit `JustOne;
558                                                     NotationPt.Implicit `JustOne;
559                                                     NotationPt.Implicit `JustOne])
560    (*                 NTactics.reduce_tac ~reduction:(`Normalize true) 
561                       ~where:default_pattern *)
562                     ] @
563                     let names_to_intro = List.tl names_to_gen in
564                     (List.map NTactics.intro_tac names_to_intro)) status
565      end
566   | _ -> assert false
567
568 ;;
569
570 let get_ctx st goal =
571     ctx_of (get_goalty st goal)
572 ;;
573
574 (* = select + classify *)
575 let select_eq ctx acc domain status goal =
576   let classify ~use_jmeq ~subst ctx' l r =
577     (* FIXME: metasenv *)
578     if NCicReduction.are_convertible status ~metasenv:[] ~subst ctx' l r 
579       then status, `Identity
580       else status, (match hd_of_term l, hd_of_term r with
581         | NCic.Const (NReference.Ref (_,NReference.Con (_,ki,nleft)) as kref),
582           NCic.Const (NReference.Ref (_,NReference.Con (_,kj,_))) -> 
583             if ki != kj then `Discriminate (0,true, use_jmeq)
584             else
585               let rit = NReference.mk_indty true kref in
586               let _,_,its,_,itno = NCicEnvironment.get_checked_indtys status rit in 
587               let it = List.nth its itno in
588               let newprods = nargs it nleft (ki-1) in
589               `Discriminate (newprods, false, use_jmeq) 
590         | NCic.Rel j, _  
591             when NCicTypeChecker.does_not_occur status ~subst ctx' (j-1) j r
592               && l = NCic.Rel j -> `Subst `LeftToRight
593         | _, NCic.Rel j 
594             when NCicTypeChecker.does_not_occur status ~subst ctx' (j-1) j l 
595               && r = NCic.Rel j -> `Subst `RightToLeft
596         | (NCic.Rel _, _ | _, NCic.Rel _ ) -> `Cycle (* could be a blob too... *)
597         | _ -> `Blob) in
598   let rec aux i =
599     try
600       let index = List.length ctx - i in
601       pp (lazy ("provo classify di index = " ^string_of_int index));
602       match (List.nth ctx (index - 1)) with
603       | n, (NCic.Decl ty | NCic.Def (ty,_)) ->
604           (let _,ctx_ty = HExtlib.split_nth index ctx in 
605            let status, ty = NTacStatus.whd status ctx_ty (mk_cic_term ctx_ty ty) in
606            let status, ty = term_of_cic_term status ty ctx_ty in
607            pp (lazy (Printf.sprintf "select_eq tries %s" (status#ppterm ~context:ctx_ty ~subst:[] ~metasenv:[] ty)));
608            let status, kind = match ty with
609            | NCic.Appl [NCic.Const (NReference.Ref (u,_)) ;_;l;r] 
610                when NUri.name_of_uri u = "eq" ->
611                classify ~use_jmeq:false ~subst:(get_subst status) ctx_ty l r
612            | NCic.Appl [NCic.Const (NReference.Ref (u,_)) ;lty;l;rty;r]
613                when NUri.name_of_uri u = "jmeq" && 
614                  NCicReduction.are_convertible status ~metasenv:[] 
615                    ~subst:(get_subst status) ctx_ty lty rty
616                -> classify ~use_jmeq:true ~subst:(get_subst status) ctx_ty l r
617            | _ -> status, `NonEq 
618            in match kind with
619               | `Identity ->
620                   let status, goalty = term_of_cic_term status (get_goalty status goal) ctx in
621                      status, Some (List.length ctx - i), kind
622               | `Cycle | `Blob | `NonEq -> aux (i+1) (* XXX: skip cyclic/blob equations for now *)
623               | _ -> 
624                  if (List.for_all (fun x -> x <> n) acc) && 
625                     (List.exists (fun x -> x = n) domain) 
626                  then status, Some (List.length ctx - i), kind
627                  else aux (i+1))
628     with Failure _ | Invalid_argument _ -> status, None, `Blob
629   in aux 0
630 ;;
631
632 let tagged_intro_tac curtag name =
633   match curtag with
634   | `Notag -> NTactics.intro_tac name
635   | `Eq use_jmeq ->
636       NTactics.block_tac
637         [ NTactics.intro_tac name 
638         ; NTactics.reduce_tac 
639             ~reduction:(`Whd true) ~where:((if use_jmeq then hp_pattern_jm else hp_pattern) name) ]
640         
641 (*        status in
642       distribute_tac (fun s g ->
643         let eq_name,(NCic.Decl s | NCic.Def (s,_)) = List.nth context (cur_eq-1) in
644         let _,ctx' = HExtlib.split_nth cur_eq context in
645         let status, s = NTacStatus.whd status ctx' (mk_cic_term ctx' s) in
646         let status, s = term_of_cic_term status s ctx' in
647         let use_jmeq =
648           match s with
649           | NCic.Appl [_;it;t1;t2] -> false
650           | NCic.Appl [_;it;t1;_;t2] -> true
651           | _ -> assert false in
652       ) status
653     let it, t1, t2, use_jmeq = match s with
654       | NCic.Appl [_;it;t1;t2] -> it,t1,t2,false
655       | NCic.Appl [_;it;t1;_;t2] -> it,t1,t2,true
656       | _ -> assert false in
657            [ NTactics.intro_tac name
658            ; NTactics.reduce_tac ~reduction:(`Whd true) ~where:prod_pattern ]*)
659 ;;
660
661 let rec destruct_tac0 tags acc domain skip status goal =
662   let pptag = function
663     | `Eq false -> "eq"
664     | `Eq true -> "jmeq"
665     | `Notag -> "reg"
666   in
667   let pptags tags = String.concat ", " (List.map pptag tags) in
668   let ctx = get_ctx status goal in
669   let subst = get_subst status in
670   let get_newgoal os ns ogoal =
671     let go, gc = NTactics.compare_statuses ~past:os ~present:ns in
672     let go' = ([ogoal] @- gc) @+ go in
673       match go' with [] -> assert false | g::_ -> g
674   in
675   let status, selection, kind  = select_eq ctx acc domain status goal in
676   pp (lazy ("destruct: acc is " ^ String.concat "," acc ));
677   match selection, kind with
678   | None, _ -> 
679     pp (lazy (Printf.sprintf 
680        "destruct: no selection, context is %s, stack is %s" 
681        (status#ppcontext ~metasenv:[] ~subst ctx) (pptags tags)));
682      (match tags with 
683       | [] -> status
684       | curtag::tags' ->
685         let fresh = mk_fresh_name ctx 'e' 0 in 
686         let status' = NTactics.exec (tagged_intro_tac curtag fresh) status goal in
687         destruct_tac0 tags' acc (fresh::domain) skip status' 
688           (get_newgoal status status' goal))
689   | Some cur_eq, `Discriminate (newprods,conflict,use_jmeq) -> 
690     pp (lazy (Printf.sprintf 
691       "destruct: discriminate - nselection is %d, context is %s,stack is %s" 
692        cur_eq (status#ppcontext ~metasenv:[] ~subst ctx) (pptags tags)));
693       let status' = NTactics.exec (discriminate_tac ~context:ctx cur_eq) status goal in
694       if conflict then status'
695       else 
696         let newtags = HExtlib.mk_list (`Eq use_jmeq) newprods in
697         destruct_tac0 (newtags@tags) 
698              (name_of_rel ~context:ctx cur_eq::acc) 
699              (List.filter (fun x -> x <> name_of_rel ~context:ctx cur_eq) domain)
700              skip 
701              status' (get_newgoal status status' goal)
702   | Some cur_eq, `Subst dir ->
703     pp (lazy (Printf.sprintf 
704       "destruct: subst - selection is %d, context is %s, stack is %s" 
705         cur_eq (status#ppcontext ~metasenv:[] ~subst ctx) (pptags tags)));
706     let status' = NTactics.exec (subst_tac ~context:ctx ~dir skip cur_eq) status goal in
707       pp (lazy (Printf.sprintf " ctx after subst = %s" (status#ppcontext ~metasenv:[] ~subst (get_ctx status' (get_newgoal status status' goal)))));
708     let eq_name,_ = List.nth ctx (cur_eq-1) in
709     let newgoal = get_newgoal status status' goal in
710     let has_cleared = 
711      try 
712        let _ = NTactics.find_in_context eq_name (get_ctx status' newgoal) in false
713      with _ -> true in
714     let rm_eq b l = if b then List.filter (fun x -> x <> eq_name) l else l in
715     let acc = rm_eq has_cleared acc in
716     let skip = rm_eq has_cleared skip in
717     let domain = rm_eq has_cleared domain in
718       destruct_tac0 tags acc domain skip status' newgoal
719  | Some cur_eq, `Identity ->
720     pp (lazy (Printf.sprintf 
721       "destruct: identity - selection is %d, context is %s, stack is %s" 
722         cur_eq (status#ppcontext ~metasenv:[] ~subst ctx) (pptags tags)));
723       let eq_name,_ = List.nth ctx (cur_eq-1) in
724       let status' = NTactics.exec (clearid_tac ~context:ctx skip cur_eq) status goal in
725       let newgoal = get_newgoal status status' goal in
726       let has_cleared = 
727        try 
728          let _ = NTactics.find_in_context eq_name (get_ctx status' newgoal) in false
729        with _ -> true in
730       let rm_eq b l = if b then List.filter (fun x -> x <> eq_name) l else l in
731       let acc = rm_eq has_cleared acc in
732       let skip = rm_eq has_cleared skip in
733       let domain = rm_eq has_cleared domain in
734         destruct_tac0 tags acc domain skip status' newgoal
735   | Some cur_eq, `Cycle -> (* TODO, should never happen *)
736     pp (lazy (Printf.sprintf 
737       "destruct: cycle - selection is %d, context is %s, stack is %s" 
738         cur_eq (status#ppcontext ~metasenv:[] ~subst ctx) (pptags tags)));
739       assert false
740   | Some cur_eq, `Blob ->
741     pp (lazy (Printf.sprintf 
742       "destruct: blob - selection is %d, context is %s, stack is %s"
743       cur_eq (status#ppcontext ~metasenv:[] ~subst ctx) (pptags tags)));
744       assert false
745   | _ -> assert false
746 ;;
747
748 let destruct_tac dom skip s = 
749   NTactics.distribute_tac 
750     (fun s' g -> 
751      let ctx = get_ctx s' g in
752      let domain = match dom with
753        | None -> List.map (fun (n,_) -> n) ctx
754        | Some l -> l 
755      in
756      destruct_tac0 [] [] domain skip s' g) s;;