]> matita.cs.unibo.it Git - helm.git/blob - components/library/librarySync.ml
- components: composed coercions mus be generated with current base uri
[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 uris_to_remove =
161    if UriManager.uri_is_ind uri then LibraryDb.xpointers_of_ind uri else [uri]
162   in
163   let files_to_remove = uri :: derived_uris_of_uri uri in   
164   List.iter 
165    (fun uri -> 
166      (try
167        let file = Http_getter.resolve' ~writable:true uri in
168         HExtlib.safe_remove file;
169         HExtlib.rmdir_descend (Filename.dirname file)
170      with Http_getter_types.Key_not_found _ -> ());
171    ) files_to_remove ;
172   List.iter 
173    (fun uri -> 
174      ignore (LibraryDb.remove_uri uri);
175      (*CoercGraph.remove_coercion uri;*)
176    ) uris_to_remove ;
177   CicEnvironment.remove_obj uri
178
179 (*** GENERATION OF AUXILIARY LEMMAS ***)
180
181 let generate_elimination_principles uri refinement_toolkit =
182   let uris = ref [] in
183   let elim i =
184     let elim sort =
185       try
186         let uri,obj = CicElim.elim_of ~sort uri i in
187           add_single_obj uri obj refinement_toolkit;
188           uris := uri :: !uris
189       with CicElim.Can_t_eliminate -> ()
190     in
191       try
192         List.iter 
193           elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
194       with exn ->
195         List.iter remove_single_obj !uris;
196         raise exn 
197   in
198   let (obj, univ) = (CicEnvironment.get_obj CicUniv.empty_ugraph uri) in
199     match obj with
200       | Cic.InductiveDefinition (indTypes, _, _, _) ->
201           let counter = ref 0 in
202             List.iter (fun _ -> elim !counter; counter := !counter+1) indTypes;
203             !uris
204       | _  -> 
205           failwith (Printf.sprintf "not an inductive definition (%s)"
206                       (UriManager.string_of_uri uri))
207
208 (* COERCIONS ***********************************************************)
209   
210 let remove_all_coercions () =
211   UriManager.UriHashtbl.clear coercion_hashtbl;
212   CoercDb.remove_coercion (fun (_,_,u1) -> true)
213
214 let add_coercion ~add_composites refinement_toolkit uri arity baseuri =
215   let coer_ty,_ =
216     let coer = CicUtil.term_of_uri uri in
217     CicTypeChecker.type_of_aux' [] [] coer CicUniv.empty_ugraph 
218   in
219   (* we have to get the source and the tgt type uri
220    * in Coq syntax we have already their names, but
221    * since we don't support Funclass and similar I think
222    * all the coercion should be of the form
223    * (A:?)(B:?)T1->T2
224    * So we should be able to extract them from the coercion type
225    * 
226    * Currently only (_:T1)T2 is supported.
227    * should we saturate it with metas in case we insert it?
228    * 
229    *)
230   let spline2list ty =
231     let rec aux = function
232       | Cic.Prod( _, src, tgt) -> src::aux tgt
233       | t -> [t]
234     in
235     aux ty
236   in
237   let src_carr, tgt_carr = 
238     let list_remove_from_tail n l = 
239       let rec aux n = function
240         | hd::tl when n > 0 -> aux (n-1) tl
241         | l when n = 0 -> l
242         | _ -> assert false
243       in
244       aux n (List.rev l)
245     in
246     let types = spline2list coer_ty in
247     match arity, list_remove_from_tail arity types with
248     | 0,tgt::src::_ -> 
249         (* if ~delta is true, it is impossible to define an identity coercion *)
250         CoercDb.coerc_carr_of_term (CicReduction.whd ~delta:false [] src),
251         CoercDb.coerc_carr_of_term (CicReduction.whd ~delta:false [] tgt)
252     | n,_::src::_ -> 
253         CoercDb.coerc_carr_of_term (CicReduction.whd ~delta:false [] src),
254         CoercDb.Fun arity
255     | _ -> assert false    
256   in
257   let already_in = 
258      List.exists 
259       (fun (s,t,ul) -> 
260         List.exists 
261          (fun u -> 
262            UriManager.eq u uri && 
263            CoercDb.eq_carr s src_carr && 
264            CoercDb.eq_carr t tgt_carr) 
265          ul)
266       (CoercDb.to_list ())
267   in
268   if not add_composites then
269     (CoercDb.add_coercion (src_carr, tgt_carr, uri);[])
270   else
271     let new_coercions = 
272       CicCoercion.close_coercion_graph refinement_toolkit src_carr tgt_carr uri 
273        baseuri
274     in
275     let composite_uris = List.map (fun (_,_,uri,_) -> uri) new_coercions in
276     if already_in then
277       (* this if starts here just to be sure the closure function works fine *)
278       begin 
279         assert (new_coercions = []); 
280         HLog.warn
281           (UriManager.string_of_uri uri ^ 
282             " is already declared as a coercion! skipping...");
283         [] 
284       end
285     else
286       begin
287         (* update the DB *)
288         List.iter 
289           (fun (src,tgt,uri,_) -> CoercDb.add_coercion (src,tgt,uri)) 
290           new_coercions;
291         CoercDb.add_coercion (src_carr, tgt_carr, uri);
292         (* add the composites obj and they eventual lemmas *)
293         let lemmas = 
294           if add_composites then
295             List.fold_left
296               (fun acc (_,_,uri,obj) -> 
297                 add_single_obj uri obj refinement_toolkit;
298                 uri::acc) 
299               [] new_coercions
300           else
301             []
302         in
303         (* store that composite_uris are related to uri. the first component is
304          * the stuff in the DB while the second is stuff for remove_obj *)
305         (* 
306            prerr_endline ("adding: " ^ 
307              string_of_bool add_composites ^ UriManager.string_of_uri uri);
308            List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
309             composite_uris; 
310         *)
311         UriManager.UriHashtbl.add coercion_hashtbl uri 
312           (composite_uris,if add_composites then composite_uris else []);
313         (*
314         prerr_endline ("lemmas:");
315           List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
316           lemmas;
317         prerr_endline ("lemmas END");*)
318         lemmas
319       end
320 ;;
321
322 let remove_coercion uri =
323   try
324     let (composites_in_db, composites_in_lib) = 
325       UriManager.UriHashtbl.find coercion_hashtbl uri 
326     in
327     (*prerr_endline ("removing: " ^UriManager.string_of_uri uri);
328     List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
329       composites_in_db;*)
330     UriManager.UriHashtbl.remove coercion_hashtbl uri;
331     CoercDb.remove_coercion (fun (_,_,u) -> UriManager.eq uri u);
332     (* remove from the DB *) 
333     List.iter 
334       (fun u -> CoercDb.remove_coercion (fun (_,_,u1) -> UriManager.eq u u1))
335       composites_in_db;
336     (* remove composites from the lib *)
337     List.iter remove_single_obj composites_in_lib
338   with
339     Not_found -> () (* mhh..... *)
340     
341
342 let generate_projections refinement_toolkit uri fields =
343  let uris = ref [] in
344  let projections = 
345    CicRecord.projections_of uri 
346      (List.map (fun (x,_,_) -> x) fields) 
347  in
348   try
349    List.iter2 
350     (fun (uri, name, bo) (_name, coercion, arity) ->
351       try
352        let ty, ugraph =
353          CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph in
354        let attrs = [`Class `Projection; `Generated] in
355        let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
356         add_single_obj uri obj refinement_toolkit;
357         let composites = 
358          if coercion then
359             begin
360 (*prerr_endline ("composite for " ^ UriManager.string_of_uri uri);*)
361               let x = 
362                 add_coercion ~add_composites:true refinement_toolkit uri arity
363                  (UriManager.buri_of_uri uri)
364               in
365 (*prerr_endline ("are: ");
366   List.iter (fun u -> prerr_endline (UriManager.string_of_uri u)) x;
367   prerr_endline "---";
368 *)
369               x
370             end
371           else  
372             []
373         in
374         uris := uri :: composites @ !uris
375       with
376          CicTypeChecker.TypeCheckerFailure s ->
377           HLog.message
378            ("Unable to create projection " ^ name ^ " cause: " ^ Lazy.force s);
379        | CicEnvironment.Object_not_found uri ->
380           let depend = UriManager.name_of_uri uri in
381            HLog.message
382             ("Unable to create projection " ^ name ^ " because it requires " ^
383                depend)
384     ) projections fields;
385    !uris
386   with exn ->
387    List.iter remove_single_obj !uris;
388    raise exn
389
390 let build_inversion_principle = ref (fun a b -> assert false);;
391
392 let generate_inversion refinement_toolkit uri obj =
393   List.map 
394     (fun (ind_uri,ind_obj) -> 
395        add_single_obj ind_uri ind_obj refinement_toolkit;ind_uri)
396     (!build_inversion_principle uri obj)
397
398 let add_obj refinement_toolkit uri obj =
399  add_single_obj uri obj refinement_toolkit;
400  let uris = ref [] in
401  try
402   begin
403    match obj with
404     | Cic.Constant _ -> ()
405     | Cic.InductiveDefinition (_,_,_,attrs) ->
406         uris := !uris @ 
407           generate_elimination_principles uri refinement_toolkit;
408         uris := !uris @ generate_inversion refinement_toolkit uri obj;
409         let rec get_record_attrs =
410           function
411           | [] -> None
412           | (`Class (`Record fields))::_ -> Some fields
413           | _::tl -> get_record_attrs tl
414         in
415          (match get_record_attrs attrs with
416          | None -> () (* not a record *)
417          | Some fields ->
418             uris := !uris @ 
419               (generate_projections refinement_toolkit uri fields))
420     | Cic.CurrentProof _
421     | Cic.Variable _ -> assert false
422   end;
423   UriManager.UriHashtbl.add auxiliary_lemmas_hashtbl uri !uris;
424   !uris
425  with exn ->
426   List.iter remove_single_obj !uris;
427   raise exn
428
429 let remove_obj uri =
430  let uris =
431   try
432    let res = UriManager.UriHashtbl.find auxiliary_lemmas_hashtbl uri in
433     UriManager.UriHashtbl.remove auxiliary_lemmas_hashtbl uri;
434     res
435   with
436     Not_found -> [] (*assert false*)
437  in
438   List.iter remove_single_obj (uri::uris)
439