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