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