]> matita.cs.unibo.it Git - helm.git/blob - components/library/librarySync.ml
9b08ba6dc5a662dcc0f6dd2865f686ad7374a4f9
[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' ~local:true ~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, innertypes, ids_to_inner_sorts, generate_attributes =
74    if Helm_registry.get_bool "matita.system" then
75     let annobj, _, _, ids_to_inner_sorts, ids_to_inner_types, _, _ =
76      Cic2acic.acic_object_of_cic_object obj 
77     in
78     let innertypesxml = 
79      Cic2Xml.print_inner_types
80       uri ~ids_to_inner_sorts ~ids_to_inner_types ~ask_dtd_to_the_getter:false
81     in
82     annobj, Some innertypesxml, Some ids_to_inner_sorts, false
83    else 
84     let annobj = Cic2acic.plain_acic_object_of_cic_object obj in  
85     annobj, None, None, true 
86   in 
87   (* prepare XML *)
88   let xml, bodyxml =
89    Cic2Xml.print_object
90     uri ?ids_to_inner_sorts ~ask_dtd_to_the_getter:false 
91     ~generate_attributes annobj 
92   in    
93   let xmlpath, xmlbodypath, innertypespath, bodyuri, innertypesuri, 
94       xmlunivgraphpath, univgraphuri = 
95     paths_and_uris_of_obj uri 
96   in
97   write (List.iter HExtlib.mkdir) (List.map Filename.dirname [xmlpath]);
98   (* now write to disk *)
99   write ensure_path_exists xmlpath;
100   write (Xml.pp ~gzip:true xml) (Some xmlpath);
101   write (CicUniv.write_xml_of_ugraph xmlunivgraphpath ugraph) univlist;
102   (* we return a list of uri,path we registered/created *)
103   (uri,xmlpath) ::
104   (univgraphuri,xmlunivgraphpath) ::
105     (* now the optional inner types, both write and register *)
106     (match innertypes with 
107      | None -> []
108      | Some innertypesxml ->
109          write ensure_path_exists innertypespath;
110          write (Xml.pp ~gzip:true innertypesxml) (Some innertypespath);
111          [innertypesuri, innertypespath]
112     ) @
113     (* now the optional body, both write and register *)
114     (match bodyxml,bodyuri with
115        None,_ -> []
116      | Some bodyxml,Some bodyuri->
117          write ensure_path_exists xmlbodypath;
118          write (Xml.pp ~gzip:true bodyxml) (Some xmlbodypath);
119          [bodyuri, xmlbodypath]
120      | _-> assert false) 
121
122
123 let typecheck_obj =
124  let profiler = HExtlib.profile "add_obj.typecheck_obj" in
125   fun uri obj -> profiler.HExtlib.profile (CicTypeChecker.typecheck_obj uri) obj
126
127 let index_obj =
128  let profiler = HExtlib.profile "add_obj.index_obj" in
129   fun ~dbd ~uri ->
130    profiler.HExtlib.profile (fun uri -> MetadataDb.index_obj ~dbd ~uri) uri
131
132 let add_single_obj uri obj refinement_toolkit =
133   let module RT = RefinementTool in
134   let obj = 
135     if (*List.mem `Generated (CicUtil.attributes_of_obj obj) &&*)
136        not (CoercDb.is_a_coercion' (Cic.Const (uri, [])))
137     then
138       refinement_toolkit.RT.pack_coercion_obj obj
139     else
140       obj 
141   in
142   let dbd = LibraryDb.instance () in
143   if CicEnvironment.in_library uri then
144     raise (AlreadyDefined uri)
145   else begin
146     (*CicUniv.reset_spent_time ();
147     let before = Unix.gettimeofday () in*)
148     typecheck_obj uri obj; (* 1 *)
149     (*let after = Unix.gettimeofday () in
150     let univ_time = CicUniv.get_spent_time () in
151     let total_time = after -. before in
152     prerr_endline 
153       (Printf.sprintf "QED: %%univ = %2.5f, total = %2.5f, univ = %2.5f, %s\n" 
154       (univ_time *. 100. /. total_time) (total_time) (univ_time)
155       (UriManager.name_of_uri uri));*)
156     let _, ugraph, univlist = 
157       CicEnvironment.get_cooked_obj_with_univlist CicUniv.empty_ugraph uri in
158     try 
159       index_obj ~dbd ~uri; (* 2 must be in the env *)
160       try
161         (*3*)
162         let new_stuff = save_object_to_disk uri obj ugraph univlist in
163         try 
164          HLog.message
165           (Printf.sprintf "%s defined" (UriManager.string_of_uri uri))
166         with exc ->
167           List.iter HExtlib.safe_remove (List.map snd new_stuff); (* -3 *)
168           raise exc
169       with exc ->
170         ignore(LibraryDb.remove_uri uri); (* -2 *)
171         raise exc
172     with exc ->
173       CicEnvironment.remove_obj uri; (* -1 *)
174       raise exc
175   end
176
177 let remove_single_obj uri =
178   let derived_uris_of_uri uri =
179    let innertypesuri, bodyuri, univgraphuri = uris_of_obj uri in
180     innertypesuri::univgraphuri::(match bodyuri with None -> [] | Some u -> [u])
181   in
182   let uris_to_remove =
183    if UriManager.uri_is_ind uri then LibraryDb.xpointers_of_ind uri else [uri]
184   in
185   let files_to_remove = uri :: derived_uris_of_uri uri in   
186   List.iter 
187    (fun uri -> 
188      (try
189        let file = Http_getter.resolve' ~local:true ~writable:true uri in
190         HExtlib.safe_remove file;
191         HExtlib.rmdir_descend (Filename.dirname file)
192      with Http_getter_types.Key_not_found _ -> ());
193    ) files_to_remove ;
194   List.iter 
195    (fun uri -> 
196      ignore (LibraryDb.remove_uri uri);
197      (*CoercGraph.remove_coercion uri;*)
198    ) uris_to_remove ;
199   CicEnvironment.remove_obj uri
200
201 (*** GENERATION OF AUXILIARY LEMMAS ***)
202
203 let generate_elimination_principles uri refinement_toolkit =
204   let uris = ref [] in
205   let elim i =
206     let elim sort =
207       try
208         let uri,obj = CicElim.elim_of ~sort uri i in
209           add_single_obj uri obj refinement_toolkit;
210           uris := uri :: !uris
211       with CicElim.Can_t_eliminate -> ()
212     in
213       try
214         List.iter 
215           elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
216       with exn ->
217         List.iter remove_single_obj !uris;
218         raise exn 
219   in
220   let (obj, univ) = (CicEnvironment.get_obj CicUniv.empty_ugraph uri) in
221     match obj with
222       | Cic.InductiveDefinition (indTypes, _, _, _) ->
223           let counter = ref 0 in
224             List.iter (fun _ -> elim !counter; counter := !counter+1) indTypes;
225             !uris
226       | _  -> 
227           failwith (Printf.sprintf "not an inductive definition (%s)"
228                       (UriManager.string_of_uri uri))
229
230 (* COERCIONS ***********************************************************)
231   
232 let remove_all_coercions () =
233   UriManager.UriHashtbl.clear coercion_hashtbl;
234   CoercDb.remove_coercion (fun (_,_,_,_) -> true)
235
236 let add_coercion ~add_composites refinement_toolkit uri arity saturations
237  baseuri
238 =
239   let coer_ty,_ =
240     let coer = CicUtil.term_of_uri uri in
241     CicTypeChecker.type_of_aux' [] [] coer CicUniv.empty_ugraph 
242   in
243   (* we have to get the source and the tgt type uri
244    * in Coq syntax we have already their names, but
245    * since we don't support Funclass and similar I think
246    * all the coercion should be of the form
247    * (A:?)(B:?)T1->T2
248    * So we should be able to extract them from the coercion type
249    * 
250    * Currently only (_:T1)T2 is supported.
251    * should we saturate it with metas in case we insert it?
252    * 
253    *)
254   let spine2list ty =
255     let rec aux = function
256       | Cic.Prod( _, src, tgt) -> src::aux tgt
257       | t -> [t]
258     in
259     aux ty
260   in
261   let src_carr, tgt_carr = 
262     let get_classes arity saturations l = 
263       (* this is the ackerman's function revisited *)
264       let rec aux = function
265          0,0,None,tgt::src::_ -> src,Some (`Class tgt)
266        | 0,0,target,src::_ -> src,target
267        | 0,saturations,None,tgt::tl -> aux (0,saturations,Some (`Class tgt),tl)
268        | 0,saturations,target,_::tl -> aux (0,saturations - 1,target,tl)
269        | arity,saturations,None,_::tl -> 
270             aux (arity, saturations, Some `Funclass, tl)
271        | arity,saturations,target,_::tl -> 
272             aux (arity - 1, saturations, target, tl)
273        | _ -> assert false
274       in
275        aux (arity,saturations,None,List.rev l)
276     in
277     let types = spine2list coer_ty in
278     let src,tgt = get_classes arity saturations types in
279      CoercDb.coerc_carr_of_term (CicReduction.whd ~delta:false [] src),
280      match tgt with
281         None -> assert false
282       | Some `Funclass -> CoercDb.Fun arity
283       | Some (`Class tgt) ->
284          CoercDb.coerc_carr_of_term (CicReduction.whd ~delta:false [] tgt)
285   in
286   let already_in_obj src_carr tgt_carr uri obj = 
287      List.exists 
288       (fun (s,t,ul) -> 
289         List.exists 
290          (fun u,_ -> 
291            let bo = 
292             match obj with 
293             | Cic.Constant (_, Some bo, _, _, _) -> bo
294             | _ -> assert false
295            in
296            CoercDb.eq_carr s src_carr && 
297            CoercDb.eq_carr t tgt_carr &&
298            if fst (CicReduction.are_convertible [] (CicUtil.term_of_uri u) bo
299            CicUniv.oblivion_ugraph)
300            then true else
301             (HLog.warn
302               ("Coercions " ^ 
303                 UriManager.string_of_uri u ^ " and " ^ UriManager.string_of_uri
304                 uri^" are not convertible, but are between the same nodes.\n"^
305                 "From now on unification can fail randomly.");
306              false))
307          ul)
308       (CoercDb.to_list ())
309   in
310   if not add_composites then
311     (CoercDb.add_coercion (src_carr, tgt_carr, uri, saturations);[])
312   else
313     let new_coercions = 
314       CicCoercion.close_coercion_graph src_carr tgt_carr uri saturations
315        baseuri
316     in
317     let new_coercions = 
318       List.filter (fun (s,t,u,_,obj,_) -> not(already_in_obj s t u obj))
319       new_coercions 
320     in
321     let composite_uris = List.map (fun (_,_,uri,_,_,_) -> uri) new_coercions in
322     (* update the DB *)
323     List.iter 
324       (fun (src,tgt,uri,saturations,_,_) ->
325         CoercDb.add_coercion (src,tgt,uri,saturations)) 
326       new_coercions;
327     CoercDb.add_coercion (src_carr, tgt_carr, uri, saturations);
328     (* add the composites obj and they eventual lemmas *)
329     let lemmas = 
330       if add_composites then
331         List.fold_left
332           (fun acc (_,tgt,uri,saturations,obj,arity) -> 
333             add_single_obj uri obj refinement_toolkit;
334              (uri,arity,saturations)::acc) 
335           [] new_coercions
336       else
337         []
338     in
339     (* store that composite_uris are related to uri. the first component is
340      * the stuff in the DB while the second is stuff for remove_obj *)
341     (* 
342        prerr_endline ("adding: " ^ 
343          string_of_bool add_composites ^ UriManager.string_of_uri uri);
344        List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
345         composite_uris; 
346     *)
347     UriManager.UriHashtbl.add coercion_hashtbl uri 
348       (composite_uris,if add_composites then composite_uris else []);
349     (*
350     prerr_endline ("lemmas:");
351       List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
352       lemmas;
353     prerr_endline ("lemmas END");*)
354     lemmas
355 ;;
356
357 let remove_coercion uri =
358   try
359     let (composites_in_db, composites_in_lib) = 
360       UriManager.UriHashtbl.find coercion_hashtbl uri 
361     in
362     (*prerr_endline ("removing: " ^UriManager.string_of_uri uri);
363     List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
364       composites_in_db;*)
365     UriManager.UriHashtbl.remove coercion_hashtbl uri;
366     CoercDb.remove_coercion (fun (_,_,u,_) -> UriManager.eq uri u);
367     (* remove from the DB *) 
368     List.iter 
369       (fun u -> CoercDb.remove_coercion (fun (_,_,u1,_) -> UriManager.eq u u1))
370       composites_in_db;
371     (* remove composites from the lib *)
372     List.iter remove_single_obj composites_in_lib
373   with
374     Not_found -> () (* mhh..... *)
375     
376
377 let generate_projections refinement_toolkit uri fields =
378  let uris = ref [] in
379  let projections = 
380    CicRecord.projections_of uri 
381      (List.map (fun (x,_,_) -> x) fields) 
382  in
383   try
384    List.iter2 
385     (fun (uri, name, bo) (_name, coercion, arity) ->
386       let saturations = 0 in
387       try
388        let ty, ugraph =
389          CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph in
390        let attrs = [`Class `Projection; `Generated] in
391        let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
392         add_single_obj uri obj refinement_toolkit;
393         let composites = 
394          if coercion then
395             begin
396 (*prerr_endline ("composite for " ^ UriManager.string_of_uri uri);*)
397               (*CSC: I think there is a bug here. The composite coercions
398                 are not remembered in the .moo file. Thus they are re-generated
399                 every time. Right? *)
400               let x = 
401                 add_coercion ~add_composites:true refinement_toolkit uri arity
402                  saturations (UriManager.buri_of_uri uri)
403               in
404 (*prerr_endline ("are: ");
405   List.iter (fun u -> prerr_endline (UriManager.string_of_uri u)) x;
406   prerr_endline "---";
407 *)
408               (*CSC: I throw the arity away. See comment above *)
409               List.map (fun u,_,_ -> u) x
410             end
411           else  
412             []
413         in
414         uris := uri :: composites @ !uris
415       with
416          CicTypeChecker.TypeCheckerFailure s ->
417           HLog.message
418            ("Unable to create projection " ^ name ^ " cause: " ^ Lazy.force s);
419        | CicEnvironment.Object_not_found uri ->
420           let depend = UriManager.name_of_uri uri in
421            HLog.message
422             ("Unable to create projection " ^ name ^ " because it requires " ^
423                depend)
424     ) projections fields;
425    !uris
426   with exn ->
427    List.iter remove_single_obj !uris;
428    raise exn
429
430 let build_inversion_principle = ref (fun a b -> assert false);;
431
432 let generate_inversion refinement_toolkit uri obj =
433   List.map 
434     (fun (ind_uri,ind_obj) -> 
435        add_single_obj ind_uri ind_obj refinement_toolkit;ind_uri)
436     (!build_inversion_principle uri obj)
437
438 let
439  generate_sibling_mutual_definitions refinement_toolkit uri attrs name_to_avoid
440 =
441  function
442     Cic.Fix (_,funs) ->
443      snd (
444       List.fold_right
445        (fun (name,idx,ty,bo) (n,uris) ->
446          if name = name_to_avoid then
447           (n+1,uris)
448          else
449           let uri =
450            UriManager.uri_of_string
451             (UriManager.buri_of_uri uri ^ "/" ^ name ^ ".con") in
452           let bo = Cic.Fix (n,funs) in 
453           let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
454            add_single_obj uri obj refinement_toolkit;
455            (n+1,uri::uris)
456        ) funs (1,[]))
457   | Cic.CoFix (_,funs) ->
458      snd (
459       List.fold_right
460        (fun (name,ty,bo) (n,uris) ->
461          if name = name_to_avoid then
462           (n+1,uris)
463          else
464           let uri =
465            UriManager.uri_of_string
466             (UriManager.buri_of_uri uri ^ "/" ^ name ^ ".con") in
467           let bo = Cic.CoFix (n,funs) in 
468           let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
469            add_single_obj uri obj refinement_toolkit;
470            (n+1,uri::uris)
471        ) funs (1,[]))
472   | _ -> assert false
473
474 let add_obj refinement_toolkit uri obj =
475  add_single_obj uri obj refinement_toolkit;
476  let uris = ref [] in
477  let not_debug = not (Helm_registry.get_bool "matita.debug") in
478  try
479   begin
480    match obj with
481     | Cic.Constant (name,Some bo,_,_,attrs) when
482        List.mem (`Flavour `MutualDefinition) attrs ->
483         uris :=
484          !uris @
485            generate_sibling_mutual_definitions refinement_toolkit uri attrs
486             name bo
487     | Cic.Constant _ -> ()
488     | Cic.InductiveDefinition (_,_,_,attrs) ->
489         uris := !uris @ 
490           generate_elimination_principles uri refinement_toolkit;
491         uris := !uris @ generate_inversion refinement_toolkit uri obj;
492         let rec get_record_attrs =
493           function
494           | [] -> None
495           | (`Class (`Record fields))::_ -> Some fields
496           | _::tl -> get_record_attrs tl
497         in
498          (match get_record_attrs attrs with
499          | None -> () (* not a record *)
500          | Some fields ->
501             uris := !uris @ 
502               (generate_projections refinement_toolkit uri fields))
503     | Cic.CurrentProof _
504     | Cic.Variable _ -> assert false
505   end;
506   UriManager.UriHashtbl.add auxiliary_lemmas_hashtbl uri !uris;
507   !uris
508  with 
509  | exn when not_debug ->
510     List.iter remove_single_obj !uris;
511     raise exn
512
513 let remove_obj uri =
514  let uris =
515   try
516    let res = UriManager.UriHashtbl.find auxiliary_lemmas_hashtbl uri in
517     UriManager.UriHashtbl.remove auxiliary_lemmas_hashtbl uri;
518     res
519   with
520     Not_found -> [] (*assert false*)
521  in
522   List.iter remove_single_obj (uri::uris)
523