]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/discriminationTactics.ml
bug fix in injection e relocate term
[helm.git] / components / tactics / discriminationTactics.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 P = PrimitiveTactics
31 module T = Tacticals
32 module CR = CicReduction 
33 module PST = ProofEngineStructuralRules
34 module PET = ProofEngineTypes
35 module CTC = CicTypeChecker
36 module CU = CicUniv
37 module S = CicSubstitution
38 module RT = ReductionTactics
39 module PEH = ProofEngineHelpers
40
41 let debug = false
42 let debug_print = 
43   if debug then (fun x -> prerr_endline (Lazy.force x)) else (fun _ -> ())
44
45 (* funzione generale di rilocazione dei riferimenti locali *)
46
47 let relocate_term map t =
48    let rec map_xnss k xnss =
49       let imap (uri, t) = uri, map_term k t in
50       List.map imap xnss
51    and map_mss k mss =
52       let imap = function
53          | None   -> None
54          | Some t -> Some (map_term k t)
55       in
56       List.map imap mss
57    and map_fs len k fs = 
58       let imap (name, i, ty, bo) = name, i, map_term k ty, map_term (k + len) bo in
59       List.map imap fs
60    and map_cfs len k cfs = 
61       let imap (name, ty, bo) = name, map_term k ty, map_term (k + len) bo in
62       List.map imap cfs
63    and map_term k = function
64       | C.Rel m -> if m < k then C.Rel m else C.Rel (map (m - k))
65       | C.Sort _ as t -> t
66       | C.Implicit _ as t -> t
67       | C.Var (uri, xnss) -> C.Var (uri, map_xnss k xnss)
68       | C.Const (uri, xnss) -> C.Const (uri, map_xnss k xnss)
69       | C.MutInd (uri, tyno, xnss) -> C.MutInd (uri, tyno, map_xnss k xnss)
70       | C.MutConstruct (uri, tyno, consno, xnss) ->
71          C.MutConstruct (uri, tyno, consno, map_xnss k xnss)
72       | C.Meta (i, mss) -> C.Meta(i, map_mss k mss)
73       | C.Cast (te, ty) -> C.Cast (map_term k te, map_term k ty)
74       | C.Appl ts -> C.Appl (List.map (map_term k) ts)
75       | C.MutCase (sp, i, outty, t, pl) ->
76          C.MutCase (sp, i, map_term k outty, map_term k t, List.map (map_term k) pl)    
77       | C.Prod (n, s, t) -> C.Prod (n, map_term k s, map_term (succ k) t)
78       | C.Lambda (n, s, t) -> C.Lambda (n, map_term k s, map_term (succ k) t)
79       | C.LetIn (n, s, t) -> C.LetIn (n, map_term k s, map_term (succ k) t)
80       | C.Fix (i, fs) -> C.Fix (i, map_fs (List.length fs) k fs)
81       | C.CoFix (i, cfs) -> C.CoFix (i, map_cfs (List.length cfs) k cfs)
82    in
83    map_term 0 t
84
85 let id n = n
86
87 let after continuation aftermap beforemap = 
88    continuation ~map:(fun n -> aftermap (beforemap n))
89
90 let after2 continuation aftermap beforemap ~map = 
91    continuation ~map:(fun n -> map (aftermap (beforemap n)))
92
93 (* term ha tipo t1=t2; funziona solo se t1 e t2 hanno in testa costruttori
94 diversi *)
95
96 let discriminate_tac ~term =
97  let true_URI =
98   match LibraryObjects.true_URI () with
99      Some uri -> uri
100    | None -> raise (PET.Fail (lazy "You need to register the default \"true\" definition first. Please use the \"default\" command")) in
101  let false_URI =
102   match LibraryObjects.false_URI () with
103      Some uri -> uri
104    | None -> raise (PET.Fail (lazy "You need to register the default \"false\" definition first. Please use the \"default\" command")) in
105  let fail msg = raise (PET.Fail (lazy ("Discriminate: " ^ msg))) in
106  let find_discriminating_consno t1 t2 =
107    let rec aux t1 t2 =
108      match t1, t2 with
109      | C.MutConstruct _, C.MutConstruct _ when t1 = t2 -> None
110      | C.Appl ((C.MutConstruct _ as constr1) :: args1),
111        C.Appl ((C.MutConstruct _ as constr2) :: args2)
112        when constr1 = constr2 ->
113          let rec aux_list l1 l2 =
114            match l1, l2 with
115            | [], [] -> None
116            | hd1 :: tl1, hd2 :: tl2 ->
117                (match aux hd1 hd2 with
118                | None -> aux_list tl1 tl2
119                | Some _ as res -> res)
120            | _ -> (* same constructor applied to a different number of args *)
121                assert false
122          in
123          aux_list args1 args2
124      | ((C.MutConstruct (_,_,consno1,subst1)),
125        (C.MutConstruct (_,_,consno2,subst2)))
126      | ((C.MutConstruct (_,_,consno1,subst1)),
127        (C.Appl ((C.MutConstruct (_,_,consno2,subst2)) :: _)))
128      | ((C.Appl ((C.MutConstruct (_,_,consno1,subst1)) :: _)),
129        (C.MutConstruct (_,_,consno2,subst2)))
130      | ((C.Appl ((C.MutConstruct (_,_,consno1,subst1)) :: _)),
131        (C.Appl ((C.MutConstruct (_,_,consno2,subst2)) :: _)))
132        when (consno1 <> consno2) || (subst1 <> subst2) ->
133          Some consno2
134      | _ -> fail "not a discriminable equality"
135    in
136    aux t1 t2
137  in
138  let mk_branches_and_outtype turi typeno consno context args =
139     (* a list of "True" except for the element in position consno which
140      * is "False" *)
141     match fst (CicEnvironment.get_obj CicUniv.empty_ugraph turi) with
142     | C.InductiveDefinition (ind_type_list,_,paramsno,_)  ->
143         let _,_,rty,constructor_list = List.nth ind_type_list typeno in 
144         let false_constr_id,_ = List.nth constructor_list (consno - 1) in
145         let branches =
146          List.map 
147            (fun (id,cty) ->
148              (* dubbio: e' corretto ridurre in questo context ??? *)
149              let red_ty = CR.whd context cty in
150              let rec aux t k =
151                match t with
152                | C.Prod (_,_,target) when (k <= paramsno) ->
153                    S.subst (List.nth args (k-1))
154                      (aux target (k+1))
155                | C.Prod (binder,source,target) when (k > paramsno) ->
156                    C.Lambda (binder, source, (aux target (k+1)))
157                | _ -> 
158                    if (id = false_constr_id)
159                    then (C.MutInd(false_URI,0,[]))
160                    else (C.MutInd(true_URI,0,[]))
161              in
162              (S.lift 1 (aux red_ty 1)))
163            constructor_list in
164         let outtype =
165          let seed = ref 0 in
166          let rec mk_lambdas rev_left_args =
167           function
168              0, args, C.Prod (_,so,ta) ->
169               C.Lambda
170                (C.Name (incr seed; "x" ^ string_of_int !seed),
171                so,
172                mk_lambdas rev_left_args (0,args,ta))
173            | 0, args, C.Sort _ ->
174               let rec mk_rels =
175                function
176                   0 -> []
177                 | n -> C.Rel n :: mk_rels (n - 1) in
178               let argsno = List.length args in
179                C.Lambda
180                 (C.Name "x",
181                  (if argsno + List.length rev_left_args > 0 then
182                    C.Appl
183                     (C.MutInd (turi, typeno, []) ::
184                      (List.map
185                       (S.lift (argsno + 1))
186                       (List.rev rev_left_args)) @
187                      mk_rels argsno)
188                   else
189                    C.MutInd (turi,typeno,[])),
190                  C.Sort C.Prop)
191            | 0, _, _ -> assert false (* seriously screwed up *)
192            | n, he::tl, C.Prod (_,_,ta) ->
193               mk_lambdas (he::rev_left_args)(n-1,tl,S.subst he ta)
194            | n,_,_ ->
195               assert false (* we should probably reduce in some context *)
196          in
197           mk_lambdas [] (paramsno, args, rty)
198         in
199          branches, outtype 
200     | _ -> assert false
201  in
202  let discriminate'_tac ~term status = 
203   let (proof, goal) = status in
204   let _,metasenv,_subst,_,_, _ = proof in
205   let _,context,_ = CicUtil.lookup_meta goal metasenv in
206   let termty,_ = 
207     CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph
208   in
209   match termty with
210    | C.Appl [(C.MutInd (equri, 0, [])) ; tty ; t1 ; t2]
211      when LibraryObjects.is_eq_URI equri ->
212       let turi,typeno,exp_named_subst,args = 
213         match tty with
214         | (C.MutInd (turi,typeno,exp_named_subst)) ->
215             turi,typeno,exp_named_subst,[]
216         | (C.Appl (C.MutInd (turi,typeno,exp_named_subst)::args)) ->
217             turi,typeno,exp_named_subst,args
218         | _ -> fail "not a discriminable equality"
219       in
220       let consno =
221         match find_discriminating_consno t1 t2 with
222         | Some consno -> consno
223         | None -> fail "discriminating terms are structurally equal"
224       in
225       let branches,outtype =
226        mk_branches_and_outtype turi typeno consno context args
227       in
228       PET.apply_tactic
229        (T.then_
230          ~start:(EliminationTactics.elim_type_tac (C.MutInd (false_URI, 0, [])))
231          ~continuation:
232            (T.then_
233              ~start:
234                (RT.change_tac 
235                  ~pattern:(PET.conclusion_pattern None)
236                  (fun _ m u ->
237                    C.Appl [
238                      C.Lambda ( C.Name "x", tty,
239                        C.MutCase (turi, typeno, outtype, (C.Rel 1), branches));
240                      t2 ],
241                    m, u))
242              ~continuation:
243                (T.then_
244                  ~start:
245                    (EqualityTactics.rewrite_simpl_tac
246                      ~direction:`RightToLeft
247                      ~pattern:(PET.conclusion_pattern None)
248                      term [])
249                  ~continuation:
250                    (IntroductionTactics.constructor_tac ~n:1)))) status
251     | _ -> fail "not an equality"
252   in
253   PET.mk_tactic (discriminate'_tac ~term)
254
255 let exn_nonproj = 
256   PET.Fail (lazy "Injection: not a projectable equality")
257 let exn_noneq = 
258   PET.Fail (lazy "Injection: not an equality")
259 let exn_nothingtodo = 
260   PET.Fail (lazy "Nothing to do")
261 let exn_discrnonind =
262   PET.Fail (lazy "Discriminate: object is not an Inductive Definition: it's imposible")
263 let exn_injwronggoal = 
264   PET.Fail (lazy "Injection: goal after cut is not correct")
265 let exn_noneqind =
266   PET.Fail (lazy "Injection: not an equality over elements of an inductive type")
267
268 let pp ctx t = 
269   let names = List.map (function Some (n,_) -> Some n | None -> None) ctx in
270   CicPp.pp t names
271
272 let clear_term first_time context term =
273    let g () = if first_time then raise exn_nothingtodo else T.id_tac in
274    match term with
275       | C.Rel n -> 
276          begin match List.nth context (pred n) with
277             | Some (C.Name id, _) -> PST.clear ~hyps:[id]
278             | _                   -> assert false
279          end
280        | _      -> g ()
281
282 let simpl_in_term context = function
283    | Cic.Rel i ->
284       let name = match List.nth context (pred i) with
285          | Some (Cic.Name s, Cic.Def _) -> s
286          | Some (Cic.Name s, Cic.Decl _) -> s
287          | _ -> assert false
288       in
289       RT.simpl_tac ~pattern:(None,[name,Cic.Implicit (Some `Hole)],None)
290    | _ -> raise exn_nonproj
291
292 (* ~term vive nel contesto della tattica una volta ~mappato
293  * ~continuation riceve la mappa assoluta
294  *)
295 let rec injection_tac ~map ~term ~i ~continuation =
296  let give_name seed = function
297    | C.Name _ as name -> name
298    | C.Anonymous -> C.Name (incr seed; "y" ^ string_of_int !seed)
299  in
300  let rec mk_rels = function | 0 -> [] | n -> C.Rel n :: (mk_rels (n - 1)) in
301  let injection_tac status =
302   let (proof, goal) = status in
303   (* precondizione: t1 e t2 hanno in testa lo stesso costruttore ma 
304    * differiscono (o potrebbero differire?) nell'i-esimo parametro 
305    * del costruttore *)
306   let _,metasenv,_subst,_,_, _ = proof in
307   let _,context,_ = CicUtil.lookup_meta goal metasenv in
308   let term = relocate_term map term in
309   let termty,_ = 
310     CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph
311   in
312   debug_print (lazy ("\ninjection su : " ^ pp context termty)); 
313   match termty with (* an equality *)
314    | C.Appl [(C.MutInd (equri, 0, [])) ; tty ; t1 ; t2]
315     when LibraryObjects.is_eq_URI equri -> 
316       let turi,typeno,ens,params =
317         match tty with (* some inductive type *)
318         | C.MutInd (turi,typeno,ens) -> turi,typeno,ens,[]
319         | C.Appl (C.MutInd (turi,typeno,ens)::params) -> turi,typeno,ens,params
320         | _ -> raise exn_noneqind
321       in
322       let t1',t2',consno = (* sono i due sottotermini che differiscono *)
323         match t1,t2 with
324         | C.Appl ((C.MutConstruct (uri1,typeno1,consno1,ens1))::applist1),
325           C.Appl ((C.MutConstruct (uri2,typeno2,consno2,ens2))::applist2)
326           when (uri1 = uri2) && (typeno1 = typeno2) && 
327                (consno1 = consno2) && (ens1 = ens2) -> 
328                (* controllo ridondante *)
329             List.nth applist1 (pred i),List.nth applist2 (pred i),consno2
330         | _ -> assert false
331       in
332       let tty',_ = CTC.type_of_aux' metasenv context t1' CU.empty_ugraph in
333       let patterns,outtype =
334         match fst (CicEnvironment.get_obj CicUniv.empty_ugraph turi) with
335         | C.InductiveDefinition (ind_type_list,_,paramsno,_)->
336            let left_params, right_params = HExtlib.split_nth paramsno params in
337            let _,_,_,constructor_list = List.nth ind_type_list typeno in
338            let i_constr_id,_ = List.nth constructor_list (consno - 1) in
339            let patterns =
340              let seed = ref 0 in
341              List.map
342                (function (id,cty) ->
343                  let reduced_cty = CR.whd context cty in
344                  let rec aux k = function
345                    | C.Prod (_,_,tgt) when k <= paramsno -> 
346                        let left = List.nth left_params (k-1) in
347                        aux (k+1) (S.subst left tgt)
348                    | C.Prod (binder,source,target) when k > paramsno ->
349                       let binder' = give_name seed binder in
350                       C.Lambda (binder',source,(aux (k+1) target))
351                    | _ ->
352                      let nr_param_constr = k - paramsno - 1 in
353                      if id = i_constr_id then C.Rel (k - i)
354                      else S.lift nr_param_constr t1' 
355                      (* + 1 per liftare anche il lambda aggiunto
356                       * esternamente al case *)
357                  in S.lift 1 (aux 1 reduced_cty))
358                constructor_list 
359            in
360            (* this code should be taken from cases_tac *)
361            let outtype =
362              let seed = ref 0 in
363              let rec to_lambdas te head =
364                match CR.whd context te with
365                | C.Prod (binder,so,ta) ->
366                    let binder' = give_name seed binder in
367                    C.Lambda (binder',so,to_lambdas ta head)
368                | _ -> head 
369              in
370              let rec skip_prods params te =
371                match params, CR.whd context te with
372                | [], _ -> te
373                | left::tl, C.Prod (_,_,ta) -> 
374                    skip_prods tl (S.subst left ta)
375                | _, _ -> assert false
376              in
377              let abstracted_tty =
378                let tty =
379                  List.fold_left (fun x y -> S.subst y x) tty left_params
380                in
381                (* non lift, ma subst coi left! *)
382                match S.lift 1 tty with
383                | C.MutInd _ as tty' -> tty'
384                | C.Appl l ->
385                    let keep,abstract = HExtlib.split_nth (paramsno +1) l in
386                    let keep = List.map (S.lift paramsno) keep in
387                    C.Appl (keep@mk_rels (List.length abstract))
388                | _ -> assert false
389              in
390              match ind_type_list with
391              | [] -> assert false
392              | (_,_,ty,_)::_ ->
393                (* this is in general wrong, do as in cases_tac *)
394                to_lambdas (skip_prods left_params ty)
395                  (C.Lambda 
396                    (C.Name "cased", abstracted_tty,
397                      (* here we should capture right parameters *)
398                      (* 1 for his Lambda, one for the Lambda outside the match
399                       * and then one for each to_lambda *)
400                      S.lift (2+List.length right_params) tty'))
401           in
402             patterns,outtype
403         | _ -> raise exn_discrnonind
404       in
405       let cutted = C.Appl [C.MutInd (equri,0,[]) ; tty' ; t1' ; t2'] in
406       let changed = 
407         C.Appl [ C.Lambda (C.Name "x", tty, 
408                   C.MutCase (turi,typeno,outtype,C.Rel 1,patterns)) ; t1]
409       in
410       (* check if cutted and changed are well typed and if t1' ~ changed *)
411       let go_on =
412         try
413           let _,g = CTC.type_of_aux' metasenv context  cutted
414             CicUniv.empty_ugraph
415           in
416           let _,g = CTC.type_of_aux' metasenv context changed g in
417           fst (CR.are_convertible ~metasenv context  t1' changed g)
418         with
419         | CTC.TypeCheckerFailure _ -> false
420       in
421       if not go_on then
422         PET.apply_tactic T.id_tac status (* FG: ??????? *)
423       else
424         let tac term = 
425            let tac status =
426                debug_print (lazy "riempio il cut"); 
427                let (proof, goal) = status in
428                let _,metasenv,_subst,_,_, _ = proof in
429                let _,context,gty = CicUtil.lookup_meta goal metasenv in
430                let gty = Unshare.unshare gty in
431                let new_t1' = match gty with 
432                   | (C.Appl (C.MutInd (_,_,_)::_::t::_)) -> t
433                   | _ -> raise exn_injwronggoal
434                in
435                debug_print (lazy ("metto: " ^ pp context changed));
436                debug_print (lazy ("al posto di: " ^ pp context new_t1'));
437                debug_print (lazy ("nel goal: " ^ pp context gty));
438                debug_print (lazy ("nel contesto:\n" ^ CicPp.ppcontext context));
439                debug_print (lazy ("e poi rewrite con: "^pp context term));
440                let tac = T.seq ~tactics:[
441                   RT.change_tac
442                      ~pattern:(None, [], Some (PEH.pattern_of ~term:gty [new_t1']))
443                      (fun _ m u -> changed,m,u);
444                   EqualityTactics.rewrite_simpl_tac
445                      ~direction:`LeftToRight
446                      ~pattern:(PET.conclusion_pattern None)
447                      term [];
448                   EqualityTactics.reflexivity_tac   
449                ] in
450                PET.apply_tactic tac status
451            in
452            PET.mk_tactic tac
453         in
454         debug_print (lazy ("CUT: " ^ pp context cutted));  
455         PET.apply_tactic   
456           (T.thens ~start: (P.cut_tac cutted)
457                    ~continuations:[
458                       (qnify_tac ~first_time:false ~term:(C.Rel 1) ~map:id 
459                                  ~continuation:(after2 continuation succ map) 
460                       );  
461                       tac term] 
462           ) status
463    | _ -> raise exn_noneq
464  in
465   PET.mk_tactic injection_tac
466
467 (* ~term vive nel contesto della tattica una volta ~mappato
468  * ~continuation riceve la mappa assoluta
469  *)
470 and qnify_tac ~first_time ~map ~term ~continuation =
471  let are_convertible hd1 hd2 metasenv context = 
472    fst (CR.are_convertible ~metasenv context hd1 hd2 CicUniv.empty_ugraph)
473  in
474  let qnify_tac status = 
475   let (proof, goal) = status in
476   let _,metasenv,_subst, _,_, _ = proof in
477   let _,context,_ = CicUtil.lookup_meta goal metasenv in
478   let term = relocate_term map term in
479   debug_print (lazy ("\nqnify di: " ^ pp context term)); 
480   debug_print (lazy ("nel contesto:\n" ^ CicPp.ppcontext context));
481   let termty,_ = 
482     CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph
483   in
484   debug_print (lazy ("\nqnify su: " ^ pp context termty)); 
485   let tac = match termty with
486     | C.Appl [(C.MutInd (equri, 0, [])) ; tty ; t1 ; t2] 
487       when LibraryObjects.is_eq_URI equri -> begin
488         match (CR.whd ~delta:true context tty) with
489         | C.MutInd _
490         | C.Appl (C.MutInd _ :: _) -> 
491            begin match t1,t2 with
492             | C.MutConstruct _,
493               C.MutConstruct _
494               when t1 = t2 ->
495                 T.then_ ~start:(clear_term first_time context term)
496                         ~continuation:(continuation ~map)
497             | C.Appl (C.MutConstruct _ as mc1 :: applist1),
498               C.Appl (C.MutConstruct _ as mc2 :: applist2)
499               when mc1 = mc2 ->
500                 let rec traverse_list first_time i l1 l2 = 
501                    match l1, l2 with
502                       | [], [] ->
503                          fun ~map:aftermap ->
504                             T.then_ ~start:(clear_term first_time context term)
505                                     ~continuation:(after continuation aftermap map)
506                       | hd1 :: tl1, hd2 :: tl2 -> 
507                         if are_convertible hd1 hd2 metasenv context then
508                            traverse_list first_time (succ i) tl1 tl2
509                         else
510                            injection_tac ~i ~term ~continuation:
511                               (traverse_list false (succ i) tl1 tl2)
512                       | _ -> assert false 
513                       (* i 2 termini hanno in testa lo stesso costruttore, 
514                        * ma applicato a un numero diverso di termini *)
515                 in
516                   traverse_list first_time 1 applist1 applist2 ~map:id
517             | C.MutConstruct (_,_,consno1,ens1),
518               C.MutConstruct (_,_,consno2,ens2)
519             | C.MutConstruct (_,_,consno1,ens1),
520               C.Appl ((C.MutConstruct (_,_,consno2,ens2))::_)
521             | C.Appl ((C.MutConstruct (_,_,consno1,ens1))::_),
522               C.MutConstruct (_,_,consno2,ens2)
523             | C.Appl ((C.MutConstruct (_,_,consno1,ens1))::_),
524               C.Appl ((C.MutConstruct (_,_,consno2,ens2))::_)
525               when (consno1 <> consno2) || (ens1 <> ens2) -> 
526                 discriminate_tac ~term
527             | _ when not first_time -> continuation ~map
528             | _ (* when first_time *) -> 
529                T.then_ ~start:(simpl_in_term context term)
530                        ~continuation:(qnify_tac ~first_time:false ~term ~map ~continuation)
531            end
532         | _ when not first_time -> continuation ~map
533         | _ (* when first_time *) -> raise exn_nonproj
534         end 
535     | _ -> raise exn_nonproj
536   in  
537     PET.apply_tactic tac status
538  in 
539    PET.mk_tactic qnify_tac
540
541 (* destruct performs either injection or discriminate *)
542 (* equivalent to Coq's "analyze equality"             *)
543 let destruct_tac =
544  qnify_tac
545   ~first_time:true ~map:id ~continuation:(fun ~map -> T.id_tac)