]> matita.cs.unibo.it Git - helm.git/blob - matitaB/components/ng_library/nCicLibrary.ml
1) removed many debug prints
[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  | _ -> prerr_endline "WARNING: ng_path_of_baseuri called without a uid"; 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
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 db = {
150   storage : 
151     [ `Obj of NUri.uri * NCic.obj 
152     | `Constr of NCic.universe * NCic.universe] list ref;
153   local_aliases : 
154     (NUri.uri * string * NReference.reference) list ref
155 }
156
157 class type g_status =
158   object
159     inherit NCicEnvironment.g_status
160     method lib_db : db
161   end
162
163 class virtual status uid =
164  object
165   inherit NCicEnvironment.status uid
166
167   val lib_db = {
168     storage = ref [];
169     local_aliases = ref []
170   }
171   method lib_db = lib_db
172
173   val timestamp = (time0 : timestamp)
174   method timestamp = timestamp
175
176   method set_timestamp v = {< timestamp = v >}
177   method set_lib_db v = {< lib_db = v >}
178   method set_lib_status : 's.#g_status as 's -> 'self
179    = fun o -> {< lib_db = o#lib_db >}#set_env_status o
180  end
181
182 let reset_timestamp st =
183   st#lib_db.storage := [];
184   st#lib_db.local_aliases := []
185 ;;
186
187 let time_travel0 st (sto,ali) =
188  let diff_len = List.length !(st#lib_db.storage) - List.length sto in
189  let to_be_deleted,_ = HExtlib.split_nth diff_len !(st#lib_db.storage) in
190   if List.length to_be_deleted > 0 then
191    List.iter (NCicEnvironment.invalidate_item st) to_be_deleted;
192   st#lib_db.storage := sto; st#lib_db.local_aliases := ali
193 ;;
194
195 let time_travel status = time_travel0 status status#timestamp;;
196
197 type obj = string * Obj.t
198 (* includes are transitively closed; dependencies are only immediate *)
199 type dump =
200  { objs: obj list ; includes: NUri.uri list; dependencies: string list }
201
202 class type g_dumpable_status =
203  object
204   method dump: dump
205  end
206
207 (* uid = None --> single user mode *)
208 class dumpable_status uid =
209  object
210   inherit NCicPp.status uid
211   inherit status uid
212
213   val db = { objs = []; includes = []; dependencies = [] }
214   method dump = db
215   method set_dump v = {< db = v >}
216   method set_dumpable_status
217    : 'status. #g_dumpable_status as 'status -> 'self
218    = fun o -> {< db = o#dump >}
219  end
220
221 let get_transitively_included status =
222  status#dump.includes
223 ;;
224
225 let dump_obj status obj =
226  status#set_dump {status#dump with objs = obj::status#dump.objs }
227 ;;
228
229 module type SerializerType =
230  sig
231   type dumpable_status
232
233   type 'a register_type =
234    'a ->
235     refresh_uri_in_universe:(NCic.universe -> NCic.universe) ->
236     refresh_uri_in_term:(NCicEnvironment.status -> NCic.term -> NCic.term) ->
237     refresh_uri_in_reference:(NReference.reference -> NReference.reference) ->
238     alias_only:bool ->
239      dumpable_status -> dumpable_status
240
241   val register: < run: 'a.  string -> 'a register_type -> ('a -> obj) >
242   val serialize: baseuri:NUri.uri -> dumpable_status -> unit
243   val require:
244    baseuri:NUri.uri -> fname:string -> alias_only:bool ->
245     dumpable_status -> dumpable_status
246   val dependencies_of: string option -> baseuri:NUri.uri -> string list
247  end
248
249 module Serializer(D: sig type dumpable_s val get: dumpable_s -> dumpable_status
250   val set: dumpable_s -> dumpable_status -> dumpable_s (*val user : dumpable_s ->
251   string option*) end) =
252  struct
253   type dumpable_status = D.dumpable_s
254   type 'a register_type =
255    'a ->
256     refresh_uri_in_universe:(NCic.universe -> NCic.universe) ->
257     refresh_uri_in_term:(NCicEnvironment.status -> NCic.term -> NCic.term) ->
258     refresh_uri_in_reference:(NReference.reference -> NReference.reference) ->
259     alias_only:bool ->
260      dumpable_status -> dumpable_status
261
262   let require1 = ref (fun ~alias_only:_ _ -> assert false) (* unknown data*)
263   let already_registered = ref []
264
265   let register =
266    object
267     method run : 'a.  string -> 'a register_type -> ('a -> obj)
268     = fun tag require ->
269      assert (not (List.mem tag !already_registered));
270      already_registered := tag :: !already_registered;
271      let old_require1 = !require1 in
272      prerr_endline "let old_require 1 superata";
273      require1 :=
274       (fun ~alias_only ((tag',data) as x) ->
275         if tag=tag' then
276                 (prerr_endline ("requiring tag': " ^ tag');
277          require (Obj.magic data) ~refresh_uri_in_universe ~refresh_uri_in_term
278           ~refresh_uri_in_reference ~alias_only)
279         else
280          old_require1 ~alias_only x);
281      prerr_endline ("added require tag" ^ tag);
282      (fun x -> tag,Obj.repr x)
283    end
284
285   let serialize ~baseuri status =
286    let ch = open_out (ng_path_of_baseuri (D.get status)#user baseuri) in
287    Marshal.to_channel ch (magic,((D.get status)#dump.dependencies,(D.get status)#dump.objs)) [];
288    close_out ch;
289    let deps = String.concat ", " ((D.get status)#dump.dependencies) in 
290    prerr_endline ("dumping dependencies:\n" ^ deps ^ "\nend of deps");
291    List.iter
292     (function 
293      | `Obj (uri,obj) ->
294          let ch = open_out (ng_path_of_baseuri (D.get status)#user uri) in
295          Marshal.to_channel ch (magic,obj) [];
296          close_out ch
297      | `Constr _ -> ()
298     ) !((D.get status)#lib_db.storage);
299    set_global_aliases (!((D.get status)#lib_db.local_aliases) @ get_global_aliases ());
300    List.iter (fun u -> add_deps u [baseuri]) (D.get status)#dump.includes;
301    reset_timestamp (D.get status)
302
303   let require2 ~baseuri ~alias_only status =
304    try
305     let s = D.get status in
306     let status =
307      D.set status
308       (s#set_dump
309         {s#dump with
310         includes = baseuri::List.filter ((<>) baseuri) s#dump.includes}) in
311     let _dependencies,dump = require0 (D.get status)#user ~baseuri in
312      List.fold_right (!require1 ~alias_only) dump status
313    with
314     Sys_error _ ->
315      raise (IncludedFileNotCompiled(ng_path_of_baseuri (D.get status)#user baseuri,NUri.string_of_uri baseuri))
316
317   let dependencies_of user ~baseuri = fst (require0 user ~baseuri)
318
319   let record_include =
320    let aux (baseuri,fname) ~refresh_uri_in_universe:_ ~refresh_uri_in_term:_
321    ~refresh_uri_in_reference:_ ~alias_only status =
322      let alias_only =
323       alias_only || List.mem baseuri (get_transitively_included (D.get status))
324      in
325       HLog.warn ("include " ^ (if alias_only then "alias " else "") ^ fname);
326       let status = require2 ~baseuri ~alias_only status in
327       HLog.warn ("done: include " ^ (if alias_only then "alias " else "") ^ fname);
328       status
329    in
330     register#run "include" aux
331
332   let require ~baseuri ~fname ~alias_only status =
333    let alias_only =
334     alias_only || List.mem baseuri (get_transitively_included (D.get status)) in
335    let status =
336     if not alias_only then
337      let s = D.get status in
338       D.set status
339        (s#set_dump
340          {s#dump with
341            includes = baseuri::s#dump.includes;
342            dependencies = fname::s#dump.dependencies})
343     else
344      status in
345    let status = require2 ~baseuri ~alias_only status in
346    let s = D.get status in
347     D.set status
348      (s#set_dump
349        {s#dump with
350          objs = record_include (baseuri,fname)::s#dump.objs })
351 end
352
353 let fetch_obj user status uri =
354  let obj = require0 user ~baseuri:uri in
355   refresh_uri_in_obj status obj
356 ;;
357
358 let resolve st name =
359  try
360   HExtlib.filter_map
361    (fun (_,name',nref) -> if name'=name then Some nref else None)
362    (!(st#lib_db.local_aliases) @ get_global_aliases ())
363  with
364   Not_found -> 
365    (prerr_endline ("can't resolve object " ^ name);
366     raise (NCicEnvironment.ObjectNotFound (lazy name)))
367 ;;
368
369 let aliases_of st uri =
370   HExtlib.filter_map
371    (fun (uri',_,nref) ->
372      if NUri.eq uri' uri then Some nref else None) !(st#lib_db.local_aliases)
373 ;;
374
375 let add_obj status ((u,_,_,_,_) as obj) =
376  NCicEnvironment.check_and_add_obj status obj;
377  status#lib_db.storage := (`Obj (u,obj))::!(status#lib_db.storage);
378   let _,height,_,_,obj = obj in
379   let references =
380    match obj with
381       NCic.Constant (_,name,None,_,_) ->
382        [u,name,NReference.reference_of_spec u NReference.Decl]
383     | NCic.Constant (_,name,Some _,_,_) ->
384        [u,name,NReference.reference_of_spec u (NReference.Def height)]
385     | NCic.Fixpoint (is_ind,fl,_) ->
386        HExtlib.list_mapi
387         (fun (_,name,recno,_,_) i ->
388           if is_ind then
389            u,name,NReference.reference_of_spec u(NReference.Fix(i,recno,height))
390           else
391            u,name,NReference.reference_of_spec u (NReference.CoFix i)) fl
392     | NCic.Inductive (inductive,leftno,il,_) ->
393        List.flatten
394         (HExtlib.list_mapi
395          (fun (_,iname,_,cl) i ->
396            HExtlib.list_mapi
397             (fun (_,cname,_) j->
398               u,cname,
399                NReference.reference_of_spec u (NReference.Con (i,j+1,leftno))
400             ) cl @
401            [u,iname,
402              NReference.reference_of_spec u
403               (NReference.Ind (inductive,i,leftno))]
404          ) il)
405   in
406   status#lib_db.local_aliases := references @ !(status#lib_db.local_aliases);
407   status#set_timestamp (!(status#lib_db.storage),!(status#lib_db.local_aliases))
408 ;;
409
410 let add_constraint status u1 u2 = 
411   if
412    List.exists
413     (function `Constr (u1',u2') when u1=u1' && u2=u2' -> true | _ -> false)
414     !(status#lib_db.storage)
415   then
416    (*CSC: raise an exception here! *)
417    (prerr_endline "CANNOT ADD A CONSTRAINT TWICE"; assert false);
418   NCicEnvironment.add_lt_constraint status u1 u2;
419   status#lib_db.storage := (`Constr (u1,u2)) :: !(status#lib_db.storage);
420   status#set_timestamp (!(status#lib_db.storage),!(status#lib_db.local_aliases))
421 ;;
422
423 let get_obj status u =
424 (*
425  try 
426   List.assq u 
427    (HExtlib.filter_map 
428     (function `Obj (u,o) -> Some (u,o) | _ -> None )
429     !(status#lib_db.storage))
430  with Not_found ->*)
431   try fetch_obj (status#user) status u
432   with Sys_error _ ->
433    (prerr_endline ("can't fetch object " ^ NUri.string_of_uri u);
434    raise (NCicEnvironment.ObjectNotFound (lazy (NUri.string_of_uri u))))
435 ;;
436
437 NCicEnvironment.set_get_obj 
438   (get_obj :> NCicEnvironment.status -> NUri.uri -> NCic.obj);;