]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/cic_unification/coercGraph.ml
huge commit regarding the grafite_status:
[helm.git] / helm / software / components / cic_unification / coercGraph.ml
1 (* Copyright (C) 2000, 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://cs.unibo.it/helm/.
24  *)
25
26 (* $Id$ *)
27
28 open Printf;;
29
30 type coercion_search_result = 
31      (* metasenv, last coercion argument, fully saturated coercion *)
32      (* to apply the coercion it is sufficient to unify the last coercion
33         argument (that is a Meta) with the term to be coerced *)
34   | SomeCoercion of (Cic.metasenv * Cic.term * Cic.term) list
35   | SomeCoercionToTgt of (Cic.metasenv * Cic.term * Cic.term) list
36   | NoCoercion
37   | NotHandled
38
39 let debug = false
40 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
41
42 let saturate_coercion ul metasenv subst context =
43   let cl =
44    List.map 
45      (fun u,saturations -> 
46         let t = CicUtil.term_of_uri u in 
47         let arity = 
48           match CoercDb.is_a_coercion t with
49           | Some (_,CoercDb.Fun i,_,_,_) -> i
50           | _ -> 0
51         in
52         arity,t,saturations) ul
53   in
54   let freshmeta = CicMkImplicit.new_meta metasenv subst in
55    List.map
56     (fun (arity,c,saturations) -> 
57       let ty,_ =
58        CicTypeChecker.type_of_aux' ~subst metasenv context c
59         CicUniv.oblivion_ugraph in
60       let _,metasenv,args,lastmeta =
61        TermUtil.saturate_term ~delta:false freshmeta metasenv context ty arity in
62       let irl =
63        CicMkImplicit.identity_relocation_list_for_metavariable context
64       in
65        metasenv, Cic.Meta (lastmeta - saturations - 1,irl),
66         match args with
67            [] -> c
68          | _ -> Cic.Appl (c::args)
69     ) cl
70 ;;
71           
72 (* searches a coercion fron src to tgt in the !coercions list *)
73 let look_for_coercion_carr metasenv subst context src tgt =
74   let is_dead = function CoercDb.Dead -> true | _ -> false in
75   let pp_l s l =
76    match l with
77    | [] -> 
78        debug_print 
79          (lazy 
80          (sprintf ":-( coercion non trovata[%s] da %s a %s" s
81              (CoercDb.string_of_carr src) 
82              (CoercDb.string_of_carr tgt)));
83    | _::_ -> 
84        debug_print (lazy (
85                sprintf ":-) TROVATE[%s] %d coercion(s) da %s a %s" s
86            (List.length l)
87            (CoercDb.string_of_carr src) 
88            (CoercDb.string_of_carr tgt)));
89   in
90   if is_dead src || is_dead tgt then NotHandled
91   else
92     let l = 
93       CoercDb.find_coercion 
94         (fun (s,t) -> 
95           CoercDb.eq_carr s src && 
96           match t, tgt with
97           | CoercDb.Sort Cic.Prop, CoercDb.Sort Cic.Prop 
98           | CoercDb.Sort Cic.Set, CoercDb.Sort Cic.Set 
99           | CoercDb.Sort _, CoercDb.Sort (Cic.Type _|Cic.CProp _) -> true
100           | _ -> CoercDb.eq_carr t tgt) 
101     in
102     pp_l "precise" l;
103      (match l with
104      | [] -> 
105          let l = 
106            CoercDb.find_coercion 
107              (fun (_,t) -> CoercDb.eq_carr t tgt) 
108          in
109          pp_l "approx" l;
110          (match l with
111          | [] -> NoCoercion
112          | ul -> 
113             SomeCoercionToTgt (saturate_coercion ul metasenv subst context))
114      | ul -> SomeCoercion (saturate_coercion ul metasenv subst context))
115 ;;
116
117 let rec count_pi c s t =
118   match CicReduction.whd ~delta:false ~subst:s c t with
119   | Cic.Prod (_,_,t) -> 1 + count_pi c s t
120   | _ -> 0
121 ;;
122
123 let look_for_coercion metasenv subst context src tgt = 
124   let src_arity = count_pi context subst src in
125   let tgt_arity = count_pi context subst tgt in
126   let src_carr = CoercDb.coerc_carr_of_term src src_arity in
127   let tgt_carr = CoercDb.coerc_carr_of_term tgt tgt_arity in
128   look_for_coercion_carr metasenv subst context src_carr tgt_carr
129
130 let source_of t = 
131   match CoercDb.is_a_coercion t with
132   | None -> assert false
133   | Some (CoercDb.Sort s,_,_,_,_) -> Cic.Sort s
134   | Some (CoercDb.Uri u,_,_,_,_) -> CicUtil.term_of_uri u
135   | Some _ -> assert false (* t must be a coercion not to funclass *)
136 ;;
137
138 let generate_dot_file () =
139   let l = CoercDb.to_list (CoercDb.dump ()) in
140   let module Pp = GraphvizPp.Dot in
141   let buf = Buffer.create 10240 in
142   let fmt = Format.formatter_of_buffer buf in
143   Pp.header ~node_attrs:["fontsize", "9"; "width", ".4"; "height", ".4"]
144     ~edge_attrs:["fontsize", "10"] fmt;
145   if List.exists (fun (_,t,_) -> CoercDb.string_of_carr t = "Type") l then
146     Format.fprintf fmt "subgraph cluster_rest { style=\"filled\";
147     color=\"white\"; label=<%s>; labelloc=\"b\"; %s; }\n" 
148        ("<FONT POINT-SIZE=\"10.0\"><TABLE BORDER=\"1\" CELLBORDER=\"1\" >
149          <TR><TD BGCOLOR=\"gray95\">Source</TD>
150          <TD BGCOLOR=\"gray95\">Target</TD>
151          <TD BGCOLOR=\"gray95\">Arrows</TD></TR>"^
152        String.concat "</TR>"   
153          (List.map 
154            (fun (src,tgt,ul) -> 
155             let src_name = CoercDb.string_of_carr src in
156             let tgt_name = CoercDb.string_of_carr tgt in
157             let names = 
158               List.map (fun (u,_,_) -> 
159                 UriManager.name_of_uri u ^ 
160                   (match CicEnvironment.get_obj CicUniv.empty_ugraph u with
161                   | Cic.Constant (_,Some (Cic.Const (u',_)),_,_,attrs), _
162                     when List.exists ((=) (`Flavour `Variant)) attrs -> "*"
163                   | _ -> "")
164               ) ul 
165             in
166             "<TR><TD>"  ^ src_name ^ "</TD><TD>" ^ tgt_name ^ "</TD><TD>" ^
167             String.concat ",&nbsp;" names ^ "</TD>")
168          (List.sort (fun (x,y,_) (x1,y1,_) -> 
169              let rc = compare x x1 in
170              if rc = 0 then compare y y1 else rc) l))
171        ^ "</TR></TABLE></FONT>")
172        (String.concat ";" ["Type"]);
173   let type_uri u = 
174     let ty, _ = 
175       CicTypeChecker.type_of_aux' [] [] (CicUtil.term_of_uri u)
176       CicUniv.oblivion_ugraph
177     in
178       ty
179   in
180   let deref_coercion u =
181    match CicEnvironment.get_obj CicUniv.empty_ugraph u with
182    | Cic.Constant (_,Some (Cic.Const (u',_)),_,_,attrs), _
183      when List.exists ((=) (`Flavour `Variant)) attrs ->
184        UriManager.name_of_uri u'
185    | Cic.Constant (_,Some t,_,_,_), _ when
186        let rec is_id = function 
187          | Cic.Lambda (_,_,t) -> is_id t
188          | Cic.Rel _ -> true
189          | _ -> false
190          in is_id t -> "ID"
191    | _ -> UriManager.name_of_uri u
192   in
193   List.iter
194     (fun (src, tgt, ul) ->
195       List.iter
196         (fun (u,saturations,cpos) ->
197           let ty = type_uri u in
198           let src_name, tgt_name = 
199             let rec aux ctx cpos t =
200               match cpos, t with
201               | 0,Cic.Prod (_,src,tgt) ->
202                   CicPp.pp src ctx, tgt, (Some (Cic.Name "_")::ctx)
203               | 0,t -> CicPp.pp t ctx, Cic.Implicit None, []
204               | n,Cic.Prod (_,_,tgt) -> aux (Some (Cic.Name "_")::ctx) (n-1) tgt
205               | _ -> assert false
206             in
207             let ssrc, rest, ctx = aux [] cpos ty in
208             let stgt, rest, _ = aux ctx saturations rest in
209             let stgt = 
210               if rest <> Cic.Implicit None then
211                 match tgt with 
212                 | CoercDb.Fun _ -> CoercDb.string_of_carr tgt
213                 | _ -> assert false
214               else
215                 stgt
216             in
217             ssrc, stgt
218           in
219           Pp.node src_name fmt;
220           Pp.node tgt_name fmt;
221           Pp.edge src_name tgt_name
222             ~attrs:[ "label",
223                  (deref_coercion u ^
224                   if saturations = 0 then ""
225                   else "(" ^ string_of_int saturations ^ ")");
226               "href", UriManager.string_of_uri u ]
227             fmt)
228         ul)
229     l;
230   Pp.trailer fmt;
231   Buffer.contents buf
232 ;;
233     
234 let coerced_arg l =
235   match l with
236   | [] | [_] -> None
237   | c::tl -> 
238      match CoercDb.is_a_coercion c with 
239      | None -> None
240      | Some (_,_,_,_,cpos) -> 
241         if List.length tl > cpos then Some (List.nth tl cpos, cpos) else None
242 ;;
243
244 (************************* meet calculation stuff ********************)
245 let eq_uri_opt u1 u2 = 
246   match u1,u2 with
247   | Some (u1,_), Some (u2,_) -> UriManager.eq u1 u2
248   | None,Some _ | Some _, None -> false
249   | None, None -> true
250 ;;
251
252 let eq_carr_uri (c1,u1) (c2,u2) = CoercDb.eq_carr c1 c2 && eq_uri_opt u1 u2;;
253
254 let eq_carr_uri_uri (c1,u1,u11) (c2,u2,u22) = 
255   CoercDb.eq_carr c1 c2 && eq_uri_opt u1 u2 && eq_uri_opt u11 u22
256 ;;
257
258 let uniq = HExtlib.list_uniq ~eq:eq_carr_uri;;
259
260 let uniq2 = HExtlib.list_uniq ~eq:eq_carr_uri_uri;;
261
262 let splat e l = List.map (fun (x1,x2,_) -> e, Some (x1,x2)) l;;
263
264 (* : carr -> (carr * uri option) where the option is always Some *)
265 let get_coercions_to carr = 
266   let l = CoercDb.to_list (CoercDb.dump ()) in
267   let splat_coercion_to carr (src,tgt,cl) =
268     if CoercDb.eq_carr tgt carr then Some (splat src cl) else None
269   in
270   let l = List.flatten (HExtlib.filter_map (splat_coercion_to carr) l) in
271   l
272 ;;
273
274 (* : carr -> (carr * uri option) where the option is always Some *)
275 let get_coercions_from carr = 
276   let l = CoercDb.to_list (CoercDb.dump ()) in
277   let splat_coercion_from carr (src,tgt,cl) =
278     if CoercDb.eq_carr src carr then Some (splat tgt cl) else None
279   in
280   List.flatten (HExtlib.filter_map (splat_coercion_from carr) l)
281 ;;
282
283 (* intersect { (s1,u1) | u1:s1->t1 } { (s2,u2) | u2:s2->t2 } 
284  * gives the set { (s,u1,u2) | u1:s->t1 /\ u2:s->t2 } *)
285 let intersect l1 l2 = 
286   let is_in_l1 (x,u2) = 
287     HExtlib.filter_map 
288       (fun (src,u1) -> 
289          if CoercDb.eq_carr x src then Some (src,u1,u2) else None)
290     l1
291   in
292   uniq2 (List.flatten (List.map is_in_l1 l2))
293 ;;
294
295 (* grow tgt gives all the (src,u) such that u:tgt->src *)
296 let grow tgt = 
297   uniq ((tgt,None)::(get_coercions_to tgt))
298 ;;
299
300 let lb (c,_,_) = 
301   let l = get_coercions_from c in
302   fun (x,_,_) -> List.exists (fun (y,_) -> CoercDb.eq_carr x y) l
303 ;;
304
305 (* given the set { (s,u1,u2) | u1:s->t1 /\ u2:s->t2 } removes the elements 
306  * (s,_,_) such that (s',_,_) is in the set and there exists a coercion s->s' *)
307 let rec min acc skipped = function
308   | c::tl -> 
309     if List.exists (lb c) (tl@acc) 
310     then min acc (c::skipped) tl else min (c::acc) skipped tl
311   | [] -> acc, skipped
312 ;;
313
314
315 let sort l = 
316   let low, high = min [] [] l in low @ high
317 ;;
318
319 let meets metasenv subst context (grow_left,left) (grow_right,right) =
320   let saturate metasenv uo =
321     match uo with 
322     | None -> metasenv, None
323     | Some u -> 
324         match saturate_coercion [u] metasenv subst context with
325         | [metasenv, sat, last] -> metasenv, Some (sat, last)
326         | _ -> assert false
327   in
328   List.map 
329     (fun (c,uo1,uo2) -> 
330       let metasenv, uo1 = saturate metasenv uo1 in
331       let metasenv, uo2 = saturate metasenv uo2 in
332       c,metasenv, uo1, uo2)
333     (sort (intersect 
334       (if grow_left then grow left else [left,None]) 
335       (if grow_right then grow right else [right,None])))
336 ;;
337
338 (* EOF *)