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