]> matita.cs.unibo.it Git - helm.git/blob - matitaB/components/ng_library/nCicLibrary.ml
Added debug print in NCicLibrary.serialize.
[helm.git] / matitaB / 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 refresh_uri_in_term status =
29  let rec aux =
30   function
31   | NCic.Meta (i,(n,NCic.Ctx l)) ->
32      NCic.Meta (i,(n,NCic.Ctx (List.map aux l)))
33   | NCic.Meta _ as t -> t
34   | NCic.Const ref -> NCic.Const (refresh_uri_in_reference ref)
35   | NCic.Sort (NCic.Type l) -> NCic.Sort (NCic.Type (refresh_uri_in_universe l))
36   | NCic.Match (NReference.Ref (uri,spec),outtype,term,pl) ->
37      let r = NReference.reference_of_spec (refresh_uri uri) spec in
38      let outtype = aux outtype in
39      let term = aux term in
40      let pl = List.map aux pl in
41       NCic.Match (r,outtype,term,pl)
42   | t -> NCicUtils.map status (fun _ _ -> ()) () (fun _ -> aux) t
43 in
44  aux
45 ;;
46
47 let refresh_uri_in_obj status (uri,height,metasenv,subst,obj_kind) =
48  assert (metasenv = []);
49  assert (subst = []);
50  refresh_uri uri,height,metasenv,subst,
51   NCicUntrusted.map_obj_kind (refresh_uri_in_term status) obj_kind
52 ;;
53
54 let ng_path_of_baseuri ?(no_suffix=false) user baseuri =
55  let uri = NUri.string_of_uri baseuri in
56  let path = String.sub uri 4 (String.length uri - 4) in
57  let path = match user with
58  | Some u -> "/" ^ u ^ path
59  | _ -> path
60  in
61  let path = Helm_registry.get "matita.basedir" ^ path in
62  let dirname = Filename.dirname path in
63   HExtlib.mkdir dirname;
64   if no_suffix then
65    path
66   else
67    path ^ ".ng"
68 ;;
69
70 let require_path path =
71  let ch = open_in path in
72  let mmagic,dump = Marshal.from_channel ch in
73   close_in ch;
74   if mmagic <> magic then
75    raise (LibraryOutOfSync (lazy "The library is out of sync with the implementation. Please recompile the library."))
76   else
77    dump
78 ;;
79
80 let require0 user ~baseuri = require_path (ng_path_of_baseuri user baseuri)
81
82 let db_path () = Helm_registry.get "matita.basedir" ^ "/ng_db.ng";;
83
84 type timestamp =
85  [ `Obj of NUri.uri * NCic.obj 
86  | `Constr of NCic.universe * NCic.universe] list *
87  (NUri.uri * string * NReference.reference) list
88 ;;
89
90 let time0 = [],[];;
91 let storage = ref [];;
92 let local_aliases = 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 virtual status uid =
152  object
153   inherit NCic.status uid
154   val timestamp = (time0 : timestamp)
155   method timestamp = timestamp
156   method set_timestamp v = {< timestamp = v >}
157  end
158
159 let time_travel0 (sto,ali) =
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    List.iter NCicEnvironment.invalidate_item to_be_deleted;
164   storage := sto; local_aliases := ali
165 ;;
166
167 let time_travel status = time_travel0 status#timestamp;;
168
169 type obj = string * Obj.t
170 (* includes are transitively closed; dependencies are only immediate *)
171 type dump =
172  { objs: obj list ; includes: NUri.uri list; dependencies: string list }
173
174 class type g_dumpable_status =
175  object
176   method dump: dump
177  end
178
179 (* uid = None --> single user mode *)
180 class dumpable_status =
181  object
182   val db = { objs = []; includes = []; dependencies = [] }
183   method dump = db
184   method set_dump v = {< db = v >}
185   method set_dumpable_status
186    : 'status. #g_dumpable_status as 'status -> 'self
187    = fun o -> {< db = o#dump >}
188  end
189
190 let get_transitively_included status =
191  status#dump.includes
192 ;;
193
194 let dump_obj status obj =
195  status#set_dump {status#dump with objs = obj::status#dump.objs }
196 ;;
197
198 module type SerializerType =
199  sig
200   type dumpable_status
201
202   type 'a register_type =
203    'a ->
204     refresh_uri_in_universe:(NCic.universe -> NCic.universe) ->
205     refresh_uri_in_term:(NCic.status -> NCic.term -> NCic.term) ->
206     refresh_uri_in_reference:(NReference.reference -> NReference.reference) ->
207     alias_only:bool ->
208      dumpable_status -> dumpable_status
209
210   val register: < run: 'a.  string -> 'a register_type -> ('a -> obj) >
211   val serialize: baseuri:NUri.uri -> dumpable_status -> unit
212   val require:
213    baseuri:NUri.uri -> fname:string -> alias_only:bool ->
214     dumpable_status -> dumpable_status
215   val dependencies_of: string option -> baseuri:NUri.uri -> string list
216  end
217
218 module Serializer(D: sig type dumpable_s val get: dumpable_s -> dumpable_status
219   val set: dumpable_s -> dumpable_status -> dumpable_s val user : dumpable_s ->
220   string option end) =
221  struct
222   type dumpable_status = D.dumpable_s
223   type 'a register_type =
224    'a ->
225     refresh_uri_in_universe:(NCic.universe -> NCic.universe) ->
226     refresh_uri_in_term:(NCic.status -> NCic.term -> NCic.term) ->
227     refresh_uri_in_reference:(NReference.reference -> NReference.reference) ->
228     alias_only:bool ->
229      dumpable_status -> dumpable_status
230
231   let require1 = ref (fun ~alias_only:_ _ -> assert false) (* unknown data*)
232   let already_registered = ref []
233
234   let register =
235    object
236     method run : 'a.  string -> 'a register_type -> ('a -> obj)
237     = fun tag require ->
238      assert (not (List.mem tag !already_registered));
239      already_registered := tag :: !already_registered;
240      let old_require1 = !require1 in
241      prerr_endline "let old_require 1 superata";
242      require1 :=
243       (fun ~alias_only ((tag',data) as x) ->
244         if tag=tag' then
245                 (prerr_endline ("requiring tag': " ^ tag');
246          require (Obj.magic data) ~refresh_uri_in_universe ~refresh_uri_in_term
247           ~refresh_uri_in_reference ~alias_only)
248         else
249          old_require1 ~alias_only x);
250      prerr_endline ("added require tag" ^ tag);
251      (fun x -> tag,Obj.repr x)
252    end
253
254   let serialize ~baseuri status =
255    let ch = open_out (ng_path_of_baseuri (D.user status) baseuri) in
256    Marshal.to_channel ch (magic,((D.get status)#dump.dependencies,(D.get status)#dump.objs)) [];
257    close_out ch;
258    let deps = String.concat ", " ((D.get status)#dump.dependencies) in 
259    prerr_endline ("dumping dependencies:\n" ^ deps ^ "\nend of deps");
260    List.iter
261     (function 
262      | `Obj (uri,obj) ->
263          let ch = open_out (ng_path_of_baseuri (D.user status) uri) in
264          Marshal.to_channel ch (magic,obj) [];
265          close_out ch
266      | `Constr _ -> ()
267     ) !storage;
268    set_global_aliases (!local_aliases @ get_global_aliases ());
269    List.iter (fun u -> add_deps u [baseuri]) (D.get status)#dump.includes;
270    time_travel0 time0
271
272   let require2 ~baseuri ~alias_only status =
273    try
274     let s = D.get status in
275     let status =
276      D.set status
277       (s#set_dump
278         {s#dump with
279         includes = baseuri::List.filter ((<>) baseuri) s#dump.includes}) in
280     let _dependencies,dump = require0 (D.user status) ~baseuri in
281      List.fold_right (!require1 ~alias_only) dump status
282    with
283     Sys_error _ ->
284      raise (IncludedFileNotCompiled(ng_path_of_baseuri (D.user status) baseuri,NUri.string_of_uri baseuri))
285
286   let dependencies_of user ~baseuri = fst (require0 user ~baseuri)
287
288   let record_include =
289    let aux (baseuri,fname) ~refresh_uri_in_universe:_ ~refresh_uri_in_term:_
290    ~refresh_uri_in_reference:_ ~alias_only status =
291      let alias_only =
292       alias_only || List.mem baseuri (get_transitively_included (D.get status))
293      in
294       HLog.warn ("include " ^ (if alias_only then "alias " else "") ^ fname);
295       let status = require2 ~baseuri ~alias_only status in
296       HLog.warn ("done: include " ^ (if alias_only then "alias " else "") ^ fname);
297       status
298    in
299     register#run "include" aux
300
301   let require ~baseuri ~fname ~alias_only status =
302    let alias_only =
303     alias_only || List.mem baseuri (get_transitively_included (D.get status)) in
304    let status =
305     if not alias_only then
306      let s = D.get status in
307       D.set status
308        (s#set_dump
309          {s#dump with
310            includes = baseuri::s#dump.includes;
311            dependencies = fname::s#dump.dependencies})
312     else
313      status in
314    let status = require2 ~baseuri ~alias_only status in
315    let s = D.get status in
316     D.set status
317      (s#set_dump
318        {s#dump with
319          objs = record_include (baseuri,fname)::s#dump.objs })
320 end
321
322 let fetch_obj user status uri =
323  let obj = require0 user ~baseuri:uri in
324   refresh_uri_in_obj status obj
325 ;;
326
327 let resolve name =
328  try
329   HExtlib.filter_map
330    (fun (_,name',nref) -> if name'=name then Some nref else None)
331    (!local_aliases @ get_global_aliases ())
332  with
333   Not_found -> raise (NCicEnvironment.ObjectNotFound (lazy name))
334 ;;
335
336 let aliases_of uri =
337   HExtlib.filter_map
338    (fun (uri',_,nref) ->
339      if NUri.eq uri' uri then Some nref else None) !local_aliases
340 ;;
341
342 let add_obj status ((u,_,_,_,_) as obj) =
343  NCicEnvironment.check_and_add_obj status obj;
344  storage := (`Obj (u,obj))::!storage;
345   let _,height,_,_,obj = obj in
346   let references =
347    match obj with
348       NCic.Constant (_,name,None,_,_) ->
349        [u,name,NReference.reference_of_spec u NReference.Decl]
350     | NCic.Constant (_,name,Some _,_,_) ->
351        [u,name,NReference.reference_of_spec u (NReference.Def height)]
352     | NCic.Fixpoint (is_ind,fl,_) ->
353        HExtlib.list_mapi
354         (fun (_,name,recno,_,_) i ->
355           if is_ind then
356            u,name,NReference.reference_of_spec u(NReference.Fix(i,recno,height))
357           else
358            u,name,NReference.reference_of_spec u (NReference.CoFix i)) fl
359     | NCic.Inductive (inductive,leftno,il,_) ->
360        List.flatten
361         (HExtlib.list_mapi
362          (fun (_,iname,_,cl) i ->
363            HExtlib.list_mapi
364             (fun (_,cname,_) j->
365               u,cname,
366                NReference.reference_of_spec u (NReference.Con (i,j+1,leftno))
367             ) cl @
368            [u,iname,
369              NReference.reference_of_spec u
370               (NReference.Ind (inductive,i,leftno))]
371          ) il)
372   in
373   local_aliases := references @ !local_aliases;
374   status#set_timestamp (!storage,!local_aliases)
375 ;;
376
377 let add_constraint status u1 u2 = 
378   if
379    List.exists
380     (function `Constr (u1',u2') when u1=u1' && u2=u2' -> true | _ -> false)
381     !storage
382   then
383    (*CSC: raise an exception here! *)
384    (prerr_endline "CANNOT ADD A CONSTRAINT TWICE"; assert false);
385   NCicEnvironment.add_lt_constraint u1 u2;
386   storage := (`Constr (u1,u2)) :: !storage;
387   status#set_timestamp (!storage,!local_aliases)
388 ;;
389
390 let get_obj status u =
391  try 
392   List.assq u 
393    (HExtlib.filter_map 
394     (function `Obj (u,o) -> Some (u,o) | _ -> None )
395     !storage)
396  with Not_found ->
397   try fetch_obj (status#user) status u
398   with Sys_error _ ->
399    raise (NCicEnvironment.ObjectNotFound (lazy (NUri.string_of_uri u)))
400 ;;
401
402 NCicEnvironment.set_get_obj get_obj;;