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