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