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