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