]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/primitiveTactics.ml
experimental branch with no set baseuri command and no developments
[helm.git] / 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,t) ->
66          let (context',ty,bo) =
67           collect_context ((Some (n,(C.Def (s,None))))::context) (howmany - 1) do_whd t
68          in
69           (context',ty,C.LetIn(n,s,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,t) -> C.LetIn (nn, aux n s, 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.empty_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             | Some (n,Cic.Def (s,None)) ->
163                Some (n,Cic.Def ((subst_in canonical_context' s),None))
164             | None -> None
165             | Some (n,Cic.Def (bo,Some ty)) ->
166                Some
167                 (n,
168                   Cic.Def
169                    (subst_in canonical_context' bo,
170                     Some (subst_in canonical_context' ty)))
171           in
172            entry'::canonical_context'
173         ) canonical_context []
174      in
175       if i < newmeta then
176        ((i,canonical_context',ty')::old_uninst),new_uninst
177       else
178        old_uninst,((i,canonical_context',ty')::new_uninst)
179   ) metasenv ([],[])
180
181 (* Useful only inside apply_tac *)
182 let
183  generalize_exp_named_subst_with_fresh_metas context newmeta uri exp_named_subst
184 =
185  let module C = Cic in
186   let params =
187     let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
188     CicUtil.params_of_obj o
189   in
190    let exp_named_subst_diff,new_fresh_meta,newmetasenvfragment,exp_named_subst'=
191     let next_fresh_meta = ref newmeta in
192     let newmetasenvfragment = ref [] in
193     let exp_named_subst_diff = ref [] in
194      let rec aux =
195       function
196          [],[] -> []
197        | uri::tl,[] ->
198           let ty =
199             let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
200               match o with
201                   C.Variable (_,_,ty,_,_) ->
202                     CicSubstitution.subst_vars !exp_named_subst_diff ty
203                 | _ -> raise (WrongUriToVariable (UriManager.string_of_uri uri))
204           in
205 (* CSC: patch to generate ?1 : ?2 : Type in place of ?1 : Type to simulate ?1 :< Type
206            (match ty with
207                C.Sort (C.Type _) as s -> (* TASSI: ?? *)
208                  let fresh_meta = !next_fresh_meta in
209                  let fresh_meta' = fresh_meta + 1 in
210                   next_fresh_meta := !next_fresh_meta + 2 ;
211                   let subst_item = uri,C.Meta (fresh_meta',[]) in
212                    newmetasenvfragment :=
213                     (fresh_meta,[],C.Sort (C.Type (CicUniv.fresh()))) ::
214                      (* TASSI: ?? *)
215                      (fresh_meta',[],C.Meta (fresh_meta,[])) :: !newmetasenvfragment ;
216                    exp_named_subst_diff := !exp_named_subst_diff @ [subst_item] ;
217                    subst_item::(aux (tl,[]))
218              | _ ->
219 *)
220               let irl =
221                 CicMkImplicit.identity_relocation_list_for_metavariable context
222               in
223               let subst_item = uri,C.Meta (!next_fresh_meta,irl) in
224                newmetasenvfragment :=
225                 (!next_fresh_meta,context,ty)::!newmetasenvfragment ;
226                exp_named_subst_diff := !exp_named_subst_diff @ [subst_item] ;
227                incr next_fresh_meta ;
228                subst_item::(aux (tl,[]))(*)*)
229        | uri::tl1,((uri',_) as s)::tl2 ->
230           assert (UriManager.eq uri uri') ;
231           s::(aux (tl1,tl2))
232        | [],_ -> assert false
233      in
234       let exp_named_subst' = aux (params,exp_named_subst) in
235        !exp_named_subst_diff,!next_fresh_meta,
236         List.rev !newmetasenvfragment, exp_named_subst'
237    in
238     new_fresh_meta,newmetasenvfragment,exp_named_subst',exp_named_subst_diff
239 ;;
240
241 let new_metasenv_and_unify_and_t newmeta' metasenv' subst context term' ty termty goal_arity =
242   let (consthead,newmetasenv,arguments,_) =
243    TermUtil.saturate_term newmeta' metasenv' context termty
244     goal_arity in
245   let subst,newmetasenv',_ = 
246    CicUnification.fo_unif_subst 
247      subst context newmetasenv consthead ty CicUniv.empty_ugraph
248   in
249   let t = 
250     if List.length arguments = 0 then term' else Cic.Appl (term'::arguments)
251   in
252   subst,newmetasenv',t
253
254 let rec count_prods context ty =
255  match CicReduction.whd context ty with
256     Cic.Prod (n,s,t) -> 1 + count_prods (Some (n,Cic.Decl s)::context) t
257   | _ -> 0
258
259 let apply_with_subst ~term ~subst ~maxmeta (proof, goal) =
260   (* Assumption: The term "term" must be closed in the current context *)
261  let module T = CicTypeChecker in
262  let module R = CicReduction in
263  let module C = Cic in
264   let (_,metasenv,_subst,_,_, _) = proof in
265   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
266   let newmeta = max (CicMkImplicit.new_meta metasenv subst) maxmeta in
267    let exp_named_subst_diff,newmeta',newmetasenvfragment,term' =
268     match term with
269        C.Var (uri,exp_named_subst) ->
270         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
271          generalize_exp_named_subst_with_fresh_metas context newmeta uri
272           exp_named_subst
273         in
274          exp_named_subst_diff,newmeta',newmetasenvfragment,
275           C.Var (uri,exp_named_subst')
276      | C.Const (uri,exp_named_subst) ->
277         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
278          generalize_exp_named_subst_with_fresh_metas context newmeta uri
279           exp_named_subst
280         in
281          exp_named_subst_diff,newmeta',newmetasenvfragment,
282           C.Const (uri,exp_named_subst')
283      | C.MutInd (uri,tyno,exp_named_subst) ->
284         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
285          generalize_exp_named_subst_with_fresh_metas context newmeta uri
286           exp_named_subst
287         in
288          exp_named_subst_diff,newmeta',newmetasenvfragment,
289           C.MutInd (uri,tyno,exp_named_subst')
290      | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
291         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
292          generalize_exp_named_subst_with_fresh_metas context newmeta uri
293           exp_named_subst
294         in
295          exp_named_subst_diff,newmeta',newmetasenvfragment,
296           C.MutConstruct (uri,tyno,consno,exp_named_subst')
297      | _ -> [],newmeta,[],term
298    in
299    let metasenv' = metasenv@newmetasenvfragment in
300    let termty,_ = 
301      CicTypeChecker.type_of_aux' metasenv' context term' CicUniv.empty_ugraph
302    in
303    let termty =
304      CicSubstitution.subst_vars exp_named_subst_diff termty in
305    let goal_arity = count_prods context ty in
306    let subst,newmetasenv',t = 
307     let rec add_one_argument n =
308      try
309       new_metasenv_and_unify_and_t newmeta' metasenv' subst context term' ty
310         termty n
311      with CicUnification.UnificationFailure _ when n > 0 ->
312       add_one_argument (n - 1)
313     in
314      add_one_argument goal_arity
315    in
316    let in_subst_domain i = List.exists (function (j,_) -> i=j) subst in
317    let apply_subst = CicMetaSubst.apply_subst subst in
318    let old_uninstantiatedmetas,new_uninstantiatedmetas =
319      (* subst_in doesn't need the context. Hence the underscore. *)
320      let subst_in _ = CicMetaSubst.apply_subst subst in
321      classify_metas newmeta in_subst_domain subst_in newmetasenv'
322    in
323    let bo' = apply_subst t in
324    let newmetasenv'' = new_uninstantiatedmetas@old_uninstantiatedmetas in
325    let subst_in =
326      (* if we just apply the subtitution, the type is irrelevant:
327               we may use Implicit, since it will be dropped *)
328       ((metano,(context,bo',Cic.Implicit None))::subst)
329    in
330    let (newproof, newmetasenv''') = 
331     ProofEngineHelpers.subst_meta_and_metasenv_in_proof proof metano subst_in
332      newmetasenv''
333    in
334    let subst = ((metano,(context,bo',ty))::subst) in
335    subst,
336    (newproof, List.map (function (i,_,_) -> i) new_uninstantiatedmetas),
337    max maxmeta (CicMkImplicit.new_meta newmetasenv''' subst)
338
339
340 (* ALB *)
341 let apply_with_subst ~term ?(subst=[]) ?(maxmeta=0) status =
342   try
343 (*     apply_tac_verbose ~term status *)
344     apply_with_subst ~term ~subst ~maxmeta status
345       (* TODO cacciare anche altre eccezioni? *)
346   with 
347   | CicUnification.UnificationFailure msg
348   | CicTypeChecker.TypeCheckerFailure msg -> raise (PET.Fail msg)
349
350 (* ALB *)
351 let apply_tac_verbose ~term status =
352   let subst, status, _ = apply_with_subst ~term status in
353   (CicMetaSubst.apply_subst subst), status
354
355 let apply_tac ~term status = snd (apply_tac_verbose ~term status)
356
357   (* TODO per implementare i tatticali e' necessario che tutte le tattiche
358   sollevino _solamente_ Fail *)
359 let apply_tac ~term =
360  let apply_tac ~term status =
361   try
362     apply_tac ~term status
363       (* TODO cacciare anche altre eccezioni? *)
364   with 
365   | CicUnification.UnificationFailure msg
366   | CicTypeChecker.TypeCheckerFailure msg ->
367       raise (PET.Fail msg)
368  in
369   PET.mk_tactic (apply_tac ~term)
370
371 let intros_tac ?howmany ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[]) ()=
372  let intros_tac (proof, goal)
373  =
374   let module C = Cic in
375   let module R = CicReduction in
376    let (_,metasenv,_subst,_,_, _) = proof in
377    let metano,context,ty = CicUtil.lookup_meta goal metasenv in
378     let newmeta = ProofEngineHelpers.new_meta_of_proof ~proof in
379      let (context',ty',bo') =
380       lambda_abstract ?howmany metasenv context newmeta ty mk_fresh_name_callback
381      in
382       let (newproof, _) =
383        ProofEngineHelpers.subst_meta_in_proof proof metano bo'
384         [newmeta,context',ty']
385       in
386        (newproof, [newmeta])
387  in
388   PET.mk_tactic intros_tac
389   
390 let cut_tac ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[]) term =
391  let cut_tac
392   ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[])
393   term (proof, goal)
394  =
395   let module C = Cic in
396    let curi,metasenv,_subst,pbo,pty, attrs = proof in
397    let metano,context,ty = CicUtil.lookup_meta goal metasenv in
398     let newmeta1 = ProofEngineHelpers.new_meta_of_proof ~proof in
399     let newmeta2 = newmeta1 + 1 in
400     let fresh_name =
401      mk_fresh_name_callback metasenv context (Cic.Name "Hcut") ~typ:term in
402     let context_for_newmeta1 =
403      (Some (fresh_name,C.Decl term))::context in
404     let irl1 =
405      CicMkImplicit.identity_relocation_list_for_metavariable
406       context_for_newmeta1
407     in
408     let irl2 =
409       CicMkImplicit.identity_relocation_list_for_metavariable context
410     in
411      let newmeta1ty = CicSubstitution.lift 1 ty in
412 (* This is the pre-letin implementation
413      let bo' =
414       C.Appl
415        [C.Lambda (fresh_name,term,C.Meta (newmeta1,irl1)) ;
416         C.Meta (newmeta2,irl2)]
417      in
418 *)
419       let bo' = 
420         Cic.LetIn (fresh_name, C.Meta (newmeta2,irl2), C.Meta (newmeta1,irl1))
421       in
422       let (newproof, _) =
423        ProofEngineHelpers.subst_meta_in_proof proof metano bo'
424         [newmeta2,context,term; newmeta1,context_for_newmeta1,newmeta1ty];
425       in
426        (newproof, [newmeta1 ; newmeta2])
427  in
428   PET.mk_tactic (cut_tac ~mk_fresh_name_callback term)
429
430 let letin_tac ?(mk_fresh_name_callback=FreshNamesGenerator.mk_fresh_name ~subst:[]) term =
431  let letin_tac
432   ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[])
433   term (proof, goal)
434  =
435   let module C = Cic in
436    let curi,metasenv,_subst,pbo,pty, attrs = proof in
437    (* occur check *)
438    let occur i t =
439      let m = CicUtil.metas_of_term t in 
440      List.exists (fun (j,_) -> i=j) m
441    in
442    let metano,context,ty = CicUtil.lookup_meta goal metasenv in
443    if occur metano term then
444      raise 
445        (ProofEngineTypes.Fail (lazy
446          "You can't letin a term containing the current goal"));
447     let _,_ =
448       CicTypeChecker.type_of_aux' metasenv context term CicUniv.empty_ugraph in
449      let newmeta = ProofEngineHelpers.new_meta_of_proof ~proof in
450      let fresh_name =
451       mk_fresh_name_callback metasenv context (Cic.Name "Hletin") ~typ:term in
452      let context_for_newmeta =
453       (Some (fresh_name,C.Def (term,None)))::context in
454      let irl =
455       CicMkImplicit.identity_relocation_list_for_metavariable
456        context_for_newmeta
457      in
458       let newmetaty = CicSubstitution.lift 1 ty in
459       let bo' = C.LetIn (fresh_name,term,C.Meta (newmeta,irl)) in
460        let (newproof, _) =
461          ProofEngineHelpers.subst_meta_in_proof
462            proof metano bo'[newmeta,context_for_newmeta,newmetaty]
463        in
464         (newproof, [newmeta])
465  in
466   PET.mk_tactic (letin_tac ~mk_fresh_name_callback term)
467
468   (** functional part of the "exact" tactic *)
469 let exact_tac ~term =
470  let exact_tac ~term (proof, goal) =
471   (* Assumption: the term bo must be closed in the current context *)
472   let (_,metasenv,_subst,_,_, _) = proof in
473   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
474   let module T = CicTypeChecker in
475   let module R = CicReduction in
476   let ty_term,u = T.type_of_aux' metasenv context term CicUniv.empty_ugraph in
477   let b,_ = R.are_convertible context ty_term ty u in (* TASSI: FIXME *)
478   if b then
479    begin
480     let (newproof, metasenv') =
481       ProofEngineHelpers.subst_meta_in_proof proof metano term [] in
482     (newproof, [])
483    end
484   else
485    raise (PET.Fail (lazy "The type of the provided term is not the one expected."))
486  in
487   PET.mk_tactic (exact_tac ~term)
488
489 (* not really "primitive" tactics .... *)
490   
491 module TC  = CicTypeChecker
492 module UM  = UriManager
493 module R   = CicReduction
494 module C   = Cic
495 module PEH = ProofEngineHelpers
496 module PER = ProofEngineReduction
497 module MS  = CicMetaSubst 
498 module S   = CicSubstitution 
499 module T   = Tacticals
500 module RT  = ReductionTactics
501
502 let rec args_init n f =
503    if n <= 0 then [] else f n :: args_init (pred n) f
504
505 let mk_predicate_for_elim 
506  ~context ~metasenv ~ugraph ~goal ~arg ~using ~cpattern ~args_no = 
507    let instantiated_eliminator =
508       let f n = if n = 1 then arg else C.Implicit None in
509       C.Appl (using :: args_init args_no f)
510    in
511    let _actual_arg, iety, _metasenv', _ugraph = 
512       CicRefine.type_of_aux' metasenv context instantiated_eliminator ugraph
513    in
514    let _actual_meta, actual_args = match iety with
515       | C.Meta (i, _)                  -> i, []
516       | C.Appl (C.Meta (i, _) :: args) -> i, args
517       | _                              -> assert false
518    in
519 (* let _, upto = PEH.split_with_whd (List.nth splits pred_pos) in *)
520    let rec mk_pred metasenv context' pred arg' cpattern' = function
521       | []           -> metasenv, pred, arg'
522       | arg :: tail -> 
523 (* FG: we find the predicate for the eliminator as in the rewrite tactic ****)
524          let argty, _ugraph = TC.type_of_aux' metasenv context arg ugraph in
525          let argty = CicReduction.whd context argty in         
526                let fresh_name = 
527             FreshNamesGenerator.mk_fresh_name 
528             ~subst:[] metasenv context' C.Anonymous ~typ:argty
529          in
530          let hyp = Some (fresh_name, C.Decl argty) in
531          let lazy_term c m u =  
532             let distance  = List.length c - List.length context in
533             S.lift distance arg, m, u
534          in
535          let pattern = Some lazy_term, [], Some cpattern' in
536          let subst, metasenv, _ugraph, _conjecture, selected_terms =
537             ProofEngineHelpers.select
538             ~metasenv ~ugraph ~conjecture:(0, context, pred) ~pattern
539          in
540          let metasenv = MS.apply_subst_metasenv subst metasenv in  
541          let map (_context_of_t, t) l = t :: l in
542          let what = List.fold_right map selected_terms [] in
543          let arg' = MS.apply_subst subst arg' in
544          let argty = MS.apply_subst subst argty in
545          let pred = PER.replace_with_rel_1_from ~equality:(==) ~what 1 pred in
546          let pred = MS.apply_subst subst pred in
547          let pred = C.Lambda (fresh_name, argty, pred) in
548          let cpattern' = C.Lambda (C.Anonymous, C.Implicit None, cpattern') in
549          mk_pred metasenv (hyp :: context') pred arg' cpattern' tail 
550    in
551    let metasenv, pred, arg = 
552       mk_pred metasenv context goal arg cpattern (List.rev actual_args)
553    in
554    HLog.debug ("PREDICATE: " ^ CicPp.ppterm ~metasenv pred ^ " ARGS: " ^ String.concat " " (List.map (CicPp.ppterm ~metasenv) actual_args));
555    metasenv, pred, arg, actual_args
556
557 let beta_after_elim_tac upto predicate =
558    let beta_after_elim_tac status =
559       let proof, goal = status in
560       let _, metasenv, _subst, _, _, _ = proof in
561       let _, _, ty = CicUtil.lookup_meta goal metasenv in
562       let mk_pattern ~equality ~upto ~predicate ty =
563          (* code adapted from ProceduralConversion.generalize *)
564          let meta = C.Implicit None in
565          let hole = C.Implicit (Some `Hole) in
566          let anon = C.Anonymous in
567          let is_meta =
568             let map b = function
569                | C.Implicit None when b -> b
570                | _                      -> false
571             in
572             List.fold_left map true
573          in
574          let rec gen_fix len k (name, i, ty, bo) =
575             name, i, gen_term k ty, gen_term (k + len) bo
576          and gen_cofix len k (name, ty, bo) =
577             name, gen_term k ty, gen_term (k + len) bo
578          and gen_term k = function
579             | C.Sort _ 
580             | C.Implicit _
581             | C.Const (_, _)
582             | C.Var (_, _)
583             | C.MutInd (_, _, _)
584             | C.MutConstruct (_, _, _, _)
585             | C.Meta (_, _) 
586             | C.Rel _ -> meta
587             | C.Appl (hd :: tl) when equality hd (S.lift k predicate) ->
588                assert (List.length tl = upto);
589                hole
590             | C.Appl ts -> 
591                let ts = List.map (gen_term k) ts in
592                if is_meta ts then meta else C.Appl ts
593             | C.Cast (te, ty) -> 
594                let te, ty = gen_term k te, gen_term k ty in
595                if is_meta [te; ty] then meta else C.Cast (te, ty)
596             | C.MutCase (sp, i, outty, t, pl) ->         
597                let outty, t, pl = gen_term k outty, gen_term k t, List.map (gen_term k) pl in
598                if is_meta (outty :: t :: pl) then meta else hole (* C.MutCase (sp, i, outty, t, pl) *)
599             | C.Prod (_, s, t) -> 
600                let s, t = gen_term k s, gen_term (succ k) t in
601                if is_meta [s; t] then meta else C.Prod (anon, s, t)
602             | C.Lambda (_, s, t) ->
603                let s, t = gen_term k s, gen_term (succ k) t in
604                if is_meta [s; t] then meta else C.Lambda (anon, s, t)
605             | C.LetIn (_, s, t) -> 
606                let s, t = gen_term k s, gen_term (succ k) t in
607                if is_meta [s; t] then meta else C.LetIn (anon, s, t)
608             | C.Fix (i, fl) -> C.Fix (i, List.map (gen_fix (List.length fl) k) fl)
609             | C.CoFix (i, fl) -> C.CoFix (i, List.map (gen_cofix (List.length fl) k) fl)
610          in
611          None, [], Some (gen_term 0 ty)
612       in
613       let equality = CicUtil.alpha_equivalence in
614       let pattern = mk_pattern ~equality ~upto ~predicate ty in
615       let tactic = RT.head_beta_reduce_tac ~delta:false ~upto ~pattern in
616       PET.apply_tactic tactic status
617    in
618    PET.mk_tactic beta_after_elim_tac
619    
620 let elim_tac ?using ?(pattern = PET.conclusion_pattern None) term = 
621  let elim_tac (proof, goal) =
622    let cpattern = match pattern with 
623       | None, [], Some cpattern -> cpattern
624       | _                       -> raise (PET.Fail (lazy "not implemented"))
625    in    
626    let ugraph = CicUniv.empty_ugraph in
627    let curi, metasenv, _subst, proofbo, proofty, attrs = proof in
628    let conjecture = CicUtil.lookup_meta goal metasenv in
629    let metano, context, ty = conjecture in 
630     let termty,_ugraph = TC.type_of_aux' metasenv context term ugraph in
631     let termty = CicReduction.whd context termty in
632     let termty, metasenv', arguments, _fresh_meta =
633      TermUtil.saturate_term
634       (ProofEngineHelpers.new_meta_of_proof proof) metasenv context termty 0 in
635     let term = if arguments = [] then term else Cic.Appl (term::arguments) in
636     let uri, exp_named_subst, typeno, _args =
637      match termty with
638         C.MutInd (uri,typeno,exp_named_subst) -> (uri,exp_named_subst,typeno,[])
639       | C.Appl ((C.MutInd (uri,typeno,exp_named_subst))::args) ->
640           (uri,exp_named_subst,typeno,args)
641       | _ -> raise NotAnInductiveTypeToEliminate
642     in
643      let eliminator_uri =
644       let buri = UM.buri_of_uri uri in
645       let name = 
646         let o,_ugraph = CicEnvironment.get_obj ugraph uri in
647        match o with
648           C.InductiveDefinition (tys,_,_,_) ->
649            let (name,_,_,_) = List.nth tys typeno in
650             name
651         | _ -> assert false
652       in
653       let ty_ty,_ugraph = TC.type_of_aux' metasenv' context ty ugraph in
654       let ext =
655        match ty_ty with
656           C.Sort C.Prop -> "_ind"
657         | C.Sort C.Set  -> "_rec"
658         | C.Sort C.CProp -> "_rec"
659         | C.Sort (C.Type _)-> "_rect" 
660         | C.Meta (_,_) -> raise TheTypeOfTheCurrentGoalIsAMetaICannotChooseTheRightElimiantionPrinciple
661         | _ -> assert false
662       in
663        UM.uri_of_string (buri ^ "/" ^ name ^ ext ^ ".con")
664      in
665       let eliminator_ref = match using with
666          | None   -> C.Const (eliminator_uri, exp_named_subst)
667          | Some t -> t 
668        in
669        let ety, _ugraph = 
670          TC.type_of_aux' metasenv' context eliminator_ref ugraph in
671 (* FG: ADDED PART ***********************************************************)
672 (* FG: we can not assume eliminator is the default eliminator ***************)
673    let splits, args_no = PEH.split_with_whd (context, ety) in
674    let pred_pos = match List.hd splits with
675       | _, C.Rel i when i > 1 && i <= args_no -> i
676       | _, C.Appl (C.Rel i :: _) when i > 1 && i <= args_no -> i
677       | _ -> raise NotAnEliminator
678    in
679    let metasenv', pred, term, actual_args = match pattern with 
680       | None, [], Some (C.Implicit (Some `Hole)) ->
681          metasenv', C.Implicit None, term, []
682       | _                                        ->
683          mk_predicate_for_elim 
684             ~args_no ~context ~ugraph ~cpattern
685             ~metasenv:metasenv' ~arg:term ~using:eliminator_ref ~goal:ty
686    in
687 (* FG: END OF ADDED PART ****************************************************)
688       let term_to_refine =
689          let f n =
690             if n = pred_pos then pred else
691             if n = 1 then term else C.Implicit None
692          in
693          C.Appl (eliminator_ref :: args_init args_no f)
694       in
695       let refined_term,_refined_termty,metasenv'',_ugraph = 
696          CicRefine.type_of_aux' metasenv' context term_to_refine ugraph
697       in
698       let new_goals =
699          ProofEngineHelpers.compare_metasenvs
700             ~oldmetasenv:metasenv ~newmetasenv:metasenv''
701       in
702       let proof' = curi,metasenv'',_subst,proofbo,proofty, attrs in
703       let proof'', new_goals' =
704          PET.apply_tactic (apply_tac ~term:refined_term) (proof',goal)
705       in
706       (* The apply_tactic can have closed some of the new_goals *)
707       let patched_new_goals =
708          let (_,metasenv''',_subst,_,_, _) = proof'' in
709          List.filter
710             (function i -> List.exists (function (j,_,_) -> j=i) metasenv''')
711             new_goals @ new_goals'
712       in
713       let res = proof'', patched_new_goals in
714       let upto = List.length actual_args in
715       if upto = 0 then res else 
716       let continuation = beta_after_elim_tac upto pred in
717       let dummy_status = proof,goal in
718       PET.apply_tactic
719          (T.then_ ~start:(PET.mk_tactic (fun _ -> res)) ~continuation)
720          dummy_status
721    in
722    PET.mk_tactic elim_tac
723 ;;
724
725 let cases_intros_tac ?(howmany=(-1)) ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[]) term =
726  let cases_tac ~term (proof, goal) =
727   let module TC = CicTypeChecker in
728   let module U = UriManager in
729   let module R = CicReduction in
730   let module C = Cic in
731   let (curi,metasenv,_subst, proofbo,proofty, attrs) = proof in
732   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
733   let termty,_ = TC.type_of_aux' metasenv context term CicUniv.empty_ugraph in
734   let termty = CicReduction.whd context termty in
735   let (termty,metasenv',arguments,fresh_meta) =
736    TermUtil.saturate_term
737     (ProofEngineHelpers.new_meta_of_proof proof) metasenv context termty 0 in
738   let term = if arguments = [] then term else Cic.Appl (term::arguments) in
739   let uri,exp_named_subst,typeno,args =
740     match termty with
741     | C.MutInd (uri,typeno,exp_named_subst) -> (uri,exp_named_subst,typeno,[])
742     | C.Appl ((C.MutInd (uri,typeno,exp_named_subst))::args) ->
743         (uri,exp_named_subst,typeno,args)
744     | _ -> raise NotAnInductiveTypeToEliminate
745   in
746   let paramsno,itty,patterns,right_args =
747     match CicEnvironment.get_obj CicUniv.empty_ugraph uri with
748     | C.InductiveDefinition (tys,_,paramsno,_),_ ->
749        let _,left_parameters,right_args = 
750          List.fold_right 
751            (fun x (n,acc1,acc2) -> 
752              if n > 0 then (n-1,acc1,x::acc2) else (n,x::acc1,acc2)) 
753            args (List.length args - paramsno, [],[])
754        in
755        let _,_,itty,cl = List.nth tys typeno in
756        let rec aux left_parameters context t =
757          match left_parameters,CicReduction.whd context t with
758          | [],C.Prod (name,source,target) ->
759             let fresh_name =
760               mk_fresh_name_callback metasenv' context name ~typ:source
761             in
762              C.Lambda (fresh_name,C.Implicit None,
763              aux [] (Some (fresh_name,C.Decl source)::context) target)
764          | hd::tl,C.Prod (name,source,target) ->
765              (* left parameters instantiation *)
766              aux tl context (CicSubstitution.subst hd target)
767          | [],_ -> C.Implicit None
768          | _ -> assert false
769        in
770         paramsno,itty,
771         List.map (function (_,cty) -> aux left_parameters context cty) cl,
772         right_args
773     | _ -> assert false
774   in
775   let outtype =
776     let n_right_args = List.length right_args in
777     let n_lambdas = n_right_args + 1 in
778     let lifted_ty = CicSubstitution.lift n_lambdas ty in
779     let captured_ty = 
780       let what = 
781         List.map (CicSubstitution.lift n_lambdas) (right_args)
782       in
783       let with_what meta = 
784         let rec mkargs = function 
785           | 0 -> assert false
786           | 1 -> []
787           | n -> 
788               (if meta then Cic.Implicit None else Cic.Rel n)::(mkargs (n-1)) 
789         in
790         mkargs n_lambdas 
791       in
792       let replaced = ref false in
793       let replace = ProofEngineReduction.replace_lifting
794        ~equality:(fun _ a b -> let rc = CicUtil.alpha_equivalence a b in 
795                   if rc then replaced := true; rc)
796        ~context:[]
797       in
798       let captured = 
799         replace ~what:[CicSubstitution.lift n_lambdas term] 
800           ~with_what:[Cic.Rel 1] ~where:lifted_ty
801       in
802       if not !replaced then
803         (* this means the matched term is not there, 
804          * but maybe right params are: we user rels (to right args lambdas) *)
805         replace ~what ~with_what:(with_what false) ~where:captured
806       else
807         (* since the matched is there, rights should be inferrable *)
808         replace ~what ~with_what:(with_what true) ~where:captured
809     in
810     let captured_term_ty = 
811       let term_ty = CicSubstitution.lift n_right_args termty in
812       let rec mkrels = function 0 -> []|n -> (Cic.Rel n)::(mkrels (n-1)) in
813       let rec fstn acc l n = 
814         if n = 0 then acc else fstn (acc@[List.hd l]) (List.tl l) (n-1) 
815       in
816       match term_ty with
817       | C.MutInd _ -> term_ty
818       | C.Appl ((C.MutInd (a,b,c))::args) -> 
819            C.Appl ((C.MutInd (a,b,c))::
820                fstn [] args paramsno @ mkrels n_right_args)
821       | _ -> raise NotAnInductiveTypeToEliminate
822     in
823     let rec add_lambdas = function
824       | 0 -> captured_ty
825       | 1 -> 
826           C.Lambda (C.Name "matched", captured_term_ty, (add_lambdas 0))
827       | n -> 
828            C.Lambda (C.Name ("right_"^(string_of_int (n-1))),
829                      C.Implicit None, (add_lambdas (n-1)))
830     in
831     add_lambdas n_lambdas
832   in
833   let term_to_refine = C.MutCase (uri,typeno,outtype,term,patterns) in
834   let refined_term,_,metasenv'',_ = 
835     CicRefine.type_of_aux' metasenv' context term_to_refine
836       CicUniv.empty_ugraph
837   in
838   let new_goals =
839     ProofEngineHelpers.compare_metasenvs
840       ~oldmetasenv:metasenv ~newmetasenv:metasenv''
841   in
842   let proof' = curi,metasenv'',_subst,proofbo,proofty, attrs in
843   let proof'', new_goals' =
844     PET.apply_tactic (apply_tac ~term:refined_term) (proof',goal)
845   in
846   (* The apply_tactic can have closed some of the new_goals *)
847   let patched_new_goals =
848     let (_,metasenv''',_subst,_,_,_) = proof'' in
849       List.filter
850         (function i -> List.exists (function (j,_,_) -> j=i) metasenv''')
851         new_goals @ new_goals'
852     in
853     proof'', patched_new_goals
854   in
855   PET.mk_tactic (cases_tac ~term)
856 ;;
857
858
859 let elim_intros_tac ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[]) 
860                     ?depth ?using ?pattern what =
861  Tacticals.then_ ~start:(elim_tac ?using ?pattern what)
862   ~continuation:(intros_tac ~mk_fresh_name_callback ?howmany:depth ())
863 ;;
864
865 (* The simplification is performed only on the conclusion *)
866 let elim_intros_simpl_tac ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[])
867                           ?depth ?using ?pattern what =
868  Tacticals.then_ ~start:(elim_tac ?using ?pattern what)
869   ~continuation:
870    (Tacticals.thens
871      ~start:(intros_tac ~mk_fresh_name_callback ?howmany:depth ())
872      ~continuations:
873        [ReductionTactics.simpl_tac
874          ~pattern:(ProofEngineTypes.conclusion_pattern None)])
875 ;;
876
877 (* FG: insetrts a "hole" in the context (derived from letin_tac) *)
878
879 let letout_tac =
880    let mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[] in
881    let term = C.Sort C.Set in
882    let letout_tac (proof, goal) =
883       let curi, metasenv, _subst, pbo, pty, attrs = proof in
884       let metano, context, ty = CicUtil.lookup_meta goal metasenv in
885       let newmeta = ProofEngineHelpers.new_meta_of_proof ~proof in
886       let fresh_name = mk_fresh_name_callback metasenv context (Cic.Name "hole") ~typ:term in
887       let context_for_newmeta = None :: context in
888       let irl = CicMkImplicit.identity_relocation_list_for_metavariable context_for_newmeta in
889       let newmetaty = CicSubstitution.lift 1 ty in
890       let bo' = C.LetIn (fresh_name, term, C.Meta (newmeta,irl)) in
891       let newproof, _ = ProofEngineHelpers.subst_meta_in_proof proof metano bo'[newmeta,context_for_newmeta,newmetaty] in
892       newproof, [newmeta]
893    in
894    PET.mk_tactic letout_tac