]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_kernel/nCicLibrary.ml
- Bug fixed: removed URIs were not removed from the dependencies DB.
[helm.git] / helm / software / components / ng_kernel / nCicLibrary.ml
1 (*
2     ||M||  This file is part of HELM, an Hypertextual, Electronic        
3     ||A||  Library of Mathematics, developed at the Computer Science     
4     ||T||  Department, University of Bologna, Italy.                     
5     ||I||                                                                
6     ||T||  HELM is free software; you can redistribute it and/or         
7     ||A||  modify it under the terms of the GNU General Public License   
8     \   /  version 2 or (at your option) any later version.      
9      \ /   This software is distributed as is, NO WARRANTY.     
10       V_______________________________________________________________ *)
11
12 (* $Id$ *)
13
14 exception LibraryOutOfSync of string Lazy.t
15
16 let magic = 1;;
17
18 let refresh_uri uri = NUri.uri_of_string (NUri.string_of_uri uri);;
19
20 let rec refresh_uri_in_term =
21  function
22     NCic.Const (NReference.Ref (u,spec)) ->
23      NCic.Const (NReference.reference_of_spec (refresh_uri u) spec)
24   | t -> NCicUtils.map (fun _ _ -> ()) () (fun _ -> refresh_uri_in_term) t
25 ;;
26
27 let refresh_uri_in_obj (uri,height,metasenv,subst,obj_kind) =
28  assert (metasenv = []);
29  assert (subst = []);
30  uri,height,metasenv,subst,
31   NCicUntrusted.map_obj_kind refresh_uri_in_term obj_kind
32 ;;
33
34 let path_of_baseuri ?(no_suffix=false) baseuri =
35  let uri = NUri.string_of_uri baseuri in
36  let path = String.sub uri 4 (String.length uri - 4) in
37  let path = Helm_registry.get "matita.basedir" ^ path in
38  let dirname = Filename.dirname path in
39   HExtlib.mkdir dirname;
40   if no_suffix then
41    path
42   else
43    path ^ ".ng"
44 ;;
45
46 let require_path path =
47  let ch = open_in path in
48  let mmagic,dump = Marshal.from_channel ch in
49   close_in ch;
50   if mmagic <> magic then
51    raise (LibraryOutOfSync (lazy "The library is out of sync with the implementation. Please recompile the library."))
52   else
53    dump
54 ;;
55
56 let require0 ~baseuri = require_path (path_of_baseuri baseuri);;
57
58 let db_path () = Helm_registry.get "matita.basedir" ^ "/ng_db.ng";;
59
60 type timestamp =
61  (NUri.uri * NCic.obj) list *
62  (NUri.uri * string * NReference.reference) list *
63  NCic.obj NUri.UriMap.t *
64  NUri.uri list;;
65
66 let time0 = [],[],NUri.UriMap.empty,[];;
67 let storage = ref [];;
68 let local_aliases = ref [];;
69 let cache = ref NUri.UriMap.empty;;
70 let includes = ref [];;
71
72 let load_db,set_global_aliases,get_global_aliases,add_deps,get_deps,remove_deps=
73  let global_aliases = ref [] in
74  let rev_includes_map = ref NUri.UriMap.empty in
75  let store_db () =
76   let ch = open_out (db_path ()) in
77   Marshal.to_channel ch (magic,(!global_aliases,!rev_includes_map)) [];
78   close_out ch in
79  let load_db () =
80   try
81    let ga,im = require_path (db_path ()) in
82    let ga =
83     List.map
84      (fun (uri,name,NReference.Ref (uri2,spec)) ->
85        refresh_uri uri,name,NReference.reference_of_spec (refresh_uri uri2) spec
86      ) ga in
87    let im =
88     NUri.UriMap.fold
89      (fun u l im -> NUri.UriMap.add (refresh_uri u) (List.map refresh_uri l) im
90      ) im NUri.UriMap.empty
91    in
92     global_aliases := ga;
93     rev_includes_map := im
94   with
95    Sys_error _ -> () in
96  let get_deps u =
97   let get_deps_one_step u =
98     try NUri.UriMap.find u !rev_includes_map with Not_found -> [] in
99   let rec aux res =
100    function
101       [] -> res
102     | he::tl ->
103        if List.mem he res then
104         aux res tl
105        else
106         aux (he::res) (get_deps_one_step he @ tl)
107   in
108    aux [] [u] in
109  let remove_deps u =
110   rev_includes_map := NUri.UriMap.remove u !rev_includes_map;
111   rev_includes_map :=
112    NUri.UriMap.map
113     (fun l -> List.filter (fun uri -> not (NUri.eq u uri)) l) !rev_includes_map;
114   store_db ()
115  in
116   load_db,
117   (fun ga -> global_aliases := ga; store_db ()),
118   (fun () -> !global_aliases),
119   (fun u l ->
120     rev_includes_map := NUri.UriMap.add u (l @ get_deps u) !rev_includes_map;
121     store_db ()),
122   get_deps,
123   remove_deps
124 ;;
125
126 let init = load_db;;
127
128 class status =
129  object
130   val timestamp = (time0 : timestamp)
131   method timestamp = timestamp
132   method set_timestamp v = {< timestamp = v >}
133   method set_library_status
134    : 'status. < timestamp : timestamp; .. > as 'status -> 'self
135    = fun o -> {< timestamp = o#timestamp >}
136  end
137
138 let time_travel status =
139  let sto,ali,cac,inc = status#timestamp in
140   storage := sto; local_aliases := ali; cache := cac; includes := inc
141 ;;
142
143 let serialize ~baseuri dump =
144  let ch = open_out (path_of_baseuri baseuri) in
145  Marshal.to_channel ch (magic,dump) [];
146  close_out ch;
147  List.iter
148   (fun (uri,obj) ->
149     let ch = open_out (path_of_baseuri uri) in
150     Marshal.to_channel ch (magic,obj) [];
151     close_out ch
152   ) !storage;
153  set_global_aliases (!local_aliases @ get_global_aliases ());
154  List.iter (fun u -> add_deps u [baseuri]) !includes;
155  time_travel (new status)
156 ;;
157
158 module type Serializer =
159  sig
160   type status
161   type obj
162   val register:
163    string ->
164     ('a -> refresh_uri_in_term:(NCic.term -> NCic.term) -> status -> status) ->
165     ('a -> obj)
166   val serialize: baseuri:NUri.uri -> obj list -> unit
167   val require: baseuri:NUri.uri -> status -> status
168  end
169
170 module Serializer(S: sig type status end) =
171  struct
172   type status = S.status
173   type obj = string * Obj.t
174
175   let require1 = ref (fun _ -> assert false (* unknown data*))
176   let already_registered = ref []
177
178   let register tag require =
179    assert (not (List.mem tag !already_registered));
180    already_registered := tag :: !already_registered;
181    require1 :=
182     (fun (tag',data) as x ->
183      if tag=tag' then
184       require (Obj.magic data) ~refresh_uri_in_term
185      else
186       !require1 x);
187    (fun x -> tag,Obj.repr x)
188
189   let serialize = serialize
190
191   let require ~baseuri status =
192    includes := baseuri::!includes;
193    let dump = require0 ~baseuri in
194     List.fold_right !require1 dump status
195 end
196
197 let decompile ~baseuri =
198  let baseuris = get_deps baseuri in
199  List.iter (fun baseuri ->
200   remove_deps baseuri;
201   HExtlib.safe_remove (path_of_baseuri baseuri);
202   let basepath = path_of_baseuri ~no_suffix:true baseuri in
203   try
204    let od = Unix.opendir basepath in
205    let rec aux names =
206     try
207      let name = Unix.readdir od in
208       if name <> "." && name <> ".." then aux (name::names) else aux names
209     with
210      End_of_file -> names in
211    let names = List.map (fun name -> basepath ^ "/" ^ name) (aux []) in
212     Unix.closedir od;
213     List.iter Unix.unlink names;
214     HExtlib.rmdir_descend basepath;
215     set_global_aliases
216      (List.filter
217       (fun (_,_,NReference.Ref (nuri,_)) ->
218         Filename.dirname (NUri.string_of_uri nuri) <> NUri.string_of_uri baseuri
219       ) (get_global_aliases ()))
220   with
221    Unix.Unix_error _ -> () (* raised by Unix.opendir, we hope :-) *)
222  ) baseuris
223 ;;
224
225 LibraryClean.set_decompile_cb
226  (fun ~baseuri -> decompile ~baseuri:(NUri.uri_of_string baseuri));;
227
228 let fetch_obj uri =
229  let obj = require0 ~baseuri:uri in
230   refresh_uri_in_obj obj
231 ;;
232
233 let resolve name =
234  try
235   HExtlib.filter_map
236    (fun (_,name',nref) -> if name'=name then Some nref else None)
237    (!local_aliases @ get_global_aliases ())
238  with
239   Not_found -> raise (NCicEnvironment.ObjectNotFound (lazy name))
240 ;;
241
242 let aliases_of uri =
243  try
244   HExtlib.filter_map
245    (fun (uri',_,nref) ->
246      if NUri.eq uri' uri then Some nref else None) !local_aliases
247  with
248   Not_found -> raise (NCicEnvironment.ObjectNotFound (lazy (NUri.string_of_uri uri)))
249 ;;
250
251 let add_obj status u obj =
252  storage := (u,obj)::!storage;
253   let _,height,_,_,obj = obj in
254   let references =
255    match obj with
256       NCic.Constant (_,name,None,_,_) ->
257        [u,name,NReference.reference_of_spec u NReference.Decl]
258     | NCic.Constant (_,name,Some _,_,_) ->
259        [u,name,NReference.reference_of_spec u (NReference.Def height)]
260     | NCic.Fixpoint (is_ind,fl,_) ->
261        HExtlib.list_mapi
262         (fun (_,name,recno,_,_) i ->
263           if is_ind then
264            u,name,NReference.reference_of_spec u(NReference.Fix(i,recno,height))
265           else
266            u,name,NReference.reference_of_spec u (NReference.CoFix i)) fl
267     | NCic.Inductive (inductive,leftno,il,_) ->
268        List.flatten
269         (HExtlib.list_mapi
270          (fun (_,iname,_,cl) i ->
271            HExtlib.list_mapi
272             (fun (_,cname,_) j->
273               u,cname,
274                NReference.reference_of_spec u (NReference.Con (i,j+1,leftno))
275             ) cl @
276            [u,iname,
277              NReference.reference_of_spec u
278               (NReference.Ind (inductive,i,leftno))]
279          ) il)
280   in
281   local_aliases := references @ !local_aliases;
282   status#set_timestamp (!storage,!local_aliases,!cache,!includes)
283 ;;
284
285 let get_obj u =
286  try List.assq u !storage
287  with Not_found ->
288   try fetch_obj u
289   with Sys_error _ ->
290    try NUri.UriMap.find u !cache
291    with Not_found ->
292     let ouri = NCic2OCic.ouri_of_nuri u in
293     try
294       let o,_ = CicEnvironment.get_obj CicUniv.oblivion_ugraph ouri in
295       let l = OCic2NCic.convert_obj ouri o in
296       List.iter (fun (u,_,_,_,_ as o) -> cache:= NUri.UriMap.add u o !cache) l;
297       HExtlib.list_last l
298     with CicEnvironment.Object_not_found u -> 
299       raise (NCicEnvironment.ObjectNotFound 
300                (lazy (NUri.string_of_uri (OCic2NCic.nuri_of_ouri u))))
301 ;;
302
303 let clear_cache () = cache := NUri.UriMap.empty;;
304
305 NCicEnvironment.set_get_obj get_obj;;
306 NCicPp.set_get_obj get_obj;;