]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/library/cicElim.ml
Generation of auxiliary lemmas for inductive types and records moved
[helm.git] / helm / ocaml / library / cicElim.ml
1 (* Copyright (C) 2004, 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://helm.cs.unibo.it/
24  *)
25
26 open Printf
27
28 exception Elim_failure of string Lazy.t
29 exception Can_t_eliminate
30
31 let debug_print = fun _ -> ()
32 (*let debug_print s = prerr_endline (Lazy.force s) *)
33
34 let counter = ref ~-1 ;;
35
36 let fresh_binder () =  Cic.Name "matita_dummy"
37 (*
38  incr counter;
39  Cic.Name ("e" ^ string_of_int !counter) *)
40
41   (** verifies if a given inductive type occurs in a term in target position *)
42 let rec recursive uri typeno = function
43   | Cic.Prod (_, _, target) -> recursive uri typeno target
44   | Cic.MutInd (uri', typeno', [])
45   | Cic.Appl (Cic.MutInd  (uri', typeno', []) :: _) ->
46       UriManager.eq uri uri' && typeno = typeno'
47   | _ -> false
48
49   (** given a list of constructor types, return true if at least one of them is
50   * recursive, false otherwise *)
51 let recursive_type uri typeno constructors =
52   let rec aux = function
53     | Cic.Prod (_, src, tgt) -> recursive uri typeno src || aux tgt
54     | _ -> false
55   in
56   List.exists (fun (_, ty) -> aux ty) constructors
57
58 let unfold_appl = function
59   | Cic.Appl ((Cic.Appl args) :: tl) -> Cic.Appl (args @ tl)
60   | t -> t
61
62 let rec split l n =
63  match (l,n) with
64     (l,0) -> ([], l)
65   | (he::tl, n) -> let (l1,l2) = split tl (n-1) in (he::l1,l2)
66   | (_,_) -> assert false
67
68   (** build elimination principle part related to a single constructor
69   * @param paramsno number of Prod to ignore in this constructor (i.e. number of
70   * inductive parameters)
71   * @param dependent true if we are in the dependent case (i.e. sort <> Prop) *)
72 let rec delta (uri, typeno) dependent paramsno consno t p args =
73   match t with
74   | Cic.MutInd (uri', typeno', []) when
75     UriManager.eq uri uri' && typeno = typeno' ->
76       if dependent then
77         (match args with
78         | [] -> assert false
79         | [arg] -> unfold_appl (Cic.Appl [p; arg])
80         | _ -> unfold_appl (Cic.Appl [p; unfold_appl (Cic.Appl args)]))
81       else
82         p
83   | Cic.Appl (Cic.MutInd (uri', typeno', []) :: tl) when
84     UriManager.eq uri uri' && typeno = typeno' ->
85       let (lparams, rparams) = split tl paramsno in
86       if dependent then
87         (match args with
88         | [] -> assert false
89         | [arg] -> unfold_appl (Cic.Appl (p :: rparams @ [arg]))
90         | _ ->
91             unfold_appl (Cic.Appl (p ::
92               rparams @ [unfold_appl (Cic.Appl args)])))
93       else  (* non dependent *)
94         (match rparams with
95         | [] -> p
96         | _ -> Cic.Appl (p :: rparams))
97   | Cic.Prod (binder, src, tgt) ->
98       if recursive uri typeno src then
99         let args = List.map (CicSubstitution.lift 2) args in
100         let phi =
101           let src = CicSubstitution.lift 1 src in
102           delta (uri, typeno) dependent paramsno consno src
103             (CicSubstitution.lift 1 p) [Cic.Rel 1]
104         in
105         let tgt = CicSubstitution.lift 1 tgt in
106         Cic.Prod (fresh_binder (), src,
107           Cic.Prod (Cic.Anonymous, phi,
108             delta (uri, typeno) dependent paramsno consno tgt
109               (CicSubstitution.lift 2 p) (args @ [Cic.Rel 2])))
110       else  (* non recursive *)
111         let args = List.map (CicSubstitution.lift 1) args in
112         Cic.Prod (fresh_binder (), src,
113           delta (uri, typeno) dependent paramsno consno tgt
114             (CicSubstitution.lift 1 p) (args @ [Cic.Rel 1]))
115   | _ -> assert false
116
117 let rec strip_left_params consno leftno = function
118   | t when leftno = 0 -> t (* no need to lift, the term is (hopefully) closed *)
119   | Cic.Prod (_, _, tgt) (* when leftno > 0 *) ->
120       (* after stripping the parameters we lift of consno. consno is 1 based so,
121       * the first constructor will be lifted by 1 (for P), the second by 2 (1
122       * for P and 1 for the 1st constructor), and so on *)
123       if leftno = 1 then
124         CicSubstitution.lift consno tgt
125       else
126         strip_left_params consno (leftno - 1) tgt
127   | _ -> assert false
128
129 let delta (ury, typeno) dependent paramsno consno t p args =
130   let t = strip_left_params consno paramsno t in
131   delta (ury, typeno) dependent paramsno consno t p args
132
133 let rec add_params binder indno ty eliminator =
134   if indno = 0 then
135     eliminator
136   else
137     match ty with
138     | Cic.Prod (name, src, tgt) ->
139        let name =
140         match name with
141            Cic.Name _ -> name
142          | Cic.Anonymous -> fresh_binder ()
143        in
144         binder name src (add_params binder (indno - 1) tgt eliminator)
145     | _ -> assert false
146
147 let rec mk_rels consno = function
148   | 0 -> []
149   | n -> Cic.Rel (n+consno) :: mk_rels consno (n-1)
150
151 let rec strip_pi = function
152   | Cic.Prod (_, _, tgt) -> strip_pi tgt
153   | t -> t
154
155 let rec count_pi = function
156   | Cic.Prod (_, _, tgt) -> count_pi tgt + 1
157   | t -> 0
158
159 let rec type_of_p sort dependent leftno indty = function
160   | Cic.Prod (n, src, tgt) when leftno = 0 ->
161       let n =
162        if dependent then 
163         match n with
164            Cic.Name _ -> n
165          | Cic.Anonymous -> fresh_binder ()
166        else
167         n
168       in
169        Cic.Prod (n, src, type_of_p sort dependent leftno indty tgt)
170   | Cic.Prod (_, _, tgt) -> type_of_p sort dependent (leftno - 1) indty tgt
171   | t ->
172       if dependent then
173         Cic.Prod (Cic.Anonymous, indty, Cic.Sort sort)
174       else
175         Cic.Sort sort
176
177 let rec add_right_pi dependent strip liftno liftfrom rightno indty = function
178   | Cic.Prod (_, src, tgt) when strip = 0 ->
179       Cic.Prod (fresh_binder (),
180         CicSubstitution.lift_from liftfrom liftno src,
181         add_right_pi dependent strip liftno (liftfrom + 1) rightno indty tgt)
182   | Cic.Prod (_, _, tgt) ->
183       add_right_pi dependent (strip - 1) liftno liftfrom rightno indty tgt
184   | t ->
185       if dependent then
186         Cic.Prod (fresh_binder (),
187           CicSubstitution.lift_from (rightno + 1) liftno indty,
188           Cic.Appl (Cic.Rel (1 + liftno + rightno) :: mk_rels 0 (rightno + 1)))
189       else
190         Cic.Prod (Cic.Anonymous,
191           CicSubstitution.lift_from (rightno + 1) liftno indty,
192           if rightno = 0 then
193             Cic.Rel (1 + liftno + rightno)
194           else
195             Cic.Appl (Cic.Rel (1 + liftno + rightno) :: mk_rels 1 rightno))
196
197 let rec add_right_lambda dependent strip liftno liftfrom rightno indty case =
198 function
199   | Cic.Prod (_, src, tgt) when strip = 0 ->
200       Cic.Lambda (fresh_binder (),
201         CicSubstitution.lift_from liftfrom liftno src,
202         add_right_lambda dependent strip liftno (liftfrom + 1) rightno indty
203           case tgt)
204   | Cic.Prod (_, _, tgt) ->
205       add_right_lambda true (strip - 1) liftno liftfrom rightno indty
206         case tgt
207   | t ->
208       Cic.Lambda (fresh_binder (),
209         CicSubstitution.lift_from (rightno + 1) liftno indty, case)
210
211 let rec branch (uri, typeno) insource paramsno t fix head args =
212   match t with
213   | Cic.MutInd (uri', typeno', []) when
214     UriManager.eq uri uri' && typeno = typeno' ->
215       if insource then
216         (match args with
217         | [arg] -> Cic.Appl (fix :: args)
218         | _ -> Cic.Appl (head :: [Cic.Appl args]))
219       else
220         (match args with
221         | [] -> head
222         | _ -> Cic.Appl (head :: args))
223   | Cic.Appl (Cic.MutInd (uri', typeno', []) :: tl) when
224     UriManager.eq uri uri' && typeno = typeno' ->
225       if insource then
226         let (lparams, rparams) = split tl paramsno in
227         match args with
228         | [arg] -> Cic.Appl (fix :: rparams @ args)
229         | _ -> Cic.Appl (fix :: rparams @ [Cic.Appl args])
230       else
231         (match args with
232         | [] -> head
233         | _ -> Cic.Appl (head :: args))
234   | Cic.Prod (binder, src, tgt) ->
235       if recursive uri typeno src then
236         let args = List.map (CicSubstitution.lift 1) args in
237         let phi =
238           let fix = CicSubstitution.lift 1 fix in
239           let src = CicSubstitution.lift 1 src in
240           branch (uri, typeno) true paramsno src fix head [Cic.Rel 1]
241         in
242         Cic.Lambda (fresh_binder (), src,
243           branch (uri, typeno) insource paramsno tgt
244             (CicSubstitution.lift 1 fix) (CicSubstitution.lift 1 head)
245             (args @ [Cic.Rel 1; phi]))
246       else  (* non recursive *)
247         let args = List.map (CicSubstitution.lift 1) args in
248         Cic.Lambda (fresh_binder (), src,
249           branch (uri, typeno) insource paramsno tgt
250           (CicSubstitution.lift 1 fix) (CicSubstitution.lift 1 head)
251             (args @ [Cic.Rel 1]))
252   | _ -> assert false
253
254 let branch (uri, typeno) insource liftno paramsno t fix head args =
255   let t = strip_left_params liftno paramsno t in
256   branch (uri, typeno) insource paramsno t fix head args
257
258 let elim_of ~sort uri typeno =
259   counter := ~-1;
260   let (obj, univ) = (CicEnvironment.get_obj CicUniv.empty_ugraph uri) in
261   match obj with
262   | Cic.InductiveDefinition (indTypes, params, leftno, _) ->
263       let (name, inductive, ty, constructors) =
264         try
265           List.nth indTypes typeno
266         with Failure _ -> assert false
267       in
268       let paramsno = count_pi ty in (* number of (left or right) parameters *)
269       let rightno = paramsno - leftno in
270       let dependent = (strip_pi ty <> Cic.Sort Cic.Prop) in
271       let head =
272        match strip_pi ty with
273           Cic.Sort s -> s
274         | _ -> assert false
275       in
276       let conslen = List.length constructors in
277       let consno = ref (conslen + 1) in
278       if
279        not
280         (CicTypeChecker.check_allowed_sort_elimination uri typeno head sort)
281       then
282        raise Can_t_eliminate;
283       let indty =
284         let indty = Cic.MutInd (uri, typeno, []) in
285         if paramsno = 0 then
286           indty
287         else
288           Cic.Appl (indty :: mk_rels 0 paramsno)
289       in
290       let mk_constructor consno =
291         let constructor = Cic.MutConstruct (uri, typeno, consno, []) in
292         if leftno = 0 then
293           constructor
294         else
295           Cic.Appl (constructor :: mk_rels consno leftno)
296       in
297       let p_ty = type_of_p sort dependent leftno indty ty in
298       let final_ty =
299         add_right_pi dependent leftno (conslen + 1) 1 rightno indty ty
300       in
301       let eliminator_type =
302         let cic =
303           Cic.Prod (Cic.Name "P", p_ty,
304             (List.fold_right
305               (fun (_, constructor) acc ->
306                 decr consno;
307                 let p = Cic.Rel !consno in
308                 Cic.Prod (Cic.Anonymous,
309                   (delta (uri, typeno) dependent leftno !consno
310                     constructor p [mk_constructor !consno]),
311                   acc))
312               constructors final_ty))
313         in
314         add_params (fun b s t -> Cic.Prod (b, s, t)) leftno ty cic
315       in
316       let consno = ref (conslen + 1) in
317       let eliminator_body =
318         let fix = Cic.Rel (rightno + 2) in
319         let is_recursive = recursive_type uri typeno constructors in
320         let recshift = if is_recursive then 1 else 0 in
321         let (_, branches) =
322           List.fold_right
323             (fun (_, ty) (shift, branches) ->
324               let head = Cic.Rel (rightno + shift + 1 + recshift) in
325               let b =
326                 branch (uri, typeno) false
327                   (rightno + conslen + 2 + recshift) leftno ty fix head []
328               in
329               (shift + 1,  b :: branches))
330             constructors (1, [])
331         in
332         let shiftno  = conslen + rightno + 2 + recshift in
333         let outtype =
334          if dependent then
335           Cic.Rel shiftno
336          else
337           let head =
338            if rightno = 0 then
339             CicSubstitution.lift 1 (Cic.Rel shiftno)
340            else
341             Cic.Appl
342              ((CicSubstitution.lift (rightno + 1) (Cic.Rel shiftno)) ::
343               mk_rels 1 rightno)
344           in
345            add_right_lambda true leftno shiftno 1 rightno indty head ty
346         in
347         let mutcase =
348           Cic.MutCase (uri, typeno, outtype, Cic.Rel 1, branches)
349         in
350         let body =
351           if is_recursive then
352             let fixfun =
353               add_right_lambda dependent leftno (conslen + 2) 1 rightno
354                 indty mutcase ty
355             in
356             (* rightno is the decreasing argument, i.e. the argument of
357              * inductive type *)
358             Cic.Fix (0, ["f", rightno, final_ty, fixfun])
359           else
360             add_right_lambda dependent leftno (conslen + 1) 1 rightno indty
361               mutcase ty
362         in
363         let cic =
364           Cic.Lambda (Cic.Name "P", p_ty,
365             (List.fold_right
366               (fun (_, constructor) acc ->
367                 decr consno;
368                 let p = Cic.Rel !consno in
369                 Cic.Lambda (fresh_binder (),
370                   (delta (uri, typeno) dependent leftno !consno
371                     constructor p [mk_constructor !consno]),
372                   acc))
373               constructors body))
374         in
375         add_params (fun b s t -> Cic.Lambda (b, s, t)) leftno ty cic
376       in
377 (*
378 debug_print (lazy (CicPp.ppterm eliminator_type));
379 debug_print (lazy (CicPp.ppterm eliminator_body));
380 *)
381       let eliminator_type = 
382         FreshNamesGenerator.mk_fresh_names [] [] [] eliminator_type in
383       let eliminator_body = 
384         FreshNamesGenerator.mk_fresh_names [] [] [] eliminator_body in
385 (*
386 debug_print (lazy (CicPp.ppterm eliminator_type));
387 debug_print (lazy (CicPp.ppterm eliminator_body));
388 *)
389       let (computed_type, ugraph) =
390         try
391           CicTypeChecker.type_of_aux' [] [] eliminator_body CicUniv.empty_ugraph
392         with CicTypeChecker.TypeCheckerFailure msg ->
393           raise (Elim_failure (lazy (sprintf 
394             "type checker failure while type checking:\n%s\nerror:\n%s"
395             (CicPp.ppterm eliminator_body) (Lazy.force msg))))
396       in
397       if not (fst (CicReduction.are_convertible []
398         eliminator_type computed_type ugraph))
399       then
400         raise (Failure (sprintf
401           "internal error: type mismatch on eliminator type\n%s\n%s"
402           (CicPp.ppterm eliminator_type) (CicPp.ppterm computed_type)));
403       let suffix =
404         match sort with
405         | Cic.Prop -> "_ind"
406         | Cic.Set -> "_rec"
407         | Cic.Type _ -> "_rect"
408         | _ -> assert false
409       in
410       let name = UriManager.name_of_uri uri ^ suffix in
411       let buri = UriManager.buri_of_uri uri in
412       let uri = UriManager.uri_of_string (buri ^ "/" ^ name ^ ".con") in
413       let obj_attrs = [`Class (`Elim sort); `Generated] in
414        uri,
415        Cic.Constant (name, Some eliminator_body, eliminator_type, [], obj_attrs)
416   | _ ->
417       failwith (sprintf "not an inductive definition (%s)"
418         (UriManager.string_of_uri uri))
419