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