]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/closeCoercionGraph.ml
maxipatch for support of multiple DBs.
[helm.git] / components / tactics / closeCoercionGraph.ml
1 (* Copyright (C) 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: cicCoercion.ml 7077 2006-12-05 15:44:54Z fguidi $ *)
27
28 let debug = false
29 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
30
31 (* given the new coercion uri from src to tgt returns the list 
32  * of new coercions to create. hte list elements are
33  * (source, list of coercions to follow, target)
34  *)
35 let get_closure_coercions src tgt uri coercions =
36   let eq_carr s t = 
37     try
38       CoercDb.eq_carr s t
39     with
40     | CoercDb.EqCarrNotImplemented _ | CoercDb.EqCarrOnNonMetaClosed -> false
41   in
42   match src,tgt with
43   | CoercDb.Uri _, CoercDb.Uri _ ->
44       let c_from_tgt = 
45         List.filter 
46           (fun (f,t,_) -> eq_carr f tgt (*&& not (eq_carr t src)*)) 
47           coercions 
48       in
49       let c_to_src = 
50         List.filter 
51           (fun (f,t,_) -> eq_carr t src (*&& not (eq_carr f tgt)*)) 
52           coercions 
53       in
54         (HExtlib.flatten_map 
55           (fun (_,t,ul) -> List.map (fun u -> src,[uri; u],t) ul) c_from_tgt) @
56         (HExtlib.flatten_map 
57           (fun (s,_,ul) -> List.map (fun u -> s,[u; uri],tgt) ul) c_to_src) @
58         (HExtlib.flatten_map 
59           (fun (s,_,u1l) ->
60             HExtlib.flatten_map 
61               (fun (_,t,u2l) ->
62                 HExtlib.flatten_map
63                   (fun u1 ->
64                     List.map 
65                       (fun u2 -> (s,[u1;uri;u2],t)) 
66                       u2l)
67                   u1l) 
68               c_from_tgt) 
69           c_to_src)
70   | _ -> [] (* do not close in case source or target is not an indty ?? *)
71 ;;
72
73 let obj_attrs n = [`Class (`Coercion n); `Generated]
74
75 exception UnableToCompose
76
77 (* generate_composite (c2 (c1 s)) in the universe graph univ
78  * both living in the same context and metasenv *)
79 let generate_composite c1 c2 context metasenv univ arity last_lam_with_inn_arg =
80   let original_metasenv = metasenv in 
81   let c1_ty,univ = CicTypeChecker.type_of_aux' metasenv context c1 univ in
82   let c2_ty,univ = CicTypeChecker.type_of_aux' metasenv context c2 univ in
83   let rec mk_implicits = function
84     | 0 -> [] | n -> (Cic.Implicit None) :: mk_implicits (n-1)
85   in
86   let rec mk_lambda_spline c namer = function
87     | 0 -> c
88     | n -> 
89         Cic.Lambda 
90           (namer n,
91            (Cic.Implicit None), 
92            mk_lambda_spline (CicSubstitution.lift 1 c) namer (n-1))
93   in 
94   let count_saturations_needed t arity = 
95     let rec aux acc n = function
96       | Cic.Prod (name,src, ((Cic.Prod _) as t)) -> 
97           aux (acc@[name]) (n+1) t
98       | _ -> n,acc
99     in
100     let len,names = aux [] 0 t in
101     let len = len - arity in
102     List.fold_left 
103       (fun (n,l) x -> if n < len then n+1,l@[x] else n,l) (0,[]) 
104       names
105   in
106   let compose c1 nc1 c2 nc2 =
107     Cic.Lambda 
108       (Cic.Name "x", (Cic.Implicit (Some `Type)),
109           (Cic.Appl (  CicSubstitution.lift 1 c2 :: mk_implicits nc2 @ 
110             [ Cic.Appl (  CicSubstitution.lift 1 c1 :: mk_implicits nc1 @ 
111              [if last_lam_with_inn_arg then Cic.Rel 1 else Cic.Implicit None])
112             ])))
113   in
114 (*
115   let order_metasenv metasenv = 
116     let module OT = struct type t = int let compare = Pervasives.compare end in
117     let module S = HTopoSort.Make (OT) in
118     let dep i = 
119       let _,_,ty = List.find (fun (j,_,_) -> j=i) metasenv in
120       let metas = List.map fst (CicUtil.metas_of_term ty) in
121       HExtlib.list_uniq (List.sort Pervasives.compare metas)
122     in
123     let om =  
124       S.topological_sort (List.map (fun (i,_,_) -> i) metasenv) dep 
125     in
126     List.map (fun i -> List.find (fun (j,_,_) -> i=j) metasenv) om
127   in 
128 *)
129   let rec create_subst_from_metas_to_rels n = function 
130     | [] -> []
131     | (metano, ctx, ty)::tl -> 
132         (metano,(ctx,Cic.Rel (n+1),ty)) ::
133           create_subst_from_metas_to_rels (n-1) tl
134   in
135   let split_metasenv metasenv n =
136     List.partition (fun (_,ctx,_) -> List.length ctx > n) metasenv
137   in
138   let purge_unused_lambdas metasenv t =
139     let rec aux = function
140         | Cic.Lambda (_, Cic.Meta (i,_), t) when  
141           List.exists (fun (j,_,_) -> j = i) metasenv ->
142             aux (CicSubstitution.subst (Cic.Rel ~-100) t)
143         | Cic.Lambda (name, s, t) -> 
144             Cic.Lambda (name, s, aux t)
145         | t -> t
146     in
147     aux t
148   in
149   let order_body_menv term body_metasenv =
150     let rec purge_lambdas = function
151       | Cic.Lambda (_,_,t) -> purge_lambdas t
152       | t -> t
153     in
154     let skip_appl = function | Cic.Appl l -> List.tl l | _ -> assert false in
155     let metas_that_saturate l =
156       List.fold_left 
157         (fun (acc,n) t ->
158           let metas = CicUtil.metas_of_term t in
159           let metas = List.map fst metas in
160           let metas = 
161             List.filter 
162               (fun i -> List.for_all (fun (j,_) -> j<>i) acc) 
163               metas 
164           in
165           let metas = List.map (fun i -> i,n) metas in
166           metas @ acc, n+1)
167         ([],0) l
168     in
169     let l_c2 = skip_appl (purge_lambdas term) in
170     let l_c1 = 
171       match HExtlib.list_last l_c2 with
172       | Cic.Appl l -> List.tl l
173       | _ -> assert false
174     in
175     (* i should cut off the laet elem of l_c2 *)
176     let meta2no = fst (metas_that_saturate (l_c1 @ l_c2)) in
177     List.sort 
178       (fun (i,ctx1,ty1) (j,ctx1,ty1) -> 
179           try List.assoc i meta2no -  List.assoc j meta2no 
180           with Not_found -> assert false) 
181       body_metasenv
182   in
183   let namer l n = 
184     let l = List.map (function Cic.Name s -> s | _ -> "A") l in
185     let l = List.fold_left
186       (fun acc s -> 
187         let rec add' s =
188           if List.exists ((=) s) acc then add' (s^"'") else s
189         in
190         acc@[add' s])
191       [] l
192     in
193     let l = List.rev l in 
194     Cic.Name (List.nth l (n-1))
195   in 
196   debug_print (lazy ("\nCOMPOSING"));
197   debug_print (lazy (" c1= "^CicPp.ppterm c1 ^"  :  "^ CicPp.ppterm c1_ty));
198   debug_print (lazy (" c2= "^CicPp.ppterm c2 ^"  :  "^ CicPp.ppterm c2_ty));
199   let saturations_for_c1, names_c1 = count_saturations_needed c1_ty 0 in 
200   let saturations_for_c2, names_c2 = count_saturations_needed c2_ty arity in
201   let c = compose c1 saturations_for_c1 c2 saturations_for_c2 in
202   let spline_len = saturations_for_c1 + saturations_for_c2 in
203   let c = mk_lambda_spline c (namer (names_c1 @ names_c2)) spline_len in
204   debug_print (lazy ("COMPOSTA: " ^ CicPp.ppterm c));
205   let c, metasenv, univ = 
206     try
207       let term, ty, metasenv, ugraph = 
208         CicRefine.type_of_aux' metasenv context c univ
209       in
210       debug_print(lazy("COMPOSED REFINED: "^CicPp.ppterm term));
211 (*       let metasenv = order_metasenv metasenv in *)
212 (*       debug_print(lazy("ORDERED MENV: "^CicMetaSubst.ppmetasenv [] metasenv)); *)
213       let body_metasenv, lambdas_metasenv = 
214         split_metasenv metasenv (spline_len + List.length context)
215       in
216       debug_print(lazy("B_MENV: "^CicMetaSubst.ppmetasenv [] body_metasenv));
217       debug_print(lazy("L_MENV: "^CicMetaSubst.ppmetasenv [] lambdas_metasenv));
218       let body_metasenv = order_body_menv term body_metasenv in
219       debug_print(lazy("ORDERED_B_MENV: "^CicMetaSubst.ppmetasenv [] body_metasenv));
220       let subst = create_subst_from_metas_to_rels spline_len body_metasenv in
221       debug_print (lazy("SUBST: "^CicMetaSubst.ppsubst body_metasenv subst));
222       let term = CicMetaSubst.apply_subst subst term in
223       let metasenv = CicMetaSubst.apply_subst_metasenv subst metasenv in
224       debug_print (lazy ("COMPOSED SUBSTITUTED: " ^ CicPp.ppterm term));
225       let term, ty, metasenv, ugraph = 
226         CicRefine.type_of_aux' metasenv context term ugraph
227       in
228       let body_metasenv, lambdas_metasenv = 
229         split_metasenv metasenv (spline_len + List.length context)
230       in
231       let lambdas_metasenv = 
232         List.filter 
233           (fun (i,_,_) -> 
234             List.for_all (fun (j,_,_) -> i <> j) original_metasenv)
235           lambdas_metasenv
236       in
237       let term = purge_unused_lambdas lambdas_metasenv term in
238       let metasenv = 
239         List.filter 
240           (fun (i,_,_) -> 
241             List.for_all 
242               (fun (j,_,_) ->
243                 i <> j || List.exists (fun (j,_,_) -> j=i) original_metasenv) 
244               lambdas_metasenv) 
245           metasenv 
246       in
247       debug_print (lazy ("COMPOSED: " ^ CicPp.ppterm term));
248       debug_print(lazy("MENV: "^CicMetaSubst.ppmetasenv [] metasenv));
249       term, metasenv, ugraph
250     with
251     | CicRefine.RefineFailure s 
252     | CicRefine.Uncertain s -> debug_print s; 
253         raise UnableToCompose
254   in  
255   c, metasenv, univ 
256 ;;
257
258 let build_obj c univ arity =
259   let c_ty,univ = 
260     try 
261       CicTypeChecker.type_of_aux' [] [] c univ
262     with CicTypeChecker.TypeCheckerFailure s ->
263       debug_print (lazy (Printf.sprintf "Generated composite coercion:\n%s\n%s" 
264         (CicPp.ppterm c) (Lazy.force s)));
265       raise UnableToCompose
266   in
267   let cleaned_ty =
268     FreshNamesGenerator.clean_dummy_dependent_types c_ty 
269   in
270   let obj = Cic.Constant ("xxxx",Some c,cleaned_ty,[],obj_attrs arity) in 
271     obj,univ
272 ;;
273
274 (* removes from l the coercions that are in !coercions *)
275 let filter_duplicates l coercions =
276   List.filter (
277       fun (src,l1,tgt) ->
278         not (List.exists (fun (s,t,l2) -> 
279           CoercDb.eq_carr s src && 
280           CoercDb.eq_carr t tgt &&
281           try 
282             List.for_all2 (fun u1 u2 -> UriManager.eq u1 u2) l1 l2
283           with
284           | Invalid_argument "List.for_all2" -> false)
285         coercions))
286   l
287
288 let mangle s t l = 
289   (*List.fold_left
290     (fun s x -> s ^ "_" ^ x)
291     (s ^ "_OF_" ^ t ^ "_BY" ^ string_of_int (List.length l)) l*)
292   s ^ "_OF_" ^ t
293 ;;
294
295 exception ManglingFailed of string 
296
297 let number_if_already_defined buri name l =
298   let err () =
299     raise 
300       (ManglingFailed 
301         ("Unable to give an altenative name to " ^ buri ^ "/" ^ name ^ ".con"))
302   in
303   let rec aux n =
304     let suffix = if n > 0 then string_of_int n else "" in
305     let suri = buri ^ "/" ^ name ^ suffix ^ ".con" in
306     let uri = UriManager.uri_of_string suri in
307     let retry () = 
308       if n < 100 then 
309         begin
310           HLog.warn ("Uri " ^ suri ^ " already exists.");
311           aux (n+1)
312         end
313       else
314         err ()
315     in
316     if List.exists (UriManager.eq uri) l then retry ()
317     else
318       try
319         let _  = Http_getter.resolve' ~local:true ~writable:true uri in
320         if Http_getter.exists' ~local:true uri then retry () else uri
321       with 
322       | Http_getter_types.Key_not_found _ -> uri
323       | Http_getter_types.Unresolvable_URI _ -> assert false
324   in
325   aux 0
326 ;;
327   
328 (* given a new coercion uri from src to tgt returns 
329  * a list of (new coercion uri, coercion obj, universe graph) 
330  *)
331 let close_coercion_graph src tgt uri baseuri =
332   (* check if the coercion already exists *)
333   let coercions = CoercDb.to_list () in
334   let todo_list = get_closure_coercions src tgt uri coercions in
335   let todo_list = filter_duplicates todo_list coercions in
336   try
337     let new_coercions = 
338       List.fold_left 
339         (fun acc (src, l , tgt) ->
340           try 
341             (match l with
342             | [] -> assert false 
343             | he :: tl ->
344                 let arity = match tgt with CoercDb.Fun n -> n | _ -> 0 in
345                 let first_step = 
346                   Cic.Constant ("", 
347                     Some (CoercDb.term_of_carr (CoercDb.Uri he)),
348                     Cic.Sort Cic.Prop, [], obj_attrs arity)
349                 in
350                 let o,_ = 
351                   List.fold_left (fun (o,univ) coer ->
352                     match o with 
353                     | Cic.Constant (_,Some c,_,[],_) ->
354                         let t, menv, univ = 
355                           generate_composite c 
356                             (CoercDb.term_of_carr (CoercDb.Uri coer)) 
357                             [] [] univ arity true
358                         in
359                         if (menv = []) then
360                           HLog.warn "MENV non empty after composing coercions";
361                         build_obj t univ arity
362                     | _ -> assert false 
363                   ) (first_step, CicUniv.empty_ugraph) tl
364                 in
365                 let name_src = CoercDb.name_of_carr src in
366                 let name_tgt = CoercDb.name_of_carr tgt in
367                 let by = List.map UriManager.name_of_uri l in
368                 let name = mangle name_tgt name_src by in
369                 let c_uri = 
370                   number_if_already_defined baseuri name 
371                     (List.map (fun (_,_,u,_) -> u) acc) 
372                 in
373                 let named_obj = 
374                   match o with
375                   | Cic.Constant (_,bo,ty,vl,attrs) ->
376                       Cic.Constant (name,bo,ty,vl,attrs)
377                   | _ -> assert false 
378                 in
379                   (src,tgt,c_uri,named_obj))::acc
380           with UnableToCompose -> acc
381       ) [] todo_list
382     in
383     new_coercions
384   with ManglingFailed s -> HLog.error s; []
385 ;;
386
387 CicCoercion.set_close_coercion_graph close_coercion_graph;;