]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/tactics/primitiveTactics.ml
Oooops. I forgot the convertibility test that makes the change tactic correct!
[helm.git] / helm / ocaml / 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 open ProofEngineHelpers
27 open ProofEngineTypes
28
29 exception TheTypeOfTheCurrentGoalIsAMetaICannotChooseTheRightElimiantionPrinciple
30 exception NotAnInductiveTypeToEliminate
31 exception WrongUriToVariable of string
32
33 (* lambda_abstract newmeta ty *)
34 (* returns a triple [bo],[context],[ty'] where              *)
35 (* [ty] = Pi/LetIn [context].[ty'] ([context] is a vector!) *)
36 (* and [bo] = Lambda/LetIn [context].(Meta [newmeta])       *)
37 (* So, lambda_abstract is the core of the implementation of *)
38 (* the Intros tactic.                                       *)
39 (* howmany = -1 means Intros, howmany > 0 means Intros n    *)
40 let lambda_abstract ?(howmany=(-1)) metasenv context newmeta ty mk_fresh_name =
41  let module C = Cic in
42   let rec collect_context context howmany ty =
43    match howmany with
44    | 0 ->  
45         let irl =
46           CicMkImplicit.identity_relocation_list_for_metavariable context
47         in
48          context, ty, (C.Meta (newmeta,irl))
49    | _ -> 
50       match ty with 
51         C.Cast (te,_)   -> collect_context context howmany te 
52       | C.Prod (n,s,t)  ->
53          let n' = mk_fresh_name metasenv context n ~typ:s in
54           let (context',ty,bo) =
55            collect_context ((Some (n',(C.Decl s)))::context) (howmany - 1) t 
56           in
57            (context',ty,C.Lambda(n',s,bo))
58       | C.LetIn (n,s,t) ->
59          let (context',ty,bo) =
60           collect_context ((Some (n,(C.Def (s,None))))::context) (howmany - 1) t
61          in
62           (context',ty,C.LetIn(n,s,bo))
63       | _ as t ->
64         let irl =
65           CicMkImplicit.identity_relocation_list_for_metavariable context
66         in
67          context, t, (C.Meta (newmeta,irl))
68   in
69    collect_context context howmany ty 
70
71 let eta_expand metasenv context t arg =
72  let module T = CicTypeChecker in
73  let module S = CicSubstitution in
74  let module C = Cic in
75   let rec aux n =
76    function
77       t' when t' = S.lift n arg -> C.Rel (1 + n)
78     | C.Rel m  -> if m <= n then C.Rel m else C.Rel (m+1)
79     | C.Var (uri,exp_named_subst) ->
80        let exp_named_subst' = aux_exp_named_subst n exp_named_subst in
81         C.Var (uri,exp_named_subst')
82     | C.Meta (i,l) ->
83        let l' =
84         List.map (function None -> None | Some t -> Some (aux n t)) l
85        in
86         C.Meta (i, l')
87     | C.Sort _
88     | C.Implicit _ as t -> t
89     | C.Cast (te,ty) -> C.Cast (aux n te, aux n ty)
90     | C.Prod (nn,s,t) -> C.Prod (nn, aux n s, aux (n+1) t)
91     | C.Lambda (nn,s,t) -> C.Lambda (nn, aux n s, aux (n+1) t)
92     | C.LetIn (nn,s,t) -> C.LetIn (nn, aux n s, aux (n+1) t)
93     | C.Appl l -> C.Appl (List.map (aux n) l)
94     | C.Const (uri,exp_named_subst) ->
95        let exp_named_subst' = aux_exp_named_subst n exp_named_subst in
96         C.Const (uri,exp_named_subst')
97     | C.MutInd (uri,i,exp_named_subst) ->
98        let exp_named_subst' = aux_exp_named_subst n exp_named_subst in
99         C.MutInd (uri,i,exp_named_subst')
100     | C.MutConstruct (uri,i,j,exp_named_subst) ->
101        let exp_named_subst' = aux_exp_named_subst n exp_named_subst in
102         C.MutConstruct (uri,i,j,exp_named_subst')
103     | C.MutCase (sp,i,outt,t,pl) ->
104        C.MutCase (sp,i,aux n outt, aux n t,
105         List.map (aux n) pl)
106     | C.Fix (i,fl) ->
107        let tylen = List.length fl in
108         let substitutedfl =
109          List.map
110           (fun (name,i,ty,bo) -> (name, i, aux n ty, aux (n+tylen) bo))
111            fl
112         in
113          C.Fix (i, substitutedfl)
114     | C.CoFix (i,fl) ->
115        let tylen = List.length fl in
116         let substitutedfl =
117          List.map
118           (fun (name,ty,bo) -> (name, aux n ty, aux (n+tylen) bo))
119            fl
120         in
121          C.CoFix (i, substitutedfl)
122   and aux_exp_named_subst n =
123    List.map (function uri,t -> uri,aux n t)
124   in
125    let argty,_ = 
126     T.type_of_aux' metasenv context arg CicUniv.empty_ugraph (* TASSI: FIXME *)
127    in
128     let fresh_name =
129      FreshNamesGenerator.mk_fresh_name ~subst:[]
130       metasenv context (Cic.Name "Heta") ~typ:argty
131     in
132      (C.Appl [C.Lambda (fresh_name,argty,aux 0 t) ; arg])
133
134 (*CSC: ma serve solamente la prima delle new_uninst e l'unione delle due!!! *)
135 let classify_metas newmeta in_subst_domain subst_in metasenv =
136  List.fold_right
137   (fun (i,canonical_context,ty) (old_uninst,new_uninst) ->
138     if in_subst_domain i then
139      old_uninst,new_uninst
140     else
141      let ty' = subst_in canonical_context ty in
142       let canonical_context' =
143        List.fold_right
144         (fun entry canonical_context' ->
145           let entry' =
146            match entry with
147               Some (n,Cic.Decl s) ->
148                Some (n,Cic.Decl (subst_in canonical_context' s))
149             | Some (n,Cic.Def (s,None)) ->
150                Some (n,Cic.Def ((subst_in canonical_context' s),None))
151             | None -> None
152             | Some (_,Cic.Def (_,Some _)) -> assert false
153           in
154            entry'::canonical_context'
155         ) canonical_context []
156      in
157       if i < newmeta then
158        ((i,canonical_context',ty')::old_uninst),new_uninst
159       else
160        old_uninst,((i,canonical_context',ty')::new_uninst)
161   ) metasenv ([],[])
162
163 (* Auxiliary function for apply: given a type (a backbone), it returns its   *)
164 (* head, a META environment in which there is new a META for each hypothesis,*)
165 (* a list of arguments for the new applications and the indexes of the first *)
166 (* and last new METAs introduced. The nth argument in the list of arguments  *)
167 (* is just the nth new META.                                                 *)
168 let new_metasenv_for_apply newmeta proof context ty =
169  let module C = Cic in
170  let module S = CicSubstitution in
171   let rec aux newmeta ty =
172    let ty' = ty in
173    match ty' with
174       C.Cast (he,_) -> aux newmeta he
175 (* CSC: patch to generate ?1 : ?2 : Type in place of ?1 : Type to simulate ?1 :< Type
176       (* If the expected type is a Type, then also Set is OK ==>
177       *  we accept any term of type Type *)
178       (*CSC: BUG HERE: in this way it is possible for the term of
179       * type Type to be different from a Sort!!! *)
180     | C.Prod (name,(C.Sort (C.Type _) as s),t) ->
181        (* TASSI: ask CSC if BUG HERE refers to the C.Cast or C.Propd case *)
182        let irl =
183          CicMkImplicit.identity_relocation_list_for_metavariable context
184        in
185         let newargument = C.Meta (newmeta+1,irl) in
186          let (res,newmetasenv,arguments,lastmeta) =
187           aux (newmeta + 2) (S.subst newargument t)
188          in
189           res,
190            (newmeta,[],s)::(newmeta+1,context,C.Meta (newmeta,[]))::newmetasenv,
191            newargument::arguments,lastmeta
192 *)
193     | C.Prod (name,s,t) ->
194        let irl =
195          CicMkImplicit.identity_relocation_list_for_metavariable context
196        in
197         let newargument = C.Meta (newmeta,irl) in
198          let (res,newmetasenv,arguments,lastmeta) =
199           aux (newmeta + 1) (S.subst newargument t)
200          in
201          let s' = CicReduction.normalize ~delta:false context s in
202           res,(newmeta,context,s')::newmetasenv,newargument::arguments,lastmeta
203           (** NORMALIZE RATIONALE 
204            * we normalize the target only NOW since we may be in this case:
205            * A1 -> A2 -> T where T = (\lambda x.A3 -> P) k  
206            * and we want a mesasenv with ?1:A1 and ?2:A2 and not
207            * ?1, ?2, ?3 (that is the one we whould get if we start from the
208            * beta-normalized A1 -> A2 -> A3 -> P **)
209     | t -> (CicReduction.normalize ~delta:false context t),[],[],newmeta
210   in
211    (* WARNING: here we are using the invariant that above the most *)
212    (* recente new_meta() there are no used metas.                  *)
213    let (res,newmetasenv,arguments,lastmeta) = aux newmeta ty in
214     res,newmetasenv,arguments,lastmeta
215
216 (* Useful only inside apply_tac *)
217 let
218  generalize_exp_named_subst_with_fresh_metas context newmeta uri exp_named_subst
219 =
220  let module C = Cic in
221   let params =
222     let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
223     CicUtil.params_of_obj o
224   in
225    let exp_named_subst_diff,new_fresh_meta,newmetasenvfragment,exp_named_subst'=
226     let next_fresh_meta = ref newmeta in
227     let newmetasenvfragment = ref [] in
228     let exp_named_subst_diff = ref [] in
229      let rec aux =
230       function
231          [],[] -> []
232        | uri::tl,[] ->
233           let ty =
234             let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
235               match o with
236                   C.Variable (_,_,ty,_,_) ->
237                     CicSubstitution.subst_vars !exp_named_subst_diff ty
238                 | _ -> raise (WrongUriToVariable (UriManager.string_of_uri uri))
239           in
240 (* CSC: patch to generate ?1 : ?2 : Type in place of ?1 : Type to simulate ?1 :< Type
241            (match ty with
242                C.Sort (C.Type _) as s -> (* TASSI: ?? *)
243                  let fresh_meta = !next_fresh_meta in
244                  let fresh_meta' = fresh_meta + 1 in
245                   next_fresh_meta := !next_fresh_meta + 2 ;
246                   let subst_item = uri,C.Meta (fresh_meta',[]) in
247                    newmetasenvfragment :=
248                     (fresh_meta,[],C.Sort (C.Type (CicUniv.fresh()))) ::
249                      (* TASSI: ?? *)
250                      (fresh_meta',[],C.Meta (fresh_meta,[])) :: !newmetasenvfragment ;
251                    exp_named_subst_diff := !exp_named_subst_diff @ [subst_item] ;
252                    subst_item::(aux (tl,[]))
253              | _ ->
254 *)
255               let irl =
256                 CicMkImplicit.identity_relocation_list_for_metavariable context
257               in
258               let subst_item = uri,C.Meta (!next_fresh_meta,irl) in
259                newmetasenvfragment :=
260                 (!next_fresh_meta,context,ty)::!newmetasenvfragment ;
261                exp_named_subst_diff := !exp_named_subst_diff @ [subst_item] ;
262                incr next_fresh_meta ;
263                subst_item::(aux (tl,[]))(*)*)
264        | uri::tl1,((uri',_) as s)::tl2 ->
265           assert (UriManager.eq uri uri') ;
266           s::(aux (tl1,tl2))
267        | [],_ -> assert false
268      in
269       let exp_named_subst' = aux (params,exp_named_subst) in
270        !exp_named_subst_diff,!next_fresh_meta,
271         List.rev !newmetasenvfragment, exp_named_subst'
272    in
273     new_fresh_meta,newmetasenvfragment,exp_named_subst',exp_named_subst_diff
274 ;;
275
276 let new_metasenv_and_unify_and_t newmeta' metasenv' proof context term' ty termty =
277   let (consthead,newmetas,arguments,_) =
278     new_metasenv_for_apply newmeta' proof context termty
279   in
280   let newmetasenv = metasenv'@newmetas in
281   let subst,newmetasenv',_ = 
282     CicUnification.fo_unif newmetasenv context consthead ty CicUniv.empty_ugraph
283   in
284   let t = 
285     if List.length newmetas = 0 then term' else Cic.Appl (term'::arguments)
286   in
287   subst,newmetasenv',t
288
289 let apply_tac_verbose ~term (proof, goal) =
290   (* Assumption: The term "term" must be closed in the current context *)
291  let module T = CicTypeChecker in
292  let module R = CicReduction in
293  let module C = Cic in
294   let (_,metasenv,_,_) = proof in
295   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
296   let newmeta = new_meta_of_proof ~proof in
297    let exp_named_subst_diff,newmeta',newmetasenvfragment,term' =
298     match term with
299        C.Var (uri,exp_named_subst) ->
300         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
301          generalize_exp_named_subst_with_fresh_metas context newmeta uri
302           exp_named_subst
303         in
304          exp_named_subst_diff,newmeta',newmetasenvfragment,
305           C.Var (uri,exp_named_subst')
306      | C.Const (uri,exp_named_subst) ->
307         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
308          generalize_exp_named_subst_with_fresh_metas context newmeta uri
309           exp_named_subst
310         in
311          exp_named_subst_diff,newmeta',newmetasenvfragment,
312           C.Const (uri,exp_named_subst')
313      | C.MutInd (uri,tyno,exp_named_subst) ->
314         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
315          generalize_exp_named_subst_with_fresh_metas context newmeta uri
316           exp_named_subst
317         in
318          exp_named_subst_diff,newmeta',newmetasenvfragment,
319           C.MutInd (uri,tyno,exp_named_subst')
320      | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
321         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
322          generalize_exp_named_subst_with_fresh_metas context newmeta uri
323           exp_named_subst
324         in
325          exp_named_subst_diff,newmeta',newmetasenvfragment,
326           C.MutConstruct (uri,tyno,consno,exp_named_subst')
327      | _ -> [],newmeta,[],term
328    in
329    let metasenv' = metasenv@newmetasenvfragment in
330    let termty,_ = 
331      CicTypeChecker.type_of_aux' metasenv' context term' CicUniv.empty_ugraph in
332    let termty =
333      CicSubstitution.subst_vars exp_named_subst_diff termty
334    in
335    let subst,newmetasenv',t = 
336      try
337        new_metasenv_and_unify_and_t newmeta' metasenv' proof context term' ty
338          termty
339      with CicUnification.UnificationFailure _ -> 
340        new_metasenv_and_unify_and_t newmeta' metasenv' proof context term' ty
341          (CicReduction.whd context termty)
342    in
343    let in_subst_domain i = List.exists (function (j,_) -> i=j) subst in
344    let apply_subst = CicMetaSubst.apply_subst subst in
345    let old_uninstantiatedmetas,new_uninstantiatedmetas =
346      (* subst_in doesn't need the context. Hence the underscore. *)
347      let subst_in _ = CicMetaSubst.apply_subst subst in
348      classify_metas newmeta in_subst_domain subst_in newmetasenv'
349    in
350    let bo' = apply_subst t in
351    let newmetasenv'' = new_uninstantiatedmetas@old_uninstantiatedmetas in
352 (*    prerr_endline ("me: " ^ CicMetaSubst.ppmetasenv newmetasenv'' subst); *)
353    let subst_in =
354      (* if we just apply the subtitution, the type is irrelevant:
355               we may use Implicit, since it will be dropped *)
356      CicMetaSubst.apply_subst ((metano,(context,bo',Cic.Implicit None))::subst)
357    in
358    let (newproof, newmetasenv''') = 
359      subst_meta_and_metasenv_in_proof proof metano subst_in newmetasenv''
360    in
361      (subst_in,
362        (newproof, 
363           List.map (function (i,_,_) -> i) new_uninstantiatedmetas))
364
365 let apply_tac ~term status = snd (apply_tac_verbose ~term status)
366
367 let apply_tac_verbose ~term status =
368   try
369     apply_tac_verbose ~term status
370       (* TODO cacciare anche altre eccezioni? *)
371   with CicUnification.UnificationFailure _ as e ->
372     raise (Fail (Printexc.to_string e))
373
374   (* TODO per implementare i tatticali e' necessario che tutte le tattiche
375   sollevino _solamente_ Fail *)
376 let apply_tac ~term =
377  let apply_tac ~term status =
378   try
379     apply_tac ~term status
380       (* TODO cacciare anche altre eccezioni? *)
381   with CicUnification.UnificationFailure _ as e ->
382     raise (Fail (Printexc.to_string e))
383  in
384   mk_tactic (apply_tac ~term)
385
386 let intros_tac ?howmany ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[]) ()=
387  let intros_tac
388   ?(mk_fresh_name_callback = (FreshNamesGenerator.mk_fresh_name ~subst:[])) ()
389   (proof, goal)
390  =
391   let module C = Cic in
392   let module R = CicReduction in
393    let (_,metasenv,_,_) = proof in
394    let metano,context,ty = CicUtil.lookup_meta goal metasenv in
395     let newmeta = new_meta_of_proof ~proof in
396      let (context',ty',bo') =
397       lambda_abstract ?howmany metasenv context newmeta ty mk_fresh_name_callback
398      in
399       let (newproof, _) =
400         subst_meta_in_proof proof metano bo' [newmeta,context',ty']
401       in
402        (newproof, [newmeta])
403  in
404   mk_tactic (intros_tac ~mk_fresh_name_callback ())
405   
406 let cut_tac ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[]) term =
407  let cut_tac
408   ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[])
409   term (proof, goal)
410  =
411   let module C = Cic in
412    let curi,metasenv,pbo,pty = proof in
413    let metano,context,ty = CicUtil.lookup_meta goal metasenv in
414     let newmeta1 = new_meta_of_proof ~proof in
415     let newmeta2 = newmeta1 + 1 in
416     let fresh_name =
417      mk_fresh_name_callback metasenv context (Cic.Name "Hcut") ~typ:term in
418     let context_for_newmeta1 =
419      (Some (fresh_name,C.Decl term))::context in
420     let irl1 =
421      CicMkImplicit.identity_relocation_list_for_metavariable
422       context_for_newmeta1
423     in
424     let irl2 =
425       CicMkImplicit.identity_relocation_list_for_metavariable context
426     in
427      let newmeta1ty = CicSubstitution.lift 1 ty in
428      let bo' =
429       C.Appl
430        [C.Lambda (fresh_name,term,C.Meta (newmeta1,irl1)) ;
431         C.Meta (newmeta2,irl2)]
432      in
433       let (newproof, _) =
434        subst_meta_in_proof proof metano bo'
435         [newmeta2,context,term; newmeta1,context_for_newmeta1,newmeta1ty];
436       in
437        (newproof, [newmeta1 ; newmeta2])
438  in
439   mk_tactic (cut_tac ~mk_fresh_name_callback term)
440
441 let letin_tac ?(mk_fresh_name_callback=FreshNamesGenerator.mk_fresh_name ~subst:[]) term =
442  let letin_tac
443   ?(mk_fresh_name_callback = FreshNamesGenerator.mk_fresh_name ~subst:[])
444   term (proof, goal)
445  =
446   let module C = Cic in
447    let curi,metasenv,pbo,pty = proof in
448    let metano,context,ty = CicUtil.lookup_meta goal metasenv in
449     let _,_ = (* TASSI: FIXME *)
450       CicTypeChecker.type_of_aux' metasenv context term CicUniv.empty_ugraph in
451      let newmeta = new_meta_of_proof ~proof in
452      let fresh_name =
453       mk_fresh_name_callback metasenv context (Cic.Name "Hletin") ~typ:term in
454      let context_for_newmeta =
455       (Some (fresh_name,C.Def (term,None)))::context in
456      let irl =
457       CicMkImplicit.identity_relocation_list_for_metavariable
458        context_for_newmeta
459      in
460       let newmetaty = CicSubstitution.lift 1 ty in
461       let bo' = C.LetIn (fresh_name,term,C.Meta (newmeta,irl)) in
462        let (newproof, _) =
463          subst_meta_in_proof
464            proof metano bo'[newmeta,context_for_newmeta,newmetaty]
465        in
466         (newproof, [newmeta])
467  in
468   mk_tactic (letin_tac ~mk_fresh_name_callback term)
469
470   (** functional part of the "exact" tactic *)
471 let exact_tac ~term =
472  let exact_tac ~term (proof, goal) =
473   (* Assumption: the term bo must be closed in the current context *)
474   let (_,metasenv,_,_) = proof in
475   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
476   let module T = CicTypeChecker in
477   let module R = CicReduction in
478   let ty_term,u = T.type_of_aux' metasenv context term CicUniv.empty_ugraph in
479   let b,_ = R.are_convertible context ty_term ty u in (* TASSI: FIXME *)
480   if b then
481    begin
482     let (newproof, metasenv') =
483       subst_meta_in_proof proof metano term [] in
484     (newproof, [])
485    end
486   else
487    raise (Fail "The type of the provided term is not the one expected.")
488  in
489   mk_tactic (exact_tac ~term)
490
491 (* not really "primitive" tactics .... *)
492 let elim_tac ~term = 
493  let elim_tac ~term (proof, goal) =
494   let module T = CicTypeChecker in
495   let module U = UriManager in
496   let module R = CicReduction in
497   let module C = Cic in
498    let (curi,metasenv,proofbo,proofty) = proof in
499    let metano,context,ty = CicUtil.lookup_meta goal metasenv in
500     let termty,_ = T.type_of_aux' metasenv context term CicUniv.empty_ugraph in
501       (* TASSI: FIXME *)
502     let uri,exp_named_subst,typeno,args =
503      match termty with
504         C.MutInd (uri,typeno,exp_named_subst) -> (uri,exp_named_subst,typeno,[])
505       | C.Appl ((C.MutInd (uri,typeno,exp_named_subst))::args) ->
506           (uri,exp_named_subst,typeno,args)
507       | _ -> raise NotAnInductiveTypeToEliminate
508     in
509      let eliminator_uri =
510       let buri = U.buri_of_uri uri in
511       let name = 
512         let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
513        match o with
514           C.InductiveDefinition (tys,_,_,_) ->
515            let (name,_,_,_) = List.nth tys typeno in
516             name
517         | _ -> assert false
518       in
519       let ty_ty,_ = T.type_of_aux' metasenv context ty CicUniv.empty_ugraph in
520         (* TASSI: FIXME *)
521       let ext =
522        match ty_ty with
523           C.Sort C.Prop -> "_ind"
524         | C.Sort C.Set  -> "_rec"
525         | C.Sort C.CProp -> "_rec"
526         | C.Sort (C.Type _)-> "_rect" 
527         | C.Meta (_,_) -> raise TheTypeOfTheCurrentGoalIsAMetaICannotChooseTheRightElimiantionPrinciple
528         | _ -> assert false
529       in
530        U.uri_of_string (buri ^ "/" ^ name ^ ext ^ ".con")
531      in
532       let eliminator_ref = C.Const (eliminator_uri,exp_named_subst) in
533        let ety,_ = 
534          T.type_of_aux' metasenv context eliminator_ref CicUniv.empty_ugraph in
535         let rec find_args_no =
536          function
537             C.Prod (_,_,t) -> 1 + find_args_no t
538           | C.Cast (s,_) -> find_args_no s
539           | C.LetIn (_,_,t) -> 0 + find_args_no t
540           | _ -> 0
541         in
542          let args_no = find_args_no ety in
543          let term_to_refine =
544           let rec make_tl base_case =
545            function
546               0 -> [base_case]
547             | n -> (C.Implicit None)::(make_tl base_case (n - 1))
548           in
549            C.Appl (eliminator_ref :: make_tl term (args_no - 1))
550          in
551           let metasenv', term_to_refine' =
552            CicMkImplicit.expand_implicits metasenv [] context term_to_refine in
553           let refined_term,_,metasenv'',_ = (* TASSI: FIXME *)
554            CicRefine.type_of_aux' metasenv' context term_to_refine' 
555              CicUniv.empty_ugraph
556           in
557            let new_goals =
558             ProofEngineHelpers.compare_metasenvs
559              ~oldmetasenv:metasenv ~newmetasenv:metasenv''
560            in
561            let proof' = curi,metasenv'',proofbo,proofty in
562             let proof'', new_goals' =
563              apply_tactic (apply_tac ~term:refined_term) (proof',goal)
564             in
565              (* The apply_tactic can have closed some of the new_goals *)
566              let patched_new_goals =
567               let (_,metasenv''',_,_) = proof'' in
568                List.filter
569                 (function i -> List.exists (function (j,_,_) -> j=i) metasenv'''
570                 ) new_goals @ new_goals'
571              in
572               proof'', patched_new_goals
573  in
574   mk_tactic (elim_tac ~term)
575 ;;
576
577 let elim_intros_tac ~term =
578  Tacticals.then_ ~start:(elim_tac ~term)
579   ~continuation:(intros_tac ())
580 ;;
581
582 (* The simplification is performed only on the conclusion *)
583 let elim_intros_simpl_tac ~term =
584  Tacticals.then_ ~start:(elim_tac ~term)
585   ~continuation:
586    (Tacticals.thens
587      ~start:(intros_tac ())
588      ~continuations:
589        [ReductionTactics.simpl_tac
590          ~pattern:(ProofEngineTypes.conclusion_pattern None)])
591 ;;
592
593 exception NotConvertible
594
595 (* Note: this code is almost identical to ReductionTactics.reduction_tac and
596 *  it could be unified by making the change function a callback *)
597 (* CSC: with_what is parsed in the context of the goal, but it should replace
598         something that lives in a completely different context. Thus we
599         perform a delift + lift phase to move it in the right context. However,
600         in this way the tactic is less powerful than expected: with_what cannot
601         reference variables that are local to the term that is going to be
602         replaced. To fix this we should parse with_what in the context of the
603         term(s) to be replaced. *)
604 let change_tac ~pattern with_what  =
605  let change_tac ~pattern ~with_what (proof, goal) =
606   let curi,metasenv,pbo,pty = proof in
607   let (metano,context,ty) as conjecture = CicUtil.lookup_meta goal metasenv in
608   let context_len = List.length context in
609   let change context'_len where terms =
610    if terms = [] then where
611    else
612     let terms, terms' = 
613       List.split
614        (List.map
615         (fun (context_of_t, t) ->
616           let context_of_t_len = List.length context_of_t in
617           let with_what_in_context' =
618             if context_len > context'_len then
619              begin
620               let with_what,subst,metasenv' =
621                CicMetaSubst.delift_rels [] metasenv
622                 (context_len - context'_len) with_what
623               in
624                assert (subst = []);
625                assert (metasenv = metasenv');
626                with_what
627              end
628             else
629              with_what in
630           let with_what_in_context_of_t =
631            if context_of_t_len > context'_len then
632             CicSubstitution.lift (context_of_t_len - context'_len)
633              with_what_in_context'
634            else
635             with_what in
636           let _,u =
637            CicTypeChecker.type_of_aux' metasenv context_of_t with_what
638             CicUniv.empty_ugraph in
639           let b,_ =
640            CicReduction.are_convertible ~metasenv context_of_t t with_what u in
641           if b then
642            t, with_what_in_context_of_t
643           else
644            raise NotConvertible) terms)
645     in
646      ProofEngineReduction.replace ~equality:(==) ~what:terms ~with_what:terms'
647       ~where:where in
648   let (selected_context,selected_ty) =
649    ProofEngineHelpers.select ~metasenv ~conjecture ~pattern in
650   let ty' = change context_len ty selected_ty in
651   let context' =
652    List.fold_right2
653     (fun entry selected_entry context' ->
654      let context'_len = List.length context' in
655      match entry,selected_entry with
656          None,None -> None::context'
657        | Some (name,Cic.Decl ty),Some (`Decl selected_ty) ->
658           let ty' = change context'_len ty selected_ty in
659            Some (name,Cic.Decl ty')::context'
660        | Some (name,Cic.Def (bo,ty)),Some (`Def (selected_bo,selected_ty)) ->
661           let bo' = change context'_len bo selected_bo in
662           let ty' =
663            match ty,selected_ty with
664               None,None -> None
665             | Some ty,Some selected_ty ->
666                Some (change context'_len ty selected_ty)
667             | _,_ -> assert false
668           in
669            Some (name,Cic.Def (bo',ty'))::context'
670        | _,_ -> assert false
671     ) context selected_context [] in
672  let metasenv' = 
673    List.map (function 
674      | (n,_,_) when n = metano -> (metano,context',ty')
675      | _ as t -> t
676    ) metasenv
677  in
678   (curi,metasenv',pbo,pty), [metano]
679   in
680     mk_tactic (change_tac ~pattern ~with_what)