]> matita.cs.unibo.it Git - helm.git/blob - components/library/librarySync.ml
8a0c2bcc4406f8832a2fbe0e6fac5300ee4232ba
[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" &&
79       not (Helm_registry.get_bool "matita.noinnertypes")
80    then
81     let annobj, _, _, ids_to_inner_sorts, ids_to_inner_types, _, _ =
82      Cic2acic.acic_object_of_cic_object obj 
83     in
84     let innertypesxml = 
85      Cic2Xml.print_inner_types
86       uri ~ids_to_inner_sorts ~ids_to_inner_types ~ask_dtd_to_the_getter:false
87     in
88     annobj, Some innertypesxml, Some ids_to_inner_sorts, false
89    else 
90     let annobj = Cic2acic.plain_acic_object_of_cic_object obj in  
91     annobj, None, None, true 
92   in 
93   (* prepare XML *)
94   let xml, bodyxml =
95    Cic2Xml.print_object
96     uri ?ids_to_inner_sorts ~ask_dtd_to_the_getter:false 
97     ~generate_attributes annobj 
98   in    
99   let xmlpath, xmlbodypath, innertypespath, bodyuri, innertypesuri, 
100       xmlunivgraphpath, univgraphuri = 
101     paths_and_uris_of_obj uri 
102   in
103   write (List.iter HExtlib.mkdir) (List.map Filename.dirname [xmlpath]);
104   (* now write to disk *)
105   write ensure_path_exists xmlpath;
106   write (Xml.pp ~gzip:true xml) (Some xmlpath);
107   write (CicUniv.write_xml_of_ugraph xmlunivgraphpath ugraph) univlist;
108   (* we return a list of uri,path we registered/created *)
109   (uri,xmlpath) ::
110   (univgraphuri,xmlunivgraphpath) ::
111     (* now the optional inner types, both write and register *)
112     (match innertypes with 
113      | None -> []
114      | Some innertypesxml ->
115          write ensure_path_exists innertypespath;
116          write (Xml.pp ~gzip:true innertypesxml) (Some innertypespath);
117          [innertypesuri, innertypespath]
118     ) @
119     (* now the optional body, both write and register *)
120     (match bodyxml,bodyuri with
121        None,_ -> []
122      | Some bodyxml,Some bodyuri->
123          write ensure_path_exists xmlbodypath;
124          write (Xml.pp ~gzip:true bodyxml) (Some xmlbodypath);
125          [bodyuri, xmlbodypath]
126      | _-> assert false) 
127
128
129 let typecheck_obj =
130  let profiler = HExtlib.profile "add_obj.typecheck_obj" in
131   fun uri obj -> profiler.HExtlib.profile (CicTypeChecker.typecheck_obj uri)
132   (Unshare.fresh_types obj)
133
134 let index_obj =
135  let profiler = HExtlib.profile "add_obj.index_obj" in
136   fun ~dbd ~uri ->
137    profiler.HExtlib.profile (fun uri -> MetadataDb.index_obj ~dbd ~uri) uri
138
139 let add_single_obj uri obj refinement_toolkit =
140   let module RT = RefinementTool in
141   let obj = 
142     if (*List.mem `Generated (CicUtil.attributes_of_obj obj) &&*)
143        not (CoercDb.is_a_coercion' (Cic.Const (uri, [])))
144     then
145       refinement_toolkit.RT.pack_coercion_obj obj
146     else
147       obj 
148   in
149   let dbd = LibraryDb.instance () in
150   if CicEnvironment.in_library uri then
151     raise (AlreadyDefined uri)
152   else begin
153     (*CicUniv.reset_spent_time ();
154     let before = Unix.gettimeofday () in*)
155     typecheck_obj uri obj; (* 1 *)
156     (*let after = Unix.gettimeofday () in
157     let univ_time = CicUniv.get_spent_time () in
158     let total_time = after -. before in
159     prerr_endline 
160       (Printf.sprintf "QED: %%univ = %2.5f, total = %2.5f, univ = %2.5f, %s\n" 
161       (univ_time *. 100. /. total_time) (total_time) (univ_time)
162       (UriManager.name_of_uri uri));*)
163     let _, ugraph, univlist = 
164       CicEnvironment.get_cooked_obj_with_univlist CicUniv.empty_ugraph uri in
165     try 
166       index_obj ~dbd ~uri; (* 2 must be in the env *)
167       try
168         (*3*)
169         let new_stuff = save_object_to_disk uri obj ugraph univlist in
170         (* EXPERIMENTAL: pretty print the object in natural language *)
171         (try !object_declaration_hook uri obj
172          with exc ->
173           prerr_endline ("Error: object_declaration_hook failed"^
174           Printexc.to_string exc));
175         try 
176          HLog.message
177           (Printf.sprintf "%s defined" (UriManager.string_of_uri uri))
178         with exc ->
179           List.iter HExtlib.safe_remove (List.map snd new_stuff); (* -3 *)
180           raise exc
181       with exc ->
182         ignore(LibraryDb.remove_uri uri); (* -2 *)
183         raise exc
184     with exc ->
185       CicEnvironment.remove_obj uri; (* -1 *)
186       raise exc
187   end
188
189 let remove_single_obj uri =
190   let derived_uris_of_uri uri =
191    let innertypesuri, bodyuri, univgraphuri = uris_of_obj uri in
192     innertypesuri::univgraphuri::(match bodyuri with None -> [] | Some u -> [u])
193   in
194   let uris_to_remove =
195    if UriManager.uri_is_ind uri then LibraryDb.xpointers_of_ind uri else [uri]
196   in
197   let files_to_remove = uri :: derived_uris_of_uri uri in   
198   List.iter 
199    (fun uri -> 
200      (try
201        let file = Http_getter.resolve' ~local:true ~writable:true uri in
202         HExtlib.safe_remove file;
203         HExtlib.rmdir_descend (Filename.dirname file)
204      with Http_getter_types.Key_not_found _ -> ());
205    ) files_to_remove ;
206   List.iter 
207    (fun uri -> 
208      ignore (LibraryDb.remove_uri uri);
209      (*CoercGraph.remove_coercion uri;*)
210    ) uris_to_remove ;
211   CicEnvironment.remove_obj uri
212
213 (*** GENERATION OF AUXILIARY LEMMAS ***)
214
215 let generate_elimination_principles uri refinement_toolkit =
216   let uris = ref [] in
217   let elim i =
218     let elim sort =
219       try
220         let uri,obj = CicElim.elim_of ~sort uri i in
221           add_single_obj uri obj refinement_toolkit;
222           uris := uri :: !uris
223       with CicElim.Can_t_eliminate -> ()
224     in
225       try
226         List.iter 
227           elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
228       with exn ->
229         List.iter remove_single_obj !uris;
230         raise exn 
231   in
232   let (obj, univ) = (CicEnvironment.get_obj CicUniv.empty_ugraph uri) in
233     match obj with
234       | Cic.InductiveDefinition (indTypes, _, _, _) ->
235           let counter = ref 0 in
236             List.iter (fun _ -> elim !counter; counter := !counter+1) indTypes;
237             !uris
238       | _  -> 
239           failwith (Printf.sprintf "not an inductive definition (%s)"
240                       (UriManager.string_of_uri uri))
241
242 (* COERCIONS ***********************************************************)
243   
244 let remove_all_coercions () =
245   UriManager.UriHashtbl.clear coercion_hashtbl;
246   CoercDb.remove_coercion (fun (_,_,_,_) -> true)
247
248 let stack = ref [];;
249
250 let h2l h =
251   UriManager.UriHashtbl.fold 
252   (fun k v acc -> (k,v) :: acc) h []
253 ;;
254
255 let push () =
256   stack := (CoercDb.dump (), h2l coercion_hashtbl) :: !stack;
257   remove_all_coercions ()
258 ;;
259
260 let pop () =
261   match !stack with
262   | [] -> raise (Failure "Unable to POP from librarySync.ml")
263   | (db,h) :: tl -> 
264       stack := tl;
265       remove_all_coercions ();
266       CoercDb.restore db;
267       List.iter (fun (k,v) -> UriManager.UriHashtbl.add coercion_hashtbl k v)
268       h
269 ;;
270
271 let add_coercion ~add_composites refinement_toolkit uri arity saturations
272  baseuri
273 =
274   let coer_ty,_ =
275     let coer = CicUtil.term_of_uri uri in
276     CicTypeChecker.type_of_aux' [] [] coer CicUniv.empty_ugraph 
277   in
278   (* we have to get the source and the tgt type uri
279    * in Coq syntax we have already their names, but
280    * since we don't support Funclass and similar I think
281    * all the coercion should be of the form
282    * (A:?)(B:?)T1->T2
283    * So we should be able to extract them from the coercion type
284    * 
285    * Currently only (_:T1)T2 is supported.
286    * should we saturate it with metas in case we insert it?
287    * 
288    *)
289   let spine2list ty =
290     let rec aux = function
291       | Cic.Prod( _, src, tgt) -> src::aux tgt
292       | t -> [t]
293     in
294     aux ty
295   in
296   let src_carr, tgt_carr = 
297     let get_classes arity saturations l = 
298       (* this is the ackerman's function revisited *)
299       let rec aux = function
300          0,0,None,tgt::src::_ -> src,Some (`Class tgt)
301        | 0,0,target,src::_ -> src,target
302        | 0,saturations,None,tgt::tl -> aux (0,saturations,Some (`Class tgt),tl)
303        | 0,saturations,target,_::tl -> aux (0,saturations - 1,target,tl)
304        | arity,saturations,None,_::tl -> 
305             aux (arity, saturations, Some `Funclass, tl)
306        | arity,saturations,target,_::tl -> 
307             aux (arity - 1, saturations, target, tl)
308        | _ -> assert false
309       in
310        aux (arity,saturations,None,List.rev l)
311     in
312     let types = spine2list coer_ty in
313     let src,tgt = get_classes arity saturations types in
314      CoercDb.coerc_carr_of_term (CicReduction.whd ~delta:false [] src),
315      match tgt with
316         None -> assert false
317       | Some `Funclass -> CoercDb.Fun arity
318       | Some (`Class tgt) ->
319          CoercDb.coerc_carr_of_term (CicReduction.whd ~delta:false [] tgt)
320   in
321   let already_in_obj src_carr tgt_carr uri obj = 
322      List.exists 
323       (fun (s,t,ul) -> 
324         List.exists 
325          (fun u,_ -> 
326            let bo = 
327             match obj with 
328             | Cic.Constant (_, Some bo, _, _, _) -> bo
329             | _ -> assert false
330            in
331            CoercDb.eq_carr s src_carr && 
332            CoercDb.eq_carr t tgt_carr &&
333            if fst (CicReduction.are_convertible [] (CicUtil.term_of_uri u) bo
334            CicUniv.oblivion_ugraph)
335            then true else
336             (HLog.warn
337               ("Coercions " ^ 
338                 UriManager.string_of_uri u ^ " and " ^ UriManager.string_of_uri
339                 uri^" are not convertible, but are between the same nodes.\n"^
340                 "From now on unification can fail randomly.");
341              false))
342          ul)
343       (CoercDb.to_list ())
344   in
345   if not add_composites then
346     (CoercDb.add_coercion (src_carr, tgt_carr, uri, saturations);
347     UriManager.UriHashtbl.add coercion_hashtbl uri ([],[]);
348     [])
349   else
350     let new_coercions = 
351       CicCoercion.close_coercion_graph src_carr tgt_carr uri saturations
352        baseuri
353     in
354     let new_coercions = 
355       List.filter (fun (s,t,u,_,obj,_) -> not(already_in_obj s t u obj))
356       new_coercions 
357     in
358     let composite_uris = List.map (fun (_,_,uri,_,_,_) -> uri) new_coercions in
359     (* update the DB *)
360     List.iter 
361       (fun (src,tgt,uri,saturations,_,_) ->
362         CoercDb.add_coercion (src,tgt,uri,saturations)) 
363       new_coercions;
364     CoercDb.add_coercion (src_carr, tgt_carr, uri, saturations);
365     (* add the composites obj and they eventual lemmas *)
366     let lemmas = 
367         List.fold_left
368           (fun acc (_,tgt,uri,saturations,obj,arity) -> 
369             add_single_obj uri obj refinement_toolkit;
370              (uri,arity,saturations)::acc) 
371           [] new_coercions
372     in
373     (* store that composite_uris are related to uri. the first component is
374      * the stuff in the DB while the second is stuff for remove_obj *)
375     (* 
376        prerr_endline ("adding: " ^ 
377          string_of_bool add_composites ^ UriManager.string_of_uri uri);
378        List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
379         composite_uris; 
380     *)
381     UriManager.UriHashtbl.add 
382       coercion_hashtbl uri (composite_uris,composite_uris);
383     (*
384     prerr_endline ("lemmas:");
385       List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
386       lemmas;
387     prerr_endline ("lemmas END");*)
388     lemmas
389 ;;
390
391 let remove_coercion uri =
392   try
393     let (composites_in_db, composites_in_lib) = 
394       UriManager.UriHashtbl.find coercion_hashtbl uri 
395     in
396     (*prerr_endline ("removing: " ^UriManager.string_of_uri uri);
397     List.iter (fun u -> prerr_endline (UriManager.string_of_uri u))
398       composites_in_db;*)
399     UriManager.UriHashtbl.remove coercion_hashtbl uri;
400     CoercDb.remove_coercion 
401       (fun (_,_,u,_) -> UriManager.eq uri u);
402     (* remove from the DB *) 
403     List.iter 
404       (fun u -> CoercDb.remove_coercion (fun (_,_,u1,_) -> UriManager.eq u u1))
405       composites_in_db;
406     (* remove composites from the lib *)
407     List.iter remove_single_obj composites_in_lib
408   with
409     Not_found -> HLog.warn "Coercion removal raise Not_found" (* mhh..... *)
410     
411
412 let generate_projections refinement_toolkit uri fields =
413  let uris = ref [] in
414  let projections = 
415    CicRecord.projections_of uri 
416      (List.map (fun (x,_,_) -> x) fields) 
417  in
418   try
419    List.iter2 
420     (fun (uri, name, bo) (_name, coercion, arity) ->
421       let saturations = 0 in
422       try
423        let ty, ugraph =
424          CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph in
425        let attrs = [`Class `Projection; `Generated] in
426        let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
427         add_single_obj uri obj refinement_toolkit;
428         let composites = 
429          if coercion then
430             begin
431 (*prerr_endline ("composite for " ^ UriManager.string_of_uri uri);*)
432               (*CSC: I think there is a bug here. The composite coercions
433                 are not remembered in the .moo file. Thus they are re-generated
434                 every time. Right? *)
435               let x = 
436                 add_coercion ~add_composites:true refinement_toolkit uri arity
437                  saturations (UriManager.buri_of_uri uri)
438               in
439 (*prerr_endline ("are: ");
440   List.iter (fun u -> prerr_endline (UriManager.string_of_uri u)) x;
441   prerr_endline "---";
442 *)
443               (*CSC: I throw the arity away. See comment above *)
444               List.map (fun u,_,_ -> u) x
445             end
446           else  
447             []
448         in
449         uris := uri :: composites @ !uris
450       with
451          CicTypeChecker.TypeCheckerFailure s ->
452           HLog.message
453            ("Unable to create projection " ^ name ^ " cause: " ^ Lazy.force s);
454        | CicEnvironment.Object_not_found uri ->
455           let depend = UriManager.name_of_uri uri in
456            HLog.message
457             ("Unable to create projection " ^ name ^ " because it requires " ^
458                depend)
459     ) projections fields;
460    !uris
461   with exn ->
462    List.iter remove_single_obj !uris;
463    raise exn
464
465 let build_inversion_principle = ref (fun a b -> assert false);;
466
467 let generate_inversion refinement_toolkit uri obj =
468   List.map 
469     (fun (ind_uri,ind_obj) -> 
470        add_single_obj ind_uri ind_obj refinement_toolkit;ind_uri)
471     (!build_inversion_principle uri obj)
472
473 let
474  generate_sibling_mutual_definitions refinement_toolkit uri attrs name_to_avoid
475 =
476  function
477     Cic.Fix (_,funs) ->
478      snd (
479       List.fold_right
480        (fun (name,idx,ty,bo) (n,uris) ->
481          if name = name_to_avoid then
482           (n+1,uris)
483          else
484           let uri =
485            UriManager.uri_of_string
486             (UriManager.buri_of_uri uri ^ "/" ^ name ^ ".con") in
487           let bo = Cic.Fix (n,funs) in 
488           let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
489            add_single_obj uri obj refinement_toolkit;
490            (n+1,uri::uris)
491        ) funs (1,[]))
492   | Cic.CoFix (_,funs) ->
493      snd (
494       List.fold_right
495        (fun (name,ty,bo) (n,uris) ->
496          if name = name_to_avoid then
497           (n+1,uris)
498          else
499           let uri =
500            UriManager.uri_of_string
501             (UriManager.buri_of_uri uri ^ "/" ^ name ^ ".con") in
502           let bo = Cic.CoFix (n,funs) in 
503           let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
504            add_single_obj uri obj refinement_toolkit;
505            (n+1,uri::uris)
506        ) funs (1,[]))
507   | _ -> assert false
508
509 let add_obj refinement_toolkit uri obj =
510  add_single_obj uri obj refinement_toolkit;
511  let uris = ref [] in
512  let not_debug = not (Helm_registry.get_bool "matita.debug") in
513  try
514   begin
515    match obj with
516     | Cic.Constant (name,Some bo,_,_,attrs) when
517        List.mem (`Flavour `MutualDefinition) attrs ->
518         uris :=
519          !uris @
520            generate_sibling_mutual_definitions refinement_toolkit uri attrs
521             name bo
522     | Cic.Constant _ -> ()
523     | Cic.InductiveDefinition (inductivefuns,_,_,attrs) ->
524        let _,inductive,_,_ = List.hd inductivefuns in
525        if inductive then
526         begin
527          uris := !uris @ 
528            generate_elimination_principles uri refinement_toolkit;
529          uris := !uris @ generate_inversion refinement_toolkit uri obj;
530         end ;
531        let rec get_record_attrs =
532          function
533          | [] -> None
534          | (`Class (`Record fields))::_ -> Some fields
535          | _::tl -> get_record_attrs tl
536        in
537         (match get_record_attrs attrs with
538         | None -> () (* not a record *)
539         | Some fields ->
540            uris := !uris @ 
541              (generate_projections refinement_toolkit uri fields))
542     | Cic.CurrentProof _
543     | Cic.Variable _ -> assert false
544   end;
545   UriManager.UriHashtbl.add auxiliary_lemmas_hashtbl uri !uris;
546   !uris
547  with 
548  | exn when not_debug ->
549     List.iter remove_single_obj !uris;
550     raise exn
551
552 let remove_obj uri =
553  let uris =
554   try
555    let res = UriManager.UriHashtbl.find auxiliary_lemmas_hashtbl uri in
556     UriManager.UriHashtbl.remove auxiliary_lemmas_hashtbl uri;
557     res
558   with
559     Not_found -> [] (*assert false*)
560  in
561   List.iter remove_single_obj (uri::uris)
562