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