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