]> matita.cs.unibo.it Git - helm.git/blob - components/library/librarySync.ml
Added inversion principle creation for inductive predicates.
[helm.git] / components / library / librarySync.ml
1 (* Copyright (C) 2004-2005, 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 exception AlreadyDefined of UriManager.uri
29
30 let auxiliary_lemmas_hashtbl = UriManager.UriHashtbl.create 29
31
32 (* uri |-->  (derived_coercions_in_the_coercion_DB, derived_coercions_in_lib)
33  * 
34  * in case of remove_coercion uri, the first component is removed from the
35  * coercion DB, while the second is passed to remove_obj (and is not [] only if
36  * add_coercion is called with add_composites 
37  * *)
38 let coercion_hashtbl = UriManager.UriHashtbl.create 3
39
40 let uris_of_obj uri =
41  let innertypesuri = UriManager.innertypesuri_of_uri uri in
42  let bodyuri = UriManager.bodyuri_of_uri uri in
43  let univgraphuri = UriManager.univgraphuri_of_uri uri in
44   innertypesuri,bodyuri,univgraphuri
45
46 let paths_and_uris_of_obj uri ~basedir =
47   let basedir = basedir ^ "/xml" in
48   let innertypesuri, bodyuri, univgraphuri = uris_of_obj uri in
49   let innertypesfilename = Str.replace_first (Str.regexp "^cic:") ""
50         (UriManager.string_of_uri innertypesuri) ^ ".xml.gz" in
51   let innertypespath = basedir ^ "/" ^ innertypesfilename in
52   let xmlfilename = Str.replace_first (Str.regexp "^cic:/") ""
53         (UriManager.string_of_uri uri) ^ ".xml.gz" in
54   let xmlpath = basedir ^ "/" ^ xmlfilename in
55   let xmlbodyfilename = Str.replace_first (Str.regexp "^cic:/") ""
56         (UriManager.string_of_uri uri) ^ ".body.xml.gz" in
57   let xmlbodypath = basedir ^ "/" ^  xmlbodyfilename in
58   let xmlunivgraphfilename = Str.replace_first (Str.regexp "^cic:/") ""
59         (UriManager.string_of_uri univgraphuri) ^ ".xml.gz" in
60   let xmlunivgraphpath = basedir ^ "/" ^ xmlunivgraphfilename in
61   xmlpath, xmlbodypath, innertypespath, bodyuri, innertypesuri, 
62   xmlunivgraphpath, univgraphuri
63
64 let save_object_to_disk ~basedir uri obj ugraph univlist =
65   let ensure_path_exists path =
66     let dir = Filename.dirname path in
67     HExtlib.mkdir dir
68   in
69   (* generate annobj, ids_to_inner_sorts and ids_to_inner_types *)
70   let annobj = Cic2acic.plain_acic_object_of_cic_object obj in 
71   (* prepare XML *)
72   let xml, bodyxml =
73    Cic2Xml.print_object
74     uri ?ids_to_inner_sorts:None ~ask_dtd_to_the_getter:false annobj 
75   in
76   let xmlpath, xmlbodypath, innertypespath, bodyuri, innertypesuri, 
77       xmlunivgraphpath, univgraphuri = 
78     paths_and_uris_of_obj uri basedir 
79   in
80   List.iter HExtlib.mkdir (List.map Filename.dirname [xmlpath]);
81   (* now write to disk *)
82   ensure_path_exists xmlpath;
83   Xml.pp ~gzip:true xml (Some xmlpath);
84   CicUniv.write_xml_of_ugraph xmlunivgraphpath ugraph univlist;
85   (* we return a list of uri,path we registered/created *)
86   (uri,xmlpath) ::
87   (univgraphuri,xmlunivgraphpath) ::
88     (* now the optional body, both write and register *)
89     (match bodyxml,bodyuri with
90        None,None -> []
91      | Some bodyxml,Some bodyuri->
92          ensure_path_exists xmlbodypath;
93          Xml.pp ~gzip:true bodyxml (Some xmlbodypath);
94          [bodyuri, xmlbodypath]
95      | _-> assert false) 
96
97
98 let typecheck_obj =
99  let profiler = HExtlib.profile "add_obj.typecheck_obj" in
100   fun uri obj -> profiler.HExtlib.profile (CicTypeChecker.typecheck_obj uri) obj
101
102 let index_obj =
103  let profiler = HExtlib.profile "add_obj.index_obj" in
104   fun ~dbd ~uri ->
105    profiler.HExtlib.profile (fun uri -> MetadataDb.index_obj ~dbd ~uri) uri
106
107 let add_single_obj uri obj refinement_toolkit ~basedir =
108   let module RT = RefinementTool in
109   let obj = 
110     if (*List.mem `Generated (CicUtil.attributes_of_obj obj) &&*)
111        not (CoercGraph.is_a_coercion (Cic.Const (uri, [])))
112     then
113       refinement_toolkit.RT.pack_coercion_obj obj
114     else
115       obj 
116   in
117   let dbd = LibraryDb.instance () in
118   if CicEnvironment.in_library uri then
119     raise (AlreadyDefined uri)
120   else begin
121     (*CicUniv.reset_spent_time ();
122     let before = Unix.gettimeofday () in*)
123     typecheck_obj uri obj; (* 1 *)
124     (*let after = Unix.gettimeofday () in
125     let univ_time = CicUniv.get_spent_time () in
126     let total_time = after -. before in
127     prerr_endline 
128       (Printf.sprintf "QED: %%univ = %2.5f, total = %2.5f, univ = %2.5f, %s\n" 
129       (univ_time *. 100. /. total_time) (total_time) (univ_time)
130       (UriManager.name_of_uri uri));*)
131     let _, ugraph, univlist = 
132       CicEnvironment.get_cooked_obj_with_univlist CicUniv.empty_ugraph uri in
133     try 
134       index_obj ~dbd ~uri; (* 2 must be in the env *)
135       try
136         (*3*)
137         let new_stuff = save_object_to_disk ~basedir uri obj ugraph univlist in
138         try 
139          HLog.message
140           (Printf.sprintf "%s defined" (UriManager.string_of_uri uri))
141         with exc ->
142           List.iter HExtlib.safe_remove (List.map snd new_stuff); (* -3 *)
143           raise exc
144       with exc ->
145         ignore(LibraryDb.remove_uri uri); (* -2 *)
146         raise exc
147     with exc ->
148       CicEnvironment.remove_obj uri; (* -1 *)
149     raise exc
150   end
151
152 let remove_single_obj uri =
153   let derived_uris_of_uri uri =
154    let innertypesuri, bodyuri, univgraphuri = uris_of_obj uri in
155     innertypesuri::univgraphuri::(match bodyuri with None -> [] | Some u -> [u])
156   in
157   let to_remove =
158     uri :: 
159     (if UriManager.uri_is_ind uri then LibraryDb.xpointers_of_ind uri else []) @
160     derived_uris_of_uri uri
161   in   
162   List.iter 
163     (fun uri -> 
164       (try
165         let file = Http_getter.resolve' uri in
166          HExtlib.safe_remove file;
167          HExtlib.rmdir_descend (Filename.dirname file)
168       with Http_getter_types.Key_not_found _ -> ());
169       ignore (LibraryDb.remove_uri uri);
170       (*CoercGraph.remove_coercion uri;*)
171       CicEnvironment.remove_obj uri)
172   to_remove
173
174 (*** GENERATION OF AUXILIARY LEMMAS ***)
175
176 let generate_elimination_principles ~basedir uri refinement_toolkit =
177   let uris = ref [] in
178   let elim sort =
179     try
180       let uri,obj = CicElim.elim_of ~sort uri 0 in
181        add_single_obj uri obj refinement_toolkit ~basedir;
182        uris := uri :: !uris
183     with CicElim.Can_t_eliminate -> ()
184   in
185   try
186     List.iter elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
187     !uris
188   with exn ->
189    List.iter remove_single_obj !uris;
190    raise exn
191
192 (* COERCIONS ***********************************************************)
193   
194 let remove_all_coercions () =
195   UriManager.UriHashtbl.clear coercion_hashtbl;
196   CoercDb.remove_coercion (fun (_,_,u1) -> true)
197
198 let add_coercion ~basedir ~add_composites refinement_toolkit uri =
199   let coer_ty,_ =
200     let coer = CicUtil.term_of_uri uri in
201     CicTypeChecker.type_of_aux' [] [] coer CicUniv.empty_ugraph 
202   in
203   (* we have to get the source and the tgt type uri
204    * in Coq syntax we have already their names, but
205    * since we don't support Funclass and similar I think
206    * all the coercion should be of the form
207    * (A:?)(B:?)T1->T2
208    * So we should be able to extract them from the coercion type
209    * 
210    * Currently only (_:T1)T2 is supported.
211    * should we saturate it with metas in case we insert it?
212    * 
213    *)
214   let extract_last_two_p ty =
215     let rec aux = function
216       | Cic.Prod( _, _, ((Cic.Prod _) as t)) -> 
217           aux t
218       | Cic.Prod( _, src, tgt) -> src, tgt
219       | _ -> assert false
220     in
221     aux ty
222   in
223   let ty_src, ty_tgt = extract_last_two_p coer_ty in
224   let src_carr = CoercDb.coerc_carr_of_term (CicReduction.whd [] ty_src) in
225   let tgt_carr = CoercDb.coerc_carr_of_term (CicReduction.whd [] ty_tgt) in
226   let new_coercions = 
227     CicCoercion.close_coercion_graph refinement_toolkit src_carr tgt_carr uri in
228   let composite_uris = List.map (fun (_,_,uri,_) -> uri) new_coercions in
229   (* update the DB *)
230   List.iter 
231     (fun (src,tgt,uri,_) -> CoercDb.add_coercion (src,tgt,uri)) 
232       new_coercions;
233   CoercDb.add_coercion (src_carr, tgt_carr, uri);
234   (* add the composites obj and they eventual lemmas *)
235   let lemmas = 
236     if add_composites then
237       List.fold_left
238         (fun acc (_,_,uri,obj) -> 
239           add_single_obj ~basedir uri obj refinement_toolkit;
240           uri::acc) 
241         composite_uris new_coercions
242     else
243       []
244   in
245   (* store that composite_uris are related to uri. the first component is the
246    * stuff in the DB while the second is stuff for remove_obj *)
247   (* 
248      prerr_endline ("adding: " ^ 
249        string_of_bool add_composites ^ UriManager.string_of_uri uri);
250      List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
251       composite_uris; 
252   *)
253   UriManager.UriHashtbl.add coercion_hashtbl uri 
254     (composite_uris,if add_composites then composite_uris else []);
255   lemmas
256
257 let remove_coercion uri =
258   try
259     let (composites_in_db, composites_in_lib) = 
260       UriManager.UriHashtbl.find coercion_hashtbl uri 
261     in
262     prerr_endline ("removing: " ^UriManager.string_of_uri uri);
263     List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
264       composites_in_db;
265     UriManager.UriHashtbl.remove coercion_hashtbl uri;
266     CoercDb.remove_coercion (fun (_,_,u) -> UriManager.eq uri u);
267     (* remove from the DB *) 
268     List.iter 
269       (fun u -> CoercDb.remove_coercion (fun (_,_,u1) -> UriManager.eq u u1))
270       composites_in_db;
271     (* remove composites from the lib *)
272     List.iter remove_single_obj composites_in_lib
273   with
274     Not_found -> () (* mhh..... *)
275     
276
277 let generate_projections ~basedir refinement_toolkit uri fields =
278  let uris = ref [] in
279  let projections = CicRecord.projections_of uri (List.map fst fields) in
280   try
281    List.iter2 
282     (fun (uri, name, bo) (_name, coercion) ->
283       try
284        let ty, ugraph =
285          CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph in
286        let attrs = [`Class `Projection; `Generated] in
287        let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
288         add_single_obj ~basedir uri obj refinement_toolkit;
289         let composites = 
290          if coercion then
291             add_coercion ~basedir ~add_composites:true refinement_toolkit uri
292           else  
293             []
294         in
295         uris := uri :: composites @ !uris
296       with
297          CicTypeChecker.TypeCheckerFailure s ->
298           HLog.message
299            ("Unable to create projection " ^ name ^ " cause: " ^ Lazy.force s);
300        | CicEnvironment.Object_not_found uri ->
301           let depend = UriManager.name_of_uri uri in
302            HLog.message
303             ("Unable to create projection " ^ name ^ " because it requires " ^
304                depend)
305     ) projections fields;
306    !uris
307   with exn ->
308    List.iter remove_single_obj !uris;
309    raise exn
310
311
312 let build_inversion_principle = ref (fun a b -> assert false);;
313
314 let generate_inversion refinement_toolkit ~basedir uri obj =
315  match !build_inversion_principle uri obj with
316     None -> []
317   | Some (ind_uri,ind_obj) ->
318      add_single_obj ind_uri ind_obj refinement_toolkit ~basedir;
319      [ind_uri]
320
321
322 let add_obj refinement_toolkit uri obj ~basedir =
323  add_single_obj uri obj refinement_toolkit ~basedir;
324  let uris = ref [] in
325  try
326   begin
327    match obj with
328     | Cic.Constant _ -> ()
329     | Cic.InductiveDefinition (_,_,_,attrs) ->
330         uris := !uris @ 
331           generate_elimination_principles ~basedir uri refinement_toolkit;
332         uris := !uris @ generate_inversion refinement_toolkit ~basedir uri obj;
333         let rec get_record_attrs =
334           function
335           | [] -> None
336           | (`Class (`Record fields))::_ -> Some fields
337           | _::tl -> get_record_attrs tl
338         in
339          (match get_record_attrs attrs with
340          | None -> () (* not a record *)
341          | Some fields ->
342             uris := !uris @ 
343               (generate_projections ~basedir refinement_toolkit uri fields))
344     | Cic.CurrentProof _
345     | Cic.Variable _ -> assert false
346   end;
347   UriManager.UriHashtbl.add auxiliary_lemmas_hashtbl uri !uris;
348   !uris
349  with exn ->
350   List.iter remove_single_obj !uris;
351   raise exn
352
353 let remove_obj uri =
354  let uris =
355   try
356    let res = UriManager.UriHashtbl.find auxiliary_lemmas_hashtbl uri in
357     UriManager.UriHashtbl.remove auxiliary_lemmas_hashtbl uri;
358     res
359   with
360     Not_found -> [] (*assert false*)
361  in
362   List.iter remove_single_obj (uri::uris)
363