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