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