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