]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/tactics/primitiveTactics.ml
Hypotheses patterns for elim implemented. No more need to generalize in advance.
[helm.git] / helm / software / components / tactics / primitiveTactics.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 exception TheTypeOfTheCurrentGoalIsAMetaICannotChooseTheRightElimiantionPrinciple
29 exception NotAnInductiveTypeToEliminate
30 exception WrongUriToVariable of string
31 exception NotAnEliminator
32
33 module PET = ProofEngineTypes
34
35 (* lambda_abstract newmeta ty *)
36 (* returns a triple [bo],[context],[ty'] where              *)
37 (* [ty] = Pi/LetIn [context].[ty'] ([context] is a vector!) *)
38 (* and [bo] = Lambda/LetIn [context].(Meta [newmeta])       *)
39 (* So, lambda_abstract is the core of the implementation of *)
40 (* the Intros tactic.                                       *)
41 (* howmany = -1 means Intros, howmany > 0 means Intros n    *)
42 let lambda_abstract ?(howmany=(-1)) metasenv context newmeta ty mk_fresh_name =
43  let module C = Cic in
44   let rec collect_context context howmany do_whd ty =
45    match howmany with
46    | 0 ->  
47         let irl =
48           CicMkImplicit.identity_relocation_list_for_metavariable context
49         in
50          context, ty, (C.Meta (newmeta,irl))
51    | _ -> 
52       match ty with 
53         C.Cast (te,_)   -> collect_context context howmany do_whd te 
54       | C.Prod (n,s,t)  ->
55          let n' = mk_fresh_name metasenv context n ~typ:s in
56           let (context',ty,bo) =
57            let entry = match n' with
58               | C.Name _    -> Some (n',(C.Decl s))
59               | C.Anonymous -> None
60            in
61            let ctx = entry :: context in
62            collect_context ctx (howmany - 1) do_whd t 
63           in
64            (context',ty,C.Lambda(n',s,bo))
65       | C.LetIn (n,s,sty,t) ->
66          let (context',ty,bo) =
67           collect_context ((Some (n,(C.Def (s,sty))))::context) (howmany - 1) do_whd t
68          in
69           (context',ty,C.LetIn(n,s,sty,bo))
70       | _ as t ->
71         if howmany <= 0 then
72          let irl =
73           CicMkImplicit.identity_relocation_list_for_metavariable context
74          in
75           context, t, (C.Meta (newmeta,irl))
76         else if do_whd then
77           let t = CicReduction.whd ~delta:true context t in
78           collect_context context howmany false t
79         else
80          raise (PET.Fail (lazy "intro(s): not enough products or let-ins"))
81   in
82    collect_context context howmany true ty 
83
84 let eta_expand metasenv context t arg =
85  let module T = CicTypeChecker in
86  let module S = CicSubstitution in
87  let module C = Cic in
88   let rec aux n =
89    function
90       t' when t' = S.lift n arg -> C.Rel (1 + n)
91     | C.Rel m  -> if m <= n then C.Rel m else C.Rel (m+1)
92     | C.Var (uri,exp_named_subst) ->
93        let exp_named_subst' = aux_exp_named_subst n exp_named_subst in
94         C.Var (uri,exp_named_subst')
95     | C.Meta (i,l) ->
96        let l' =
97         List.map (function None -> None | Some t -> Some (aux n t)) l
98        in
99         C.Meta (i, l')
100     | C.Sort _
101     | C.Implicit _ as t -> t
102     | C.Cast (te,ty) -> C.Cast (aux n te, aux n ty)
103     | C.Prod (nn,s,t) -> C.Prod (nn, aux n s, aux (n+1) t)
104     | C.Lambda (nn,s,t) -> C.Lambda (nn, aux n s, aux (n+1) t)
105     | C.LetIn (nn,s,ty,t) -> C.LetIn (nn, aux n s, aux n ty, aux (n+1) t)
106     | C.Appl l -> C.Appl (List.map (aux n) l)
107     | C.Const (uri,exp_named_subst) ->
108        let exp_named_subst' = aux_exp_named_subst n exp_named_subst in
109         C.Const (uri,exp_named_subst')
110     | C.MutInd (uri,i,exp_named_subst) ->
111        let exp_named_subst' = aux_exp_named_subst n exp_named_subst in
112         C.MutInd (uri,i,exp_named_subst')
113     | C.MutConstruct (uri,i,j,exp_named_subst) ->
114        let exp_named_subst' = aux_exp_named_subst n exp_named_subst in
115         C.MutConstruct (uri,i,j,exp_named_subst')
116     | C.MutCase (sp,i,outt,t,pl) ->
117        C.MutCase (sp,i,aux n outt, aux n t,
118         List.map (aux n) pl)
119     | C.Fix (i,fl) ->
120        let tylen = List.length fl in
121         let substitutedfl =
122          List.map
123           (fun (name,i,ty,bo) -> (name, i, aux n ty, aux (n+tylen) bo))
124            fl
125         in
126          C.Fix (i, substitutedfl)
127     | C.CoFix (i,fl) ->
128        let tylen = List.length fl in
129         let substitutedfl =
130          List.map
131           (fun (name,ty,bo) -> (name, aux n ty, aux (n+tylen) bo))
132            fl
133         in
134          C.CoFix (i, substitutedfl)
135   and aux_exp_named_subst n =
136    List.map (function uri,t -> uri,aux n t)
137   in
138    let argty,_ = 
139     T.type_of_aux' metasenv context arg CicUniv.oblivion_ugraph (* TASSI: FIXME *)
140    in
141     let fresh_name =
142      FreshNamesGenerator.mk_fresh_name ~subst:[]
143       metasenv context (Cic.Name "Heta") ~typ:argty
144     in
145      (C.Appl [C.Lambda (fresh_name,argty,aux 0 t) ; arg])
146
147 (*CSC: ma serve solamente la prima delle new_uninst e l'unione delle due!!! *)
148 let classify_metas newmeta in_subst_domain subst_in metasenv =
149  List.fold_right
150   (fun (i,canonical_context,ty) (old_uninst,new_uninst) ->
151     if in_subst_domain i then
152      old_uninst,new_uninst
153     else
154      let ty' = subst_in canonical_context ty in
155       let canonical_context' =
156        List.fold_right
157         (fun entry canonical_context' ->
158           let entry' =
159            match entry with
160               Some (n,Cic.Decl s) ->
161                Some (n,Cic.Decl (subst_in canonical_context' s))
162             | None -> None
163             | Some (n,Cic.Def (bo,ty)) ->
164                Some
165                 (n,
166                   Cic.Def
167                    (subst_in canonical_context' bo,
168                     subst_in canonical_context' ty))
169           in
170            entry'::canonical_context'
171         ) canonical_context []
172      in
173       if i < newmeta then
174        ((i,canonical_context',ty')::old_uninst),new_uninst
175       else
176        old_uninst,((i,canonical_context',ty')::new_uninst)
177   ) metasenv ([],[])
178
179 (* Useful only inside apply_tac *)
180 let
181  generalize_exp_named_subst_with_fresh_metas context newmeta uri exp_named_subst
182 =
183  let module C = Cic in
184   let params =
185     let o,_ = CicEnvironment.get_obj CicUniv.oblivion_ugraph uri in
186     CicUtil.params_of_obj o
187   in
188    let exp_named_subst_diff,new_fresh_meta,newmetasenvfragment,exp_named_subst'=
189     let next_fresh_meta = ref newmeta in
190     let newmetasenvfragment = ref [] in
191     let exp_named_subst_diff = ref [] in
192      let rec aux =
193       function
194          [],[] -> []
195        | uri::tl,[] ->
196           let ty =
197             let o,_ = CicEnvironment.get_obj CicUniv.oblivion_ugraph uri in
198               match o with
199                   C.Variable (_,_,ty,_,_) ->
200                     CicSubstitution.subst_vars !exp_named_subst_diff ty
201                 | _ -> raise (WrongUriToVariable (UriManager.string_of_uri uri))
202           in
203 (* CSC: patch to generate ?1 : ?2 : Type in place of ?1 : Type to simulate ?1 :< Type
204            (match ty with
205                C.Sort (C.Type _) as s -> (* TASSI: ?? *)
206                  let fresh_meta = !next_fresh_meta in
207                  let fresh_meta' = fresh_meta + 1 in
208                   next_fresh_meta := !next_fresh_meta + 2 ;
209                   let subst_item = uri,C.Meta (fresh_meta',[]) in
210                    newmetasenvfragment :=
211                     (fresh_meta,[],C.Sort (C.Type (CicUniv.fresh()))) ::
212                      (* TASSI: ?? *)
213                      (fresh_meta',[],C.Meta (fresh_meta,[])) :: !newmetasenvfragment ;
214                    exp_named_subst_diff := !exp_named_subst_diff @ [subst_item] ;
215                    subst_item::(aux (tl,[]))
216              | _ ->
217 *)
218               let irl =
219                 CicMkImplicit.identity_relocation_list_for_metavariable context
220               in
221               let subst_item = uri,C.Meta (!next_fresh_meta,irl) in
222                newmetasenvfragment :=
223                 (!next_fresh_meta,context,ty)::!newmetasenvfragment ;
224                exp_named_subst_diff := !exp_named_subst_diff @ [subst_item] ;
225                incr next_fresh_meta ;
226                subst_item::(aux (tl,[]))(*)*)
227        | uri::tl1,((uri',_) as s)::tl2 ->
228           assert (UriManager.eq uri uri') ;
229           s::(aux (tl1,tl2))
230        | [],_ -> assert false
231      in
232       let exp_named_subst' = aux (params,exp_named_subst) in
233        !exp_named_subst_diff,!next_fresh_meta,
234         List.rev !newmetasenvfragment, exp_named_subst'
235    in
236     new_fresh_meta,newmetasenvfragment,exp_named_subst',exp_named_subst_diff
237 ;;
238
239 let new_metasenv_and_unify_and_t newmeta' metasenv' subst context term' ty termty goal_arity =
240   let (consthead,newmetasenv,arguments,_) =
241    TermUtil.saturate_term newmeta' metasenv' context termty
242     goal_arity in
243   let subst,newmetasenv',_ = 
244    CicUnification.fo_unif_subst 
245      subst context newmetasenv consthead ty CicUniv.oblivion_ugraph
246   in
247   let t = 
248     if List.length arguments = 0 then term' else Cic.Appl (term'::arguments)
249   in
250   subst,newmetasenv',t
251
252 let rec count_prods context ty =
253  match CicReduction.whd context ty with
254     Cic.Prod (n,s,t) -> 1 + count_prods (Some (n,Cic.Decl s)::context) t
255   | _ -> 0
256
257 let apply_with_subst ~term ~subst ~maxmeta (proof, goal) =
258   (* Assumption: The term "term" must be closed in the current context *)
259  let module T = CicTypeChecker in
260  let module R = CicReduction in
261  let module C = Cic in
262   let (_,metasenv,_subst,_,_, _) = proof in
263   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
264   let newmeta = max (CicMkImplicit.new_meta metasenv subst) maxmeta in
265    let exp_named_subst_diff,newmeta',newmetasenvfragment,term' =
266     match term with
267        C.Var (uri,exp_named_subst) ->
268         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
269          generalize_exp_named_subst_with_fresh_metas context newmeta uri
270           exp_named_subst
271         in
272          exp_named_subst_diff,newmeta',newmetasenvfragment,
273           C.Var (uri,exp_named_subst')
274      | C.Const (uri,exp_named_subst) ->
275         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
276          generalize_exp_named_subst_with_fresh_metas context newmeta uri
277           exp_named_subst
278         in
279          exp_named_subst_diff,newmeta',newmetasenvfragment,
280           C.Const (uri,exp_named_subst')
281      | C.MutInd (uri,tyno,exp_named_subst) ->
282         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
283          generalize_exp_named_subst_with_fresh_metas context newmeta uri
284           exp_named_subst
285         in
286          exp_named_subst_diff,newmeta',newmetasenvfragment,
287           C.MutInd (uri,tyno,exp_named_subst')
288      | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
289         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
290          generalize_exp_named_subst_with_fresh_metas context newmeta uri
291           exp_named_subst
292         in
293          exp_named_subst_diff,newmeta',newmetasenvfragment,
294           C.MutConstruct (uri,tyno,consno,exp_named_subst')
295      | _ -> [],newmeta,[],term
296    in
297    let metasenv' = metasenv@newmetasenvfragment in
298    let termty,_ = 
299      CicTypeChecker.type_of_aux' metasenv' context term' CicUniv.oblivion_ugraph
300    in
301    let termty =
302      CicSubstitution.subst_vars exp_named_subst_diff termty in
303    let goal_arity = count_prods context ty in
304    let subst,newmetasenv',t = 
305     let rec add_one_argument n =
306      try
307       new_metasenv_and_unify_and_t newmeta' metasenv' subst context term' ty
308         termty n
309      with CicUnification.UnificationFailure _ when n > 0 ->
310       add_one_argument (n - 1)
311     in
312      add_one_argument goal_arity
313    in
314    let in_subst_domain i = List.exists (function (j,_) -> i=j) subst in
315    let apply_subst = CicMetaSubst.apply_subst subst in
316    let old_uninstantiatedmetas,new_uninstantiatedmetas =
317      (* subst_in doesn't need the context. Hence the underscore. *)
318      let subst_in _ = CicMetaSubst.apply_subst subst in
319      classify_metas newmeta in_subst_domain subst_in newmetasenv'
320    in
321    let bo' = apply_subst t in
322    let newmetasenv'' = new_uninstantiatedmetas@old_uninstantiatedmetas in
323    let subst_in =
324      (* if we just apply the subtitution, the type is irrelevant:
325               we may use Implicit, since it will be dropped *)
326       ((metano,(context,bo',Cic.Implicit None))::subst)
327    in
328    let (newproof, newmetasenv''') = 
329     ProofEngineHelpers.subst_meta_and_metasenv_in_proof proof metano subst_in
330      newmetasenv''
331    in
332    let subst = ((metano,(context,bo',ty))::subst) in
333    subst,
334    (newproof, List.map (function (i,_,_) -> i) new_uninstantiatedmetas),
335    max maxmeta (CicMkImplicit.new_meta newmetasenv''' subst)
336
337
338 (* ALB *)
339 let apply_with_subst ~term ?(subst=[]) ?(maxmeta=0) status =
340   try
341 (*     apply_tac_verbose ~term status *)
342     apply_with_subst ~term ~subst ~maxmeta status
343       (* TODO cacciare anche altre eccezioni? *)
344   with 
345   | CicUnification.UnificationFailure msg
346   | CicTypeChecker.TypeCheckerFailure msg -> raise (PET.Fail msg)
347
348 (* ALB *)
349 let apply_tac_verbose ~term status =
350   let subst, status, _ = apply_with_subst ~term status in
351   (CicMetaSubst.apply_subst subst), status
352
353 let apply_tac ~term status = snd (apply_tac_verbose ~term status)
354
355   (* TODO per implementare i tatticali e' necessario che tutte le tattiche
356   sollevino _solamente_ Fail *)
357 let apply_tac ~term =
358  let apply_tac ~term status =
359   try
360     apply_tac ~term status
361       (* TODO cacciare anche altre eccezioni? *)
362   with 
363   | CicUnification.UnificationFailure msg
364   | CicTypeChecker.TypeCheckerFailure msg ->
365       raise (PET.Fail msg)
366  in
367   PET.mk_tactic (apply_tac ~term)
368
369 let intros_tac ?howmany ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[]) ()=
370  let intros_tac (proof, goal)
371  =
372   let module C = Cic in
373   let module R = CicReduction in
374    let (_,metasenv,_subst,_,_, _) = proof in
375    let metano,context,ty = CicUtil.lookup_meta goal metasenv in
376     let newmeta = ProofEngineHelpers.new_meta_of_proof ~proof in
377      let (context',ty',bo') =
378       lambda_abstract ?howmany metasenv context newmeta ty mk_fresh_name_callback
379      in
380       let (newproof, _) =
381        ProofEngineHelpers.subst_meta_in_proof proof metano bo'
382         [newmeta,context',ty']
383       in
384        (newproof, [newmeta])
385  in
386   PET.mk_tactic intros_tac
387   
388 let cut_tac ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[]) term =
389  let cut_tac
390   ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[])
391   term (proof, goal)
392  =
393   let module C = Cic in
394    let curi,metasenv,_subst,pbo,pty, attrs = proof in
395    let metano,context,ty = CicUtil.lookup_meta goal metasenv in
396     let newmeta1 = ProofEngineHelpers.new_meta_of_proof ~proof in
397     let newmeta2 = newmeta1 + 1 in
398     let fresh_name =
399      mk_fresh_name_callback metasenv context (Cic.Name "Hcut") ~typ:term in
400     let context_for_newmeta1 =
401      (Some (fresh_name,C.Decl term))::context in
402     let irl1 =
403      CicMkImplicit.identity_relocation_list_for_metavariable
404       context_for_newmeta1
405     in
406     let irl2 =
407       CicMkImplicit.identity_relocation_list_for_metavariable context
408     in
409      let newmeta1ty = CicSubstitution.lift 1 ty in
410       let bo' = 
411         Cic.LetIn (fresh_name, C.Meta (newmeta2,irl2), term, C.Meta (newmeta1,irl1))
412       in
413       let (newproof, _) =
414        ProofEngineHelpers.subst_meta_in_proof proof metano bo'
415         [newmeta2,context,term; newmeta1,context_for_newmeta1,newmeta1ty];
416       in
417        (newproof, [newmeta1 ; newmeta2])
418  in
419   PET.mk_tactic (cut_tac ~mk_fresh_name_callback term)
420
421 let letin_tac ?(mk_fresh_name_callback=FreshNamesGenerator.mk_fresh_name ~subst:[]) term =
422  let letin_tac
423   ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[])
424   term (proof, goal)
425  =
426   let module C = Cic in
427    let curi,metasenv,_subst,pbo,pty, attrs = proof in
428    (* occur check *)
429    let occur i t =
430      let m = CicUtil.metas_of_term t in 
431      List.exists (fun (j,_) -> i=j) m
432    in
433    let metano,context,ty = CicUtil.lookup_meta goal metasenv in
434    if occur metano term then
435      raise 
436        (ProofEngineTypes.Fail (lazy
437          "You can't letin a term containing the current goal"));
438     let tty,_ =
439       CicTypeChecker.type_of_aux' metasenv context term CicUniv.oblivion_ugraph in
440      let newmeta = ProofEngineHelpers.new_meta_of_proof ~proof in
441      let fresh_name =
442       mk_fresh_name_callback metasenv context (Cic.Name "Hletin") ~typ:term in
443      let context_for_newmeta =
444       (Some (fresh_name,C.Def (term,tty)))::context in
445      let irl =
446       CicMkImplicit.identity_relocation_list_for_metavariable
447        context_for_newmeta
448      in
449       let newmetaty = CicSubstitution.lift 1 ty in
450       let bo' = C.LetIn (fresh_name,term,tty,C.Meta (newmeta,irl)) in
451        let (newproof, _) =
452          ProofEngineHelpers.subst_meta_in_proof
453            proof metano bo'[newmeta,context_for_newmeta,newmetaty]
454        in
455         (newproof, [newmeta])
456  in
457   PET.mk_tactic (letin_tac ~mk_fresh_name_callback term)
458
459   (** functional part of the "exact" tactic *)
460 let exact_tac ~term =
461  let exact_tac ~term (proof, goal) =
462   (* Assumption: the term bo must be closed in the current context *)
463   let (_,metasenv,_subst,_,_, _) = proof in
464   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
465   let module T = CicTypeChecker in
466   let module R = CicReduction in
467   let ty_term,u = T.type_of_aux' metasenv context term CicUniv.oblivion_ugraph in
468   let b,_ = R.are_convertible context ty_term ty u in (* TASSI: FIXME *)
469   if b then
470    begin
471     let (newproof, metasenv') =
472       ProofEngineHelpers.subst_meta_in_proof proof metano term [] in
473     (newproof, [])
474    end
475   else
476    raise (PET.Fail (lazy "The type of the provided term is not the one expected."))
477  in
478   PET.mk_tactic (exact_tac ~term)
479
480 (* not really "primitive" tactics .... *)
481   
482 module TC  = CicTypeChecker
483 module UM  = UriManager
484 module R   = CicReduction
485 module C   = Cic
486 module PEH = ProofEngineHelpers
487 module PER = ProofEngineReduction
488 module MS  = CicMetaSubst 
489 module S   = CicSubstitution 
490 module T   = Tacticals
491 module RT  = ReductionTactics
492
493 let rec args_init n f =
494    if n <= 0 then [] else f n :: args_init (pred n) f
495
496 let mk_predicate_for_elim 
497  ~context ~metasenv ~ugraph ~goal ~arg ~using ~cpattern ~args_no = 
498    let instantiated_eliminator =
499       let f n = if n = 1 then arg else C.Implicit None in
500       C.Appl (using :: args_init args_no f)
501    in
502    let _actual_arg, iety, _metasenv', _ugraph = 
503       CicRefine.type_of_aux' metasenv context instantiated_eliminator ugraph
504    in
505    let _actual_meta, actual_args = match iety with
506       | C.Meta (i, _)                  -> i, []
507       | C.Appl (C.Meta (i, _) :: args) -> i, args
508       | _                              -> assert false
509    in
510 (* let _, upto = PEH.split_with_whd (List.nth splits pred_pos) in *)
511    let rec mk_pred metasenv context' pred arg' cpattern' = function
512       | []           -> metasenv, pred, arg'
513       | arg :: tail -> 
514 (* FG: we find the predicate for the eliminator as in the rewrite tactic ****)
515          let argty, _ugraph = TC.type_of_aux' metasenv context arg ugraph in
516          let argty = CicReduction.whd context argty in         
517          let fresh_name = 
518             FreshNamesGenerator.mk_fresh_name 
519             ~subst:[] metasenv context' C.Anonymous ~typ:argty in
520          let hyp = Some (fresh_name, C.Decl argty) in
521          let lazy_term c m u =  
522           let distance  = List.length c - List.length context in
523            S.lift distance arg, m, u in
524          let pattern = Some lazy_term, [], Some cpattern' in
525          let subst, metasenv, _ugraph, _conjecture, selected_terms =
526           ProofEngineHelpers.select ~metasenv ~ugraph
527            ~conjecture:(0, context, pred) ~pattern in
528          let metasenv = MS.apply_subst_metasenv subst metasenv in  
529          let map (_context_of_t, t) l = t :: l in
530          let what = List.fold_right map selected_terms [] in
531          let arg' = MS.apply_subst subst arg' in
532          let argty = MS.apply_subst subst argty in
533          let pred = PER.replace_with_rel_1_from ~equality:(==) ~what 1 pred in
534          let pred = MS.apply_subst subst pred in
535          let pred = C.Lambda (fresh_name, argty, pred) in
536          let cpattern' = C.Lambda (C.Anonymous, C.Implicit None, cpattern') in
537          mk_pred metasenv (hyp :: context') pred arg' cpattern' tail 
538    in
539    let metasenv, pred, arg = 
540       mk_pred metasenv context goal arg cpattern (List.rev actual_args)
541    in
542    HLog.debug ("PREDICATE: " ^ CicPp.ppterm ~metasenv pred ^ " ARGS: " ^ String.concat " " (List.map (CicPp.ppterm ~metasenv) actual_args));
543    metasenv, pred, arg, actual_args
544
545 let beta_after_elim_tac upto predicate =
546    let beta_after_elim_tac status =
547       let proof, goal = status in
548       let _, metasenv, _subst, _, _, _ = proof in
549       let _, _, ty = CicUtil.lookup_meta goal metasenv in
550       let mk_pattern ~equality ~upto ~predicate ty =
551          (* code adapted from ProceduralConversion.generalize *)
552          let meta = C.Implicit None in
553          let hole = C.Implicit (Some `Hole) in
554          let anon = C.Anonymous in
555          let is_meta =
556             let map b = function
557                | C.Implicit None when b -> b
558                | _                      -> false
559             in
560             List.fold_left map true
561          in
562          let rec gen_fix len k (name, i, ty, bo) =
563             name, i, gen_term k ty, gen_term (k + len) bo
564          and gen_cofix len k (name, ty, bo) =
565             name, gen_term k ty, gen_term (k + len) bo
566          and gen_term k = function
567             | C.Sort _ 
568             | C.Implicit _
569             | C.Const (_, _)
570             | C.Var (_, _)
571             | C.MutInd (_, _, _)
572             | C.MutConstruct (_, _, _, _)
573             | C.Meta (_, _) 
574             | C.Rel _ -> meta
575             | C.Appl (hd :: tl) when equality hd (S.lift k predicate) ->
576                assert (List.length tl = upto);
577                hole
578             | C.Appl ts -> 
579                let ts = List.map (gen_term k) ts in
580                if is_meta ts then meta else C.Appl ts
581             | C.Cast (te, ty) -> 
582                let te, ty = gen_term k te, gen_term k ty in
583                if is_meta [te; ty] then meta else C.Cast (te, ty)
584             | C.MutCase (sp, i, outty, t, pl) ->         
585                let outty, t, pl = gen_term k outty, gen_term k t, List.map (gen_term k) pl in
586                if is_meta (outty :: t :: pl) then meta else hole (* C.MutCase (sp, i, outty, t, pl) *)
587             | C.Prod (_, s, t) -> 
588                let s, t = gen_term k s, gen_term (succ k) t in
589                if is_meta [s; t] then meta else C.Prod (anon, s, t)
590             | C.Lambda (_, s, t) ->
591                let s, t = gen_term k s, gen_term (succ k) t in
592                if is_meta [s; t] then meta else C.Lambda (anon, s, t)
593             | C.LetIn (_, s, ty, t) -> 
594                let s,ty,t = gen_term k s, gen_term k ty, gen_term (succ k) t in
595                if is_meta [s; t] then meta else C.LetIn (anon, s, ty, t)
596             | C.Fix (i, fl) -> C.Fix (i, List.map (gen_fix (List.length fl) k) fl)
597             | C.CoFix (i, fl) -> C.CoFix (i, List.map (gen_cofix (List.length fl) k) fl)
598          in
599          None, [], Some (gen_term 0 ty)
600       in
601       let equality = CicUtil.alpha_equivalence in
602       let pattern = mk_pattern ~equality ~upto ~predicate ty in
603       let tactic = RT.head_beta_reduce_tac ~delta:false ~upto ~pattern in
604       PET.apply_tactic tactic status
605    in
606    PET.mk_tactic beta_after_elim_tac
607
608 (* ANCORA DA DEBUGGARE *)
609
610 exception UnableToDetectTheTermThatMustBeGeneralizedYouMustGiveItExplicitly;;
611 exception TheSelectedTermsMustLiveInTheGoalContext
612 exception AllSelectedTermsMustBeConvertible;;
613 exception GeneralizationInHypothesesNotImplementedYet;;
614
615 let generalize_tac 
616  ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[])
617  pattern
618  =
619   let module PET = ProofEngineTypes in
620   let generalize_tac mk_fresh_name_callback
621        ~pattern:(term,hyps_pat,concl_pat) status
622   =
623    if hyps_pat <> [] then raise GeneralizationInHypothesesNotImplementedYet;
624    let (proof, goal) = status in
625    let module C = Cic in
626    let module T = Tacticals in
627     let uri,metasenv,_subst,pbo,pty, attrs = proof in
628     let (_,context,ty) as conjecture = CicUtil.lookup_meta goal metasenv in
629     let subst,metasenv,u,selected_hyps,terms_with_context =
630      ProofEngineHelpers.select ~metasenv ~ugraph:CicUniv.oblivion_ugraph
631       ~conjecture ~pattern in
632     let context = CicMetaSubst.apply_subst_context subst context in
633     let metasenv = CicMetaSubst.apply_subst_metasenv subst metasenv in
634     let pbo = CicMetaSubst.apply_subst subst pbo in
635     let pty = CicMetaSubst.apply_subst subst pty in
636     let term =
637      match term with
638         None -> None
639       | Some term ->
640           Some (fun context metasenv ugraph -> 
641                   let term, metasenv, ugraph = term context metasenv ugraph in
642                    CicMetaSubst.apply_subst subst term,
643                     CicMetaSubst.apply_subst_metasenv subst metasenv,
644                     ugraph)
645     in
646     let u,typ,term, metasenv' =
647      let context_of_t, (t, metasenv, u) =
648       match terms_with_context, term with
649          [], None ->
650           raise
651            UnableToDetectTheTermThatMustBeGeneralizedYouMustGiveItExplicitly
652        | [], Some t -> context, t context metasenv u
653        | (context_of_t, _)::_, Some t -> 
654            context_of_t, t context_of_t metasenv u
655        | (context_of_t, t)::_, None -> context_of_t, (t, metasenv, u)
656      in
657       let t,subst,metasenv' =
658        try
659         CicMetaSubst.delift_rels [] metasenv
660          (List.length context_of_t - List.length context) t
661        with
662         CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
663          raise TheSelectedTermsMustLiveInTheGoalContext
664       in
665        (*CSC: I am not sure about the following two assertions;
666          maybe I need to propagate the new subst and metasenv *)
667        assert (subst = []);
668        assert (metasenv' = metasenv);
669        let typ,u = CicTypeChecker.type_of_aux' ~subst metasenv context t u in
670         u,typ,t,metasenv
671     in
672     (* We need to check:
673         1. whether they live in the context of the goal;
674            if they do they are also well-typed since they are closed subterms
675            of a well-typed term in the well-typed context of the well-typed
676            term
677         2. whether they are convertible
678     *)
679     ignore (
680      List.fold_left
681       (fun u (context_of_t,t) ->
682         (* 1 *)
683         let t,subst,metasenv'' =
684          try
685           CicMetaSubst.delift_rels [] metasenv'
686            (List.length context_of_t - List.length context) t
687          with
688           CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
689            raise TheSelectedTermsMustLiveInTheGoalContext in
690         (*CSC: I am not sure about the following two assertions;
691           maybe I need to propagate the new subst and metasenv *)
692         assert (subst = []);
693         assert (metasenv'' = metasenv');
694         (* 2 *)
695         let b,u1 = CicReduction.are_convertible ~subst context term t u in 
696          if not b then 
697           raise AllSelectedTermsMustBeConvertible
698          else
699           u1
700       ) u terms_with_context) ;
701     let status = (uri,metasenv',_subst,pbo,pty, attrs),goal in
702     let proof,goals =
703      PET.apply_tactic 
704       (T.thens 
705         ~start:
706           (cut_tac 
707            (C.Prod(
708              (mk_fresh_name_callback metasenv context C.Anonymous ~typ:typ), 
709              typ,
710              (ProofEngineReduction.replace_lifting_csc 1
711                ~equality:(==) 
712                ~what:(List.map snd terms_with_context)
713                ~with_what:(List.map (function _ -> C.Rel 1) terms_with_context)
714                ~where:ty)
715            )))
716         ~continuations:
717           [(apply_tac ~term:(C.Appl [C.Rel 1; CicSubstitution.lift 1 term])) ;
718             T.id_tac])
719         status
720     in
721      let _,metasenv'',_subst,_,_, _ = proof in
722       (* CSC: the following is just a bad approximation since a meta
723          can be closed and then re-opened! *)
724       (proof,
725         goals @
726          (List.filter
727            (fun j -> List.exists (fun (i,_,_) -> i = j) metasenv'')
728            (ProofEngineHelpers.compare_metasenvs ~oldmetasenv:metasenv
729              ~newmetasenv:metasenv')))
730  in
731   PET.mk_tactic (generalize_tac mk_fresh_name_callback ~pattern)
732 ;;
733
734 let generalize_pattern_tac pattern =
735  let generalize_pattern_tac (proof,goal) =
736    let _,metasenv,_,_,_,_ = proof in
737    let conjecture = CicUtil.lookup_meta goal metasenv in
738    let _,context,_ = conjecture in 
739    let generalize_hyps =
740     let _,hpatterns,_ = ProofEngineHelpers.sort_pattern_hyps context pattern in
741      List.map fst hpatterns in
742    let ids_and_patterns =
743     List.map
744      (fun id ->
745        let rel,_ = ProofEngineHelpers.find_hyp id context in
746         id,(Some (PET.const_lazy_term rel), [], None)
747      ) generalize_hyps in
748    let tactics =
749     List.map
750      (function (id,pattern) ->
751        Tacticals.then_ ~start:(generalize_tac pattern)
752         ~continuation:(Tacticals.try_tactic
753           (ProofEngineStructuralRules.clear [id]))
754      ) ids_and_patterns
755    in
756     PET.apply_tactic (Tacticals.seq tactics) (proof,goal)
757  in
758   PET.mk_tactic (generalize_pattern_tac)
759 ;;
760
761 let pattern_after_generalize_pattern_tac (tp, hpatterns, cpattern) =
762  let cpattern =
763   match cpattern with
764      None -> ProofEngineTypes.hole
765    | Some t -> t
766  in
767  let cpattern =
768   List.fold_left
769    (fun t (_,ty) -> Cic.Prod (Cic.Anonymous, ty, t)) cpattern hpatterns
770  in
771   tp, [], Some cpattern
772 ;;
773
774 let elim_tac ?using ?(pattern = PET.conclusion_pattern None) term = 
775  let elim_tac pattern (proof, goal) =
776    let ugraph = CicUniv.oblivion_ugraph in
777    let curi, metasenv, _subst, proofbo, proofty, attrs = proof in
778    let conjecture = CicUtil.lookup_meta goal metasenv in
779    let metano, context, ty = conjecture in 
780    let pattern = pattern_after_generalize_pattern_tac pattern in
781    let cpattern =
782     match pattern with 
783       | None, [], Some cpattern -> cpattern
784       | _ -> raise (PET.Fail (lazy "not implemented")) in    
785     let termty,_ugraph = TC.type_of_aux' metasenv context term ugraph in
786     let termty = CicReduction.whd context termty in
787     let termty, metasenv', arguments, _fresh_meta =
788      TermUtil.saturate_term
789       (ProofEngineHelpers.new_meta_of_proof proof) metasenv context termty 0 in
790     let term = if arguments = [] then term else Cic.Appl (term::arguments) in
791     let uri, exp_named_subst, typeno, _args =
792      match termty with
793         C.MutInd (uri,typeno,exp_named_subst) -> (uri,exp_named_subst,typeno,[])
794       | C.Appl ((C.MutInd (uri,typeno,exp_named_subst))::args) ->
795           (uri,exp_named_subst,typeno,args)
796       | _ -> raise NotAnInductiveTypeToEliminate
797     in
798      let eliminator_uri =
799       let buri = UM.buri_of_uri uri in
800       let name = 
801         let o,_ugraph = CicEnvironment.get_obj ugraph uri in
802        match o with
803           C.InductiveDefinition (tys,_,_,_) ->
804            let (name,_,_,_) = List.nth tys typeno in
805             name
806         | _ -> assert false
807       in
808       let ty_ty,_ugraph = TC.type_of_aux' metasenv' context ty ugraph in
809       let ext =
810        match ty_ty with
811           C.Sort C.Prop -> "_ind"
812         | C.Sort C.Set  -> "_rec"
813         | C.Sort (C.CProp _) -> "_rect"
814         | C.Sort (C.Type _)-> "_rect" 
815         | C.Meta (_,_) -> raise TheTypeOfTheCurrentGoalIsAMetaICannotChooseTheRightElimiantionPrinciple
816         | _ -> assert false
817       in
818        UM.uri_of_string (buri ^ "/" ^ name ^ ext ^ ".con")
819      in
820       let eliminator_ref = match using with
821          | None   -> C.Const (eliminator_uri, exp_named_subst)
822          | Some t -> t 
823        in
824        let ety, _ugraph = 
825          TC.type_of_aux' metasenv' context eliminator_ref ugraph in
826 (* FG: ADDED PART ***********************************************************)
827 (* FG: we can not assume eliminator is the default eliminator ***************)
828    let splits, args_no = PEH.split_with_whd (context, ety) in
829    let pred_pos = match List.hd splits with
830       | _, C.Rel i when i > 1 && i <= args_no -> i
831       | _, C.Appl (C.Rel i :: _) when i > 1 && i <= args_no -> i
832       | _ -> raise NotAnEliminator
833    in
834    let metasenv', pred, term, actual_args = match pattern with 
835       | None, [], Some (C.Implicit (Some `Hole)) ->
836          metasenv', C.Implicit None, term, []
837       | _                                        ->
838          mk_predicate_for_elim 
839             ~args_no ~context ~ugraph ~cpattern
840             ~metasenv:metasenv' ~arg:term ~using:eliminator_ref ~goal:ty
841    in
842 (* FG: END OF ADDED PART ****************************************************)
843       let term_to_refine =
844          let f n =
845             if n = pred_pos then pred else
846             if n = 1 then term else C.Implicit None
847          in
848          C.Appl (eliminator_ref :: args_init args_no f)
849       in
850       let refined_term,_refined_termty,metasenv'',_ugraph = 
851          CicRefine.type_of_aux' metasenv' context term_to_refine ugraph
852       in
853       let new_goals =
854          ProofEngineHelpers.compare_metasenvs
855             ~oldmetasenv:metasenv ~newmetasenv:metasenv''
856       in
857       let proof' = curi,metasenv'',_subst,proofbo,proofty, attrs in
858       let proof'', new_goals' =
859          PET.apply_tactic (apply_tac ~term:refined_term) (proof',goal)
860       in
861       (* The apply_tactic can have closed some of the new_goals *)
862       let patched_new_goals =
863          let (_,metasenv''',_subst,_,_, _) = proof'' in
864          List.filter
865             (function i -> List.exists (function (j,_,_) -> j=i) metasenv''')
866             new_goals @ new_goals'
867       in
868       let res = proof'', patched_new_goals in
869       let upto = List.length actual_args in
870       if upto = 0 then res else 
871       let continuation = beta_after_elim_tac upto pred in
872       let dummy_status = proof,goal in
873       PET.apply_tactic
874          (T.then_ ~start:(PET.mk_tactic (fun _ -> res)) ~continuation)
875          dummy_status
876    in
877    let reorder_pattern ((proof, goal) as status) =
878      let _,metasenv,_,_,_,_ = proof in
879      let conjecture = CicUtil.lookup_meta goal metasenv in
880      let _,context,_ = conjecture in
881      let pattern = ProofEngineHelpers.sort_pattern_hyps context pattern in
882       PET.apply_tactic
883        (Tacticals.then_ ~start:(generalize_pattern_tac pattern)
884          ~continuation:(PET.mk_tactic (elim_tac pattern))) status
885    in
886     PET.mk_tactic reorder_pattern
887 ;;
888
889 let cases_intros_tac ?(howmany=(-1)) ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[]) term =
890  let cases_tac ~term (proof, goal) =
891   let module TC = CicTypeChecker in
892   let module U = UriManager in
893   let module R = CicReduction in
894   let module C = Cic in
895   let (curi,metasenv,_subst, proofbo,proofty, attrs) = proof in
896   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
897   let termty,_ = TC.type_of_aux' metasenv context term CicUniv.oblivion_ugraph in
898   let termty = CicReduction.whd context termty in
899   let (termty,metasenv',arguments,fresh_meta) =
900    TermUtil.saturate_term
901     (ProofEngineHelpers.new_meta_of_proof proof) metasenv context termty 0 in
902   let term = if arguments = [] then term else Cic.Appl (term::arguments) in
903   let uri,exp_named_subst,typeno,args =
904     match termty with
905     | C.MutInd (uri,typeno,exp_named_subst) -> (uri,exp_named_subst,typeno,[])
906     | C.Appl ((C.MutInd (uri,typeno,exp_named_subst))::args) ->
907         (uri,exp_named_subst,typeno,args)
908     | _ -> raise NotAnInductiveTypeToEliminate
909   in
910   let paramsno,itty,patterns,right_args =
911     match CicEnvironment.get_obj CicUniv.oblivion_ugraph uri with
912     | C.InductiveDefinition (tys,_,paramsno,_),_ ->
913        let _,left_parameters,right_args = 
914          List.fold_right 
915            (fun x (n,acc1,acc2) -> 
916              if n > 0 then (n-1,acc1,x::acc2) else (n,x::acc1,acc2)) 
917            args (List.length args - paramsno, [],[])
918        in
919        let _,_,itty,cl = List.nth tys typeno in
920        let rec aux left_parameters context t =
921          match left_parameters,CicReduction.whd context t with
922          | [],C.Prod (name,source,target) ->
923             let fresh_name =
924               mk_fresh_name_callback metasenv' context name ~typ:source
925             in
926              C.Lambda (fresh_name,C.Implicit None,
927              aux [] (Some (fresh_name,C.Decl source)::context) target)
928          | hd::tl,C.Prod (name,source,target) ->
929              (* left parameters instantiation *)
930              aux tl context (CicSubstitution.subst hd target)
931          | [],_ -> C.Implicit None
932          | _ -> assert false
933        in
934         paramsno,itty,
935         List.map (function (_,cty) -> aux left_parameters context cty) cl,
936         right_args
937     | _ -> assert false
938   in
939   let outtype =
940     let n_right_args = List.length right_args in
941     let n_lambdas = n_right_args + 1 in
942     let lifted_ty = CicSubstitution.lift n_lambdas ty in
943     let captured_ty = 
944       let what = 
945         List.map (CicSubstitution.lift n_lambdas) (right_args)
946       in
947       let with_what meta = 
948         let rec mkargs = function 
949           | 0 -> assert false
950           | 1 -> []
951           | n -> 
952               (if meta then Cic.Implicit None else Cic.Rel n)::(mkargs (n-1)) 
953         in
954         mkargs n_lambdas 
955       in
956       let replaced = ref false in
957       let replace = ProofEngineReduction.replace_lifting
958        ~equality:(fun _ a b -> let rc = CicUtil.alpha_equivalence a b in 
959                   if rc then replaced := true; rc)
960        ~context:[]
961       in
962       let captured = 
963         replace ~what:[CicSubstitution.lift n_lambdas term] 
964           ~with_what:[Cic.Rel 1] ~where:lifted_ty
965       in
966       if not !replaced then
967         (* this means the matched term is not there, 
968          * but maybe right params are: we user rels (to right args lambdas) *)
969         replace ~what ~with_what:(with_what false) ~where:captured
970       else
971         (* since the matched is there, rights should be inferrable *)
972         replace ~what ~with_what:(with_what true) ~where:captured
973     in
974     let captured_term_ty = 
975       let term_ty = CicSubstitution.lift n_right_args termty in
976       let rec mkrels = function 0 -> []|n -> (Cic.Rel n)::(mkrels (n-1)) in
977       let rec fstn acc l n = 
978         if n = 0 then acc else fstn (acc@[List.hd l]) (List.tl l) (n-1) 
979       in
980       match term_ty with
981       | C.MutInd _ -> term_ty
982       | C.Appl ((C.MutInd (a,b,c))::args) -> 
983            C.Appl ((C.MutInd (a,b,c))::
984                fstn [] args paramsno @ mkrels n_right_args)
985       | _ -> raise NotAnInductiveTypeToEliminate
986     in
987     let rec add_lambdas = function
988       | 0 -> captured_ty
989       | 1 -> 
990           C.Lambda (C.Name "matched", captured_term_ty, (add_lambdas 0))
991       | n -> 
992            C.Lambda (C.Name ("right_"^(string_of_int (n-1))),
993                      C.Implicit None, (add_lambdas (n-1)))
994     in
995     add_lambdas n_lambdas
996   in
997   let term_to_refine = C.MutCase (uri,typeno,outtype,term,patterns) in
998   let refined_term,_,metasenv'',_ = 
999     CicRefine.type_of_aux' metasenv' context term_to_refine
1000       CicUniv.oblivion_ugraph
1001   in
1002   let new_goals =
1003     ProofEngineHelpers.compare_metasenvs
1004       ~oldmetasenv:metasenv ~newmetasenv:metasenv''
1005   in
1006   let proof' = curi,metasenv'',_subst,proofbo,proofty, attrs in
1007   let proof'', new_goals' =
1008     PET.apply_tactic (apply_tac ~term:refined_term) (proof',goal)
1009   in
1010   (* The apply_tactic can have closed some of the new_goals *)
1011   let patched_new_goals =
1012     let (_,metasenv''',_subst,_,_,_) = proof'' in
1013       List.filter
1014         (function i -> List.exists (function (j,_,_) -> j=i) metasenv''')
1015         new_goals @ new_goals'
1016     in
1017     proof'', patched_new_goals
1018   in
1019   PET.mk_tactic (cases_tac ~term)
1020 ;;
1021
1022
1023 let elim_intros_tac ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[]) 
1024                     ?depth ?using ?pattern what =
1025  Tacticals.then_ ~start:(elim_tac ?using ?pattern what)
1026   ~continuation:(intros_tac ~mk_fresh_name_callback ?howmany:depth ())
1027 ;;
1028
1029 (* The simplification is performed only on the conclusion *)
1030 let elim_intros_simpl_tac ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[])
1031                           ?depth ?using ?pattern what =
1032  Tacticals.then_ ~start:(elim_tac ?using ?pattern what)
1033   ~continuation:
1034    (Tacticals.thens
1035      ~start:(intros_tac ~mk_fresh_name_callback ?howmany:depth ())
1036      ~continuations:
1037        [ReductionTactics.simpl_tac
1038          ~pattern:(ProofEngineTypes.conclusion_pattern None)])
1039 ;;