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