]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/discriminationTactics.ml
Several bugs fixed in discriminate.
[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 let debug_print = fun _ -> ()
29
30 let rec injection_tac ~first_time ~term ~liftno ~continuation =
31  let injection_tac ~term status = 
32   let (proof, goal) = status in
33   let module C = Cic in
34   let module U = UriManager in
35   let module P = PrimitiveTactics in
36   let module T = Tacticals in
37   let _,metasenv,_,_ = proof in
38   let _,context,_ = CicUtil.lookup_meta goal metasenv in
39   let term = CicSubstitution.lift liftno term in
40   let termty,_ = (* TASSI: FIXME *)
41     CicTypeChecker.type_of_aux' metasenv context term CicUniv.empty_ugraph
42   in
43     ProofEngineTypes.apply_tactic
44      (match termty with
45          (C.Appl [(C.MutInd (equri, 0, [])) ; tty ; t1 ; t2])
46             when LibraryObjects.is_eq_URI equri ->
47           begin
48            match tty with
49               (C.MutInd (turi,typeno,exp_named_subst))
50             | (C.Appl (C.MutInd (turi,typeno,exp_named_subst)::_)) ->
51                begin
52                 match t1,t2 with
53                    ((C.MutConstruct (uri1,typeno1,consno1,exp_named_subst1)),
54                     (C.MutConstruct (uri2,typeno2,consno2,exp_named_subst2)))
55                       when (uri1 = uri2) && (typeno1 = typeno2) && 
56                     (consno1 = consno2) &&
57                     (exp_named_subst1 = exp_named_subst2)
58                    ->
59                     if first_time then
60                      raise
61                       (ProofEngineTypes.Fail (lazy "Injection: nothing to do"))
62                     else
63                      continuation ~liftno
64                  | C.Appl
65                     ((C.MutConstruct
66                        (uri1,typeno1,consno1,exp_named_subst1))::applist1),
67                    C.Appl
68                     ((C.MutConstruct
69                        (uri2,typeno2,consno2,exp_named_subst2))::applist2)
70                       when (uri1 = uri2) && (typeno1 = typeno2) &&
71                        (consno1 = consno2) &&
72                        (exp_named_subst1 = exp_named_subst2)
73                     ->
74                      let rec traverse_list i l1 l2 =
75                        match l1,l2 with
76                           [],[] ->
77                            if first_time then
78                             continuation
79                            else
80                             (match term with
81                                 C.Rel n ->
82                                  (match List.nth context (n-1) with
83                                      Some (C.Name id,_) ->
84                                       fun ~liftno ->
85                                        T.then_
86                                         ~start:
87                                           (ProofEngineStructuralRules.clear
88                                             ~hyps:[id])
89                                         ~continuation:(continuation ~liftno)
90                                    | _ -> assert false)
91                               | _ -> assert false)
92                         | hd1::tl1,hd2::tl2 -> 
93                            if
94                             fst
95                              (CicReduction.are_convertible ~metasenv
96                                context hd1 hd2 CicUniv.empty_ugraph)
97                            then
98                             traverse_list (i+1) tl1 tl2
99                            else
100                             injection1_tac ~i ~term
101                              ~continuation:(traverse_list (i+1) tl1 tl2)
102                         | _ -> raise (ProofEngineTypes.Fail (lazy "Discriminate: i 2 termini hanno in testa lo stesso costruttore, ma applicato a un numero diverso di termini. possibile???"))
103                      in
104                       traverse_list 1 applist1 applist2 ~liftno
105                  | ((C.MutConstruct (uri1,typeno1,consno1,exp_named_subst1)),
106                     (C.MutConstruct (uri2,typeno2,consno2,exp_named_subst2)))
107                  | ((C.MutConstruct (uri1,typeno1,consno1,exp_named_subst1)),
108                     (C.Appl ((C.MutConstruct (uri2,typeno2,consno2,exp_named_subst2))::_)))
109                  | ((C.Appl ((C.MutConstruct (uri1,typeno1,consno1,exp_named_subst1))::_)),
110                     (C.MutConstruct (uri2,typeno2,consno2,exp_named_subst2)))
111                  | ((C.Appl ((C.MutConstruct (uri1,typeno1,consno1,exp_named_subst1))::_)),
112                     (C.Appl ((C.MutConstruct (uri2,typeno2,consno2,exp_named_subst2))::_)))
113                       when (consno1 <> consno2) || (exp_named_subst1 <> exp_named_subst2) ->
114                     raise (ProofEngineTypes.Fail (lazy "Injection: not a projectable equality but a discriminable one"))
115                  | _ ->
116                    if first_time then
117                     raise (ProofEngineTypes.Fail (lazy "Injection: not a projectable equality"))
118                    else
119                     continuation ~liftno 
120                end
121             | _ ->
122               if first_time then
123                raise (ProofEngineTypes.Fail (lazy "Injection: not a projectable equality"))
124               else
125                continuation ~liftno 
126            end
127        | _ -> raise (ProofEngineTypes.Fail (lazy "Injection: not an equation"))
128      ) status
129  in 
130   ProofEngineTypes.mk_tactic (injection_tac ~term)
131
132 and injection1_tac ~term ~i ~liftno ~continuation =
133  let injection1_tac ~term ~i status =
134   let (proof, goal) = status in
135   (* precondizione: t1 e t2 hanno in testa lo stesso costruttore ma differiscono (o potrebbero differire?) nell'i-esimo parametro del costruttore *)
136    let module C = Cic in
137    let module S = CicSubstitution in
138    let module U = UriManager in
139    let module P = PrimitiveTactics in
140    let module T = Tacticals in
141    let term = CicSubstitution.lift liftno term in
142    let _,metasenv,_,_ = proof in
143    let _,context,_ = CicUtil.lookup_meta goal metasenv in
144    let termty,_ = (* TASSI: FIXME *)
145      CicTypeChecker.type_of_aux' metasenv context term CicUniv.empty_ugraph
146    in
147      match termty with (* an equality *)
148          (C.Appl [(C.MutInd (equri, 0, [])) ; tty ; t1 ; t2])
149              when LibraryObjects.is_eq_URI equri -> (
150            match tty with (* some inductive type *)
151               (C.MutInd (turi,typeno,exp_named_subst))
152             | (C.Appl (C.MutInd (turi,typeno,exp_named_subst)::_)) ->
153                let t1',t2',consno = (* sono i due sottotermini che differiscono *)
154                 match t1,t2 with
155                    ((C.Appl ((C.MutConstruct (uri1,typeno1,consno1,exp_named_subst1))::applist1)),
156                     (C.Appl ((C.MutConstruct (uri2,typeno2,consno2,exp_named_subst2))::applist2)))
157                       when (uri1 = uri2) && (typeno1 = typeno2) && (consno1 = consno2) && (exp_named_subst1 = exp_named_subst2) -> (* controllo ridondante *)
158                     (List.nth applist1 (i-1)),(List.nth applist2 (i-1)),consno2
159                  | _ -> assert false
160                in
161                 let tty',_ = 
162                   CicTypeChecker.type_of_aux' metasenv context t1' 
163                     CicUniv.empty_ugraph  in
164                 let patterns,outtype =
165                  match
166                   fst (CicEnvironment.get_obj CicUniv.empty_ugraph turi)
167                  with
168                     C.InductiveDefinition (ind_type_list,_,paramsno,_)->
169                      let _,_,_,constructor_list =
170                       List.nth ind_type_list typeno in
171                      let i_constr_id,_ =
172                       List.nth constructor_list (consno - 1) in
173                      let seed = ref 0 in
174                      let patterns =
175                       List.map
176                        (function (id,cty) ->
177                          let reduced_cty = CicReduction.whd context cty in
178                           let rec aux t k =
179                            match t with
180                               C.Prod (_,_,target) when k <= paramsno ->
181                                aux target (k+1)
182                             | C.Prod (binder,source,target) when k > paramsno ->
183                                let binder' =
184                                 match binder with
185                                    C.Name _ -> binder
186                                  | C.Anonymous ->
187                                     C.Name
188                                      (incr seed; "y" ^ string_of_int !seed)
189                                in
190                                 C.Lambda (binder',source,(aux target (k+1)))
191                             | _ ->
192                                let nr_param_constr = k - 1 - paramsno in
193                                 if id = i_constr_id
194                                  then C.Rel (k - i)
195                                  else S.lift (nr_param_constr + 1) t1' (* + 1 per liftare anche il lambda aggiunto esternamente al case *)
196                           in aux reduced_cty 1
197                        ) constructor_list in
198                      let outtype =
199                       let seed = ref 0 in
200                       let rec to_lambdas te head =
201                        match CicReduction.whd context te with
202                         | C.Prod (binder,so,ta) ->
203                            let binder' =
204                             match binder with
205                                C.Name _ -> binder
206                              | C.Anonymous ->
207                                 C.Name (incr seed; "d" ^ string_of_int !seed)
208                            in
209                             C.Lambda (binder',so,to_lambdas ta head)
210                         | _ -> head in
211                       let rec skip_prods n te =
212                        match n, CicReduction.whd context te with
213                           0, _ -> te
214                         | n, C.Prod (_,_,ta) -> skip_prods (n - 1) ta
215                         | _, _ -> assert false
216                       in
217                        let abstracted_tty =
218                         match CicSubstitution.lift (paramsno + 1) tty with
219                            C.MutInd _ as tty' -> tty'
220                          | C.Appl l ->
221                              let keep,abstract =
222                               HExtlib.split_nth (paramsno +1) l in
223                              let rec mk_rels =
224                               function
225                                  0 -> []
226                                | n -> C.Rel n :: (mk_rels (n - 1))
227                              in
228                               C.Appl (keep@mk_rels (List.length abstract))
229                          | _ -> assert false
230                        in
231                         match ind_type_list with
232                            [] -> assert false
233                          | (_,_,ty,_)::_ ->
234                             to_lambdas (skip_prods paramsno ty)
235                              (C.Lambda (C.Name "x", abstracted_tty,
236                                S.lift (2+paramsno) tty'))
237                       in
238                        patterns,outtype
239                   | _ -> raise (ProofEngineTypes.Fail (lazy "Discriminate: object is not an Inductive Definition: it's imposible"))
240                 in
241                 ProofEngineTypes.apply_tactic   
242                  (T.thens 
243                   ~start:
244                     (P.cut_tac
245                      (C.Appl [C.MutInd (equri,0,[]) ; tty' ; t1' ; t2']))
246                   ~continuations:
247                     [ injection_tac ~first_time:false ~liftno:0
248                        ~term:(C.Rel 1)
249                        (* here I need to lift all the continuations by 1;
250                           since I am setting back liftno to 0, I actually
251                           need to lift all the continuations by liftno + 1 *)
252                        ~continuation:
253                          (fun ~liftno:x ->
254                            continuation ~liftno:(liftno + 1 + x)) ;
255                       T.then_ 
256                        ~start:(ProofEngineTypes.mk_tactic 
257                          (fun status ->    
258                            let (proof, goal) = status in
259                            let _,metasenv,_,_ = proof in
260                             let _,context,gty =
261                              CicUtil.lookup_meta goal metasenv
262                             in
263                              let new_t1' = 
264                               match gty with 
265                                  (C.Appl (C.MutInd (_,_,_)::arglist)) -> 
266                                   List.nth arglist 1
267                                | _ ->
268                                  raise
269                                   (ProofEngineTypes.Fail
270                                     (lazy
271                                       "Injection: goal after cut is not correct"))
272                              in
273                               ProofEngineTypes.apply_tactic 
274                               (ReductionTactics.change_tac
275                                  ~pattern:(ProofEngineTypes.conclusion_pattern
276                                   (Some new_t1'))
277                                  (fun _ m u ->
278                                    C.Appl [
279                                     C.Lambda
280                                      (C.Name "x",
281                                        tty,
282                                        C.MutCase
283                                         (turi,typeno,outtype,C.Rel 1,patterns)) ;
284                                     t1],
285                                    m, u))
286                           status
287                          ))
288                        ~continuation:
289                          (T.then_
290                            ~start:
291                              (EqualityTactics.rewrite_simpl_tac
292                                ~direction:`LeftToRight
293                                ~pattern:(ProofEngineTypes.conclusion_pattern None)
294                                term)
295                            ~continuation:EqualityTactics.reflexivity_tac)
296                    ])     
297                   status
298             | _ -> raise (ProofEngineTypes.Fail (lazy "Injection: not an equality over elements of an inductive type"))
299            )
300         | _ -> raise (ProofEngineTypes.Fail (lazy "Injection: not an equality"))
301  in
302   ProofEngineTypes.mk_tactic (injection1_tac ~term ~i)
303 ;;
304
305 let injection_tac =
306  injection_tac ~first_time:true ~liftno:0 ~continuation:(fun ~liftno -> Tacticals.id_tac)
307 ;;
308
309 (* term ha tipo t1=t2; funziona solo se t1 e t2 hanno in testa costruttori
310 diversi *)
311
312 let discriminate'_tac ~term =
313  let module C = Cic in
314  let module U = UriManager in
315  let module P = PrimitiveTactics in
316  let module T = Tacticals in
317  let true_URI =
318   match LibraryObjects.true_URI () with
319      Some uri -> uri
320    | None -> raise (ProofEngineTypes.Fail (lazy "You need to register the default \"true\" definition first. Please use the \"default\" command")) in
321  let false_URI =
322   match LibraryObjects.false_URI () with
323      Some uri -> uri
324    | None -> raise (ProofEngineTypes.Fail (lazy "You need to register the default \"false\" definition first. Please use the \"default\" command")) in
325  let fail msg = raise (ProofEngineTypes.Fail (lazy ("Discriminate: " ^ msg))) in
326  let find_discriminating_consno t1 t2 =
327    let rec aux t1 t2 =
328      match t1, t2 with
329      | C.MutConstruct _, C.MutConstruct _ when t1 = t2 -> None
330      | C.Appl ((C.MutConstruct _ as constr1) :: args1),
331        C.Appl ((C.MutConstruct _ as constr2) :: args2)
332        when constr1 = constr2 ->
333          let rec aux_list l1 l2 =
334            match l1, l2 with
335            | [], [] -> None
336            | hd1 :: tl1, hd2 :: tl2 ->
337                (match aux hd1 hd2 with
338                | None -> aux_list tl1 tl2
339                | Some _ as res -> res)
340            | _ -> (* same constructor applied to a different number of args *)
341                assert false
342          in
343          aux_list args1 args2
344      | ((C.MutConstruct (_,_,consno1,subst1)),
345        (C.MutConstruct (_,_,consno2,subst2)))
346      | ((C.MutConstruct (_,_,consno1,subst1)),
347        (C.Appl ((C.MutConstruct (_,_,consno2,subst2)) :: _)))
348      | ((C.Appl ((C.MutConstruct (_,_,consno1,subst1)) :: _)),
349        (C.MutConstruct (_,_,consno2,subst2)))
350      | ((C.Appl ((C.MutConstruct (_,_,consno1,subst1)) :: _)),
351        (C.Appl ((C.MutConstruct (_,_,consno2,subst2)) :: _)))
352        when (consno1 <> consno2) || (subst1 <> subst2) ->
353          Some consno2
354      | _ -> fail "not a discriminable equality"
355    in
356    aux t1 t2
357  in
358  let mk_branches_and_outtype turi typeno consno context args =
359     (* a list of "True" except for the element in position consno which
360      * is "False" *)
361     match fst (CicEnvironment.get_obj CicUniv.empty_ugraph turi) with
362     | C.InductiveDefinition (ind_type_list,_,paramsno,_)  ->
363         let _,_,rty,constructor_list = List.nth ind_type_list typeno in 
364         let false_constr_id,_ = List.nth constructor_list (consno - 1) in
365         let branches =
366          List.map 
367            (fun (id,cty) ->
368              (* dubbio: e' corretto ridurre in questo context ??? *)
369              let red_ty = CicReduction.whd context cty in
370              let rec aux t k =
371                match t with
372                | C.Prod (_,_,target) when (k <= paramsno) ->
373                    CicSubstitution.subst (List.nth args (k-1))
374                      (aux target (k+1))
375                | C.Prod (binder,source,target) when (k > paramsno) ->
376                    C.Lambda (binder, source, (aux target (k+1)))
377                | _ -> 
378                    if (id = false_constr_id)
379                    then (C.MutInd(false_URI,0,[]))
380                    else (C.MutInd(true_URI,0,[]))
381              in
382              (CicSubstitution.lift 1 (aux red_ty 1)))
383            constructor_list in
384         let outtype =
385          let seed = ref 0 in
386          let rec mk_lambdas rev_left_args =
387           function
388              0, args, C.Prod (_,so,ta) ->
389               C.Lambda
390                (C.Name (incr seed; "x" ^ string_of_int !seed),
391                so,
392                mk_lambdas rev_left_args (0,args,ta))
393            | 0, args, C.Sort _ ->
394               let rec mk_rels =
395                function
396                   0 -> []
397                 | n -> C.Rel n :: mk_rels (n - 1) in
398               let argsno = List.length args in
399                C.Lambda
400                 (C.Name "x",
401                  (if argsno + List.length rev_left_args > 0 then
402                    C.Appl
403                     (C.MutInd (turi, typeno, []) ::
404                      (List.map
405                       (CicSubstitution.lift (argsno + 1))
406                       (List.rev rev_left_args)) @
407                      mk_rels argsno)
408                   else
409                    C.MutInd (turi,typeno,[])),
410                  C.Sort C.Prop)
411            | 0, _, _ -> assert false (* seriously screwed up *)
412            | n, he::tl, C.Prod (_,_,ta) ->
413               mk_lambdas (he::rev_left_args)(n-1,tl,CicSubstitution.subst he ta)
414            | n,_,_ ->
415               assert false (* we should probably reduce in some context *)
416          in
417           mk_lambdas [] (paramsno, args, rty)
418         in
419          branches, outtype 
420     | _ -> assert false
421  in
422  let discriminate'_tac ~term status = 
423   let (proof, goal) = status in
424   let _,metasenv,_,_ = proof in
425   let _,context,_ = CicUtil.lookup_meta goal metasenv in
426   let termty,_ = 
427     CicTypeChecker.type_of_aux' metasenv context term CicUniv.empty_ugraph
428   in
429   match termty with
430    | C.Appl [(C.MutInd (equri, 0, [])) ; tty ; t1 ; t2]
431      when LibraryObjects.is_eq_URI equri ->
432       let turi,typeno,exp_named_subst,args = 
433         match tty with
434         | (C.MutInd (turi,typeno,exp_named_subst)) ->
435             turi,typeno,exp_named_subst,[]
436         | (C.Appl (C.MutInd (turi,typeno,exp_named_subst)::args)) ->
437             turi,typeno,exp_named_subst,args
438         | _ -> fail "not a discriminable equality"
439       in
440       let consno =
441         match find_discriminating_consno t1 t2 with
442         | Some consno -> consno
443         | None -> fail "discriminating terms are structurally equal"
444       in
445       let branches,outtype =
446        mk_branches_and_outtype turi typeno consno context args
447       in
448       ProofEngineTypes.apply_tactic
449        (T.then_
450          ~start:(EliminationTactics.elim_type_tac (C.MutInd (false_URI, 0, [])))
451          ~continuation:
452            (T.then_
453              ~start:
454                (ReductionTactics.change_tac 
455                  ~pattern:(ProofEngineTypes.conclusion_pattern None)
456                  (fun _ m u ->
457                    C.Appl [
458                      C.Lambda ( C.Name "x", tty,
459                        C.MutCase (turi, typeno, outtype, (C.Rel 1), branches));
460                      t2 ],
461                    m, u))
462              ~continuation:
463                (T.then_
464                  ~start:
465                    (EqualityTactics.rewrite_simpl_tac
466                      ~direction:`RightToLeft
467                      ~pattern:(ProofEngineTypes.conclusion_pattern None)
468                      term)
469                  ~continuation:
470                    (IntroductionTactics.constructor_tac ~n:1)))) status
471     | _ -> fail "not an equality"
472   in
473   ProofEngineTypes.mk_tactic (discriminate'_tac ~term)
474
475 let discriminate_tac ~term = 
476  let discriminate_tac ~term status =
477   ProofEngineTypes.apply_tactic 
478   (Tacticals.then_
479     ~start:(* (injection_tac ~term) *) Tacticals.id_tac
480     ~continuation:(discriminate'_tac ~term)) (* NOOO!!! non term ma una (qualunque) delle nuove hyp introdotte da inject *)
481    status
482  in
483   ProofEngineTypes.mk_tactic (discriminate_tac ~term)