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