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