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