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