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