]> matita.cs.unibo.it Git - helm.git/blob - matita/components/ng_library/nCicLibrary.ml
Avoid duplicates in the list.
[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 ng_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 = require_path (ng_path_of_baseuri baseuri)
74
75 let db_path () = Helm_registry.get "matita.basedir" ^ "/ng_db.ng";;
76
77 type timestamp =
78  [ `Obj of NUri.uri * NCic.obj 
79  | `Constr of NCic.universe * NCic.universe] list *
80  (NUri.uri * string * NReference.reference) list
81 ;;
82
83 let time0 = [],[];;
84 let storage = ref [];;
85 let local_aliases = ref [];;
86
87 let load_db,set_global_aliases,get_global_aliases,add_deps,get_deps,remove_deps=
88  let global_aliases = ref [] in
89  let rev_includes_map = ref NUri.UriMap.empty in
90  let store_db () =
91   let ch = open_out (db_path ()) in
92   Marshal.to_channel ch (magic,(!global_aliases,!rev_includes_map)) [];
93   close_out ch in
94  let load_db () =
95   HExtlib.mkdir (Helm_registry.get "matita.basedir");
96   try
97    let ga,im = require_path (db_path ()) in
98    let ga =
99     List.map
100      (fun (uri,name,NReference.Ref (uri2,spec)) ->
101        refresh_uri uri,name,NReference.reference_of_spec (refresh_uri uri2) spec
102      ) ga in
103    let im =
104     NUri.UriMap.fold
105      (fun u l im -> NUri.UriMap.add (refresh_uri u) (List.map refresh_uri l) im
106      ) im NUri.UriMap.empty
107    in
108     global_aliases := ga;
109     rev_includes_map := im
110   with
111    Sys_error _ -> () in
112  let get_deps u =
113   let get_deps_one_step u =
114     try NUri.UriMap.find u !rev_includes_map with Not_found -> [] in
115   let rec aux res =
116    function
117       [] -> res
118     | he::tl ->
119        if List.mem he res then
120         aux res tl
121        else
122         aux (he::res) (get_deps_one_step he @ tl)
123   in
124    aux [] [u] in
125  let remove_deps u =
126   rev_includes_map := NUri.UriMap.remove u !rev_includes_map;
127   rev_includes_map :=
128    NUri.UriMap.map
129     (fun l -> List.filter (fun uri -> not (NUri.eq u uri)) l) !rev_includes_map;
130   store_db ()
131  in
132   load_db,
133   (fun ga -> global_aliases := ga; store_db ()),
134   (fun () -> !global_aliases),
135   (fun u l ->
136     rev_includes_map := NUri.UriMap.add u (l @ get_deps u) !rev_includes_map;
137     store_db ()),
138   get_deps,
139   remove_deps
140 ;;
141
142 let init = load_db;;
143
144 class status =
145  object
146   val timestamp = (time0 : timestamp)
147   method timestamp = timestamp
148   method set_timestamp v = {< timestamp = v >}
149  end
150
151 let time_travel status =
152  let sto,ali = status#timestamp in
153   let diff_len = List.length !storage - List.length sto in
154   let to_be_deleted,_ = HExtlib.split_nth diff_len !storage in
155    if List.length to_be_deleted > 0 then
156     List.iter NCicEnvironment.invalidate_item to_be_deleted;
157    storage := sto; local_aliases := ali
158 ;;
159
160 type obj = string * Obj.t
161 (* includes are transitively closed; dependencies are only immediate *)
162 type dump =
163  { objs: obj list ; includes: NUri.uri list; dependencies: string list }
164
165 class type g_dumpable_status =
166  object
167   method dump: dump
168  end
169
170 class dumpable_status =
171  object
172   val db = { objs = []; includes = []; dependencies = [] }
173   method dump = db
174   method set_dump v = {< db = v >}
175   method set_dumpable_status
176    : 'status. #g_dumpable_status as 'status -> 'self
177    = fun o -> {< db = o#dump >}
178  end
179
180 let get_transitively_included status =
181  status#dump.includes
182 ;;
183
184 let dump_obj status obj =
185  status#set_dump {status#dump with objs = obj::status#dump.objs }
186 ;;
187
188 module type SerializerType =
189  sig
190   type dumpable_status
191
192   type 'a register_type =
193    'a ->
194     refresh_uri_in_universe:(NCic.universe -> NCic.universe) ->
195     refresh_uri_in_term:(NCic.term -> NCic.term) ->
196     refresh_uri_in_reference:(NReference.reference -> NReference.reference) ->
197     alias_only:bool ->
198      dumpable_status -> dumpable_status
199
200   val register: < run: 'a.  string -> 'a register_type -> ('a -> obj) >
201   val serialize: baseuri:NUri.uri -> dumpable_status -> unit
202   val require:
203    baseuri:NUri.uri -> fname:string -> alias_only:bool ->
204     dumpable_status -> dumpable_status
205   val dependencies_of: baseuri:NUri.uri -> string list
206  end
207
208 module Serializer(D: sig type dumpable_s val get: dumpable_s -> dumpable_status  val set: dumpable_s -> dumpable_status -> dumpable_s end) =
209  struct
210   type dumpable_status = D.dumpable_s
211   type 'a register_type =
212    'a ->
213     refresh_uri_in_universe:(NCic.universe -> NCic.universe) ->
214     refresh_uri_in_term:(NCic.term -> NCic.term) ->
215     refresh_uri_in_reference:(NReference.reference -> NReference.reference) ->
216     alias_only:bool ->
217      dumpable_status -> dumpable_status
218
219   let require1 = ref (fun ~alias_only:_ _ -> assert false) (* unknown data*)
220   let already_registered = ref []
221
222   let register =
223    object
224     method run : 'a.  string -> 'a register_type -> ('a -> obj)
225     = fun tag require ->
226      assert (not (List.mem tag !already_registered));
227      already_registered := tag :: !already_registered;
228      let old_require1 = !require1 in
229      require1 :=
230       (fun ~alias_only ((tag',data) as x) ->
231         if tag=tag' then
232          require (Obj.magic data) ~refresh_uri_in_universe ~refresh_uri_in_term
233           ~refresh_uri_in_reference ~alias_only
234         else
235          old_require1 ~alias_only x);
236      (fun x -> tag,Obj.repr x)
237    end
238
239   let serialize ~baseuri status =
240    let status = D.get status in
241    let ch = open_out (ng_path_of_baseuri baseuri) in
242    Marshal.to_channel ch (magic,(status#dump.dependencies,status#dump.objs)) [];
243    close_out ch;
244    List.iter
245     (function 
246      | `Obj (uri,obj) ->
247          let ch = open_out (ng_path_of_baseuri uri) in
248          Marshal.to_channel ch (magic,obj) [];
249          close_out ch
250      | `Constr _ -> ()
251     ) !storage;
252    set_global_aliases (!local_aliases @ get_global_aliases ());
253    List.iter (fun u -> add_deps u [baseuri]) status#dump.includes;
254    time_travel (new status)
255
256   let require2 ~baseuri ~alias_only status =
257    try
258     let s = D.get status in
259     let status =
260      D.set status
261       (s#set_dump
262         {s#dump with
263         includes = baseuri::List.filter ((<>) baseuri) s#dump.includes}) in
264     let _dependencies,dump = require0 ~baseuri in
265      List.fold_right (!require1 ~alias_only) dump status
266    with
267     Sys_error _ ->
268      raise (IncludedFileNotCompiled(ng_path_of_baseuri baseuri,NUri.string_of_uri baseuri))
269
270   let dependencies_of ~baseuri = fst (require0 ~baseuri)
271
272   let record_include =
273    let aux (baseuri,fname) ~refresh_uri_in_universe:_ ~refresh_uri_in_term:_
274    ~refresh_uri_in_reference:_ ~alias_only status =
275      let alias_only =
276       alias_only || List.mem baseuri (get_transitively_included (D.get status))
277      in
278       HLog.warn ("include " ^ (if alias_only then "alias " else "") ^ fname);
279       let status = require2 ~baseuri ~alias_only status in
280       HLog.warn ("done: include " ^ (if alias_only then "alias " else "") ^ fname);
281       status
282    in
283     register#run "include" aux
284
285   let require ~baseuri ~fname ~alias_only status =
286    let alias_only =
287     alias_only || List.mem baseuri (get_transitively_included (D.get status)) in
288    let status =
289     if not alias_only then
290      let s = D.get status in
291       D.set status
292        (s#set_dump
293          {s#dump with
294            includes = baseuri::s#dump.includes;
295            dependencies = fname::s#dump.dependencies})
296     else
297      status in
298    let status = require2 ~baseuri ~alias_only status in
299    let s = D.get status in
300     D.set status
301      (s#set_dump
302        {s#dump with
303          objs = record_include (baseuri,fname)::s#dump.objs })
304 end
305
306 let fetch_obj uri =
307  let obj = require0 ~baseuri:uri in
308   refresh_uri_in_obj obj
309 ;;
310
311 let resolve name =
312  try
313   HExtlib.filter_map
314    (fun (_,name',nref) -> if name'=name then Some nref else None)
315    (!local_aliases @ get_global_aliases ())
316  with
317   Not_found -> raise (NCicEnvironment.ObjectNotFound (lazy name))
318 ;;
319
320 let aliases_of uri =
321   HExtlib.filter_map
322    (fun (uri',_,nref) ->
323      if NUri.eq uri' uri then Some nref else None) !local_aliases
324 ;;
325
326 let add_obj status ((u,_,_,_,_) as obj) =
327  NCicEnvironment.check_and_add_obj obj;
328  storage := (`Obj (u,obj))::!storage;
329   let _,height,_,_,obj = obj in
330   let references =
331    match obj with
332       NCic.Constant (_,name,None,_,_) ->
333        [u,name,NReference.reference_of_spec u NReference.Decl]
334     | NCic.Constant (_,name,Some _,_,_) ->
335        [u,name,NReference.reference_of_spec u (NReference.Def height)]
336     | NCic.Fixpoint (is_ind,fl,_) ->
337        HExtlib.list_mapi
338         (fun (_,name,recno,_,_) i ->
339           if is_ind then
340            u,name,NReference.reference_of_spec u(NReference.Fix(i,recno,height))
341           else
342            u,name,NReference.reference_of_spec u (NReference.CoFix i)) fl
343     | NCic.Inductive (inductive,leftno,il,_) ->
344        List.flatten
345         (HExtlib.list_mapi
346          (fun (_,iname,_,cl) i ->
347            HExtlib.list_mapi
348             (fun (_,cname,_) j->
349               u,cname,
350                NReference.reference_of_spec u (NReference.Con (i,j+1,leftno))
351             ) cl @
352            [u,iname,
353              NReference.reference_of_spec u
354               (NReference.Ind (inductive,i,leftno))]
355          ) il)
356   in
357   local_aliases := references @ !local_aliases;
358   status#set_timestamp (!storage,!local_aliases)
359 ;;
360
361 let add_constraint status u1 u2 = 
362   if
363    List.exists
364     (function `Constr (u1',u2') when u1=u1' && u2=u2' -> true | _ -> false)
365     !storage
366   then
367    (*CSC: raise an exception here! *)
368    (prerr_endline "CANNOT ADD A CONSTRAINT TWICE"; assert false);
369   NCicEnvironment.add_lt_constraint u1 u2;
370   storage := (`Constr (u1,u2)) :: !storage;
371   status#set_timestamp (!storage,!local_aliases)
372 ;;
373
374 let get_obj u =
375  try 
376   List.assq u 
377    (HExtlib.filter_map 
378     (function `Obj (u,o) -> Some (u,o) | _ -> None )
379     !storage)
380  with Not_found ->
381   try fetch_obj u
382   with Sys_error _ ->
383    raise (NCicEnvironment.ObjectNotFound (lazy (NUri.string_of_uri u)))
384 ;;
385
386 NCicEnvironment.set_get_obj get_obj;;
387 NCicPp.set_get_obj get_obj;;