]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/destructTactic.ml
bbfee8041ac0f827f12ca84971d0010258286c79
[helm.git] / components / tactics / destructTactic.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$ *)
27
28 module C = Cic
29 module U = UriManager
30 module P = PrimitiveTactics
31 module T = Tacticals
32 module CR = CicReduction 
33 module PST = ProofEngineStructuralRules
34 module PET = ProofEngineTypes
35 module CTC = CicTypeChecker
36 module CU = CicUniv
37 module S = CicSubstitution
38 module RT = ReductionTactics
39 module PEH = ProofEngineHelpers
40 module ET = EqualityTactics
41 module DTI = DoubleTypeInference
42 module FNG = FreshNamesGenerator
43
44 let debug = true
45 let debug_print = 
46   if debug then (fun x -> prerr_endline (Lazy.force x)) else (fun _ -> ())
47
48 (* funzione generale di rilocazione dei riferimenti locali *)
49
50 let relocate_term map t =
51    let rec map_xnss k xnss =
52       let imap (uri, t) = uri, map_term k t in
53       List.map imap xnss
54    and map_mss k mss =
55       let imap = function
56          | None   -> None
57          | Some t -> Some (map_term k t)
58       in
59       List.map imap mss
60    and map_fs len k fs = 
61       let imap (name, i, ty, bo) = name, i, map_term k ty, map_term (k + len) bo in
62       List.map imap fs
63    and map_cfs len k cfs = 
64       let imap (name, ty, bo) = name, map_term k ty, map_term (k + len) bo in
65       List.map imap cfs
66    and map_term k = function
67       | C.Rel m -> if m < k then C.Rel m else C.Rel (map (m - k))
68       | C.Sort _ as t -> t
69       | C.Implicit _ as t -> t
70       | C.Var (uri, xnss) -> C.Var (uri, map_xnss k xnss)
71       | C.Const (uri, xnss) -> C.Const (uri, map_xnss k xnss)
72       | C.MutInd (uri, tyno, xnss) -> C.MutInd (uri, tyno, map_xnss k xnss)
73       | C.MutConstruct (uri, tyno, consno, xnss) ->
74          C.MutConstruct (uri, tyno, consno, map_xnss k xnss)
75       | C.Meta (i, mss) -> C.Meta(i, map_mss k mss)
76       | C.Cast (te, ty) -> C.Cast (map_term k te, map_term k ty)
77       | C.Appl ts -> C.Appl (List.map (map_term k) ts)
78       | C.MutCase (sp, i, outty, t, pl) ->
79          C.MutCase (sp, i, map_term k outty, map_term k t, List.map (map_term k) pl)    
80       | C.Prod (n, s, t) -> C.Prod (n, map_term k s, map_term (succ k) t)
81       | C.Lambda (n, s, t) -> C.Lambda (n, map_term k s, map_term (succ k) t)
82       | C.LetIn (n, s, t) -> C.LetIn (n, map_term k s, map_term (succ k) t)
83       | C.Fix (i, fs) -> C.Fix (i, map_fs (List.length fs) k fs)
84       | C.CoFix (i, cfs) -> C.CoFix (i, map_cfs (List.length cfs) k cfs)
85    in
86    map_term 0 t
87
88 let id n = n
89
90 let after continuation aftermap beforemap = 
91    continuation ~map:(fun n -> aftermap (beforemap n))
92
93 let after2 continuation aftermap beforemap ~map = 
94    continuation ~map:(fun n -> map (aftermap (beforemap n)))
95
96 (* term ha tipo t1=t2; funziona solo se t1 e t2 hanno in testa costruttori
97 diversi *)
98
99 let discriminate_tac ~term =
100  let true_URI =
101   match LibraryObjects.true_URI () with
102      Some uri -> uri
103    | None -> raise (PET.Fail (lazy "You need to register the default \"true\" definition first. Please use the \"default\" command")) in
104  let false_URI =
105   match LibraryObjects.false_URI () with
106      Some uri -> uri
107    | None -> raise (PET.Fail (lazy "You need to register the default \"false\" definition first. Please use the \"default\" command")) in
108  let fail msg = raise (PET.Fail (lazy ("Discriminate: " ^ msg))) in
109  let find_discriminating_consno t1 t2 =
110    let rec aux t1 t2 =
111      match t1, t2 with
112      | C.MutConstruct _, C.MutConstruct _ when t1 = t2 -> None
113      | C.Appl ((C.MutConstruct _ as constr1) :: args1),
114        C.Appl ((C.MutConstruct _ as constr2) :: args2)
115        when constr1 = constr2 ->
116          let rec aux_list l1 l2 =
117            match l1, l2 with
118            | [], [] -> None
119            | hd1 :: tl1, hd2 :: tl2 ->
120                (match aux hd1 hd2 with
121                | None -> aux_list tl1 tl2
122                | Some _ as res -> res)
123            | _ -> (* same constructor applied to a different number of args *)
124                assert false
125          in
126          aux_list args1 args2
127      | ((C.MutConstruct (_,_,consno1,subst1)),
128        (C.MutConstruct (_,_,consno2,subst2)))
129      | ((C.MutConstruct (_,_,consno1,subst1)),
130        (C.Appl ((C.MutConstruct (_,_,consno2,subst2)) :: _)))
131      | ((C.Appl ((C.MutConstruct (_,_,consno1,subst1)) :: _)),
132        (C.MutConstruct (_,_,consno2,subst2)))
133      | ((C.Appl ((C.MutConstruct (_,_,consno1,subst1)) :: _)),
134        (C.Appl ((C.MutConstruct (_,_,consno2,subst2)) :: _)))
135        when (consno1 <> consno2) || (subst1 <> subst2) ->
136          Some consno2
137      | _ -> fail "not a discriminable equality"
138    in
139    aux t1 t2
140  in
141  let mk_branches_and_outtype turi typeno consno context args =
142     (* a list of "True" except for the element in position consno which
143      * is "False" *)
144     match fst (CicEnvironment.get_obj CU.empty_ugraph turi) with
145     | C.InductiveDefinition (ind_type_list,_,paramsno,_)  ->
146         let _,_,rty,constructor_list = List.nth ind_type_list typeno in 
147         let false_constr_id,_ = List.nth constructor_list (consno - 1) in
148         let branches =
149          List.map 
150            (fun (id,cty) ->
151              (* dubbio: e' corretto ridurre in questo context ??? *)
152              let red_ty = CR.whd context cty in
153              let rec aux t k =
154                match t with
155                | C.Prod (_,_,target) when (k <= paramsno) ->
156                    S.subst (List.nth args (k-1))
157                      (aux target (k+1))
158                | C.Prod (binder,source,target) when (k > paramsno) ->
159                    C.Lambda (binder, source, (aux target (k+1)))
160                | _ -> 
161                    if (id = false_constr_id)
162                    then (C.MutInd(false_URI,0,[]))
163                    else (C.MutInd(true_URI,0,[]))
164              in
165              (S.lift 1 (aux red_ty 1)))
166            constructor_list in
167         let outtype =
168          let seed = ref 0 in
169          let rec mk_lambdas rev_left_args =
170           function
171              0, args, C.Prod (_,so,ta) ->
172               C.Lambda
173                (C.Name (incr seed; "x" ^ string_of_int !seed),
174                so,
175                mk_lambdas rev_left_args (0,args,ta))
176            | 0, args, C.Sort _ ->
177               let rec mk_rels =
178                function
179                   0 -> []
180                 | n -> C.Rel n :: mk_rels (n - 1) in
181               let argsno = List.length args in
182                C.Lambda
183                 (C.Name "x",
184                  (if argsno + List.length rev_left_args > 0 then
185                    C.Appl
186                     (C.MutInd (turi, typeno, []) ::
187                      (List.map
188                       (S.lift (argsno + 1))
189                       (List.rev rev_left_args)) @
190                      mk_rels argsno)
191                   else
192                    C.MutInd (turi,typeno,[])),
193                  C.Sort C.Prop)
194            | 0, _, _ -> assert false (* seriously screwed up *)
195            | n, he::tl, C.Prod (_,_,ta) ->
196               mk_lambdas (he::rev_left_args)(n-1,tl,S.subst he ta)
197            | n,_,_ ->
198               assert false (* we should probably reduce in some context *)
199          in
200           mk_lambdas [] (paramsno, args, rty)
201         in
202          branches, outtype 
203     | _ -> assert false
204  in
205  let discriminate'_tac ~term status = 
206   let (proof, goal) = status in
207   let _,metasenv,_subst,_,_, _ = proof in
208   let _,context,_ = CicUtil.lookup_meta goal metasenv in
209   let termty,_ = 
210     CTC.type_of_aux' metasenv context term CU.empty_ugraph
211   in
212   match termty with
213    | C.Appl [(C.MutInd (equri, 0, [])) ; tty ; t1 ; t2]
214      when LibraryObjects.is_eq_URI equri ->
215       let turi,typeno,exp_named_subst,args = 
216         match tty with
217         | (C.MutInd (turi,typeno,exp_named_subst)) ->
218             turi,typeno,exp_named_subst,[]
219         | (C.Appl (C.MutInd (turi,typeno,exp_named_subst)::args)) ->
220             turi,typeno,exp_named_subst,args
221         | _ -> fail "not a discriminable equality"
222       in
223       let consno =
224         match find_discriminating_consno t1 t2 with
225         | Some consno -> consno
226         | None -> fail "discriminating terms are structurally equal"
227       in
228       let branches,outtype =
229        mk_branches_and_outtype turi typeno consno context args
230       in
231       PET.apply_tactic
232        (T.then_
233          ~start:(EliminationTactics.elim_type_tac (C.MutInd (false_URI, 0, [])))
234          ~continuation:
235            (T.then_
236              ~start:
237                (RT.change_tac 
238                  ~pattern:(PET.conclusion_pattern None)
239                  (fun _ m u ->
240                    C.Appl [
241                      C.Lambda ( C.Name "x", tty,
242                        C.MutCase (turi, typeno, outtype, (C.Rel 1), branches));
243                      t2 ],
244                    m, u))
245              ~continuation:
246                (T.then_
247                  ~start:
248                    (ET.rewrite_simpl_tac
249                      ~direction:`RightToLeft
250                      ~pattern:(PET.conclusion_pattern None)
251                      term [])
252                  ~continuation:
253                    (IntroductionTactics.constructor_tac ~n:1)))) status
254     | _ -> fail "not an equality"
255   in
256   PET.mk_tactic (discriminate'_tac ~term)
257
258 let exn_noneq = 
259   PET.Fail (lazy "Injection: not an equality")
260 let exn_nothingtodo = 
261   PET.Fail (lazy "Nothing to do")
262 let exn_discrnonind =
263   PET.Fail (lazy "Discriminate: object is not an Inductive Definition: it's imposible")
264 let exn_injwronggoal = 
265   PET.Fail (lazy "Injection: goal after cut is not correct")
266 let exn_noneqind =
267   PET.Fail (lazy "Injection: not an equality over elements of an inductive type")
268
269 let pp ctx t = 
270   let names = List.map (function Some (n,_) -> Some n | None -> None) ctx in
271   CicPp.pp t names
272
273 let clear_term first_time lterm =
274    let clear_term status =
275       let (proof, goal) = status in
276       let _,metasenv,_subst,_,_, _ = proof in
277       let _,context,_ = CicUtil.lookup_meta goal metasenv in
278       let term, metasenv, _ugraph = lterm context metasenv CU.empty_ugraph in
279       debug_print (lazy ("\nclear di: " ^ pp context term));
280       debug_print (lazy ("nel contesto:\n" ^ CicPp.ppcontext context)); 
281       let g () = if first_time then raise exn_nothingtodo else T.id_tac in
282       let tactic = match term with
283          | C.Rel n -> 
284             begin match List.nth context (pred n) with
285                | Some (C.Name id, _) -> 
286                   T.if_ ~fail:(g ()) ~start:(PST.clear ~hyps:[id]) ~continuation:T.id_tac
287                | _ -> assert false
288             end
289           | _      -> g ()
290       in
291       PET.apply_tactic tactic status
292    in
293    PET.mk_tactic clear_term
294
295 let simpl_in_term context = function
296    | Cic.Rel i ->
297       let name = match List.nth context (pred i) with
298          | Some (Cic.Name s, Cic.Def _) -> s
299          | Some (Cic.Name s, Cic.Decl _) -> s
300          | _ -> assert false
301       in
302       RT.simpl_tac ~pattern:(None,[name,Cic.Implicit (Some `Hole)],None)
303    | _ -> T.id_tac
304
305 let mk_fresh_name metasenv context name typ =
306    let name = C.Name name in
307    match FNG.mk_fresh_name ~subst:[] metasenv context name ~typ with
308       | C.Name s    -> s
309       | C.Anonymous -> assert false
310
311 let exists context = function
312    | C.Rel i -> List.nth context (pred i) <> None
313    | _       -> true
314
315 let rec recur_on_child_tac name =
316    let recur_on_child status = 
317       let (proof, goal) = status in
318       let _, metasenv, _subst, _, _, _ = proof in
319       let _, context, _ = CicUtil.lookup_meta goal metasenv in
320       debug_print (lazy ("\nrecur_on_child su: " ^ name));
321       debug_print (lazy ("nel contesto:\n" ^ CicPp.ppcontext context));      
322       let rec search_name i = function
323          | []                                      -> T.id_tac
324          | Some (Cic.Name n, _) :: _ when n = name -> 
325               destruct ~first_time:false ~term:(Cic.Rel i)
326          | _ :: tl -> search_name (succ i) tl
327       in
328       PET.apply_tactic (search_name 1 context) status  
329    in
330    PET.mk_tactic recur_on_child
331    
332 and injection_tac ~lterm ~i ~continuation =
333  let give_name seed = function
334    | C.Name _ as name -> name
335    | C.Anonymous -> C.Name (incr seed; "y" ^ string_of_int !seed)
336  in
337  let rec mk_rels = function | 0 -> [] | n -> C.Rel n :: (mk_rels (n - 1)) in
338  let injection_tac status =
339   let (proof, goal) = status in
340   (* precondizione: t1 e t2 hanno in testa lo stesso costruttore ma 
341    * differiscono (o potrebbero differire?) nell'i-esimo parametro 
342    * del costruttore *)
343   let _,metasenv,_subst,_,_, _ = proof in
344   let _,context,_ = CicUtil.lookup_meta goal metasenv in
345   let term, metasenv, _ugraph = lterm context metasenv CU.empty_ugraph in
346   let termty,_ =
347     CTC.type_of_aux' metasenv context term CU.empty_ugraph
348   in
349   debug_print (lazy ("\ninjection su : " ^ pp context termty)); 
350   match termty with (* an equality *)
351    | C.Appl [(C.MutInd (equri, 0, [])) ; tty ; t1 ; t2]
352     when LibraryObjects.is_eq_URI equri -> 
353       let turi,typeno,ens,params =
354         match tty with (* some inductive type *)
355         | C.MutInd (turi,typeno,ens) -> turi,typeno,ens,[]
356         | C.Appl (C.MutInd (turi,typeno,ens)::params) -> turi,typeno,ens,params
357         | _ -> raise exn_noneqind
358       in
359       let t1',t2',consno = (* sono i due sottotermini che differiscono *)
360         match t1,t2 with
361         | C.Appl ((C.MutConstruct (uri1,typeno1,consno1,ens1))::applist1),
362           C.Appl ((C.MutConstruct (uri2,typeno2,consno2,ens2))::applist2)
363           when (uri1 = uri2) && (typeno1 = typeno2) && 
364                (consno1 = consno2) && (ens1 = ens2) -> 
365                (* controllo ridondante *)
366             List.nth applist1 (pred i),List.nth applist2 (pred i),consno2
367         | _ -> assert false
368       in
369       let tty',_ = CTC.type_of_aux' metasenv context t1' CU.empty_ugraph in
370       let patterns,outtype =
371         match fst (CicEnvironment.get_obj CU.empty_ugraph turi) with
372         | C.InductiveDefinition (ind_type_list,_,paramsno,_)->
373            let left_params, right_params = HExtlib.split_nth paramsno params in
374            let _,_,_,constructor_list = List.nth ind_type_list typeno in
375            let i_constr_id,_ = List.nth constructor_list (consno - 1) in
376            let patterns =
377              let seed = ref 0 in
378              List.map
379                (function (id,cty) ->
380                  let reduced_cty = CR.whd context cty in
381                  let rec aux k = function
382                    | C.Prod (_,_,tgt) when k <= paramsno -> 
383                        let left = List.nth left_params (k-1) in
384                        aux (k+1) (S.subst left tgt)
385                    | C.Prod (binder,source,target) when k > paramsno ->
386                       let binder' = give_name seed binder in
387                       C.Lambda (binder',source,(aux (k+1) target))
388                    | _ ->
389                      let nr_param_constr = k - paramsno - 1 in
390                      if id = i_constr_id then C.Rel (k - i)
391                      else S.lift nr_param_constr t1' 
392                      (* + 1 per liftare anche il lambda aggiunto
393                       * esternamente al case *)
394                  in S.lift 1 (aux 1 reduced_cty))
395                constructor_list 
396            in
397            (* this code should be taken from cases_tac *)
398            let outtype =
399              let seed = ref 0 in
400              let rec to_lambdas te head =
401                match CR.whd context te with
402                | C.Prod (binder,so,ta) ->
403                    let binder' = give_name seed binder in
404                    C.Lambda (binder',so,to_lambdas ta head)
405                | _ -> head 
406              in
407              let rec skip_prods params te =
408                match params, CR.whd context te with
409                | [], _ -> te
410                | left::tl, C.Prod (_,_,ta) -> 
411                    skip_prods tl (S.subst left ta)
412                | _, _ -> assert false
413              in
414              let abstracted_tty =
415                let tty =
416                  List.fold_left (fun x y -> S.subst y x) tty left_params
417                in
418                (* non lift, ma subst coi left! *)
419                match S.lift 1 tty with
420                | C.MutInd _ as tty' -> tty'
421                | C.Appl l ->
422                    let keep,abstract = HExtlib.split_nth (paramsno +1) l in
423                    let keep = List.map (S.lift paramsno) keep in
424                    C.Appl (keep@mk_rels (List.length abstract))
425                | _ -> assert false
426              in
427              match ind_type_list with
428              | [] -> assert false
429              | (_,_,ty,_)::_ ->
430                (* this is in general wrong, do as in cases_tac *)
431                to_lambdas (skip_prods left_params ty)
432                  (C.Lambda 
433                    (C.Name "cased", abstracted_tty,
434                      (* here we should capture right parameters *)
435                      (* 1 for his Lambda, one for the Lambda outside the match
436                       * and then one for each to_lambda *)
437                      S.lift (2+List.length right_params) tty'))
438           in
439             patterns,outtype
440         | _ -> raise exn_discrnonind
441       in
442       let cutted = C.Appl [C.MutInd (equri,0,[]) ; tty' ; t1' ; t2'] in
443       let changed = 
444         C.Appl [ C.Lambda (C.Name "x", tty, 
445                   C.MutCase (turi,typeno,outtype,C.Rel 1,patterns)) ; t1]
446       in
447       (* check if cutted and changed are well typed and if t1' ~ changed *)
448       let go_on =
449         try
450           let _,g = CTC.type_of_aux' metasenv context  cutted
451             CU.empty_ugraph
452           in
453           let _,g = CTC.type_of_aux' metasenv context changed g in
454           fst (CR.are_convertible ~metasenv context  t1' changed g)
455         with
456         | CTC.TypeCheckerFailure _ -> false
457       in
458       if not go_on then begin
459         HLog.warn "destruct: injection failed";
460         PET.apply_tactic continuation status
461       end else
462         let fill_cut_tac term = 
463            let fill_cut status =
464                debug_print (lazy "riempio il cut"); 
465                let (proof, goal) = status in
466                let _,metasenv,_subst,_,_, _ = proof in
467                let _,context,gty = CicUtil.lookup_meta goal metasenv in
468                let gty = Unshare.unshare gty in
469                let new_t1' = match gty with 
470                   | (C.Appl (C.MutInd (_,_,_)::_::t::_)) -> t
471                   | _ -> raise exn_injwronggoal
472                in
473                debug_print (lazy ("metto: " ^ pp context changed));
474                debug_print (lazy ("al posto di: " ^ pp context new_t1'));
475                debug_print (lazy ("nel goal: " ^ pp context gty));
476                debug_print (lazy ("nel contesto:\n" ^ CicPp.ppcontext context));
477                debug_print (lazy ("e poi rewrite con: "^pp context term));
478                let tac = T.seq ~tactics:[
479                   RT.change_tac
480                      ~pattern:(None, [], Some (PEH.pattern_of ~term:gty [new_t1']))
481                      (fun _ m u -> changed,m,u);
482                   ET.rewrite_simpl_tac
483                      ~direction:`LeftToRight
484                      ~pattern:(PET.conclusion_pattern None)
485                      term [];
486                   ET.reflexivity_tac   
487                ] in
488                PET.apply_tactic tac status
489            in
490            PET.mk_tactic fill_cut
491         in
492         debug_print (lazy ("CUT: " ^ pp context cutted));  
493         let name = mk_fresh_name metasenv context "Hcut" cutted in
494         let mk_fresh_name_callback = PEH.namer_of [Some name] in
495         debug_print (lazy ("figlio: " ^ name));
496         let tactic = 
497            T.thens ~start: (P.cut_tac ~mk_fresh_name_callback cutted)
498                    ~continuations:[
499                       T.seq ~tactics:[continuation; recur_on_child_tac name];
500                       fill_cut_tac term
501                    ]
502         in
503         PET.apply_tactic tactic status
504    | _ -> raise exn_noneq
505  in
506   PET.mk_tactic injection_tac
507
508 and subst_tac ~lterm ~direction ~where ~continuation =
509    let subst_tac status =
510       let (proof, goal) = status in
511       let _,metasenv,_subst,_,_, _ = proof in
512       let _,context,_ = CicUtil.lookup_meta goal metasenv in
513       let term, metasenv, _ugraph = lterm context metasenv CU.empty_ugraph in
514       debug_print (lazy ("\nsubst " ^ (match direction with `LeftToRight -> "->" | `RightToLeft -> "<-") ^ " di: " ^ pp context term));
515       let tactic = match where with
516          | None      -> 
517             debug_print (lazy ("nella conclusione"));
518             let pattern = PET.conclusion_pattern None in
519             let tactic = ET.rewrite_tac ~direction ~pattern term [] in
520             T.then_ ~start:(T.try_tactic ~tactic) ~continuation
521          | Some name ->
522             debug_print (lazy ("nella premessa: " ^ name));
523             let pattern = None, [name, PET.hole], None in
524             let start = ET.rewrite_tac ~direction ~pattern term [] in
525             let ok_tactic = 
526                T.seq ~tactics:[continuation; recur_on_child_tac name]
527             in
528             debug_print (lazy ("figlio: " ^ name));
529             T.if_ ~start ~continuation:ok_tactic ~fail:continuation         
530       in 
531       PET.apply_tactic tactic status
532    in
533    PET.mk_tactic subst_tac
534
535 (* ~term vive nel contesto della tattica una volta ~mappato
536  * ~continuation riceve la mappa assoluta
537  *)
538 and destruct ~first_time ~term =
539  let are_convertible hd1 hd2 metasenv context = 
540    fst (CR.are_convertible ~metasenv context hd1 hd2 CU.empty_ugraph)
541  in
542  let destruct status = 
543   let (proof, goal) = status in
544   let _,metasenv,_subst, _,_, _ = proof in
545   let _,context,_ = CicUtil.lookup_meta goal metasenv in
546   debug_print (lazy ("\ndestruct di: " ^ pp context term)); 
547   debug_print (lazy ("nel contesto:\n" ^ CicPp.ppcontext context));
548   let termty,_ = 
549     CTC.type_of_aux' metasenv context term CU.empty_ugraph
550   in
551   debug_print (lazy ("\ndestruct su: " ^ pp context termty)); 
552   let mk_lterm term c m ug =
553      let distance = List.length c - List.length context in
554      S.lift distance term, m, ug
555   in
556   let lterm = mk_lterm term in
557   let mk_subst_chain direction index with_what what =
558      let k = match term with C.Rel i -> i | _ -> -1 in
559      let rec traverse_context first_time j = function
560         | [] ->    
561            let continuation =
562               T.seq ~tactics:[
563                  clear_term first_time lterm;
564                  clear_term false (mk_lterm what);
565                  clear_term false (mk_lterm with_what)
566               ]
567            in
568            subst_tac ~direction ~lterm ~where:None ~continuation
569         | Some (C.Name name, _) :: tl when j < index && j <> k ->
570            debug_print (lazy ("\nsubst programmata: cosa: " ^ string_of_int index ^ ", dove: " ^ string_of_int j));
571            subst_tac ~direction ~lterm ~where:(Some name) 
572                      ~continuation:(traverse_context false (succ j) tl)
573         | _ :: tl -> traverse_context first_time (succ j) tl
574      in
575      traverse_context first_time 1 context
576   in
577   let tac = match termty with
578     | C.Appl [(C.MutInd (equri, 0, [])) ; tty ; t1 ; t2] 
579       when LibraryObjects.is_eq_URI equri ->
580           begin match t1,t2 with
581 (* injection part *)
582             | C.MutConstruct _,
583               C.MutConstruct _
584               when t1 = t2 -> clear_term first_time lterm
585             | C.Appl (C.MutConstruct _ as mc1 :: applist1),
586               C.Appl (C.MutConstruct _ as mc2 :: applist2)
587               when mc1 = mc2 ->
588                 let rec traverse_list first_time i l1 l2 = 
589                    match l1, l2 with
590                       | [], [] -> clear_term first_time lterm
591                       | hd1 :: tl1, hd2 :: tl2 -> 
592                         if are_convertible hd1 hd2 metasenv context then
593                            traverse_list first_time (succ i) tl1 tl2
594                         else
595                            injection_tac ~i ~lterm ~continuation:
596                               (traverse_list false (succ i) tl1 tl2)
597                       | _ -> assert false 
598                       (* i 2 termini hanno in testa lo stesso costruttore, 
599                        * ma applicato a un numero diverso di termini *)
600                 in
601                   traverse_list first_time 1 applist1 applist2
602 (* discriminate part *)
603             | C.MutConstruct (_,_,consno1,ens1),
604               C.MutConstruct (_,_,consno2,ens2)
605             | C.MutConstruct (_,_,consno1,ens1),
606               C.Appl ((C.MutConstruct (_,_,consno2,ens2))::_)
607             | C.Appl ((C.MutConstruct (_,_,consno1,ens1))::_),
608               C.MutConstruct (_,_,consno2,ens2)
609             | C.Appl ((C.MutConstruct (_,_,consno1,ens1))::_),
610               C.Appl ((C.MutConstruct (_,_,consno2,ens2))::_)
611               when (consno1 <> consno2) || (ens1 <> ens2) -> 
612                 discriminate_tac ~term
613 (* subst part *)
614             | C.Rel _, C.Rel _ when t1 = t2 ->
615                 T.seq ~tactics:[
616                    clear_term first_time lterm;
617                    clear_term false (mk_lterm t1)
618                 ]
619             | C.Rel i1, C.Rel i2 when i1 < i2 ->  
620                mk_subst_chain `LeftToRight i1 t2 t1
621             | C.Rel i1, C.Rel i2 when i1 > i2 ->
622                mk_subst_chain `RightToLeft i2 t1 t2
623             | C.Rel i1, _ when DTI.does_not_occur i1 t2 ->
624                mk_subst_chain `LeftToRight i1 t2 t1
625             | _, C.Rel i2 when DTI.does_not_occur i2 t1 ->
626                mk_subst_chain `RightToLeft i2 t1 t2
627 (* else part *)
628             | _ when not first_time -> T.id_tac
629             | _ (* when first_time *) -> 
630                T.then_ ~start:(simpl_in_term context term)
631                        ~continuation:(destruct ~first_time:false ~term)
632            end
633      | _ when not first_time -> T.id_tac
634      | _ (* when first_time *) -> raise exn_nothingtodo
635   in  
636     PET.apply_tactic tac status
637  in 
638    PET.mk_tactic destruct
639
640 let lazy_destruct_tac ~first_time ~lterm =
641    let lazy_destruct status =
642       let (proof, goal) = status in
643       let _,metasenv,_subst,_,_, _ = proof in
644       let _,context,_ = CicUtil.lookup_meta goal metasenv in
645       let term, _, _ = lterm context metasenv CU.empty_ugraph in
646       let tactic = 
647          if exists context term then destruct ~first_time ~term else T.id_tac
648       in
649       PET.apply_tactic tactic status
650    in
651    PET.mk_tactic lazy_destruct
652
653 (* destruct performs either injection or discriminate *)
654 (* equivalent to Coq's "analyze equality"             *)
655 let destruct_tac = function
656    | Some term -> destruct ~first_time:true ~term
657    | None      ->
658       let destruct_all status =
659          let (proof, goal) = status in
660          let _,metasenv,_subst,_,_, _ = proof in
661          let _,context,_ = CicUtil.lookup_meta goal metasenv in
662          let mk_lterm term c m ug =
663             let distance = List.length c - List.length context in
664             S.lift distance term, m, ug
665          in
666          let rec mk_tactics first_time i tacs = function
667             | []           -> List.rev tacs
668             | Some _ :: tl -> 
669                let lterm = mk_lterm (C.Rel i) in
670                let tacs = lazy_destruct_tac ~first_time ~lterm :: tacs in
671                mk_tactics false (succ i) tacs tl 
672            | _ :: tl       -> mk_tactics first_time (succ i) tacs tl
673          in
674          let tactics = mk_tactics false 1 [] context in
675          PET.apply_tactic (T.seq ~tactics) status
676       in
677       PET.mk_tactic destruct_all