]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaSync.ml
"verbose" argument of remove is now optional (default false)
[helm.git] / helm / matita / matitaSync.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 open Printf
27
28 open MatitaTypes
29
30 let alias_diff ~from status = 
31   let module Map = DisambiguateTypes.Environment in
32   Map.fold
33     (fun domain_item (description1,_ as codomain_item) acc ->
34       try
35        let description2,_ = Map.find domain_item from.aliases in
36         if description1 <> description2 then
37          (domain_item,codomain_item)::acc
38         else
39           acc
40       with
41        Not_found ->
42          (domain_item,codomain_item)::acc)
43     status.aliases []
44
45 let alias_diff =
46  let profiler = CicUtil.profile "alias_diff (conteggiato anche in include)" in
47  fun ~from status -> profiler.CicUtil.profile (alias_diff ~from) status
48
49 let set_proof_aliases status new_aliases =
50  let aliases =
51   List.fold_left (fun acc (d,c) -> DisambiguateTypes.Environment.add d c acc)
52    status.aliases new_aliases in
53  let multi_aliases =
54   List.fold_left (fun acc (d,c) -> DisambiguateTypes.Environment.cons d c acc)
55    status.multi_aliases new_aliases in
56  let new_status =
57    { status with multi_aliases = multi_aliases ; aliases = aliases}
58  in
59  if new_aliases = [] then
60    new_status
61  else
62    add_moo_content
63     (DisambiguatePp.commands_of_domain_and_codomain_items_list new_aliases)
64     new_status
65
66 (** given a uri and a type list (the contructors types) builds a list of pairs
67  *  (name,uri) that is used to generate authomatic aliases **)
68 let extract_alias types uri = 
69   fst(List.fold_left (
70     fun (acc,i) (name, _, _, cl) -> 
71       (name, UriManager.string_of_uri (UriManager.uri_of_uriref uri i None))
72       ::
73       (fst(List.fold_left (
74         fun (acc,j) (name,_) ->
75           (((name,UriManager.string_of_uri (UriManager.uri_of_uriref uri i
76           (Some j))) :: acc) , j+1)
77         ) (acc,1) cl)),i+1
78   ) ([],0) types)
79
80 let build_aliases =
81  List.map
82   (fun (name,suri) ->
83     DisambiguateTypes.Id name,
84      (suri, fun _ _ _ -> CicUtil.term_of_uri (UriManager.uri_of_string suri)))
85
86 let add_aliases_for_inductive_def status types suri = 
87   let uri = UriManager.uri_of_string suri in
88   let aliases = build_aliases (extract_alias types uri) in
89    set_proof_aliases status aliases
90
91 let add_alias_for_constant status suri =
92  let uri = UriManager.uri_of_string suri in
93  let name = UriManager.name_of_uri uri in
94  let new_env = build_aliases [(name,suri)] in
95  set_proof_aliases status new_env
96
97 let add_aliases_for_object status suri =
98  function
99     Cic.InductiveDefinition (types,_,_,_) ->
100      add_aliases_for_inductive_def status types suri
101   | Cic.Constant _ -> add_alias_for_constant status suri
102   | Cic.Variable _
103   | Cic.CurrentProof _ -> assert false
104   
105 let paths_and_uris_of_obj uri status =
106   let basedir = get_string_option status "basedir" ^ "/xml" in
107   let innertypesuri = UriManager.innertypesuri_of_uri uri in
108   let bodyuri = UriManager.bodyuri_of_uri uri in
109   let univgraphuri = UriManager.univgraphuri_of_uri uri in
110   let innertypesfilename = Str.replace_first (Str.regexp "^cic:") ""
111         (UriManager.string_of_uri innertypesuri) ^ ".xml.gz" in
112   let innertypespath = basedir ^ "/" ^ innertypesfilename in
113   let xmlfilename = Str.replace_first (Str.regexp "^cic:/") ""
114         (UriManager.string_of_uri uri) ^ ".xml.gz" in
115   let xmlpath = basedir ^ "/" ^ xmlfilename in
116   let xmlbodyfilename = Str.replace_first (Str.regexp "^cic:/") ""
117         (UriManager.string_of_uri uri) ^ ".body.xml.gz" in
118   let xmlbodypath = basedir ^ "/" ^  xmlbodyfilename in
119   let xmlunivgraphfilename = Str.replace_first (Str.regexp "^cic:/") ""
120         (UriManager.string_of_uri univgraphuri) ^ ".xml.gz" in
121   let xmlunivgraphpath = basedir ^ "/" ^ xmlunivgraphfilename in
122   xmlpath, xmlbodypath, innertypespath, bodyuri, innertypesuri, 
123   xmlunivgraphpath, univgraphuri
124
125 let save_object_to_disk status uri obj ugraph univlist =
126   let ensure_path_exists path =
127     let dir = Filename.dirname path in
128     MatitaMisc.mkdir dir
129   in
130   (* generate annobj, ids_to_inner_sorts and ids_to_inner_types *)
131   let annobj = Cic2acic.plain_acic_object_of_cic_object obj in 
132   (* prepare XML *)
133   let xml, bodyxml =
134    Cic2Xml.print_object
135     uri ?ids_to_inner_sorts:None ~ask_dtd_to_the_getter:false annobj 
136   in
137   let xmlpath, xmlbodypath, innertypespath, bodyuri, innertypesuri, 
138       xmlunivgraphpath, univgraphuri = 
139     paths_and_uris_of_obj uri status 
140   in
141   let path_scheme_of path = "file://" ^ path in
142   List.iter MatitaMisc.mkdir
143     (List.map Filename.dirname [innertypespath; xmlpath]);
144   (* now write to disk *)
145   ensure_path_exists xmlpath;
146   Xml.pp ~gzip:true xml (Some xmlpath);
147   CicUniv.write_xml_of_ugraph xmlunivgraphpath ugraph univlist;
148   (* we return a list of uri,path we registered/created *)
149   (uri,xmlpath) :: (innertypesuri,innertypespath) :: 
150   (univgraphuri,xmlunivgraphpath) ::
151     (* now the optional body, both write and register *)
152     (match bodyxml,bodyuri with
153        None,None -> []
154      | Some bodyxml,Some bodyuri->
155          ensure_path_exists xmlbodypath;
156          Xml.pp ~gzip:true bodyxml (Some xmlbodypath);
157          [bodyuri, xmlbodypath]
158      | _-> assert false) 
159
160 let typecheck_obj =
161  let profiler = CicUtil.profile "add_obj.typecheck_obj" in
162   fun uri obj -> profiler.CicUtil.profile (CicTypeChecker.typecheck_obj uri) obj
163
164 let index_obj =
165  let profiler = CicUtil.profile "add_obj.index_obj" in
166   fun ~dbd ~uri ->
167    profiler.CicUtil.profile (fun uri -> MetadataDb.index_obj ~dbd ~uri) uri
168
169 let save_object_to_disk =
170  let profiler = CicUtil.profile "add_obj.save_object_to_disk" in
171   fun status uri obj ugraph univlist ->
172    profiler.CicUtil.profile (save_object_to_disk status uri obj ugraph) univlist
173
174 let add_obj uri obj status =
175   let dbd = MatitaDb.instance () in
176   let suri = UriManager.string_of_uri uri in
177   if CicEnvironment.in_library uri then
178     command_error (sprintf "%s already defined" suri)
179   else begin
180     typecheck_obj uri obj; (* 1 *)
181     let _, ugraph, univlist = 
182       CicEnvironment.get_cooked_obj_with_univlist CicUniv.empty_ugraph uri in
183     try 
184       index_obj ~dbd ~uri; (* 2 must be in the env *)
185       try
186         let new_stuff=save_object_to_disk status uri obj ugraph univlist in(*3*)
187         try 
188           MatitaLog.message (sprintf "%s defined" suri);
189           let status = add_aliases_for_object status suri obj in
190           { status with objects = new_stuff @ status.objects;
191                         proof_status = No_proof }
192         with exc ->
193           List.iter MatitaMisc.safe_remove (List.map snd new_stuff); (* -3 *)
194           raise exc
195       with exc ->
196         ignore(MatitaDb.remove_uri uri); (* -2 *)
197         raise exc
198     with exc ->
199       CicEnvironment.remove_obj uri; (* -1 *)
200     raise exc
201   end
202
203 let add_obj =
204  let profiler = CicUtil.profile "add_obj" in
205   fun uri obj status -> profiler.CicUtil.profile (add_obj uri obj) status
206    
207 module OrderedUri =
208 struct
209   type t = UriManager.uri * string
210   let compare (u1, _) (u2, _) = UriManager.compare u1 u2
211 end
212
213 module OrderedId = 
214 struct
215   type t = CicNotation.notation_id
216   let compare = Pervasives.compare
217 end
218
219 module UriSet = Set.Make (OrderedUri)
220 module IdSet  = Set.Make (OrderedId)
221
222   (** @return l2 \ l1 *)
223 let uri_list_diff l2 l1 =
224   let module S = UriSet in
225   let s1 = List.fold_left (fun set uri -> S.add uri set) S.empty l1 in
226   let s2 = List.fold_left (fun set uri -> S.add uri set) S.empty l2 in
227   let diff = S.diff s2 s1 in
228   S.fold (fun uri uris -> uri :: uris) diff []
229
230   (** @return l2 \ l1 *)
231 let id_list_diff l2 l1 =
232   let module S = IdSet in
233   let s1 = List.fold_left (fun set uri -> S.add uri set) S.empty l1 in
234   let s2 = List.fold_left (fun set uri -> S.add uri set) S.empty l2 in
235   let diff = S.diff s2 s1 in
236   S.fold (fun uri uris -> uri :: uris) diff []
237
238 let remove_coercion uri = 
239   CoercDb.remove_coercion (fun (_,_,u) -> UriManager.eq u uri)
240   
241 let time_travel ~present ~past =
242   let objs_to_remove = uri_list_diff present.objects past.objects in
243   let notation_to_remove =
244     id_list_diff present.notation_ids past.notation_ids
245   in
246   let debug_list = ref [] in
247   List.iter
248     (fun (uri,p) -> 
249       MatitaMisc.safe_remove p;
250       remove_coercion uri;
251       (try 
252         CicEnvironment.remove_obj uri
253       with CicEnvironment.Object_not_found _ -> 
254         MatitaLog.debug
255           (sprintf "time_travel removes from cache %s that is not in" 
256             (UriManager.string_of_uri uri)));
257       let l = MatitaDb.remove_uri uri in
258       debug_list := UriManager.string_of_uri uri :: !debug_list @ l) 
259     objs_to_remove;
260   List.iter CicNotation.remove_notation notation_to_remove
261   (*
262   (* this is debug code
263   * idea: debug_list is the list of objects to be removed as computed from the
264   * db, while list_of_objs_to_remove is the same list but computer from the
265   * differences between statuses *)
266   let l1 = List.sort Pervasives.compare !debug_list in
267   let l2 = List.sort Pervasives.compare 
268     (List.map (fun (x,_) -> UriManager.string_of_uri x) list_of_objs_to_remove)
269   in
270   let rec uniq = function 
271     | [] -> []
272     | h::[] -> [h]
273     | h1::h2::tl when h1 = h2 -> uniq (h2 :: tl)
274     | h1::tl (* when h1 <> h2 *) -> h1 :: uniq tl
275   in
276   let l1 =  uniq l1 in
277   let l2 =  uniq l2 in
278   try
279     List.iter2 (fun x y -> if x <> y then raise Exit) l1 l2
280   with
281   | Invalid_argument _ | Exit -> 
282       MatitaLog.debug "It seems you garbaged something...";
283       MatitaLog.debug "l1:";
284       List.iter MatitaLog.debug l1;
285       MatitaLog.debug "l2:";
286       List.iter MatitaLog.debug l2
287       *)
288     
289 let last_baseuri = ref ""
290
291 let remove ?(verbose=false) uri =
292   let derived_uris_of_uri uri =
293     UriManager.innertypesuri_of_uri uri ::
294     UriManager.univgraphuri_of_uri uri ::
295     (match UriManager.bodyuri_of_uri uri with
296     | None -> []
297     | Some u -> [u]) 
298   in
299   let to_remove =
300     uri :: 
301     (if UriManager.uri_is_ind uri then MatitaDb.xpointers_of_ind uri else []) @
302     derived_uris_of_uri uri   
303   in   
304   List.iter 
305     (fun uri -> 
306       (try
307         (* WARNING: non reentrant debugging code *)
308         if verbose then
309          let baseuri = UriManager.buri_of_uri uri in
310           if !last_baseuri <> baseuri then
311            begin
312             MatitaLog.debug ("Removing: " ^ baseuri ^ "/*");
313             last_baseuri := baseuri
314            end;
315         MatitaMisc.safe_remove (Http_getter.resolve' uri)
316       with Http_getter_types.Key_not_found _ -> ());
317       remove_coercion uri; 
318       ignore (MatitaDb.remove_uri uri);
319       CicEnvironment.remove_obj uri)
320   to_remove