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