]> matita.cs.unibo.it Git - helm.git/blob - components/library/librarySync.ml
c71c24f11c109f46458ceb7c030a8e374b5f0bcf
[helm.git] / components / library / librarySync.ml
1 (* Copyright (C) 2004-2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 (* $Id$ *)
27
28 let object_declaration_hook = ref (fun _ _ -> ());;
29 let set_object_declaration_hook f =
30  object_declaration_hook := f
31
32 exception AlreadyDefined of UriManager.uri
33
34 let auxiliary_lemmas_hashtbl = UriManager.UriHashtbl.create 29
35
36 (* uri |-->  (derived_coercions_in_the_coercion_DB, derived_coercions_in_lib)
37  * 
38  * in case of remove_coercion uri, the first component is removed from the
39  * coercion DB, while the second is passed to remove_obj (and is not [] only if
40  * add_coercion is called with add_composites 
41  * *)
42 let coercion_hashtbl = UriManager.UriHashtbl.create 3
43
44 let uris_of_obj uri =
45  let innertypesuri = UriManager.innertypesuri_of_uri uri in
46  let bodyuri = UriManager.bodyuri_of_uri uri in
47  let univgraphuri = UriManager.univgraphuri_of_uri uri in
48   innertypesuri,bodyuri,univgraphuri
49
50 let paths_and_uris_of_obj uri =
51   let resolved = Http_getter.filename' ~local:true ~writable:true uri in
52   let basepath = Filename.dirname resolved in
53   let innertypesuri, bodyuri, univgraphuri = uris_of_obj uri in
54   let innertypesfilename=(UriManager.nameext_of_uri innertypesuri)^".xml.gz"in
55   let innertypespath = basepath ^ "/" ^ innertypesfilename in
56   let xmlfilename = (UriManager.nameext_of_uri uri) ^ ".xml.gz" in
57   let xmlpath = basepath ^ "/" ^ xmlfilename in
58   let xmlbodyfilename = (UriManager.nameext_of_uri uri) ^ ".body.xml.gz" in
59   let xmlbodypath = basepath ^ "/" ^  xmlbodyfilename in
60   let xmlunivgraphfilename=(UriManager.nameext_of_uri univgraphuri)^".xml.gz"in
61   let xmlunivgraphpath = basepath ^ "/" ^ xmlunivgraphfilename in
62   xmlpath, xmlbodypath, innertypespath, bodyuri, innertypesuri, 
63   xmlunivgraphpath, univgraphuri
64
65 let save_object_to_disk uri obj ugraph univlist =
66   let write f x =
67     if not (Helm_registry.get_opt_default 
68               Helm_registry.bool "matita.nodisk" ~default:false) 
69     then      
70       f x
71   in
72   let ensure_path_exists path =
73     let dir = Filename.dirname path in
74     HExtlib.mkdir dir
75   in
76   (* generate annobj, ids_to_inner_sorts and ids_to_inner_types *)
77   let annobj, innertypes, ids_to_inner_sorts, generate_attributes =
78    if Helm_registry.get_bool "matita.system" then
79     let annobj, _, _, ids_to_inner_sorts, ids_to_inner_types, _, _ =
80      Cic2acic.acic_object_of_cic_object obj 
81     in
82     let innertypesxml = 
83      Cic2Xml.print_inner_types
84       uri ~ids_to_inner_sorts ~ids_to_inner_types ~ask_dtd_to_the_getter:false
85     in
86     annobj, Some innertypesxml, Some ids_to_inner_sorts, false
87    else 
88     let annobj = Cic2acic.plain_acic_object_of_cic_object obj in  
89     annobj, None, None, true 
90   in 
91   (* prepare XML *)
92   let xml, bodyxml =
93    Cic2Xml.print_object
94     uri ?ids_to_inner_sorts ~ask_dtd_to_the_getter:false 
95     ~generate_attributes annobj 
96   in    
97   let xmlpath, xmlbodypath, innertypespath, bodyuri, innertypesuri, 
98       xmlunivgraphpath, univgraphuri = 
99     paths_and_uris_of_obj uri 
100   in
101   write (List.iter HExtlib.mkdir) (List.map Filename.dirname [xmlpath]);
102   (* now write to disk *)
103   write ensure_path_exists xmlpath;
104   write (Xml.pp ~gzip:true xml) (Some xmlpath);
105   write (CicUniv.write_xml_of_ugraph xmlunivgraphpath ugraph) univlist;
106   (* we return a list of uri,path we registered/created *)
107   (uri,xmlpath) ::
108   (univgraphuri,xmlunivgraphpath) ::
109     (* now the optional inner types, both write and register *)
110     (match innertypes with 
111      | None -> []
112      | Some innertypesxml ->
113          write ensure_path_exists innertypespath;
114          write (Xml.pp ~gzip:true innertypesxml) (Some innertypespath);
115          [innertypesuri, innertypespath]
116     ) @
117     (* now the optional body, both write and register *)
118     (match bodyxml,bodyuri with
119        None,_ -> []
120      | Some bodyxml,Some bodyuri->
121          write ensure_path_exists xmlbodypath;
122          write (Xml.pp ~gzip:true bodyxml) (Some xmlbodypath);
123          [bodyuri, xmlbodypath]
124      | _-> assert false) 
125
126
127 let typecheck_obj =
128  let profiler = HExtlib.profile "add_obj.typecheck_obj" in
129   fun uri obj -> profiler.HExtlib.profile (CicTypeChecker.typecheck_obj uri) obj
130
131 let index_obj =
132  let profiler = HExtlib.profile "add_obj.index_obj" in
133   fun ~dbd ~uri ->
134    profiler.HExtlib.profile (fun uri -> MetadataDb.index_obj ~dbd ~uri) uri
135
136 let add_single_obj uri obj refinement_toolkit =
137   let module RT = RefinementTool in
138   let obj = 
139     if (*List.mem `Generated (CicUtil.attributes_of_obj obj) &&*)
140        not (CoercDb.is_a_coercion' (Cic.Const (uri, [])))
141     then
142       refinement_toolkit.RT.pack_coercion_obj obj
143     else
144       obj 
145   in
146   let dbd = LibraryDb.instance () in
147   if CicEnvironment.in_library uri then
148     raise (AlreadyDefined uri)
149   else begin
150     (*CicUniv.reset_spent_time ();
151     let before = Unix.gettimeofday () in*)
152     typecheck_obj uri obj; (* 1 *)
153     (*let after = Unix.gettimeofday () in
154     let univ_time = CicUniv.get_spent_time () in
155     let total_time = after -. before in
156     prerr_endline 
157       (Printf.sprintf "QED: %%univ = %2.5f, total = %2.5f, univ = %2.5f, %s\n" 
158       (univ_time *. 100. /. total_time) (total_time) (univ_time)
159       (UriManager.name_of_uri uri));*)
160     let _, ugraph, univlist = 
161       CicEnvironment.get_cooked_obj_with_univlist CicUniv.empty_ugraph uri in
162     try 
163       index_obj ~dbd ~uri; (* 2 must be in the env *)
164       try
165         (*3*)
166         let new_stuff = save_object_to_disk uri obj ugraph univlist in
167         (* EXPERIMENTAL: pretty print the object in natural language *)
168         (try !object_declaration_hook uri obj
169          with exc ->
170           prerr_endline "Error: object_declaration_hook failed");
171         try 
172          HLog.message
173           (Printf.sprintf "%s defined" (UriManager.string_of_uri uri))
174         with exc ->
175           List.iter HExtlib.safe_remove (List.map snd new_stuff); (* -3 *)
176           raise exc
177       with exc ->
178         ignore(LibraryDb.remove_uri uri); (* -2 *)
179         raise exc
180     with exc ->
181       CicEnvironment.remove_obj uri; (* -1 *)
182       raise exc
183   end
184
185 let remove_single_obj uri =
186   let derived_uris_of_uri uri =
187    let innertypesuri, bodyuri, univgraphuri = uris_of_obj uri in
188     innertypesuri::univgraphuri::(match bodyuri with None -> [] | Some u -> [u])
189   in
190   let uris_to_remove =
191    if UriManager.uri_is_ind uri then LibraryDb.xpointers_of_ind uri else [uri]
192   in
193   let files_to_remove = uri :: derived_uris_of_uri uri in   
194   List.iter 
195    (fun uri -> 
196      (try
197        let file = Http_getter.resolve' ~local:true ~writable:true uri in
198         HExtlib.safe_remove file;
199         HExtlib.rmdir_descend (Filename.dirname file)
200      with Http_getter_types.Key_not_found _ -> ());
201    ) files_to_remove ;
202   List.iter 
203    (fun uri -> 
204      ignore (LibraryDb.remove_uri uri);
205      (*CoercGraph.remove_coercion uri;*)
206    ) uris_to_remove ;
207   CicEnvironment.remove_obj uri
208
209 (*** GENERATION OF AUXILIARY LEMMAS ***)
210
211 let generate_elimination_principles uri refinement_toolkit =
212   let uris = ref [] in
213   let elim i =
214     let elim sort =
215       try
216         let uri,obj = CicElim.elim_of ~sort uri i in
217           add_single_obj uri obj refinement_toolkit;
218           uris := uri :: !uris
219       with CicElim.Can_t_eliminate -> ()
220     in
221       try
222         List.iter 
223           elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
224       with exn ->
225         List.iter remove_single_obj !uris;
226         raise exn 
227   in
228   let (obj, univ) = (CicEnvironment.get_obj CicUniv.empty_ugraph uri) in
229     match obj with
230       | Cic.InductiveDefinition (indTypes, _, _, _) ->
231           let counter = ref 0 in
232             List.iter (fun _ -> elim !counter; counter := !counter+1) indTypes;
233             !uris
234       | _  -> 
235           failwith (Printf.sprintf "not an inductive definition (%s)"
236                       (UriManager.string_of_uri uri))
237
238 (* COERCIONS ***********************************************************)
239   
240 let remove_all_coercions () =
241   UriManager.UriHashtbl.clear coercion_hashtbl;
242   CoercDb.remove_coercion (fun (_,_,_,_) -> true)
243
244 let add_coercion ~add_composites refinement_toolkit uri arity saturations
245  baseuri
246 =
247   let coer_ty,_ =
248     let coer = CicUtil.term_of_uri uri in
249     CicTypeChecker.type_of_aux' [] [] coer CicUniv.empty_ugraph 
250   in
251   (* we have to get the source and the tgt type uri
252    * in Coq syntax we have already their names, but
253    * since we don't support Funclass and similar I think
254    * all the coercion should be of the form
255    * (A:?)(B:?)T1->T2
256    * So we should be able to extract them from the coercion type
257    * 
258    * Currently only (_:T1)T2 is supported.
259    * should we saturate it with metas in case we insert it?
260    * 
261    *)
262   let spine2list ty =
263     let rec aux = function
264       | Cic.Prod( _, src, tgt) -> src::aux tgt
265       | t -> [t]
266     in
267     aux ty
268   in
269   let src_carr, tgt_carr = 
270     let get_classes arity saturations l = 
271       (* this is the ackerman's function revisited *)
272       let rec aux = function
273          0,0,None,tgt::src::_ -> src,Some (`Class tgt)
274        | 0,0,target,src::_ -> src,target
275        | 0,saturations,None,tgt::tl -> aux (0,saturations,Some (`Class tgt),tl)
276        | 0,saturations,target,_::tl -> aux (0,saturations - 1,target,tl)
277        | arity,saturations,None,_::tl -> 
278             aux (arity, saturations, Some `Funclass, tl)
279        | arity,saturations,target,_::tl -> 
280             aux (arity - 1, saturations, target, tl)
281        | _ -> assert false
282       in
283        aux (arity,saturations,None,List.rev l)
284     in
285     let types = spine2list coer_ty in
286     let src,tgt = get_classes arity saturations types in
287      CoercDb.coerc_carr_of_term (CicReduction.whd ~delta:false [] src),
288      match tgt with
289         None -> assert false
290       | Some `Funclass -> CoercDb.Fun arity
291       | Some (`Class tgt) ->
292          CoercDb.coerc_carr_of_term (CicReduction.whd ~delta:false [] tgt)
293   in
294   let already_in_obj src_carr tgt_carr uri obj = 
295      List.exists 
296       (fun (s,t,ul) -> 
297         List.exists 
298          (fun u,_ -> 
299            let bo = 
300             match obj with 
301             | Cic.Constant (_, Some bo, _, _, _) -> bo
302             | _ -> assert false
303            in
304            CoercDb.eq_carr s src_carr && 
305            CoercDb.eq_carr t tgt_carr &&
306            if fst (CicReduction.are_convertible [] (CicUtil.term_of_uri u) bo
307            CicUniv.oblivion_ugraph)
308            then true else
309             (HLog.warn
310               ("Coercions " ^ 
311                 UriManager.string_of_uri u ^ " and " ^ UriManager.string_of_uri
312                 uri^" are not convertible, but are between the same nodes.\n"^
313                 "From now on unification can fail randomly.");
314              false))
315          ul)
316       (CoercDb.to_list ())
317   in
318   if not add_composites then
319     (CoercDb.add_coercion (src_carr, tgt_carr, uri, saturations);[])
320   else
321     let new_coercions = 
322       CicCoercion.close_coercion_graph src_carr tgt_carr uri saturations
323        baseuri
324     in
325     let new_coercions = 
326       List.filter (fun (s,t,u,_,obj,_) -> not(already_in_obj s t u obj))
327       new_coercions 
328     in
329     let composite_uris = List.map (fun (_,_,uri,_,_,_) -> uri) new_coercions in
330     (* update the DB *)
331     List.iter 
332       (fun (src,tgt,uri,saturations,_,_) ->
333         CoercDb.add_coercion (src,tgt,uri,saturations)) 
334       new_coercions;
335     CoercDb.add_coercion (src_carr, tgt_carr, uri, saturations);
336     (* add the composites obj and they eventual lemmas *)
337     let lemmas = 
338       if add_composites then
339         List.fold_left
340           (fun acc (_,tgt,uri,saturations,obj,arity) -> 
341             add_single_obj uri obj refinement_toolkit;
342              (uri,arity,saturations)::acc) 
343           [] new_coercions
344       else
345         []
346     in
347     (* store that composite_uris are related to uri. the first component is
348      * the stuff in the DB while the second is stuff for remove_obj *)
349     (* 
350        prerr_endline ("adding: " ^ 
351          string_of_bool add_composites ^ UriManager.string_of_uri uri);
352        List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
353         composite_uris; 
354     *)
355     UriManager.UriHashtbl.add coercion_hashtbl uri 
356       (composite_uris,if add_composites then composite_uris else []);
357     (*
358     prerr_endline ("lemmas:");
359       List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
360       lemmas;
361     prerr_endline ("lemmas END");*)
362     lemmas
363 ;;
364
365 let remove_coercion uri =
366   try
367     let (composites_in_db, composites_in_lib) = 
368       UriManager.UriHashtbl.find coercion_hashtbl uri 
369     in
370     (*prerr_endline ("removing: " ^UriManager.string_of_uri uri);
371     List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
372       composites_in_db;*)
373     UriManager.UriHashtbl.remove coercion_hashtbl uri;
374     CoercDb.remove_coercion (fun (_,_,u,_) -> UriManager.eq uri u);
375     (* remove from the DB *) 
376     List.iter 
377       (fun u -> CoercDb.remove_coercion (fun (_,_,u1,_) -> UriManager.eq u u1))
378       composites_in_db;
379     (* remove composites from the lib *)
380     List.iter remove_single_obj composites_in_lib
381   with
382     Not_found -> () (* mhh..... *)
383     
384
385 let generate_projections refinement_toolkit uri fields =
386  let uris = ref [] in
387  let projections = 
388    CicRecord.projections_of uri 
389      (List.map (fun (x,_,_) -> x) fields) 
390  in
391   try
392    List.iter2 
393     (fun (uri, name, bo) (_name, coercion, arity) ->
394       let saturations = 0 in
395       try
396        let ty, ugraph =
397          CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph in
398        let attrs = [`Class `Projection; `Generated] in
399        let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
400         add_single_obj uri obj refinement_toolkit;
401         let composites = 
402          if coercion then
403             begin
404 (*prerr_endline ("composite for " ^ UriManager.string_of_uri uri);*)
405               (*CSC: I think there is a bug here. The composite coercions
406                 are not remembered in the .moo file. Thus they are re-generated
407                 every time. Right? *)
408               let x = 
409                 add_coercion ~add_composites:true refinement_toolkit uri arity
410                  saturations (UriManager.buri_of_uri uri)
411               in
412 (*prerr_endline ("are: ");
413   List.iter (fun u -> prerr_endline (UriManager.string_of_uri u)) x;
414   prerr_endline "---";
415 *)
416               (*CSC: I throw the arity away. See comment above *)
417               List.map (fun u,_,_ -> u) x
418             end
419           else  
420             []
421         in
422         uris := uri :: composites @ !uris
423       with
424          CicTypeChecker.TypeCheckerFailure s ->
425           HLog.message
426            ("Unable to create projection " ^ name ^ " cause: " ^ Lazy.force s);
427        | CicEnvironment.Object_not_found uri ->
428           let depend = UriManager.name_of_uri uri in
429            HLog.message
430             ("Unable to create projection " ^ name ^ " because it requires " ^
431                depend)
432     ) projections fields;
433    !uris
434   with exn ->
435    List.iter remove_single_obj !uris;
436    raise exn
437
438 let build_inversion_principle = ref (fun a b -> assert false);;
439
440 let generate_inversion refinement_toolkit uri obj =
441   List.map 
442     (fun (ind_uri,ind_obj) -> 
443        add_single_obj ind_uri ind_obj refinement_toolkit;ind_uri)
444     (!build_inversion_principle uri obj)
445
446 let
447  generate_sibling_mutual_definitions refinement_toolkit uri attrs name_to_avoid
448 =
449  function
450     Cic.Fix (_,funs) ->
451      snd (
452       List.fold_right
453        (fun (name,idx,ty,bo) (n,uris) ->
454          if name = name_to_avoid then
455           (n+1,uris)
456          else
457           let uri =
458            UriManager.uri_of_string
459             (UriManager.buri_of_uri uri ^ "/" ^ name ^ ".con") in
460           let bo = Cic.Fix (n,funs) in 
461           let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
462            add_single_obj uri obj refinement_toolkit;
463            (n+1,uri::uris)
464        ) funs (1,[]))
465   | Cic.CoFix (_,funs) ->
466      snd (
467       List.fold_right
468        (fun (name,ty,bo) (n,uris) ->
469          if name = name_to_avoid then
470           (n+1,uris)
471          else
472           let uri =
473            UriManager.uri_of_string
474             (UriManager.buri_of_uri uri ^ "/" ^ name ^ ".con") in
475           let bo = Cic.CoFix (n,funs) in 
476           let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
477            add_single_obj uri obj refinement_toolkit;
478            (n+1,uri::uris)
479        ) funs (1,[]))
480   | _ -> assert false
481
482 let add_obj refinement_toolkit uri obj =
483  add_single_obj uri obj refinement_toolkit;
484  let uris = ref [] in
485  let not_debug = not (Helm_registry.get_bool "matita.debug") in
486  try
487   begin
488    match obj with
489     | Cic.Constant (name,Some bo,_,_,attrs) when
490        List.mem (`Flavour `MutualDefinition) attrs ->
491         uris :=
492          !uris @
493            generate_sibling_mutual_definitions refinement_toolkit uri attrs
494             name bo
495     | Cic.Constant _ -> ()
496     | Cic.InductiveDefinition (_,_,_,attrs) ->
497         uris := !uris @ 
498           generate_elimination_principles uri refinement_toolkit;
499         uris := !uris @ generate_inversion refinement_toolkit uri obj;
500         let rec get_record_attrs =
501           function
502           | [] -> None
503           | (`Class (`Record fields))::_ -> Some fields
504           | _::tl -> get_record_attrs tl
505         in
506          (match get_record_attrs attrs with
507          | None -> () (* not a record *)
508          | Some fields ->
509             uris := !uris @ 
510               (generate_projections refinement_toolkit uri fields))
511     | Cic.CurrentProof _
512     | Cic.Variable _ -> assert false
513   end;
514   UriManager.UriHashtbl.add auxiliary_lemmas_hashtbl uri !uris;
515   !uris
516  with 
517  | exn when not_debug ->
518     List.iter remove_single_obj !uris;
519     raise exn
520
521 let remove_obj uri =
522  let uris =
523   try
524    let res = UriManager.UriHashtbl.find auxiliary_lemmas_hashtbl uri in
525     UriManager.UriHashtbl.remove auxiliary_lemmas_hashtbl uri;
526     res
527   with
528     Not_found -> [] (*assert false*)
529  in
530   List.iter remove_single_obj (uri::uris)
531