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