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