]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicUnifHint.ml
Preparing for 0.5.9 release.
[helm.git] / helm / software / components / ng_refiner / nCicUnifHint.ml
1 (*
2     ||M||  This file is part of HELM, an Hypertextual, Electronic        
3     ||A||  Library of Mathematics, developed at the Computer Science     
4     ||T||  Department, University of Bologna, Italy.                     
5     ||I||                                                                
6     ||T||  HELM is free software; you can redistribute it and/or         
7     ||A||  modify it under the terms of the GNU General Public License   
8     \   /  version 2 or (at your option) any later version.      
9      \ /   This software is distributed as is, NO WARRANTY.     
10       V_______________________________________________________________ *)
11
12 (* $Id: nCicRefiner.mli 9227 2008-11-21 16:00:06Z tassi $ *)
13
14 let debug s = prerr_endline (Lazy.force s);;
15 let debug _ = ();;
16
17 module HOT : Set.OrderedType 
18 with type t = int * NCic.term  * NCic.term * NCic.term = 
19   struct
20         (* precedence, skel1, skel2, term *)
21         type t = int * NCic.term * NCic.term * NCic.term
22         let compare = Pervasives.compare
23   end
24
25 module EOT : Set.OrderedType 
26 with type t = int * NCic.term =
27   struct
28         type t = int * NCic.term 
29         let compare = Pervasives.compare
30   end
31
32 module HintSet = Set.Make(HOT)
33 module EqSet = Set.Make(EOT)
34
35 module HDB = 
36   Discrimination_tree.Make(NDiscriminationTree.NCicIndexable)(HintSet)
37
38 module EQDB = 
39   Discrimination_tree.Make(NDiscriminationTree.NCicIndexable)(EqSet)
40
41 type db =
42   HDB.t * (* hint database: (dummy A B)[?] |-> \forall X.(summy a b)[X] *)
43   EQDB.t (* eqclass DB: A[?] |-> \forall X.B[X] and viceversa *)
44
45 exception HintNotValid
46
47 let skel_dummy = NCic.Implicit `Type;;
48
49 class type g_status =
50  object
51   method uhint_db: db
52  end
53
54 class status =
55  object
56   val db = HDB.empty, EQDB.empty
57   method uhint_db = db
58   method set_uhint_db v = {< db = v >}
59   method set_unifhint_status
60    : 'status. #g_status as 'status -> 'self
61    = fun o -> {< db = o#uhint_db >}
62  end
63
64 let dummy = NCic.Const (NReference.reference_of_string "cic:/dummy_conv.dec");;
65 let pair t1 t2 = (NCic.Appl [dummy;t1;t2]) ;;
66
67 let index_hint hdb context t1 t2 precedence =
68   assert (
69     (match t1 with
70     | NCic.Meta _ | NCic.Appl (NCic.Meta _ :: _) -> false | _ -> true)
71     &&
72     (match t2 with
73     | NCic.Meta _ | NCic.Appl (NCic.Meta _ :: _) -> false | _ -> true)
74   );
75   (* here we do not use skel_dummy since it could cause an assert false in 
76    * the subst function that lives in the kernel *)
77   let hole = NCic.Meta (-1,(0,NCic.Irl 0)) in
78   let t1_skeleton = 
79     List.fold_left (fun t _ -> NCicSubstitution.subst hole t) t1 context
80   in
81   let t2_skeleton = 
82     List.fold_left (fun t _ -> NCicSubstitution.subst hole t) t2 context
83   in
84   let rec cleanup_skeleton () = function
85     | NCic.Meta _ -> skel_dummy 
86     | t -> NCicUtils.map (fun _ () -> ()) () cleanup_skeleton t
87   in
88   let t1_skeleton = cleanup_skeleton () t1_skeleton in
89   let t2_skeleton = cleanup_skeleton () t2_skeleton in
90   let src = pair t1_skeleton t2_skeleton in
91   let ctx2abstractions context t = 
92     List.fold_left 
93      (fun t (n,e) -> 
94         match e with
95         | NCic.Decl ty -> NCic.Prod (n,ty,t)
96         | NCic.Def (b,ty) -> NCic.LetIn (n,ty,b,t))
97       t context 
98   in
99   let data_hint = 
100     precedence, t1_skeleton, t2_skeleton, ctx2abstractions context (pair t1 t2)
101   in
102   let data_t1 = t2_skeleton in
103   let data_t2 = t1_skeleton in
104
105   debug(lazy ("INDEXING: " ^ 
106     NCicPp.ppterm ~metasenv:[] ~subst:[] ~context:[] src ^ " |==> " ^
107     NCicPp.ppterm ~metasenv:[] ~subst:[] ~context:[] 
108       (let _,x,_,_ = data_hint in x)));
109
110   hdb#set_uhint_db (
111       HDB.index (fst (hdb#uhint_db)) src data_hint,
112       EQDB.index  
113         (EQDB.index (snd (hdb#uhint_db)) t2_skeleton (precedence, data_t2))
114         t1_skeleton (precedence, data_t1))
115 ;;
116
117 let add_user_provided_hint db t precedence =
118   let c, a, b = 
119     let rec aux ctx = function
120       | NCic.Appl l ->
121           (match List.rev l with
122           | b::a::_ -> 
123               if
124                  let ty_a = 
125                    NCicTypeChecker.typeof ~metasenv:[] ~subst:[] ctx a
126                  in
127                  let ty_b = 
128                    NCicTypeChecker.typeof ~metasenv:[] ~subst:[] ctx b
129                  in
130                  NCicReduction.are_convertible 
131                   ~metasenv:[] ~subst:[] ctx ty_a ty_b              
132                  &&     
133                  NCicReduction.are_convertible 
134                   ~metasenv:[] ~subst:[] ctx a b              
135               then ctx, a, b
136               else raise HintNotValid
137           | _ -> assert false)
138       | NCic.Prod (n,s,t) -> aux ((n, NCic.Decl s) :: ctx) t
139       | NCic.LetIn (n,ty,t,b) -> aux  ((n, NCic.Def (t,ty)) :: ctx) b
140       | _ -> assert false
141     in
142       aux [] t
143   in
144    index_hint db c a b precedence
145 ;;
146
147 (*
148 let db () = 
149   let combine f l =
150    List.flatten
151      (let rec aux = function 
152       | u1 :: tl -> List.map (f u1) tl :: aux tl
153       | [] -> []
154      in aux l)
155   in
156   let mk_hint (u1,_,_) (u2,_,_) = 
157     let l = OCic2NCic.convert_obj u1 
158       (fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph u1)) in
159     let r = OCic2NCic.convert_obj u2 
160       (fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph u2)) in
161     match List.hd l,List.hd r with
162     | (_,h1,_,_,NCic.Constant (_,_,Some l,_,_)), 
163       (_,h2,_,_,NCic.Constant (_,_,Some r,_,_)) ->
164         let rec aux ctx t1 t2 =
165           match t1, t2 with
166           | NCic.Lambda (n1,s1,b1), NCic.Lambda(_,s2,b2) ->
167               if NCicReduction.are_convertible ~subst:[] ~metasenv:[] ctx s1 s2
168               then aux ((n1, NCic.Decl s1) :: ctx) b1 b2
169               else []
170           | b1,b2 -> 
171               if NCicReduction.are_convertible ~subst:[] ~metasenv:[] ctx b1 b2 
172               then begin
173               let rec mk_rels =  
174                  function 0 -> [] | n -> NCic.Rel n :: mk_rels (n-1) 
175               in 
176               let n1 = 
177                 NCic.Appl (NCic.Const(OCic2NCic.reference_of_ouri 
178                  u1 (NReference.Def h1)) :: mk_rels (List.length ctx))
179               in
180               let n2 = 
181                 NCic.Appl (NCic.Const(OCic2NCic.reference_of_ouri 
182                  u2 (NReference.Def h2)) :: mk_rels (List.length ctx))
183               in
184                 [ctx,b1,b2; ctx,b1,n2; ctx,n1,b2; ctx,n1,n2]
185               end else []
186         in
187           aux [] l r
188     | _ -> []
189   in
190   let _hints = 
191     List.fold_left 
192       (fun acc (_,_,l) -> 
193           acc @ 
194           if List.length l > 1 then 
195            combine mk_hint l
196           else [])
197       [] (CoercDb.to_list (CoercDb.dump ()))
198   in
199   prerr_endline "MISTERO";
200   assert false (* ERA
201   List.fold_left 
202     (fun db -> function 
203      | (ctx,b1,b2) -> index_hint db ctx b1 b2 0)
204     !user_db (List.flatten hints)
205 *)
206 ;;
207 *)
208
209 let saturate ?(delta=0) metasenv subst context ty goal_arity =
210  assert (goal_arity >= 0);
211   let rec aux metasenv = function
212    | NCic.Prod (name,s,t) as ty ->
213        let metasenv1, _, arg,_ = 
214           NCicMetaSubst.mk_meta ~attrs:[`Name name] metasenv context
215            ~with_type:s `IsTerm 
216        in
217        let t, metasenv1, args, pno = 
218            aux metasenv1 (NCicSubstitution.subst arg t) 
219        in
220        if pno + 1 = goal_arity then
221          ty, metasenv, [], goal_arity+1
222        else
223          t, metasenv1, arg::args, pno+1
224    | ty ->
225         match NCicReduction.whd ~subst context ty ~delta with
226         | NCic.Prod _ as ty -> aux metasenv ty
227         | _ -> ty, metasenv, [], 0 (* differs from the other impl in this line*)
228   in
229   let res, newmetasenv, arguments, _ = aux metasenv ty in
230   res, newmetasenv, arguments
231 ;;
232
233 let eq_class_of hdb t1 = 
234  let eq_class =
235   if NDiscriminationTree.NCicIndexable.path_string_of t1 = 
236      [Discrimination_tree.Variable]
237   then
238     [] (* if the trie is unable to handle the key, we skip the query since
239           it sould retulr the whole content of the trie *)
240   else
241     let candidates = EQDB.retrieve_unifiables (snd hdb#uhint_db) t1 in
242     let candidates = EqSet.elements candidates in
243     let candidates = List.sort (fun (x,_) (y,_) -> compare x y) candidates in
244     List.map snd candidates
245  in
246  debug(lazy("eq_class of: " ^ NCicPp.ppterm ~metasenv:[] ~context:[] ~subst:[]
247    t1 ^ " is\n" ^ String.concat "\n" 
248    (List.map (NCicPp.ppterm ~subst:[] ~metasenv:[] ~context:[]) eq_class)));
249  eq_class   
250 ;;
251
252 let look_for_hint hdb metasenv subst context t1 t2 =
253   if NDiscriminationTree.NCicIndexable.path_string_of t1 =
254           [Discrimination_tree.Variable] || 
255      NDiscriminationTree.NCicIndexable.path_string_of t2 =
256              [Discrimination_tree.Variable] then [] else begin
257
258   debug(lazy ("KEY1: "^NCicPp.ppterm ~metasenv ~subst ~context t1));
259   debug(lazy ("KEY2: "^NCicPp.ppterm ~metasenv ~subst ~context t2));
260 (*
261   HDB.iter hdb
262    (fun p ds ->
263       prerr_endline ("ENTRY: " ^
264       NDiscriminationTree.NCicIndexable.string_of_path p ^ " |--> " ^
265       String.concat "|" (List.map (NCicPp.ppterm ~metasenv:[] ~subst:[]
266       ~context:[]) (HintSet.elements ds))));
267 *)
268   let candidates1 = HDB.retrieve_unifiables (fst hdb#uhint_db) (pair t1 t2) in
269   let candidates2 = HDB.retrieve_unifiables (fst hdb#uhint_db) (pair t2 t1) in
270   let candidates1 = 
271     List.map (fun (prec,_,_,ty) -> 
272        prec,true,saturate ~delta:max_int metasenv subst context ty 0) 
273     (HintSet.elements candidates1) 
274   in
275   let candidates2 = 
276     List.map (fun (prec,_,_,ty) -> 
277        prec,false,saturate ~delta:max_int metasenv subst context ty 0) 
278     (HintSet.elements candidates2) 
279   in
280   let rc = 
281     List.map
282       (fun (p,b,(t,m,_)) ->
283          let rec aux () (m,l as acc) = function
284            | NCic.Meta _ as t -> acc, t
285            | NCic.LetIn (name,ty,bo,t) ->
286                let m,_,i,_=
287                  NCicMetaSubst.mk_meta ~attrs:[`Name name] m context
288                   ~with_type:ty `IsTerm 
289                in
290                let t = NCicSubstitution.subst i t in
291                aux () (m, (i,bo)::l) t
292            | t -> NCicUntrusted.map_term_fold_a (fun _ () -> ()) () aux acc t
293          in
294          let (m,l), t = aux () (m,[]) t in
295          p,b,(t,m,l))
296    (candidates1 @ candidates2)
297   in
298   let rc = 
299   List.map
300    (function 
301     | (prec,true,(NCic.Appl [_; t1; t2],metasenv,l))-> prec,metasenv,(t1,t2),l
302     | (prec,false,(NCic.Appl [_; t1; t2],metasenv,l))-> prec,metasenv,(t2,t1),l
303     | _ -> assert false)
304     rc
305   in
306   let rc = 
307     List.sort (fun (x,_,_,_) (y,_,_,_) -> Pervasives.compare x y) rc
308   in 
309   let rc = List.map (fun (_,x,y,z) -> x,y,z) rc in
310
311   debug(lazy ("Hints:"^
312     String.concat "\n" (List.map 
313      (fun (metasenv, (t1, t2), premises) ->
314          ("\t" ^ String.concat ";  "
315                (List.map (fun (a,b) -> 
316                   NCicPp.ppterm ~margin:max_int ~metasenv ~subst ~context a ^
317                   " =?= "^
318                   NCicPp.ppterm ~margin:max_int ~metasenv ~subst ~context b)
319                premises) ^     
320              "  ==> "^
321              NCicPp.ppterm ~margin:max_int ~metasenv ~subst ~context t1 ^
322              " = "^NCicPp.ppterm ~margin:max_int ~metasenv ~subst ~context t2))
323     rc)));
324
325   rc
326              end
327 ;;
328
329 let pp_hint t p =
330   let context, t = 
331      let rec aux ctx = function
332        | NCic.Prod (name, ty, rest) -> aux ((name, NCic.Decl ty) :: ctx) rest
333        | t -> ctx, t
334      in
335       aux [] t
336   in
337   let recproblems, concl = 
338     let rec aux ctx = function
339       | NCic.LetIn (name,ty,bo,rest) -> aux ((name, NCic.Def(bo,ty))::ctx) rest
340       | t -> ctx, t
341     in
342       aux [] t
343   in
344   let buff = Buffer.create 100 in
345   let fmt = Format.formatter_of_buffer buff in
346 (*
347   F.fprintf "@[<hov>"
348    F.fprintf "@[<hov>"
349 (*    pp_ctx [] context *)
350    F.fprintf "@]"
351   F.fprintf "@;"
352    F.fprintf "@[<hov>"
353 (*    pp_ctx context recproblems *)
354    F.fprintf "@]"
355   F.fprintf "\vdash@;";
356     NCicPp.ppterm ~fmt ~context:(recproblems@context) ~subst:[] ~metasenv:[];
357   F.fprintf "@]"
358   F.fprintf formatter "@?";
359   prerr_endline (Buffer.contents buff);
360 *)
361 ()
362 ;;
363
364 let generate_dot_file status fmt =
365   let module Pp = GraphvizPp.Dot in
366   let h_db, _ = status#uhint_db in
367   let names = ref [] in
368   let id = ref 0 in
369   let mangle l =
370     try List.assoc l !names
371     with Not_found ->
372       incr id;
373       names := (l,"node"^string_of_int!id) :: !names;
374       List.assoc l !names
375   in
376   let nodes = ref [] in
377   let edges = ref [] in
378   HDB.iter h_db (fun _key dataset -> 
379       List.iter
380         (fun (precedence, l,r, hint) ->
381             let l = 
382               Str.global_substitute (Str.regexp "\n") (fun _ -> "")
383                (NCicPp.ppterm 
384                 ~margin:max_int ~metasenv:[] ~context:[] ~subst:[] l) 
385             in
386             let r = 
387               Str.global_substitute (Str.regexp "\n") (fun _ -> "")
388                (NCicPp.ppterm 
389                 ~margin:max_int ~metasenv:[] ~context:[] ~subst:[] r)
390             in
391             let shint =  "???" (*
392               string_of_int precedence ^ "..." ^
393               Str.global_substitute (Str.regexp "\n") (fun _ -> "")
394                (NCicPp.ppterm 
395                 ~margin:max_int ~metasenv:[] ~context:[] ~subst:[] hint)*)
396             in
397             nodes := (mangle l,l) :: (mangle r,r) :: !nodes;
398             edges := (mangle l, mangle r, shint, precedence, hint) :: !edges)
399         (HintSet.elements dataset);
400     );
401   List.iter (fun x, l -> Pp.node x ~attrs:["label",l] fmt) !nodes;
402   List.iter (fun x, y, l, _, _ -> 
403       Pp.raw (Printf.sprintf "%s -- %s [ label=\"%s\" ];\n" x y "?") fmt)
404   !edges;
405   edges := List.sort (fun (_,_,_,p1,_) (_,_,_,p2,_) -> p1 - p2) !edges;
406   List.iter (fun x, y, _, p, l -> pp_hint l p) !edges;
407 ;;