]> matita.cs.unibo.it Git - helm.git/blob - matita/components/ng_tactics/nDestructTac.ml
1. nInversion/nDestruct ported to work with jmeq properly
[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 rec mk_prods l t =
48   match l with
49     [] -> t
50   | hd::tl -> NotationPt.Binder (`Forall, (mk_id hd, None), mk_prods tl t)
51 ;;
52
53 let mk_appl =
54  function
55     [] -> assert false
56   | [x] -> x
57   | l -> NotationPt.Appl l
58 ;;
59
60 let rec iter f n acc =
61   if n < 0 then acc
62   else iter f (n-1) (f n acc)
63 ;;
64
65 let subst_metasenv_and_fix_names status =
66   let u,h,metasenv, subst,o = status#obj in
67   let o = 
68     NCicUntrusted.map_obj_kind ~skip_body:true 
69      (NCicUntrusted.apply_subst status subst []) o
70   in
71    status#set_obj(u,h,NCicUntrusted.apply_subst_metasenv status subst metasenv,subst,o)
72 ;;
73
74 (* input: nome della variabile riscritta
75  * output: lista dei nomi delle variabili il cui tipo dipende dall'input *)
76 let cascade_select_in_ctx status ~subst ctx skip iname =
77   let lctx, rctx = HExtlib.split_nth (iname - 1) ctx in
78   let lctx = List.rev lctx in
79   let rec rm_last = function
80       [] | [_] -> []
81     | hd::tl -> hd::(rm_last tl)
82   in
83
84   let indices,_ = List.fold_left
85        (fun (acc,context) item -> 
86           match item with
87             | n,(NCic.Decl s | NCic.Def (s,_)) 
88                   when (not (List.for_all (fun x -> NCicTypeChecker.does_not_occur status ~subst context (x-1) x s) acc)
89                    && not (List.mem n skip)) ->
90                 List.iter (fun m -> pp (lazy ("acc has " ^ (string_of_int m)))) acc;
91                 pp (lazy ("acc occurs in the type of " ^ n));
92                 (1::List.map ((+) 1) acc, item::context)
93             | _ -> (List.map ((+) 1) acc, item::context))
94        ([1], rctx) lctx in
95     let indices = rm_last indices in
96     let res = List.map (fun n -> let s,_ = List.nth ctx (n-1) in s) indices in
97     List.iter (fun n -> pp (lazy n)) res;
98     pp (lazy (status#ppcontext ~metasenv:[] ~subst ctx));
99     res, indices
100 ;;
101
102 let rec mk_fresh_name ctx firstch n =
103   let candidate = (String.make 1 firstch) ^ (string_of_int n) in
104   if (List.for_all (fun (s,_) -> s <> candidate) ctx) then candidate
105   else mk_fresh_name ctx firstch (n+1)
106 ;;
107
108 let arg_list nleft t =
109   let rec drop_prods n t =
110     if n <= 0 then t
111     else match t with
112       | NCic.Prod (_,_,ta) -> drop_prods (n-1) ta
113       | _ -> raise (Failure "drop_prods")
114   in
115   let rec aux = function
116     | NCic.Prod (_,so,ta) -> so::aux ta
117     | _ -> []
118   in aux (drop_prods nleft t)
119 ;;
120
121 let nargs it nleft consno =
122   pp (lazy (Printf.sprintf "nargs %d %d" nleft consno));
123   let _,indname,_,cl = it in
124   let _,_,t_k = List.nth cl consno in
125   List.length (arg_list nleft t_k) ;;
126
127 let default_pattern = "",0,(None,[],Some NotationPt.UserInput);;
128
129 (* returns the discrimination = injection+contradiction principle *)
130
131 let mk_discriminator it ~use_jmeq nleft xyty status =
132   let _,indname,_,cl = it in
133
134
135   let mk_eq tys ts us es n =
136     if use_jmeq then
137       mk_appl [mk_id "jmeq";
138                NotationPt.Implicit `JustOne; List.nth ts n;
139                NotationPt.Implicit `JustOne; List.nth us n] 
140     else
141     (* eqty = Tn u0 e0...un-1 en-1 *)
142     let eqty = mk_appl 
143                  (List.nth tys n :: iter (fun i acc -> 
144                                            List.nth us i::
145                                            List.nth es i:: acc) 
146                                      (n-1) []) in
147
148     (* params = [T0;t0;...;Tn;tn;u0;e0;un-1;en-1] *)
149     let params = iter (fun i acc -> 
150                          List.nth tys i ::
151                          List.nth ts i :: acc) n
152                      (iter (fun i acc ->
153                             List.nth us i::
154                             List.nth es i:: acc) (n-1) []) in
155     mk_appl [mk_id "eq"; eqty;
156                         mk_appl (mk_id ("R" ^ string_of_int n) :: params);
157                         List.nth us n]
158
159   in
160
161   let kname it j =
162     let _,_,_,cl = it in
163     let _,name,_ = List.nth cl j in
164     name
165   in
166
167   let branch i j ts us = 
168     let nargs = nargs it nleft i in
169     let es = List.map (fun x -> mk_id ("e" ^ string_of_int x)) (HExtlib.list_seq 0 nargs) in
170     let tys = List.map 
171                 (fun x -> iter 
172                   (fun i acc -> 
173                     NotationPt.Binder (`Lambda, (mk_id ("x" ^ string_of_int i), None),
174                     NotationPt.Binder (`Lambda, (mk_id ("p" ^ string_of_int i), None),
175                     acc))) (x-1) 
176                  (NotationPt.Implicit (`Tagged ("T" ^ (string_of_int x)))))
177                (HExtlib.list_seq 0 nargs) in
178     let tys = tys @ 
179       [iter (fun i acc -> 
180         NotationPt.Binder (`Lambda, (mk_id ("x" ^ string_of_int i), None),
181         NotationPt.Binder (`Lambda, (mk_id ("p" ^ string_of_int i), None),
182         acc))) (nargs-1)
183         (mk_appl [mk_id "eq"; NotationPt.Implicit `JustOne;
184           mk_appl (mk_id (kname it i)::
185            List.map (fun x -> mk_id ("x" ^string_of_int x))
186               (HExtlib.list_seq 0 (List.length ts)));
187               mk_appl (mk_id (kname it j)::us)])]
188     in
189     (** NotationPt.Binder (`Lambda, (mk_id "e", 
190       Some (mk_appl 
191         [mk_id "eq";
192          NotationPt.Implicit `JustOne;
193          mk_appl (mk_id (kname it i)::ts);
194          mk_appl (mk_id (kname it j)::us)])),
195     let ts = ts @ [mk_id "e"] in 
196     let refl2 = mk_appl
197                   [mk_id "refl";
198                    NotationPt.Implicit `JustOne;
199                    mk_appl (mk_id (kname it j)::us)] in
200     let us = us @ [refl2] in *)
201     NotationPt.Binder (`Forall, (mk_id "P", Some (NotationPt.Sort (`NType "1") )),
202       if i = j then 
203        NotationPt.Binder (`Forall, (mk_id "_",
204         Some (iter (fun i acc -> 
205               NotationPt.Binder (`Forall, (List.nth es i, Some (mk_eq tys ts us es i)), acc))
206               (nargs-1) 
207               (** (NotationPt.Binder (`Forall, (mk_id "_", 
208                 Some (mk_eq tys ts us es nargs)),*)
209                 (mk_id "P"))), mk_id "P")
210       else mk_id "P")
211   in
212
213   let inner i ts = NotationPt.Case 
214               (mk_id "y",None,
215                (*Some (NotationPt.Binder (`Lambda, (mk_id "y",None), 
216                  NotationPt.Binder (`Forall, (mk_id "_", Some
217                  (mk_appl [mk_id "eq";NotationPt.Implicit
218                  `JustOne;(*NotationPt.Implicit `JustOne*)
219                   mk_appl (mk_id (kname it i)::ts);mk_id "y"])),
220                  NotationPt.Implicit `JustOne )))*)
221                   None,
222                   List.map
223                   (fun j -> 
224                      let nargs_kty = nargs it nleft j in
225                      let us = iter (fun m acc -> mk_id ("u" ^ (string_of_int m))::acc) 
226                                 (nargs_kty - 1) [] in
227                      let nones = 
228                        iter (fun _ acc -> None::acc) (nargs_kty - 1) [] in
229                      NotationPt.Pattern (kname it j,
230                                             None,
231                                             List.combine us nones), 
232                                 branch i j ts us)
233                   (HExtlib.list_seq 0 (List.length cl)))
234   in
235   let outer = NotationPt.Case
236                 (mk_id "x",None,
237                  None ,
238                  List.map
239                    (fun i -> 
240                       let nargs_kty = nargs it nleft i in
241                       let ts = iter (fun m acc -> mk_id ("t" ^ (string_of_int m))::acc)
242                                  (nargs_kty - 1) [] in
243                      let nones = 
244                        iter (fun _ acc -> None::acc) (nargs_kty - 1) [] in
245                       NotationPt.Pattern (kname it i,
246                                              None,
247                                              List.combine ts nones),
248                                 inner i ts)
249                    (HExtlib.list_seq 0 (List.length cl))) in
250   let principle = NotationPt.Binder (`Lambda, (mk_id "x", Some xyty),
251                         NotationPt.Binder (`Lambda, (mk_id "y", Some xyty), outer))
252   in
253   pp (lazy ("discriminator = " ^ (NotationPp.pp_term status principle)));
254   
255   status, principle 
256 ;;
257
258 let hd_of_term = function
259   | NCic.Appl (hd::_) -> hd
260   | t -> t
261 ;;
262
263 let name_of_rel ~context rel =
264   let s, _ = List.nth context (rel-1) in s
265 ;;
266
267 (* let lookup_in_ctx ~context n =
268   List.nth context ((List.length context) - n - 1)
269 ;;*)
270
271 let mk_sym s = NotationPt.Symbol (s,0);;
272
273 let discriminate_tac ~context cur_eq status =
274   pp (lazy (Printf.sprintf "discriminate: equation %s" (name_of_rel ~context cur_eq)));
275
276   let dbranch it ~use_jmeq leftno consno =
277     let refl_id = mk_sym "refl" in
278     pp (lazy (Printf.sprintf "dbranch %d %d" leftno consno));
279     let nlist = HExtlib.list_seq 0 (nargs it leftno consno) in
280     (* (\forall ...\forall P.\forall DH : ( ... = ... -> P). P) *)
281     let params = List.map (fun x -> NTactics.intro_tac ("a" ^ string_of_int x)) nlist in
282         NTactics.reduce_tac ~reduction:(`Normalize true) ~where:default_pattern::
283         params @ [
284         NTactics.intro_tac "P";
285         NTactics.intro_tac "DH";
286         NTactics.apply_tac ("",0,mk_id "DH");
287         NTactics.apply_tac ("",0,refl_id); (* well, it works even if no goal is selected after applying DH... *)
288     ] in
289   let dbranches it ~use_jmeq leftno =
290     pp (lazy (Printf.sprintf "dbranches %d" leftno));
291     let _,_,_,cl = it in
292     let nbranches = List.length cl in 
293     let branches = iter (fun n acc -> 
294       let m = nbranches - n - 1 in
295       if m = 0 then acc @ (dbranch it ~use_jmeq leftno m)
296       else acc @ NTactics.shift_tac :: (dbranch it ~use_jmeq
297       leftno m))
298       (nbranches-1) [] in
299     if nbranches > 1 then
300          NTactics.branch_tac ~force:false:: branches @ [NTactics.merge_tac]
301     else branches
302   in
303   
304   let eq_name,(NCic.Decl s | NCic.Def (s,_)) = List.nth context (cur_eq-1) in
305   let _,ctx' = HExtlib.split_nth cur_eq context in
306   let status, s = NTacStatus.whd status ctx' (mk_cic_term ctx' s) in
307   let status, s = term_of_cic_term status s ctx' in
308   let status, leftno, it, use_jmeq =
309     let it, t1, t2, use_jmeq = match s with
310       | NCic.Appl [_;it;t1;t2] -> it,t1,t2,false
311       | NCic.Appl [_;it;t1;_;t2] -> it,t1,t2,true
312       | _ -> assert false in
313     (* XXX: serve? ho già fatto whd *)
314     let status, it = whd status ctx' (mk_cic_term ctx' it) in
315     let status, it = term_of_cic_term status it ctx' in
316     let _uri,indtyno,its = match it with
317       | NCic.Const (NReference.Ref (uri, NReference.Ind (_,indtyno,_)) as r) 
318       | NCic.Appl (NCic.Const 
319           (NReference.Ref (uri, NReference.Ind (_,indtyno,_)) as r)::_) -> 
320         uri, indtyno, NCicEnvironment.get_checked_indtys status r
321       | _ -> pp (lazy ("discriminate: indty ="  ^ status#ppterm
322                   ~metasenv:[] ~subst:[] ~context:[] it)) ; assert false in
323     let _,leftno,its,_,_ = its in
324     status, leftno, List.nth its indtyno, use_jmeq
325   in
326   
327   let itnargs = 
328     let _,_,arity,_ = it in 
329     List.length (arg_list 0 arity) in
330   let _,itname,_,_ = it in
331   let params = List.map (fun x -> "a" ^ string_of_int x) (HExtlib.list_seq 1 (itnargs+1)) in
332   let xyty = mk_appl (List.map mk_id (itname::params)) in
333   let print_tac s status = pp s ; status in 
334   NTactics.block_tac (
335     [(fun status ->
336      let status, discr = mk_discriminator it ~use_jmeq leftno xyty status in
337      let cut_term = mk_prods params (NotationPt.Binder (`Forall, (mk_id "x",
338                              Some xyty),
339                          NotationPt.Binder (`Forall, (mk_id "y", Some xyty),
340                           (if use_jmeq then fun tgt ->
341                            NotationPt.Binder (`Forall, (mk_id "e",
342                             Some (mk_appl
343                              [mk_sym "jmsimeq"; NotationPt.Implicit `JustOne; mk_id "x";
344                                                 NotationPt.Implicit `JustOne; mk_id "y"])),tgt)
345                           else fun tgt ->
346                            NotationPt.Binder (`Forall, (mk_id "e",
347                             Some (mk_appl [mk_sym "eq";NotationPt.Implicit `JustOne; mk_id "x"; mk_id "y"])),tgt))
348                           (mk_appl [discr; mk_id "x"; mk_id "y"(*;mk_id "e"*)])))) in
349      let status = print_tac (lazy ("cut_term = "^ NotationPp.pp_term status cut_term)) status in
350       NTactics.cut_tac ("",0, cut_term)
351       status);
352     NTactics.branch_tac;
353     print_tac (lazy "ci sono");
354      NTactics.reduce_tac ~reduction:(`Normalize true) ~where:default_pattern]
355   @ List.map (fun x -> NTactics.intro_tac x) params @
356     [NTactics.intro_tac "x";
357      NTactics.intro_tac "y";
358      NTactics.intro_tac "Deq";
359     print_tac (lazy "ci sono 2");
360      NTactics.rewrite_tac ~dir:`RightToLeft ~what:("",0,mk_id "Deq") ~where:default_pattern;
361      NTactics.cases_tac ~what:("",0,mk_id "x") ~where:default_pattern]
362   @ dbranches it ~use_jmeq leftno @ 
363    [NTactics.shift_tac;
364     print_tac (lazy "ci sono 3");
365     NTactics.intro_tac "#discriminate";
366     NTactics.apply_tac ("",0,mk_appl ([mk_id "#discriminate"]@
367                                 HExtlib.mk_list (NotationPt.Implicit `JustOne) (List.length params + 2) @
368                                 [mk_id eq_name ]));
369     NTactics.reduce_tac ~reduction:(`Normalize true) ~where:default_pattern;
370     NTactics.clear_tac ["#discriminate"];
371     NTactics.merge_tac; print_tac (lazy "the end of discriminate")] 
372   ) status
373 ;;
374
375 let saturate_skip status context skip =
376   HExtlib.list_uniq
377     (List.fold_left
378       (fun acc x -> 
379          let ix = HExtlib.list_index ((=) x) (List.map fst context)
380          in match ix with
381          | None -> acc
382          | Some (i,_) -> 
383             fst (cascade_select_in_ctx status ~subst:(get_subst status) context [] (i+1)) @ acc) skip skip)
384 ;;
385       
386 let subst_tac ~context ~dir skip cur_eq =
387   fun status as oldstatus ->
388   let eq_name,(NCic.Decl s | NCic.Def (s,_)) = List.nth context (cur_eq-1) in
389   let _,ctx' = HExtlib.split_nth cur_eq context in
390   let status, s = NTacStatus.whd status ctx' (mk_cic_term ctx' s) in
391   let status, s = term_of_cic_term status s ctx' in
392   let skip = saturate_skip status context skip in
393   pp (lazy (Printf.sprintf "subst: equation %s" eq_name));
394     let l, r = match s with
395       | NCic.Appl [_;_;t1;t2] | NCic.Appl [_;_;t1;_;t2] -> t1,t2
396       | _ -> assert false in
397     let var = match dir with
398       | `LeftToRight -> l
399       | `RightToLeft -> r in
400     (* let var = match var with
401       | NCic.Rel i -> i
402       | _ -> assert false in *)
403     let names_to_gen, _ = 
404       match var with 
405       | NCic.Rel var ->
406         cascade_select_in_ctx status ~subst:(get_subst status) context skip (var+cur_eq)
407       | _ -> cascade_select_in_ctx status ~subst:(get_subst status) context skip cur_eq in
408     let names_to_gen = List.filter (fun n -> n <> eq_name) names_to_gen in
409     if (List.exists (fun x -> List.mem x skip) names_to_gen)
410       then oldstatus
411     else 
412     let gen_tac x = 
413       NTactics.generalize_tac 
414       ~where:("",0,(Some (mk_id x),[], Some NotationPt.UserInput)) in
415     NTactics.block_tac ((List.map gen_tac names_to_gen)@
416                 [NTactics.clear_tac names_to_gen;
417                  NTactics.rewrite_tac ~dir 
418                    ~what:("",0,mk_id eq_name) ~where:default_pattern;
419                  NTactics.reduce_tac ~reduction:(`Normalize true)
420                    ~where:default_pattern;
421                  NTactics.try_tac (NTactics.clear_tac [eq_name])]@
422                  (List.map NTactics.intro_tac (List.rev names_to_gen))) status
423 ;;
424
425 let clearid_tac ~context skip cur_eq =
426   fun status ->
427   let eq_name,(NCic.Decl s | NCic.Def (s,_)) = List.nth context (cur_eq-1) in
428   let _,ctx' = HExtlib.split_nth cur_eq context in
429   let status, s = NTacStatus.whd status ctx' (mk_cic_term ctx' s) in
430   let status, s = term_of_cic_term status s ctx' in
431   let skip = saturate_skip status context skip in
432   (* 
433   let streicher_id = 
434     match s with
435     | NCic.Appl [_;_;_;_] -> mk_id "streicherK"
436     | NCic.Appl [_;_;_;_;_] -> mk_id "streicherKjmeq"
437     | _ -> assert false
438   in
439   pp (lazy (Printf.sprintf "clearid: equation %s" eq_name));
440     let names_to_gen, _ = 
441       cascade_select_in_ctx ~subst:(get_subst status) context cur_eq in
442     let names_to_gen = names_to_gen @ [eq_name] in
443     let gen_tac x = 
444       NTactics.generalize_tac 
445       ~where:("",0,(Some (mk_id x),[], Some NotationPt.UserInput)) in
446     NTactics.block_tac ((List.map gen_tac names_to_gen)@
447                 [NTactics.clear_tac names_to_gen;
448                  NTactics.apply_tac ("",0, mk_appl [streicher_id;
449                                                     NotationPt.Implicit `JustOne;
450                                                     NotationPt.Implicit `JustOne;
451                                                     NotationPt.Implicit `JustOne;
452                                                     NotationPt.Implicit `JustOne]);
453                  NTactics.reduce_tac ~reduction:(`Normalize true)
454                    ~where:default_pattern] @
455                  (let names_to_intro = 
456                     match List.rev names_to_gen with
457                     | [] -> []
458                     | _::tl -> tl in
459                   List.map NTactics.intro_tac names_to_intro)) status
460 *)
461
462   pp (lazy (Printf.sprintf "clearid: equation %s" eq_name));
463     match s with
464     | NCic.Appl [_;_;_;_] -> 
465       (* leibniz *)
466   let streicher_id = mk_id "streicherK"
467   in
468     let names_to_gen, _ = 
469       cascade_select_in_ctx status ~subst:(get_subst status) context skip cur_eq in
470     let names_to_gen = names_to_gen @ [eq_name] in
471     let gen_tac x = 
472       NTactics.generalize_tac 
473       ~where:("",0,(Some (mk_id x),[], Some NotationPt.UserInput)) in
474     NTactics.block_tac ((List.map gen_tac names_to_gen)@
475                 [NTactics.clear_tac names_to_gen;
476                  NTactics.apply_tac ("",0, mk_appl [streicher_id;
477                                                     NotationPt.Implicit `JustOne;
478                                                     NotationPt.Implicit `JustOne;
479                                                     NotationPt.Implicit `JustOne;
480                                                     NotationPt.Implicit `JustOne]);
481                  NTactics.reduce_tac ~reduction:(`Normalize true)
482                    ~where:default_pattern] @
483                  (let names_to_intro = 
484                     match List.rev names_to_gen with
485                     | [] -> []
486                     | _::tl -> tl in
487                   List.map NTactics.intro_tac names_to_intro)) status
488     | NCic.Appl [_;_;_;_;_] -> 
489       (* JMeq *) 
490   let streicher_id = mk_id "streicherK"
491   in
492     let names_to_gen, _ = 
493       cascade_select_in_ctx status ~subst:(get_subst status) context skip cur_eq in
494     let names_to_gen = names_to_gen (* @ [eq_name]*) in
495     let gen_tac x = 
496       NTactics.generalize_tac 
497       ~where:("",0,(Some (mk_id x),[], Some NotationPt.UserInput)) in
498     let gen_eq = NTactics.generalize_tac
499      ~where:("",0,(Some (mk_appl [mk_id "jmeq_to_eq";
500                                   NotationPt.Implicit `JustOne; 
501                                   NotationPt.Implicit `JustOne; 
502                                   NotationPt.Implicit `JustOne; 
503                                   mk_id eq_name]),[], Some NotationPt.UserInput)) in
504     NTactics.block_tac ((List.map gen_tac names_to_gen)@gen_eq::
505                 [NTactics.clear_tac names_to_gen;
506                  NTactics.try_tac (NTactics.clear_tac [eq_name]);
507                  NTactics.apply_tac ("",0, mk_appl [streicher_id;
508                                                     NotationPt.Implicit `JustOne;
509                                                     NotationPt.Implicit `JustOne;
510                                                     NotationPt.Implicit `JustOne;
511                                                     NotationPt.Implicit `JustOne]);
512                  NTactics.reduce_tac ~reduction:(`Normalize true)
513                    ~where:default_pattern] @
514                  (let names_to_intro = List.rev names_to_gen in
515                   List.map NTactics.intro_tac names_to_intro)) status
516     | _ -> assert false
517 ;;
518
519 let get_ctx st goal =
520     ctx_of (get_goalty st goal)
521 ;;
522
523 (* = select + classify *)
524 let select_eq ctx acc domain status goal =
525   let classify ~subst ctx' l r =
526     (* FIXME: metasenv *)
527     if NCicReduction.are_convertible status ~metasenv:[] ~subst ctx' l r 
528       then status, `Identity
529       else status, (match hd_of_term l, hd_of_term r with
530         | NCic.Const (NReference.Ref (_,NReference.Con (_,ki,nleft)) as kref),
531           NCic.Const (NReference.Ref (_,NReference.Con (_,kj,_))) -> 
532             if ki != kj then `Discriminate (0,true)
533             else
534               let rit = NReference.mk_indty true kref in
535               let _,_,its,_,itno = NCicEnvironment.get_checked_indtys status rit in 
536               let it = List.nth its itno in
537               let newprods = nargs it nleft (ki-1) in
538               `Discriminate (newprods, false) 
539         | NCic.Rel j, _  
540             when NCicTypeChecker.does_not_occur status ~subst ctx' (j-1) j r
541               && l = NCic.Rel j -> `Subst `LeftToRight
542         | _, NCic.Rel j 
543             when NCicTypeChecker.does_not_occur status ~subst ctx' (j-1) j l 
544               && r = NCic.Rel j -> `Subst `RightToLeft
545         | (NCic.Rel _, _ | _, NCic.Rel _ ) -> `Cycle (* could be a blob too... *)
546         | _ -> `Blob) in
547   let rec aux i =
548     try
549       let index = List.length ctx - i in
550       pp (lazy ("provo classify di index = " ^string_of_int index));
551       match (List.nth ctx (index - 1)) with
552       | n, (NCic.Decl ty | NCic.Def (ty,_)) ->
553           (let _,ctx_ty = HExtlib.split_nth index ctx in 
554            let status, ty = NTacStatus.whd status ctx_ty (mk_cic_term ctx_ty ty) in
555            let status, ty = term_of_cic_term status ty ctx_ty in
556            pp (lazy (Printf.sprintf "select_eq tries %s" (status#ppterm ~context:ctx_ty ~subst:[] ~metasenv:[] ty)));
557            let status, kind = match ty with
558            | NCic.Appl [NCic.Const (NReference.Ref (u,_)) ;_;l;r] 
559                when NUri.name_of_uri u = "eq" ->
560                classify ~subst:(get_subst status) ctx_ty l r
561            | NCic.Appl [NCic.Const (NReference.Ref (u,_)) ;lty;l;rty;r]
562                when NUri.name_of_uri u = "jmeq" && 
563                  NCicReduction.are_convertible status ~metasenv:[] 
564                    ~subst:(get_subst status) ctx_ty lty rty
565                -> classify ~subst:(get_subst status) ctx_ty l r
566            | _ -> status, `NonEq 
567            in match kind with
568               | `Identity ->
569                   let status, goalty = term_of_cic_term status (get_goalty status goal) ctx in
570                      status, Some (List.length ctx - i), kind
571               | `Cycle | `Blob | `NonEq -> aux (i+1) (* XXX: skip cyclic/blob equations for now *)
572               | _ -> 
573                  if (List.for_all (fun x -> x <> n) acc) && 
574                     (List.exists (fun x -> x = n) domain) 
575                  then status, Some (List.length ctx - i), kind
576                  else aux (i+1))
577     with Failure _ | Invalid_argument _ -> status, None, `Blob
578   in aux 0
579 ;;
580
581 let rec destruct_tac0 nprods acc domain skip status goal =
582   let ctx = get_ctx status goal in
583   let subst = get_subst status in
584   let get_newgoal os ns ogoal =
585     let go, gc = NTactics.compare_statuses ~past:os ~present:ns in
586     let go' = ([ogoal] @- gc) @+ go in
587       match go' with [] -> assert false | g::_ -> g
588   in
589   let status, selection, kind  = select_eq ctx acc domain status goal in
590   pp (lazy ("destruct: acc is " ^ String.concat "," acc ));
591   match selection, kind with
592   | None, _ -> 
593     pp (lazy (Printf.sprintf "destruct: nprods is %d, no selection, context is %s" nprods (status#ppcontext ~metasenv:[] ~subst ctx)));
594       if nprods > 0  then
595         let fresh = mk_fresh_name ctx 'e' 0 in 
596         let status' = NTactics.exec (NTactics.intro_tac fresh) status goal in
597         destruct_tac0 (nprods-1) acc (fresh::domain) skip status' (get_newgoal status status' goal)
598       else
599         status
600   | Some cur_eq, `Discriminate (newprods,conflict) -> 
601     pp (lazy (Printf.sprintf "destruct: discriminate - nprods is %d, selection is %d, context is %s" nprods cur_eq (status#ppcontext ~metasenv:[] ~subst ctx)));
602       let status' = NTactics.exec (discriminate_tac ~context:ctx cur_eq) status goal in
603       if conflict then status'
604       else 
605         destruct_tac0 (nprods+newprods) 
606              (name_of_rel ~context:ctx cur_eq::acc) 
607              (List.filter (fun x -> x <> name_of_rel ~context:ctx cur_eq) domain)
608              skip 
609              status' (get_newgoal status status' goal)
610   | Some cur_eq, `Subst dir ->
611     pp (lazy (Printf.sprintf "destruct: subst - nprods is %d, selection is %d, context is %s" nprods cur_eq (status#ppcontext ~metasenv:[] ~subst ctx)));
612     let status' = NTactics.exec (subst_tac ~context:ctx ~dir skip cur_eq) status goal in
613       pp (lazy (Printf.sprintf " ctx after subst = %s" (status#ppcontext ~metasenv:[] ~subst (get_ctx status' (get_newgoal status status' goal)))));
614     let eq_name,_ = List.nth ctx (cur_eq-1) in
615     let newgoal = get_newgoal status status' goal in
616     let has_cleared = 
617      try 
618        let _ = NTactics.find_in_context eq_name (get_ctx status' newgoal) in false
619      with _ -> true in
620     let rm_eq b l = if b then List.filter (fun x -> x <> eq_name) l else l in
621     let acc = rm_eq has_cleared acc in
622     let skip = rm_eq has_cleared skip in
623     let domain = rm_eq has_cleared domain in
624       destruct_tac0 nprods acc domain skip status' newgoal
625  | Some cur_eq, `Identity ->
626     pp (lazy (Printf.sprintf "destruct: identity - nprods is %d, selection is %d, context is %s" nprods cur_eq (status#ppcontext ~metasenv:[] ~subst ctx)));
627       let eq_name,_ = List.nth ctx (cur_eq-1) in
628       let status' = NTactics.exec (clearid_tac ~context:ctx skip cur_eq) status goal in
629       let newgoal = get_newgoal status status' goal in
630       let has_cleared = 
631        try 
632          let _ = NTactics.find_in_context eq_name (get_ctx status' newgoal) in false
633        with _ -> true in
634       let rm_eq b l = if b then List.filter (fun x -> x <> eq_name) l else l in
635       let acc = rm_eq has_cleared acc in
636       let skip = rm_eq has_cleared skip in
637       let domain = rm_eq has_cleared domain in
638         destruct_tac0 nprods acc domain skip status' newgoal
639   | Some cur_eq, `Cycle -> (* TODO, should never happen *)
640     pp (lazy (Printf.sprintf "destruct: cycle - nprods is %d, selection is %d, context is %s" nprods cur_eq (status#ppcontext ~metasenv:[] ~subst ctx)));
641       assert false
642   | Some cur_eq, `Blob ->
643     pp (lazy (Printf.sprintf "destruct: blob - nprods is %d, selection is %d, context is %s" nprods cur_eq (status#ppcontext ~metasenv:[] ~subst ctx)));
644       assert false
645   | _ -> assert false
646 ;;
647
648 let destruct_tac dom skip s = 
649   NTactics.distribute_tac 
650     (fun s' g -> 
651      let ctx = get_ctx s' g in
652      let domain = match dom with
653        | None -> List.map (fun (n,_) -> n) ctx
654        | Some l -> l 
655      in
656      destruct_tac0 0 [] domain skip s' g) s;;