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