]> matita.cs.unibo.it Git - helm.git/blob - helm/gTopLevel/primitiveTactics.ml
Initial revision
[helm.git] / helm / gTopLevel / 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 NotAnInductiveTypeToEliminate
30 exception NotTheRightEliminatorShape
31 exception NoHypothesesFound
32
33 (* TODO problemone del fresh_name, aggiungerlo allo status? *)
34 let fresh_name () = "FOO"
35
36 (* lambda_abstract newmeta ty *)
37 (* returns a triple [bo],[context],[ty'] where              *)
38 (* [ty] = Pi/LetIn [context].[ty'] ([context] is a vector!) *)
39 (* and [bo] = Lambda/LetIn [context].(Meta [newmeta])       *)
40 (* So, lambda_abstract is the core of the implementation of *)
41 (* the Intros tactic.                                       *)
42 let lambda_abstract context newmeta ty name =
43  let module C = Cic in
44   let rec collect_context context =
45    function
46       C.Cast (te,_)   -> collect_context context te
47     | C.Prod (n,s,t)  ->
48        let n' =
49         match n with
50            C.Name _ -> n
51 (*CSC: generatore di nomi? Chiedere il nome? *)
52          | C.Anonimous -> C.Name name
53        in
54         let (context',ty,bo) =
55          collect_context ((Some (n',(C.Decl s)))::context) 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)))::context) t
61        in
62         (context',ty,C.LetIn(n,s,bo))
63     | _ as t ->
64       let irl = identity_relocation_list_for_metavariable context in
65        context, t, (C.Meta (newmeta,irl))
66   in
67    collect_context context ty
68
69 let eta_expand metasenv context t arg =
70  let module T = CicTypeChecker in
71  let module S = CicSubstitution in
72  let module C = Cic in
73   let rec aux n =
74    function
75       t' when t' = S.lift n arg -> C.Rel (1 + n)
76     | C.Rel m  -> if m <= n then C.Rel m else C.Rel (m+1)
77     | C.Var _
78     | C.Meta _
79     | C.Sort _
80     | C.Implicit as t -> t
81     | C.Cast (te,ty) -> C.Cast (aux n te, aux n ty)
82     | C.Prod (nn,s,t) -> C.Prod (nn, aux n s, aux (n+1) t)
83     | C.Lambda (nn,s,t) -> C.Lambda (nn, aux n s, aux (n+1) t)
84     | C.LetIn (nn,s,t) -> C.LetIn (nn, aux n s, aux (n+1) t)
85     | C.Appl l -> C.Appl (List.map (aux n) l)
86     | C.Const _ as t -> t
87     | C.MutInd _
88     | C.MutConstruct _ as t -> t
89     | C.MutCase (sp,cookingsno,i,outt,t,pl) ->
90        C.MutCase (sp,cookingsno,i,aux n outt, aux n t,
91         List.map (aux n) pl)
92     | C.Fix (i,fl) ->
93        let tylen = List.length fl in
94         let substitutedfl =
95          List.map
96           (fun (name,i,ty,bo) -> (name, i, aux n ty, aux (n+tylen) bo))
97            fl
98         in
99          C.Fix (i, substitutedfl)
100     | C.CoFix (i,fl) ->
101        let tylen = List.length fl in
102         let substitutedfl =
103          List.map
104           (fun (name,ty,bo) -> (name, aux n ty, aux (n+tylen) bo))
105            fl
106         in
107          C.CoFix (i, substitutedfl)
108   in
109    let argty =
110     T.type_of_aux' metasenv context arg
111    in
112     (C.Appl [C.Lambda ((C.Name "dummy"),argty,aux 0 t) ; arg])
113
114 (*CSC: The call to the Intros tactic is embedded inside the code of the *)
115 (*CSC: Elim tactic. Do we already need tacticals?                       *)
116 (* Auxiliary function for apply: given a type (a backbone), it returns its   *)
117 (* head, a META environment in which there is new a META for each hypothesis,*)
118 (* a list of arguments for the new applications and the indexes of the first *)
119 (* and last new METAs introduced. The nth argument in the list of arguments  *)
120 (* is the nth new META lambda-abstracted as much as possible. Hence, this    *)
121 (* functions already provides the behaviour of Intros on the new goals.      *)
122 let new_metasenv_for_apply_intros proof context ty =
123  let module C = Cic in
124  let module S = CicSubstitution in
125   let rec aux newmeta =
126    function
127       C.Cast (he,_) -> aux newmeta he
128     | C.Prod (name,s,t) ->
129        let newcontext,ty',newargument =
130          lambda_abstract context newmeta s (fresh_name ())
131        in
132         let (res,newmetasenv,arguments,lastmeta) =
133          aux (newmeta + 1) (S.subst newargument t)
134         in
135          res,(newmeta,newcontext,ty')::newmetasenv,newargument::arguments,lastmeta
136     | t -> t,[],[],newmeta
137   in
138    let newmeta = new_meta ~proof in
139     (* WARNING: here we are using the invariant that above the most *)
140     (* recente new_meta() there are no used metas.                  *)
141     let (res,newmetasenv,arguments,lastmeta) = aux newmeta ty in
142      res,newmetasenv,arguments,newmeta,lastmeta
143
144 (*CSC: ma serve solamente la prima delle new_uninst e l'unione delle due!!! *)
145 let classify_metas newmeta in_subst_domain subst_in metasenv =
146  List.fold_right
147   (fun (i,canonical_context,ty) (old_uninst,new_uninst) ->
148     if in_subst_domain i then
149      old_uninst,new_uninst
150     else
151      let ty' = subst_in canonical_context ty in
152       let canonical_context' =
153        List.fold_right
154         (fun entry canonical_context' ->
155           let entry' =
156            match entry with
157               Some (n,Cic.Decl s) ->
158                Some (n,Cic.Decl (subst_in canonical_context' s))
159             | Some (n,Cic.Def s) ->
160                Some (n,Cic.Def (subst_in canonical_context' s))
161             | None -> None
162           in
163            entry'::canonical_context'
164         ) canonical_context []
165      in
166       if i < newmeta then
167        ((i,canonical_context',ty')::old_uninst),new_uninst
168       else
169        old_uninst,((i,canonical_context',ty')::new_uninst)
170   ) metasenv ([],[])
171
172 (* Auxiliary function for apply: given a type (a backbone), it returns its   *)
173 (* head, a META environment in which there is new a META for each hypothesis,*)
174 (* a list of arguments for the new applications and the indexes of the first *)
175 (* and last new METAs introduced. The nth argument in the list of arguments  *)
176 (* is just the nth new META.                                                 *)
177 let new_metasenv_for_apply proof context ty =
178  let module C = Cic in
179  let module S = CicSubstitution in
180   let rec aux newmeta =
181    function
182       C.Cast (he,_) -> aux newmeta he
183     | C.Prod (name,s,t) ->
184        let irl = identity_relocation_list_for_metavariable context in
185         let newargument = C.Meta (newmeta,irl) in
186          let (res,newmetasenv,arguments,lastmeta) =
187           aux (newmeta + 1) (S.subst newargument t)
188          in
189           res,(newmeta,context,s)::newmetasenv,newargument::arguments,lastmeta
190     | t -> t,[],[],newmeta
191   in
192    let newmeta = new_meta ~proof in
193     (* WARNING: here we are using the invariant that above the most *)
194     (* recente new_meta() there are no used metas.                  *)
195     let (res,newmetasenv,arguments,lastmeta) = aux newmeta ty in
196      res,newmetasenv,arguments,newmeta,lastmeta
197
198 let apply_tac ~term ~status:(proof, goal) =
199   (* Assumption: The term "term" must be closed in the current context *)
200  let module T = CicTypeChecker in
201  let module R = CicReduction in
202  let module C = Cic in
203   let (_,metasenv,_,_) = proof in
204   let metano,context,ty = List.find (function (m,_,_) -> m=goal) metasenv in
205    let termty = CicTypeChecker.type_of_aux' metasenv context term in
206     (* newmeta is the lowest index of the new metas introduced *)
207     let (consthead,newmetas,arguments,newmeta,_) =
208      new_metasenv_for_apply proof context termty
209     in
210      let newmetasenv = newmetas@metasenv in
211       let subst,newmetasenv' =
212        CicUnification.fo_unif newmetasenv context consthead ty
213       in
214        let in_subst_domain i = List.exists (function (j,_) -> i=j) subst in
215        let apply_subst = CicUnification.apply_subst subst in
216         let old_uninstantiatedmetas,new_uninstantiatedmetas =
217          (* subst_in doesn't need the context. Hence the underscore. *)
218          let subst_in _ = CicUnification.apply_subst subst in
219           classify_metas newmeta in_subst_domain subst_in newmetasenv'
220         in
221          let bo' =
222           if List.length newmetas = 0 then
223            term
224           else
225            let arguments' = List.map apply_subst arguments in
226             Cic.Appl (term::arguments')
227          in
228           let newmetasenv'' = new_uninstantiatedmetas@old_uninstantiatedmetas in
229           let (newproof, newmetasenv''') =
230            let subst_in = CicUnification.apply_subst ((metano,bo')::subst) in
231             subst_meta_and_metasenv_in_proof
232               proof metano subst_in newmetasenv''
233           in
234            (newproof, List.map (function (i,_,_) -> i) new_uninstantiatedmetas)
235
236   (* TODO per implementare i tatticali e' necessario che tutte le tattiche
237   sollevino _solamente_ Fail *)
238 let apply_tac ~term ~status =
239   try
240     apply_tac ~term ~status
241       (* TODO cacciare anche altre eccezioni? *)
242   with CicUnification.UnificationFailed as e ->
243     raise (Fail (Printexc.to_string e))
244
245 let intros_tac ~name ~status:(proof, goal) =
246  let module C = Cic in
247  let module R = CicReduction in
248   let (_,metasenv,_,_) = proof in
249   let metano,context,ty = List.find (function (m,_,_) -> m=goal) metasenv in
250    let newmeta = new_meta ~proof in
251     let (context',ty',bo') = lambda_abstract context newmeta ty name in
252      let (newproof, _) =
253        subst_meta_in_proof proof metano bo' [newmeta,context',ty']
254      in
255       (newproof, [newmeta])
256
257 let cut_tac ~term ~status:(proof, goal) =
258  let module C = Cic in
259   let curi,metasenv,pbo,pty = proof in
260   let metano,context,ty = List.find (function (m,_,_) -> m=goal) metasenv in
261    let newmeta1 = new_meta ~proof in
262    let newmeta2 = newmeta1 + 1 in
263    let context_for_newmeta1 =
264     (Some (C.Name "dummy_for_cut",C.Decl term))::context in
265    let irl1 =
266     identity_relocation_list_for_metavariable context_for_newmeta1 in
267    let irl2 = identity_relocation_list_for_metavariable context in
268     let newmeta1ty = CicSubstitution.lift 1 ty in
269     let bo' =
270      C.Appl
271       [C.Lambda (C.Name "dummy_for_cut",term,C.Meta (newmeta1,irl1)) ;
272        C.Meta (newmeta2,irl2)]
273     in
274      let (newproof, _) =
275       subst_meta_in_proof proof metano bo'
276        [newmeta2,context,term; newmeta1,context_for_newmeta1,newmeta1ty];
277      in
278       (newproof, [newmeta1 ; newmeta2])
279
280 let letin_tac ~term ~status:(proof, goal) =
281  let module C = Cic in
282   let curi,metasenv,pbo,pty = proof in
283   let metano,context,ty = List.find (function (m,_,_) -> m=goal) metasenv in
284    let _ = CicTypeChecker.type_of_aux' metasenv context term in
285     let newmeta = new_meta ~proof in
286     let context_for_newmeta =
287      (Some (C.Name "dummy_for_letin",C.Def term))::context in
288     let irl =
289      identity_relocation_list_for_metavariable context_for_newmeta in
290      let newmetaty = CicSubstitution.lift 1 ty in
291      let bo' = C.LetIn (C.Name "dummy_for_letin",term,C.Meta (newmeta,irl)) in
292       let (newproof, _) =
293         subst_meta_in_proof
294           proof metano bo'[newmeta,context_for_newmeta,newmetaty]
295       in
296        (newproof, [newmeta])
297
298   (** functional part of the "exact" tactic *)
299 let exact_tac ~term ~status:(proof, goal) =
300  (* Assumption: the term bo must be closed in the current context *)
301  let (_,metasenv,_,_) = proof in
302  let metano,context,ty = List.find (function (m,_,_) -> m=goal) metasenv in
303  let module T = CicTypeChecker in
304  let module R = CicReduction in
305  if R.are_convertible context (T.type_of_aux' metasenv context term) ty then
306   begin
307    let (newproof, metasenv') =
308      subst_meta_in_proof proof metano term [] in
309    (newproof, [])
310   end
311  else
312   raise (Fail "The type of the provided term is not the one expected.")
313
314
315 (* not really "primite" tactics .... *)
316
317 let elim_intros_simpl_tac ~term ~status:(proof, goal) =
318  let module T = CicTypeChecker in
319  let module U = UriManager in
320  let module R = CicReduction in
321  let module C = Cic in
322   let (curi,metasenv,_,_) = proof in
323   let metano,context,ty = List.find (function (m,_,_) -> m=goal) metasenv in
324    let termty = T.type_of_aux' metasenv context term in
325    let uri,cookingno,typeno,args =
326     match termty with
327        C.MutInd (uri,cookingno,typeno) -> (uri,cookingno,typeno,[])
328      | C.Appl ((C.MutInd (uri,cookingno,typeno))::args) ->
329          (uri,cookingno,typeno,args)
330      | _ ->
331          prerr_endline ("MALFATTORE" ^ (CicPp.ppterm termty));
332          flush stderr;
333          raise NotAnInductiveTypeToEliminate
334    in
335     let eliminator_uri =
336      let buri = U.buri_of_uri uri in
337      let name = 
338       match CicEnvironment.get_cooked_obj uri cookingno with
339          C.InductiveDefinition (tys,_,_) ->
340           let (name,_,_,_) = List.nth tys typeno in
341            name
342        | _ -> assert false
343      in
344      let ext =
345       match T.type_of_aux' metasenv context ty with
346          C.Sort C.Prop -> "_ind"
347        | C.Sort C.Set  -> "_rec"
348        | C.Sort C.Type -> "_rect"
349        | _ -> assert false
350      in
351       U.uri_of_string (buri ^ "/" ^ name ^ ext ^ ".con")
352     in
353      let eliminator_cookingno =
354       UriManager.relative_depth curi eliminator_uri 0
355      in
356      let eliminator_ref = C.Const (eliminator_uri,eliminator_cookingno) in
357       let ety =
358        T.type_of_aux' [] [] eliminator_ref
359       in
360        let (econclusion,newmetas,arguments,newmeta,lastmeta) =
361 (*
362         new_metasenv_for_apply context ety
363 *)
364         new_metasenv_for_apply_intros proof context ety
365        in
366         (* Here we assume that we have only one inductive hypothesis to *)
367         (* eliminate and that it is the last hypothesis of the theorem. *)
368         (* A better approach would be fingering the hypotheses in some  *)
369         (* way.                                                         *)
370         let meta_of_corpse =
371          let (_,canonical_context,_) =
372           List.find (function (m,_,_) -> m=(lastmeta - 1)) newmetas
373          in
374           let irl =
375            identity_relocation_list_for_metavariable canonical_context
376           in
377            Cic.Meta (lastmeta - 1, irl)
378         in
379         let newmetasenv = newmetas @ metasenv in
380         let subst1,newmetasenv' =
381          CicUnification.fo_unif newmetasenv context term meta_of_corpse
382         in
383          let ueconclusion = CicUnification.apply_subst subst1 econclusion in
384           (* The conclusion of our elimination principle is *)
385           (*  (?i farg1 ... fargn)                         *)
386           (* The conclusion of our goal is ty. So, we can   *)
387           (* eta-expand ty w.r.t. farg1 .... fargn to get   *)
388           (* a new ty equal to (P farg1 ... fargn). Now     *)
389           (* ?i can be instantiated with P and we are ready *)
390           (* to refine the term.                            *)
391           let emeta, fargs =
392            match ueconclusion with
393 (*CSC: Code to be used for Apply
394               C.Appl ((C.Meta (emeta,_))::fargs) -> emeta,fargs
395             | C.Meta (emeta,_) -> emeta,[]
396 *)
397 (*CSC: Code to be used for ApplyIntros *)
398               C.Appl (he::fargs) ->
399                let rec find_head =
400                 function
401                    C.Meta (emeta,_) -> emeta
402                  | C.Lambda (_,_,t) -> find_head t
403                  | C.LetIn (_,_,t) -> find_head t
404                  | _ ->raise NotTheRightEliminatorShape
405                in
406                 find_head he,fargs
407             | C.Meta (emeta,_) -> emeta,[]
408 (* *)
409             | _ -> raise NotTheRightEliminatorShape
410           in
411            let ty' = CicUnification.apply_subst subst1 ty in
412            let eta_expanded_ty =
413 (*CSC: newmetasenv' era metasenv ??????????? *)
414             List.fold_left (eta_expand newmetasenv' context) ty' fargs
415            in
416             let subst2,newmetasenv'' =
417 (*CSC: passo newmetasenv', ma alcune variabili sono gia' state sostituite
418 da subst1!!!! Dovrei rimuoverle o sono innocue?*)
419              CicUnification.fo_unif
420               newmetasenv' context ueconclusion eta_expanded_ty
421             in
422              let in_subst_domain i =
423               let eq_to_i = function (j,_) -> i=j in
424                List.exists eq_to_i subst1 ||
425                List.exists eq_to_i subst2
426              in
427 (*CSC: codice per l'elim
428               (* When unwinding the META that corresponds to the elimination *)
429               (* predicate (which is emeta), we must also perform one-step   *)
430               (* beta-reduction. apply_subst doesn't need the context. Hence *)
431               (* the underscore.                                             *)
432               let apply_subst _ t =
433                let t' = CicUnification.apply_subst subst1 t in
434                 CicUnification.apply_subst_reducing
435                  subst2 (Some (emeta,List.length fargs)) t'
436               in
437 *)
438 (*CSC: codice per l'elim_intros_simpl. Non effettua semplificazione. *)
439               let apply_subst context t =
440                let t' = CicUnification.apply_subst (subst1@subst2) t in
441                 ProofEngineReduction.simpl context t'
442               in
443 (* *)
444                 let old_uninstantiatedmetas,new_uninstantiatedmetas =
445                  classify_metas newmeta in_subst_domain apply_subst
446                   newmetasenv''
447                 in
448                  let arguments' = List.map (apply_subst context) arguments in
449                   let bo' = Cic.Appl (eliminator_ref::arguments') in
450                    let newmetasenv''' =
451                     new_uninstantiatedmetas@old_uninstantiatedmetas
452                    in
453                     let (newproof, newmetasenv'''') =
454                      (* When unwinding the META that corresponds to the *)
455                      (* elimination predicate (which is emeta), we must *)
456                      (* also perform one-step beta-reduction.           *)
457                      (* The only difference w.r.t. apply_subst is that  *)
458                      (* we also substitute metano with bo'.             *)
459                      (*CSC: Nota: sostituire nuovamente subst1 e' superfluo, *)
460                      (*CSC: no?                                              *)
461 (*CSC: codice per l'elim
462                      let apply_subst' t =
463                       let t' = CicUnification.apply_subst subst1 t in
464                        CicUnification.apply_subst_reducing
465                         ((metano,bo')::subst2)
466                         (Some (emeta,List.length fargs)) t'
467                      in
468 *)
469 (*CSC: codice per l'elim_intros_simpl *)
470                      let apply_subst' t =
471                       CicUnification.apply_subst
472                        ((metano,bo')::(subst1@subst2)) t
473                      in
474 (* *)
475                       subst_meta_and_metasenv_in_proof
476                         proof metano apply_subst' newmetasenv'''
477                     in
478                      (newproof,
479                       List.map (function (i,_,_) -> i) new_uninstantiatedmetas)
480
481
482 exception NotConvertible
483
484 (*CSC: Bug (or feature?). [with_what] is parsed in the context of the goal,  *)
485 (*CSC: while [what] can have a richer context (because of binders)           *)
486 (*CSC: So it is _NOT_ possible to use those binders in the [with_what] term. *)
487 (*CSC: Is that evident? Is that right? Or should it be changed?              *)
488 let change_tac ~what ~with_what ~status:(proof, goal) =
489  let curi,metasenv,pbo,pty = proof in
490  let metano,context,ty = List.find (function (m,_,_) -> m=goal) metasenv in
491   (* are_convertible works only on well-typed terms *)
492   ignore (CicTypeChecker.type_of_aux' metasenv context with_what) ;
493   if CicReduction.are_convertible context what with_what then
494    begin
495     let replace =
496      ProofEngineReduction.replace ~equality:(==) ~what ~with_what
497     in
498     let ty' = replace ty in
499     let context' =
500      List.map
501       (function
502           Some (name,Cic.Def  t) -> Some (name,Cic.Def  (replace t))
503         | Some (name,Cic.Decl t) -> Some (name,Cic.Decl (replace t))
504         | None -> None
505       ) context
506     in
507      let metasenv' = 
508       List.map
509        (function
510            (n,_,_) when n = metano -> (metano,context',ty')
511          | _ as t -> t
512        ) metasenv
513      in
514       (curi,metasenv',pbo,pty), [metano]
515    end
516   else
517    raise (ProofEngineTypes.Fail "Not convertible")