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