]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/tactics/equalityTactics.ml
c697acaedaeeb79d08940d912abd3ced915b40d6
[helm.git] / helm / software / components / tactics / equalityTactics.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 module C    = Cic
29 module U    = UriManager
30 module PET  = ProofEngineTypes
31 module PER  = ProofEngineReduction
32 module PEH  = ProofEngineHelpers
33 module PESR = ProofEngineStructuralRules
34 module P    = PrimitiveTactics 
35 module T    = Tacticals 
36 module R    = CicReduction
37 module TC   = CicTypeChecker
38 module LO   = LibraryObjects
39 module DTI  = DoubleTypeInference
40
41 let rec rewrite_tac ~direction ~(pattern: ProofEngineTypes.lazy_pattern) equality =
42  let _rewrite_tac ~direction ~pattern:(wanted,hyps_pat,concl_pat) equality status
43  =
44   assert (wanted = None);   (* this should be checked syntactically *)
45   let proof,goal = status in
46   let curi, metasenv, pbo, pty = proof in
47   let (metano,context,gty) = CicUtil.lookup_meta goal metasenv in
48   match hyps_pat with
49      he::(_::_ as tl) ->
50        PET.apply_tactic
51         (Tacticals.then_
52           (rewrite_tac ~direction
53            ~pattern:(None,[he],None) equality)
54           (rewrite_tac ~direction ~pattern:(None,tl,concl_pat)
55             (CicSubstitution.lift 1 equality))
56         ) status
57    | [_] as hyps_pat when concl_pat <> None ->
58        PET.apply_tactic
59         (Tacticals.then_
60           (rewrite_tac ~direction
61            ~pattern:(None,hyps_pat,None) equality)
62           (rewrite_tac ~direction ~pattern:(None,[],concl_pat)
63             (CicSubstitution.lift 1 equality))
64         ) status
65    | _ ->
66   let arg,dir2,tac,concl_pat,gty =
67    match hyps_pat with
68       [] -> None,true,(fun ~term _ -> P.exact_tac term),concl_pat,gty
69     | [name,pat] ->
70       let rec find_hyp n =
71        function
72           [] -> assert false
73         | Some (Cic.Name s,Cic.Decl ty)::_ when name = s ->
74            Cic.Rel n, CicSubstitution.lift n ty
75         | Some (Cic.Name s,Cic.Def _)::_ -> assert false (*CSC: not implemented yet! But does this make any sense?*)
76         | _::tl -> find_hyp (n+1) tl
77       in
78        let arg,gty = find_hyp 1 context in
79        let dummy = "dummy" in
80         Some arg,false,
81          (fun ~term typ ->
82            Tacticals.seq
83             ~tactics:
84               [ProofEngineStructuralRules.rename name dummy;
85                P.letin_tac
86                 ~mk_fresh_name_callback:(fun _ _ _ ~typ -> Cic.Name name) term;
87                ProofEngineStructuralRules.clearbody name;
88                ReductionTactics.change_tac
89                 ~pattern:
90                   (None,[name,Cic.Implicit (Some `Hole)], None)
91                 (ProofEngineTypes.const_lazy_term typ);
92                ProofEngineStructuralRules.clear [dummy]
93               ]),
94          Some pat,gty
95     | _::_ -> assert false
96   in
97   let if_right_to_left do_not_change a b = 
98     match direction with
99     | `RightToLeft -> if do_not_change then a else b
100     | `LeftToRight -> if do_not_change then b else a
101   in
102   let ty_eq,ugraph = 
103     CicTypeChecker.type_of_aux' metasenv context equality 
104       CicUniv.empty_ugraph in 
105   let (ty_eq,metasenv',arguments,fresh_meta) =
106    ProofEngineHelpers.saturate_term
107     (ProofEngineHelpers.new_meta_of_proof proof) metasenv context ty_eq 0 in  
108   let equality =
109    if List.length arguments = 0 then
110     equality
111    else
112     C.Appl (equality :: arguments) in
113   (* t1x is t2 if we are rewriting in an hypothesis *)
114   let eq_ind, ty, t1, t2, t1x =
115     match ty_eq with
116     | C.Appl [C.MutInd (uri, 0, []); ty; t1; t2]
117       when LibraryObjects.is_eq_URI uri ->
118         let ind_uri =
119          if_right_to_left dir2
120           LibraryObjects.eq_ind_URI LibraryObjects.eq_ind_r_URI
121         in
122         let eq_ind = C.Const (ind_uri uri,[]) in
123          if dir2 then
124           if_right_to_left true (eq_ind,ty,t2,t1,t2) (eq_ind,ty,t1,t2,t1)
125          else
126           if_right_to_left true (eq_ind,ty,t1,t2,t2) (eq_ind,ty,t2,t1,t1)
127     | _ -> raise (PET.Fail (lazy "Rewrite: argument is not a proof of an equality")) in
128   (* now we always do as if direction was `LeftToRight *)
129   let fresh_name = 
130     FreshNamesGenerator.mk_fresh_name 
131     ~subst:[] metasenv' context C.Anonymous ~typ:ty in
132   let lifted_t1 = CicSubstitution.lift 1 t1x in
133   let lifted_gty = CicSubstitution.lift 1 gty in
134   let lifted_conjecture =
135     metano,(Some (fresh_name,Cic.Decl ty))::context,lifted_gty in
136   let lifted_pattern =
137     let lifted_concl_pat =
138       match concl_pat with
139       | None -> None
140       | Some term -> Some (CicSubstitution.lift 1 term) in
141     Some (fun _ m u -> lifted_t1, m, u),[],lifted_concl_pat
142   in
143   let subst,metasenv',ugraph,_,selected_terms_with_context =
144    ProofEngineHelpers.select
145     ~metasenv:metasenv' ~ugraph ~conjecture:lifted_conjecture
146      ~pattern:lifted_pattern in
147   let metasenv' = CicMetaSubst.apply_subst_metasenv subst metasenv' in  
148   let what,with_what = 
149    (* Note: Rel 1 does not live in the context context_of_t           *)
150    (* The replace_lifting_csc 0 function will take care of lifting it *)
151    (* to context_of_t                                                 *)
152    List.fold_right
153     (fun (context_of_t,t) (l1,l2) -> t::l1, Cic.Rel 1::l2)
154     selected_terms_with_context ([],[]) in
155   let t1 = CicMetaSubst.apply_subst subst t1 in
156   let t2 = CicMetaSubst.apply_subst subst t2 in
157   let ty = CicMetaSubst.apply_subst subst ty in
158   let pbo = CicMetaSubst.apply_subst subst pbo in
159   let pty = CicMetaSubst.apply_subst subst pty in
160   let equality = CicMetaSubst.apply_subst subst equality in
161   let abstr_gty =
162    ProofEngineReduction.replace_lifting_csc 0
163     ~equality:(==) ~what ~with_what:with_what ~where:lifted_gty in
164   let abstr_gty = CicMetaSubst.apply_subst subst abstr_gty in
165   let pred = C.Lambda (fresh_name, ty, abstr_gty) in
166   (* The argument is either a meta if we are rewriting in the conclusion
167      or the hypothesis if we are rewriting in an hypothesis *)
168   let metasenv',arg,newtyp =
169    match arg with
170       None ->
171        let gty' = CicSubstitution.subst t2 abstr_gty in
172        let irl =
173         CicMkImplicit.identity_relocation_list_for_metavariable context in
174        let metasenv' = (fresh_meta,context,gty')::metasenv' in
175         metasenv', C.Meta (fresh_meta,irl), Cic.Rel (-1) (* dummy term, never used *)
176     | Some arg ->
177        let gty' = CicSubstitution.subst t1 abstr_gty in
178         metasenv',arg,gty'
179   in
180   let exact_proof = 
181     C.Appl [eq_ind ; ty ; t2 ; pred ; arg ; t1 ;equality]
182   in
183   try 
184     let (proof',goals) =
185       PET.apply_tactic 
186         (tac ~term:exact_proof newtyp) ((curi,metasenv',pbo,pty),goal)
187     in
188     let goals =
189      goals@(ProofEngineHelpers.compare_metasenvs ~oldmetasenv:metasenv
190       ~newmetasenv:metasenv')
191     in
192      (proof',goals)
193   with (* FG: this should be PET.Fail _ *)
194      TC.TypeCheckerFailure _ -> PET.apply_tactic (P.letout_tac ()) status
195  in
196   ProofEngineTypes.mk_tactic (_rewrite_tac ~direction ~pattern equality)
197   
198  
199 let rewrite_simpl_tac ~direction ~pattern equality =
200  let rewrite_simpl_tac ~direction ~pattern equality status =
201   ProofEngineTypes.apply_tactic
202   (Tacticals.then_ 
203    ~start:(rewrite_tac ~direction ~pattern equality)
204    ~continuation:
205      (ReductionTactics.simpl_tac
206        ~pattern:(ProofEngineTypes.conclusion_pattern None)))
207    status
208  in
209    ProofEngineTypes.mk_tactic (rewrite_simpl_tac ~direction ~pattern equality)
210 ;;
211
212 let replace_tac ~(pattern: ProofEngineTypes.lazy_pattern) ~with_what =
213  let replace_tac ~(pattern: ProofEngineTypes.lazy_pattern) ~with_what status =
214   let _wanted, hyps_pat, concl_pat = pattern in
215   let (proof, goal) = status in
216   let uri,metasenv,pbo,pty = proof in
217   let (_,context,ty) as conjecture = CicUtil.lookup_meta goal metasenv in
218   assert (hyps_pat = []); (*CSC: not implemented yet *)
219   let eq_URI =
220    match LibraryObjects.eq_URI () with
221       Some uri -> uri
222     | None -> raise (ProofEngineTypes.Fail (lazy "You need to register the default equality first. Please use the \"default\" command"))
223   in
224   let context_len = List.length context in
225   let subst,metasenv,u,_,selected_terms_with_context =
226    ProofEngineHelpers.select ~metasenv ~ugraph:CicUniv.empty_ugraph
227     ~conjecture ~pattern in
228   let metasenv = CicMetaSubst.apply_subst_metasenv subst metasenv in
229   let with_what, metasenv, u = with_what context metasenv u in
230   let with_what = CicMetaSubst.apply_subst subst with_what in
231   let pbo = CicMetaSubst.apply_subst subst pbo in
232   let pty = CicMetaSubst.apply_subst subst pty in
233   let status = (uri,metasenv,pbo,pty),goal in
234   let ty_of_with_what,u =
235    CicTypeChecker.type_of_aux'
236     metasenv context with_what CicUniv.empty_ugraph in
237   let whats =
238    match selected_terms_with_context with
239       [] -> raise (ProofEngineTypes.Fail (lazy "Replace: no term selected"))
240     | l ->
241       List.map
242        (fun (context_of_t,t) ->
243          let t_in_context =
244           try
245            let context_of_t_len = List.length context_of_t in
246            if context_of_t_len = context_len then t
247            else
248             (let t_in_context,subst,metasenv' =
249               CicMetaSubst.delift_rels [] metasenv
250                (context_of_t_len - context_len) t
251              in
252               assert (subst = []);
253               assert (metasenv = metasenv');
254               t_in_context)
255           with
256            CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
257             (*CSC: we could implement something stronger by completely changing
258               the semantics of the tactic *)
259             raise (ProofEngineTypes.Fail
260              (lazy "Replace: one of the selected terms is not closed")) in
261          let ty_of_t_in_context,u = (* TASSI: FIXME *)
262           CicTypeChecker.type_of_aux' metasenv context t_in_context
263            CicUniv.empty_ugraph in
264          let b,u = CicReduction.are_convertible ~metasenv context
265           ty_of_with_what ty_of_t_in_context u in
266          if b then
267           let concl_pat_for_t = ProofEngineHelpers.pattern_of ~term:ty [t] in
268           let pattern_for_t = None,[],Some concl_pat_for_t in
269            t_in_context,pattern_for_t
270          else
271           raise
272            (ProofEngineTypes.Fail
273              (lazy "Replace: one of the selected terms and the term to be replaced with have not convertible types"))
274        ) l in
275   let rec aux n whats status =
276    match whats with
277       [] -> ProofEngineTypes.apply_tactic T.id_tac status
278     | (what,lazy_pattern)::tl ->
279        let what = CicSubstitution.lift n what in
280        let with_what = CicSubstitution.lift n with_what in
281        let ty_of_with_what = CicSubstitution.lift n ty_of_with_what in
282        ProofEngineTypes.apply_tactic
283          (T.thens
284             ~start:(
285               P.cut_tac 
286                (C.Appl [
287                  (C.MutInd (eq_URI, 0, [])) ;
288                  ty_of_with_what ; 
289                  what ; 
290                  with_what]))
291             ~continuations:[            
292               T.then_
293                 ~start:(
294                   rewrite_tac ~direction:`LeftToRight ~pattern:lazy_pattern (C.Rel 1))
295                  ~continuation:(
296                    T.then_
297                     ~start:(
298                       ProofEngineTypes.mk_tactic
299                        (function ((proof,goal) as status) ->
300                          let _,metasenv,_,_ = proof in
301                          let _,context,_ = CicUtil.lookup_meta goal metasenv in
302                          let hyps =
303                           try
304                            match List.hd context with
305                               Some (Cic.Name name,_) -> [name]
306                             | _ -> assert false
307                           with (Failure "hd") -> assert false
308                          in
309                           ProofEngineTypes.apply_tactic
310                            (ProofEngineStructuralRules.clear ~hyps) status))
311                     ~continuation:(aux_tac (n + 1) tl));
312               T.id_tac])
313          status
314   and aux_tac n tl = ProofEngineTypes.mk_tactic (aux n tl) in
315    aux 0 whats status
316  in
317    ProofEngineTypes.mk_tactic (replace_tac ~pattern ~with_what)
318 ;;
319
320
321 (* All these tacs do is applying the right constructor/theorem *)
322
323 let reflexivity_tac =
324   IntroductionTactics.constructor_tac ~n:1
325 ;;
326
327 let symmetry_tac =
328  let symmetry_tac (proof, goal) =
329    let (_,metasenv,_,_) = proof in
330     let metano,context,ty = CicUtil.lookup_meta goal metasenv in
331      match (R.whd context ty) with
332         (C.Appl [(C.MutInd (uri, 0, [])); _; _; _])
333          when LibraryObjects.is_eq_URI uri ->
334           ProofEngineTypes.apply_tactic 
335            (PrimitiveTactics.apply_tac 
336             ~term: (C.Const (LibraryObjects.sym_eq_URI uri, []))) 
337            (proof,goal)
338
339       | _ -> raise (ProofEngineTypes.Fail (lazy "Symmetry failed"))
340  in
341   ProofEngineTypes.mk_tactic symmetry_tac
342 ;;
343
344 let transitivity_tac ~term =
345  let transitivity_tac ~term status =
346   let (proof, goal) = status in
347    let (_,metasenv,_,_) = proof in
348     let metano,context,ty = CicUtil.lookup_meta goal metasenv in
349      match (R.whd context ty) with
350         (C.Appl [(C.MutInd (uri, 0, [])); _; _; _]) 
351         when LibraryObjects.is_eq_URI uri ->
352          ProofEngineTypes.apply_tactic 
353          (T.thens
354           ~start:(PrimitiveTactics.apply_tac
355             ~term: (C.Const (LibraryObjects.trans_eq_URI uri, [])))
356           ~continuations:
357             [PrimitiveTactics.exact_tac ~term ; T.id_tac ; T.id_tac])
358           status
359
360       | _ -> raise (ProofEngineTypes.Fail (lazy "Transitivity failed"))
361  in
362   ProofEngineTypes.mk_tactic (transitivity_tac ~term)
363 ;;
364
365 (* FG *)
366
367 let msg0 = lazy "Subst: not found in context"
368 let msg1 = lazy "Subst: not a simple equality"
369 let msg2 = lazy "Subst: recursive equation" 
370
371 let subst_tac ~hyp =
372    let hole = C.Implicit (Some `Hole) in
373    let map self = function
374       | Some (C.Name s, _) when s <> self -> Some (s, hole)
375       | _                                 -> None
376    in
377    let subst_tac status =
378       let (proof, goal) = status in
379       let (_, metasenv, _, _) = proof in
380       let _, context, _ = CicUtil.lookup_meta goal metasenv in
381       let what = match PEH.get_rel context hyp with
382          | Some t -> t
383          | None   -> raise (PET.Fail msg0)
384       in
385       let ty, _ = TC.type_of_aux' metasenv context what CicUniv.empty_ugraph in
386       let direction, i, t = match ty with
387          | (C.Appl [(C.MutInd (uri, 0, [])); _; C.Rel i; t]) 
388             when LO.is_eq_URI uri -> `LeftToRight, i, t
389          | (C.Appl [(C.MutInd (uri, 0, [])); _; t; C.Rel i]) 
390             when LO.is_eq_URI uri -> `RightToLeft, i, t
391          | _ -> raise (PET.Fail msg1)
392       in    
393       let var = match PEH.get_name context i with
394          | Some name -> name
395          | None      -> raise (PET.Fail msg0)   
396       in
397       if DTI.does_not_occur i t then () else raise (PET.Fail msg2);
398       let pattern = None, PEH.list_rev_map_filter (map hyp) context, Some hole in
399       let start = rewrite_tac ~direction ~pattern what in
400       let continuation = PESR.clear ~hyps:[hyp; var] in
401       let tac = T.then_ ~start ~continuation in
402       PET.apply_tactic tac status
403    in
404    PET.mk_tactic subst_tac