]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/paramodulation/equality.ml
matita 0.5.1 tagged
[helm.git] / components / tactics / paramodulation / equality.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://cs.unibo.it/helm/.
24  *)
25
26 (* let _profiler = <:profiler<_profiler>>;; *)
27
28 (* $Id: inference.ml 6245 2006-04-05 12:07:51Z tassi $ *)
29
30 type rule = SuperpositionRight | SuperpositionLeft | Demodulation
31 type uncomparable = int -> int 
32
33 type equality =
34     uncomparable *       (* trick to break structural equality *)
35     int  *               (* weight *)
36     proof * 
37     (Cic.term *          (* type *)
38      Cic.term *          (* left side *)
39      Cic.term *          (* right side *)
40      Utils.comparison) * (* ordering *)  
41     Cic.metasenv  *      (* environment for metas *)
42     int                  (* id *)
43 and proof = 
44   | Exact of Cic.term
45   | Step of Subst.substitution * (rule * int*(Utils.pos*int)* Cic.term) 
46             (* subst, (rule,eq1, eq2,predicate) *)  
47 and goal_proof = (rule * Utils.pos * int * Subst.substitution * Cic.term) list
48 ;;
49 (* the hashtbl eq_id -> proof, max_eq_id *)
50 type equality_bag = (int,equality) Hashtbl.t * int ref
51
52 type goal = goal_proof * Cic.metasenv * Cic.term
53
54 (* globals *)
55 let mk_equality_bag () =
56   Hashtbl.create 1024, ref 0
57 ;;
58
59 let freshid (_,i) =
60   incr i; !i
61 ;;
62
63 let add_to_bag (id_to_eq,_) id eq =
64   Hashtbl.add id_to_eq id eq
65 ;;
66
67 let uncomparable = fun _ -> 0
68
69 let mk_equality bag (weight,p,(ty,l,r,o),m) =
70   let id = freshid bag in
71   let eq = (uncomparable,weight,p,(ty,l,r,o),m,id) in
72   add_to_bag bag id eq;
73   eq
74 ;;
75
76 let mk_tmp_equality (weight,(ty,l,r,o),m) =
77   let id = -1 in
78   uncomparable,weight,Exact (Cic.Implicit None),(ty,l,r,o),m,id
79 ;;
80
81
82 let open_equality (_,weight,proof,(ty,l,r,o),m,id) = 
83   (weight,proof,(ty,l,r,o),m,id)
84
85 let string_of_rule = function
86   | SuperpositionRight -> "SupR"
87   | SuperpositionLeft -> "SupL"
88   | Demodulation -> "Demod"
89 ;;
90
91 let string_of_equality ?env eq =
92   match env with
93   | None ->
94       let w, _, (ty, left, right, o), m , id = open_equality eq in
95       Printf.sprintf "Id: %d, Weight: %d, {%s}: %s =(%s) %s [%s]" 
96               id w (CicPp.ppterm ty)
97               (CicPp.ppterm left) 
98               (Utils.string_of_comparison o) (CicPp.ppterm right)
99          (String.concat ", " (List.map (fun (i,_,_) -> string_of_int i) m)) 
100 (*          "..."  *)
101   | Some (_, context, _) -> 
102       let names = Utils.names_of_context context in
103       let w, _, (ty, left, right, o), m , id = open_equality eq in
104       Printf.sprintf "Id: %d, Weight: %d, {%s}: %s =(%s) %s [%s]" 
105               id w (CicPp.pp ty names)
106               (CicPp.pp left names) (Utils.string_of_comparison o)
107               (CicPp.pp right names)
108          (String.concat ", " (List.map (fun (i,_,_) -> string_of_int i) m)) 
109 (*            "..." *)
110 ;;
111
112 let compare (_,_,_,s1,_,_) (_,_,_,s2,_,_) =
113   Pervasives.compare s1 s2
114 ;;
115
116 let rec max_weight_in_proof ((id_to_eq,_) as bag) current =
117   function
118    | Exact _ -> current
119    | Step (_, (_,id1,(_,id2),_)) ->
120        let eq1 = Hashtbl.find id_to_eq id1 in
121        let eq2 = Hashtbl.find id_to_eq id2 in  
122        let (w1,p1,(_,_,_,_),_,_) = open_equality eq1 in
123        let (w2,p2,(_,_,_,_),_,_) = open_equality eq2 in
124        let current = max current w1 in
125        let current = max_weight_in_proof bag current p1 in
126        let current = max current w2 in
127        max_weight_in_proof bag current p2
128
129 let max_weight_in_goal_proof ((id_to_eq,_) as bag) =
130   List.fold_left 
131     (fun current (_,_,id,_,_) ->
132        let eq = Hashtbl.find id_to_eq id in
133        let (w,p,(_,_,_,_),_,_) = open_equality eq in
134        let current = max current w in
135        max_weight_in_proof bag current p)
136
137 let max_weight bag goal_proof proof =
138   let current = max_weight_in_proof bag 0 proof in
139   max_weight_in_goal_proof bag current goal_proof
140
141 let proof_of_id (id_to_eq,_) id =
142   try
143     let (_,p,(_,l,r,_),_,_) = open_equality (Hashtbl.find id_to_eq id) in
144       p,l,r
145   with
146       Not_found -> assert false
147
148
149 let string_of_proof ?(names=[]) bag p gp = 
150   let str_of_pos = function
151     | Utils.Left -> "left"
152     | Utils.Right -> "right"
153   in
154   let fst3 (x,_,_) = x in
155   let rec aux margin name = 
156     let prefix = String.make margin ' ' ^ name ^ ": " in function 
157     | Exact t -> 
158         Printf.sprintf "%sExact (%s)\n" 
159           prefix (CicPp.pp t names)
160     | Step (subst,(rule,eq1,(pos,eq2),pred)) -> 
161         Printf.sprintf "%s%s(%s|%d with %d dir %s pred %s))\n"
162           prefix (string_of_rule rule) (Subst.ppsubst ~names subst) eq1 eq2 (str_of_pos pos) 
163           (CicPp.pp pred names)^ 
164         aux (margin+1) (Printf.sprintf "%d" eq1) (fst3 (proof_of_id bag eq1)) ^ 
165         aux (margin+1) (Printf.sprintf "%d" eq2) (fst3 (proof_of_id bag eq2)) 
166   in
167   aux 0 "" p ^ 
168   String.concat "\n" 
169     (List.map 
170       (fun (r,pos,i,s,t) -> 
171         (Printf.sprintf 
172           "GOAL: %s %s %d %s %s\n" (string_of_rule r)
173             (str_of_pos pos) i (Subst.ppsubst ~names s) (CicPp.pp t names)) ^ 
174         aux 1 (Printf.sprintf "%d " i) (fst3 (proof_of_id bag i)))
175       gp)
176 ;;
177
178 let rec depend ((id_to_eq,_) as bag) eq id seen =
179   let (_,p,(_,_,_,_),_,ideq) = open_equality eq in
180   if List.mem ideq seen then 
181     false,seen
182   else
183     if id = ideq then 
184       true,seen
185     else  
186       match p with
187       | Exact _ -> false,seen
188       | Step (_,(_,id1,(_,id2),_)) ->
189           let seen = ideq::seen in
190           let eq1 = Hashtbl.find id_to_eq id1 in
191           let eq2 = Hashtbl.find id_to_eq id2 in  
192           let b1,seen = depend bag eq1 id seen in
193           if b1 then b1,seen else depend bag eq2 id seen
194 ;;
195
196 let depend bag eq id = fst (depend bag eq id []);;
197
198 let ppsubst = Subst.ppsubst ~names:[];;
199
200 (* returns an explicit named subst and a list of arguments for sym_eq_URI *)
201 let build_ens uri termlist =
202   let obj, _ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
203   match obj with
204   | Cic.Constant (_, _, _, uris, _) ->
205       (* assert (List.length uris <= List.length termlist); *)
206       let rec aux = function
207         | [], tl -> [], tl
208         | (uri::uris), (term::tl) ->
209             let ens, args = aux (uris, tl) in
210             (uri, term)::ens, args
211         | _, _ -> assert false
212       in
213       aux (uris, termlist)
214   | _ -> assert false
215 ;;
216
217 let mk_sym uri ty t1 t2 p =
218   let ens, args =  build_ens uri [ty;t1;t2;p] in
219     Cic.Appl (Cic.Const(uri, ens) :: args)
220 ;;
221
222 let mk_trans uri ty t1 t2 t3 p12 p23 =
223   let ens, args = build_ens uri [ty;t1;t2;t3;p12;p23] in
224     Cic.Appl (Cic.Const (uri, ens) :: args)
225 ;;
226
227 let mk_eq_ind uri ty what pred p1 other p2 =
228   let ens, args = build_ens uri [ty; what; pred; p1; other; p2] in
229   Cic.Appl (Cic.Const (uri, ens) :: args)
230 ;;
231
232 let p_of_sym ens tl =
233   let args = List.map snd ens @ tl in
234   match args with 
235     | [_;_;_;p] -> p 
236     | _ -> assert false 
237 ;;
238
239 let open_trans ens tl =
240   let args = List.map snd ens @ tl in
241   match args with 
242     | [ty;l;m;r;p1;p2] -> ty,l,m,r,p1,p2
243     | _ -> assert false   
244 ;;
245
246 let open_sym ens tl =
247   let args = List.map snd ens @ tl in
248   match args with 
249     | [ty;l;r;p] -> ty,l,r,p
250     | _ -> assert false   
251 ;;
252
253 let open_eq_ind args =
254   match args with 
255   | [ty;l;pred;pl;r;pleqr] -> ty,l,pred,pl,r,pleqr
256   | _ -> assert false   
257 ;;
258
259 let open_pred pred =
260   match pred with 
261   | Cic.Lambda (_,_,(Cic.Appl [Cic.MutInd (uri, 0,_);ty;l;r])) 
262      when LibraryObjects.is_eq_URI uri -> ty,uri,l,r
263   | _ -> Utils.debug_print (lazy (CicPp.ppterm pred)); assert false   
264 ;;
265
266 let is_not_fixed t =
267    CicSubstitution.subst (Cic.Implicit None) t <>
268    CicSubstitution.subst (Cic.Rel 1) t
269 ;;
270
271 let canonical t context menv = 
272   let remove_cycles t =
273    let is_transitive =
274     function
275        Cic.Appl (Cic.Const (uri_trans,_)::_)
276         when LibraryObjects.is_trans_eq_URI uri_trans ->
277          true
278      | _ -> false in
279    let rec collect =
280     function
281        Cic.Appl (Cic.Const (uri_trans,ens)::tl)
282         when LibraryObjects.is_trans_eq_URI uri_trans ->
283          let ty,l,m,r,p1,p2 = open_trans ens tl in
284           (if is_transitive p1 then fst (collect p1) else [l,p1]) @
285            (if is_transitive p2 then fst (collect p2) else [m,p2]),
286           (r, uri_trans, ty)
287      | t -> assert false in
288    let rec cut_to_last_duplicate l acc =
289     function
290        [] -> List.rev acc
291      | (l',p)::tl when l=l' -> 
292 if acc <> [] then
293 Utils.debug_print (lazy ("!!! RISPARMIO " ^ string_of_int (List.length acc) ^ " PASSI"));
294          cut_to_last_duplicate l [l',p] tl
295      | (l',p)::tl ->
296          cut_to_last_duplicate l ((l',p)::acc) tl
297    in
298    let rec rebuild =
299     function
300        (l,_)::_::_ as steps, ((r,uri_trans,ty) as last) ->
301          (match cut_to_last_duplicate l [] steps with
302              (l,p1)::((m,_)::_::_ as tl) ->
303                mk_trans uri_trans ty l m r p1 (rebuild (tl,last))
304            | [l,p1 ; m,p2] -> mk_trans uri_trans ty l m r p1 p2
305            | [l,p1] -> p1
306            | [] -> assert false)
307      | _ -> assert false
308    in
309     if is_transitive t then
310      rebuild (collect t)
311     else
312      t
313   in
314   let rec remove_refl t =
315     match t with
316     | Cic.Appl (((Cic.Const(uri_trans,ens))::tl) as args)
317           when LibraryObjects.is_trans_eq_URI uri_trans ->
318           let ty,l,m,r,p1,p2 = open_trans ens tl in
319             (match p1,p2 with
320               | Cic.Appl [Cic.MutConstruct (uri, 0, 1,_);_;_],p2 -> 
321                   remove_refl p2
322               | p1,Cic.Appl [Cic.MutConstruct (uri, 0, 1,_);_;_] -> 
323                   remove_refl p1
324               | _ -> Cic.Appl (List.map remove_refl args))
325     | Cic.Appl l -> Cic.Appl (List.map remove_refl l)
326     | Cic.LetIn (name,bo,ty,rest) ->
327         Cic.LetIn (name,remove_refl bo,remove_refl ty,remove_refl rest)
328     | _ -> t
329   in
330   let rec canonical_trough_lambda context = function
331     | Cic.Lambda(name,ty,bo) -> 
332         let context' = (Some (name,Cic.Decl ty))::context in
333         Cic.Lambda(name,ty,canonical_trough_lambda context' bo)
334     | t -> canonical context t
335
336   and canonical context t =
337     match t with
338       | Cic.LetIn(name,bo,ty,rest) -> 
339           let bo = canonical_trough_lambda context bo in
340           let ty = canonical_trough_lambda context ty in
341           let context' = (Some (name,Cic.Def (bo,ty)))::context in
342           Cic.LetIn(name,bo,ty,canonical context' rest)
343       | Cic.Appl (((Cic.Const(uri_sym,ens))::tl) as args)
344           when LibraryObjects.is_sym_eq_URI uri_sym ->
345           (match p_of_sym ens tl with
346              | Cic.Appl ((Cic.Const(uri,ens))::tl)
347                  when LibraryObjects.is_sym_eq_URI uri -> 
348                    canonical context (p_of_sym ens tl)
349              | Cic.Appl ((Cic.Const(uri_trans,ens))::tl)
350                  when LibraryObjects.is_trans_eq_URI uri_trans ->
351                  let ty,l,m,r,p1,p2 = open_trans ens tl in
352                    mk_trans uri_trans ty r m l 
353                      (canonical context (mk_sym uri_sym ty m r p2)) 
354                      (canonical context (mk_sym uri_sym ty l m p1))
355              | Cic.Appl (([Cic.Const(uri_feq,ens);ty1;ty2;f;x;y;p]))
356                  when LibraryObjects.is_eq_f_URI uri_feq ->
357                  let eq = LibraryObjects.eq_URI_of_eq_f_URI uri_feq in
358                  let eq_f_sym =
359                    Cic.Const (LibraryObjects.eq_f_sym_URI ~eq, [])
360                  in
361                  let rc = Cic.Appl [eq_f_sym;ty1;ty2;f;x;y;p] in
362                  Utils.debug_print (lazy ("CANONICAL " ^ CicPp.ppterm rc));
363                  rc
364              | Cic.Appl [Cic.MutConstruct (uri, 0, 1,_);_;_] as t
365                  when LibraryObjects.is_eq_URI uri -> t
366              | _ -> Cic.Appl (List.map (canonical context) args))
367       | Cic.Appl l -> Cic.Appl (List.map (canonical context) l)
368       | _ -> t
369   in
370    remove_cycles (remove_refl (canonical context t))
371 ;;
372   
373 let compose_contexts ctx1 ctx2 = 
374   ProofEngineReduction.replace_lifting 
375   ~equality:(fun _ ->(=)) ~context:[] ~what:[Cic.Implicit(Some `Hole)] ~with_what:[ctx2] ~where:ctx1
376 ;;
377
378 let put_in_ctx ctx t = 
379   ProofEngineReduction.replace_lifting
380   ~equality:(fun _ -> (=)) ~context:[] ~what:[Cic.Implicit (Some `Hole)] ~with_what:[t] ~where:ctx
381 ;;
382
383 let mk_eq uri ty l r =
384   let ens, args = build_ens uri [ty; l; r] in
385   Cic.Appl (Cic.MutInd(uri,0,ens) :: args)
386 ;;
387
388 let mk_refl uri ty t = 
389   let ens, args = build_ens uri [ty; t] in
390   Cic.Appl (Cic.MutConstruct(uri,0,1,ens) :: args)
391 ;;
392
393 let open_eq = function 
394   | Cic.Appl [Cic.MutInd(uri,0,[]);ty;l;r] when LibraryObjects.is_eq_URI uri ->
395       uri, ty, l ,r
396   | _ -> assert false
397 ;;
398
399 let mk_feq uri_feq ty ty1 left pred right t = 
400   let ens, args = build_ens uri_feq [ty;ty1;pred;left;right;t] in
401   Cic.Appl (Cic.Const(uri_feq,ens) :: args)
402 ;;
403
404 let rec look_ahead aux = function
405   | Cic.Appl ((Cic.Const(uri_ind,ens))::tl) as t
406         when LibraryObjects.is_eq_ind_URI uri_ind || 
407              LibraryObjects.is_eq_ind_r_URI uri_ind ->
408           let ty1,what,pred,p1,other,p2 = open_eq_ind tl in
409           let ty2,eq,lp,rp = open_pred pred in 
410           let hole = Cic.Implicit (Some `Hole) in
411           let ty2 = CicSubstitution.subst hole ty2 in
412           aux ty1 (CicSubstitution.subst other lp) (CicSubstitution.subst other rp) hole ty2 t
413   | Cic.Lambda (n,s,t) -> Cic.Lambda (n,s,look_ahead aux t)
414   | t -> t
415 ;;
416
417 let contextualize uri ty left right t = 
418   let hole = Cic.Implicit (Some `Hole) in
419   (* aux [uri] [ty] [left] [right] [ctx] [ctx_ty] [t] 
420    * 
421    * the parameters validate this invariant  
422    *   t: eq(uri) ty left right
423    * that is used only by the base case
424    *
425    * ctx is a term with an hole. Cic.Implicit(Some `Hole) is the empty context
426    * ctx_ty is the type of ctx
427    *)
428     let rec aux uri ty left right ctx_d ctx_ty t =
429       match t with 
430       | Cic.Appl ((Cic.Const(uri_sym,ens))::tl) 
431         when LibraryObjects.is_sym_eq_URI uri_sym  ->
432           let ty,l,r,p = open_sym ens tl in
433           mk_sym uri_sym ty l r (aux uri ty l r ctx_d ctx_ty p)
434       | Cic.LetIn (name,body,bodyty,rest) ->
435          Cic.LetIn
436           (name,look_ahead (aux uri) body, bodyty,
437            aux uri ty left right ctx_d ctx_ty rest)
438       | Cic.Appl ((Cic.Const(uri_ind,ens))::tl)
439         when LibraryObjects.is_eq_ind_URI uri_ind || 
440              LibraryObjects.is_eq_ind_r_URI uri_ind ->
441           let ty1,what,pred,p1,other,p2 = open_eq_ind tl in
442           let ty2,eq,lp,rp = open_pred pred in 
443           let uri_trans = LibraryObjects.trans_eq_URI ~eq:uri in
444           let uri_sym = LibraryObjects.sym_eq_URI ~eq:uri in
445           let is_not_fixed_lp = is_not_fixed lp in
446           let avoid_eq_ind = LibraryObjects.is_eq_ind_URI uri_ind in
447           (* extract the context and the fixed term from the predicate *)
448           let m, ctx_c, ty2 = 
449             let m, ctx_c = if is_not_fixed_lp then rp,lp else lp,rp in
450             (* they were under a lambda *)
451             let m =  CicSubstitution.subst hole m in
452             let ctx_c = CicSubstitution.subst hole ctx_c in
453             let ty2 = CicSubstitution.subst hole ty2 in
454             m, ctx_c, ty2          
455           in
456           (* create the compound context and put the terms under it *)
457           let ctx_dc = compose_contexts ctx_d ctx_c in
458           let dc_what = put_in_ctx ctx_dc what in
459           let dc_other = put_in_ctx ctx_dc other in
460           (* m is already in ctx_c so it is put in ctx_d only *)
461           let d_m = put_in_ctx ctx_d m in
462           (* we also need what in ctx_c *)
463           let c_what = put_in_ctx ctx_c what in
464           (* now put the proofs in the compound context *)
465           let p1 = (* p1: dc_what = d_m *)
466             if is_not_fixed_lp then
467               aux uri ty2 c_what m ctx_d ctx_ty p1
468             else
469               mk_sym uri_sym ctx_ty d_m dc_what
470                 (aux uri ty2 m c_what ctx_d ctx_ty p1)
471           in
472           let p2 = (* p2: dc_other = dc_what *)
473             if avoid_eq_ind then
474               mk_sym uri_sym ctx_ty dc_what dc_other
475                 (aux uri ty1 what other ctx_dc ctx_ty p2)
476              else
477               aux uri ty1 other what ctx_dc ctx_ty p2
478           in
479           (* if pred = \x.C[x]=m --> t : C[other]=m --> trans other what m
480              if pred = \x.m=C[x] --> t : m=C[other] --> trans m what other *)
481           let a,b,c,paeqb,pbeqc =
482             if is_not_fixed_lp then
483               dc_other,dc_what,d_m,p2,p1
484             else
485               d_m,dc_what,dc_other,
486                 (mk_sym uri_sym ctx_ty dc_what d_m p1),
487                 (mk_sym uri_sym ctx_ty dc_other dc_what p2)
488           in
489           mk_trans uri_trans ctx_ty a b c paeqb pbeqc
490     | t when ctx_d = hole -> t 
491     | t -> 
492 (*         let uri_sym = LibraryObjects.sym_eq_URI ~eq:uri in *)
493 (*         let uri_ind = LibraryObjects.eq_ind_URI ~eq:uri in *)
494
495         let uri_feq = LibraryObjects.eq_f_URI ~eq:uri in
496         let pred = 
497 (*           let r = CicSubstitution.lift 1 (put_in_ctx ctx_d left) in *)
498           let l = 
499             let ctx_d = CicSubstitution.lift 1 ctx_d in
500             put_in_ctx ctx_d (Cic.Rel 1)
501           in
502 (*           let lty = CicSubstitution.lift 1 ctx_ty in  *)
503 (*           Cic.Lambda (Cic.Name "foo",ty,(mk_eq uri lty l r)) *)
504           Cic.Lambda (Cic.Name "foo",ty,l)
505         in
506 (*         let d_left = put_in_ctx ctx_d left in *)
507 (*         let d_right = put_in_ctx ctx_d right in *)
508 (*         let refl_eq = mk_refl uri ctx_ty d_left in *)
509 (*         mk_sym uri_sym ctx_ty d_right d_left *)
510 (*           (mk_eq_ind uri_ind ty left pred refl_eq right t) *)
511           (mk_feq uri_feq ty ctx_ty left pred right t)
512   in
513   aux uri ty left right hole ty t
514 ;;
515
516 let contextualize_rewrites t ty = 
517   let eq,ty,l,r = open_eq ty in
518   contextualize eq ty l r t
519 ;;
520
521 let add_subst subst =
522   function
523     | Exact t -> Exact (Subst.apply_subst subst t)
524     | Step (s,(rule, id1, (pos,id2), pred)) -> 
525         Step (Subst.concat subst s,(rule, id1, (pos,id2), pred))
526 ;;
527         
528 let build_proof_step eq lift subst p1 p2 pos l r pred =
529   let p1 = Subst.apply_subst_lift lift subst p1 in
530   let p2 = Subst.apply_subst_lift lift subst p2 in
531   let l  = CicSubstitution.lift lift l in
532   let l = Subst.apply_subst_lift lift subst l in
533   let r  = CicSubstitution.lift lift r in
534   let r = Subst.apply_subst_lift lift subst r in
535   let pred = CicSubstitution.lift lift pred in
536   let pred = Subst.apply_subst_lift lift subst pred in
537   let ty,body = 
538     match pred with
539       | Cic.Lambda (_,ty,body) -> ty,body 
540       | _ -> assert false
541   in
542   let what, other = 
543     if pos = Utils.Left then l,r else r,l
544   in
545   let p =
546     match pos with
547       | Utils.Left ->
548         mk_eq_ind (LibraryObjects.eq_ind_URI ~eq) ty what pred p1 other p2
549       | Utils.Right ->
550         mk_eq_ind (LibraryObjects.eq_ind_r_URI ~eq) ty what pred p1 other p2
551   in
552     p
553 ;;
554
555 let parametrize_proof p l r = 
556   let uniq l = HExtlib.list_uniq (List.sort (fun (i,_) (j,_) -> Pervasives.compare i j) l) in
557   let mot = CicUtil.metas_of_term_set in
558   let parameters = uniq (mot p @ mot l @ mot r) in 
559   (* ?if they are under a lambda? *)
560 (*
561   let parameters = 
562     HExtlib.list_uniq (List.sort Pervasives.compare parameters) 
563   in
564 *)
565   (* resorts l such that *hopefully* dependencies can be inferred *)
566   let guess_dependency p l =
567     match p with
568     | Cic.Appl ((Cic.Const(uri_ind,ens))::tl) 
569         when LibraryObjects.is_eq_ind_URI uri_ind || 
570              LibraryObjects.is_eq_ind_r_URI uri_ind ->
571         let ty,_,_,_,_,_ = open_eq_ind tl in
572         let metas = CicUtil.metas_of_term ty in
573         let nondep, dep = 
574           List.partition (fun (i,_) -> List.exists (fun (j,_) -> j=i) metas) l
575         in
576         nondep@dep
577     | _ -> l
578   in
579   let parameters = guess_dependency p parameters in
580   let what = List.map (fun (i,l) -> Cic.Meta (i,l)) parameters in 
581   let with_what, lift_no = 
582     List.fold_right (fun _ (acc,n) -> ((Cic.Rel n)::acc),n+1) what ([],1) 
583   in
584   let p = CicSubstitution.lift (lift_no-1) p in
585   let p = 
586     ProofEngineReduction.replace_lifting
587     ~equality:(fun _ t1 t2 -> 
588       match t1,t2 with Cic.Meta (i,_),Cic.Meta(j,_) -> i=j | _ -> false) 
589     ~context:[]
590     ~what ~with_what ~where:p
591   in
592   let ty_of_m _ = Cic.Implicit (Some `Type) in
593   let args, proof,_ = 
594     List.fold_left 
595       (fun (instance,p,n) m -> 
596         (instance@[m],
597         Cic.Lambda 
598           (Cic.Name ("X"^string_of_int n),
599           CicSubstitution.lift (lift_no - n - 1) (ty_of_m m),
600           p),
601         n+1)) 
602       ([Cic.Rel 1],p,1) 
603       what
604   in
605   let instance = match args with | [x] -> x | _ -> Cic.Appl args in
606   proof, instance
607 ;;
608
609 let wfo bag goalproof proof id =
610   let rec aux acc id =
611     let p,_,_ = proof_of_id bag id in
612     match p with
613     | Exact _ -> if (List.mem id acc) then acc else id :: acc
614     | Step (_,(_,id1, (_,id2), _)) -> 
615         let acc = if not (List.mem id1 acc) then aux acc id1 else acc in
616         let acc = if not (List.mem id2 acc) then aux acc id2 else acc in
617         id :: acc
618   in
619   let acc = 
620     match proof with
621       | Exact _ -> [id]
622       | Step (_,(_,id1, (_,id2), _)) -> aux (aux [id] id1) id2
623   in 
624   List.fold_left (fun acc (_,_,id,_,_) -> aux acc id) acc goalproof
625 ;;
626
627 let string_of_id (id_to_eq,_) names id = 
628   if id = 0 then "" else 
629   try
630     let (_,p,(t,l,r,_),m,_) = open_equality (Hashtbl.find id_to_eq id) in
631     match p with
632     | Exact t -> 
633         Printf.sprintf "%d = %s: %s = %s [%s]" id
634           (CicPp.pp t names) (CicPp.pp l names) (CicPp.pp r names)
635 (*           "..." *)
636          (String.concat ", " (List.map (fun (i,_,_) -> string_of_int i) m)) 
637     | Step (_,(step,id1, (dir,id2), p) ) ->
638         Printf.sprintf "%6d: %s %6d %6d   %s =(%s) %s [%s]" id
639           (string_of_rule step)
640           id1 id2 (CicPp.pp l names) (CicPp.pp t names) (CicPp.pp r names)
641          (String.concat ", " (List.map (fun (i,_,_) -> string_of_int i) m)) 
642           (*"..."*)
643   with
644       Not_found -> assert false
645
646 let pp_proof bag names goalproof proof subst id initial_goal =
647   String.concat "\n" (List.map (string_of_id bag names) (wfo bag goalproof proof id)) ^ 
648   "\ngoal:\n   " ^ 
649     (String.concat "\n   " 
650       (fst (List.fold_right
651         (fun (r,pos,i,s,pred) (acc,g) -> 
652           let _,_,left,right = open_eq g in
653           let ty = 
654             match pos with 
655             | Utils.Left -> CicReduction.head_beta_reduce (Cic.Appl[pred;right])
656             | Utils.Right -> CicReduction.head_beta_reduce (Cic.Appl[pred;left])
657           in
658           let ty = Subst.apply_subst s ty in
659           ("("^ string_of_rule r ^ " " ^ string_of_int i^") -> "
660           ^ CicPp.pp ty names) :: acc,ty) goalproof ([],initial_goal)))) ^
661   "\nand then subsumed by " ^ string_of_int id ^ " when " ^ Subst.ppsubst subst
662 ;;
663
664 module OT = 
665   struct
666     type t = int
667     let compare = Pervasives.compare
668   end
669
670 module M = Map.Make(OT)
671
672 let rec find_deps bag m i = 
673   if M.mem i m then m
674   else 
675     let p,_,_ = proof_of_id bag i in
676     match p with
677     | Exact _ -> M.add i [] m
678     | Step (_,(_,id1,(_,id2),_)) -> 
679         let m = find_deps bag m id1 in
680         let m = find_deps bag m id2 in
681         (* without the uniq there is a stack overflow doing concatenation *)
682         let xxx = [id1;id2] @ M.find id1 m @ M.find id2 m in 
683         let xxx = HExtlib.list_uniq (List.sort Pervasives.compare xxx) in
684         M.add i xxx m
685 ;;
686
687 let topological_sort bag l = 
688   (* build the partial order relation *)
689   let m = List.fold_left (fun m i -> find_deps bag m i) M.empty l in
690   let m = (* keep only deps inside l *) 
691     List.fold_left 
692       (fun m' i ->
693         M.add i (List.filter (fun x -> List.mem x l) (M.find i m)) m') 
694       M.empty l 
695   in
696   let m = M.map (fun x -> Some x) m in
697   (* utils *)
698   let keys m = M.fold (fun i _ acc -> i::acc) m [] in
699   let split l m = List.filter (fun i -> M.find i m = Some []) l in
700   let purge l m = 
701     M.mapi 
702       (fun k v -> if List.mem k l then None else 
703          match v with
704          | None -> None
705          | Some ll -> Some (List.filter (fun i -> not (List.mem i l)) ll)) 
706       m
707   in
708   let rec aux m res = 
709       let keys = keys m in
710       let ok = split keys m in
711       let m = purge ok m in
712       let res = ok @ res in
713       if ok = [] then res else aux m res
714   in
715   let rc = List.rev (aux m []) in
716   rc
717 ;;
718   
719
720 (* returns the list of ids that should be factorized *)
721 let get_duplicate_step_in_wfo bag l p =
722   let ol = List.rev l in
723   let h = Hashtbl.create 13 in
724   (* NOTE: here the n parameter is an approximation of the dependency 
725      between equations. To do things seriously we should maintain a 
726      dependency graph. This approximation is not perfect. *)
727   let add i = 
728     let p,_,_ = proof_of_id bag i in 
729     match p with 
730     | Exact _ -> true
731     | _ -> 
732         try 
733           let no = Hashtbl.find h i in
734           Hashtbl.replace h i (no+1);
735           false
736         with Not_found -> Hashtbl.add h i 1;true
737   in
738   let rec aux = function
739     | Exact _ -> ()
740     | Step (_,(_,i1,(_,i2),_)) -> 
741         let go_on_1 = add i1 in
742         let go_on_2 = add i2 in
743         if go_on_1 then aux (let p,_,_ = proof_of_id bag i1 in p);
744         if go_on_2 then aux (let p,_,_ = proof_of_id bag i2 in p)
745   in
746   aux p;
747   List.iter
748     (fun (_,_,id,_,_) -> aux (let p,_,_ = proof_of_id bag id in p))
749     ol;
750   (* now h is complete *)
751   let proofs = Hashtbl.fold (fun k count acc-> (k,count)::acc) h [] in
752   let proofs = List.filter (fun (_,c) -> c > 1) proofs in
753   let res = topological_sort bag (List.map (fun (i,_) -> i) proofs) in
754   res
755 ;;
756
757 let build_proof_term bag eq h lift proof =
758   let proof_of_id aux id =
759     let p,l,r = proof_of_id bag id in
760     try List.assoc id h,l,r with Not_found -> aux p, l, r
761   in
762   let rec aux = function
763      | Exact term -> 
764          CicSubstitution.lift lift term
765      | Step (subst,(rule, id1, (pos,id2), pred)) ->
766          let p1,_,_ = proof_of_id aux id1 in
767          let p2,l,r = proof_of_id aux id2 in
768          let varname = 
769            match rule with
770            | SuperpositionRight -> Cic.Name ("SupR" ^ Utils.string_of_pos pos) 
771            | Demodulation -> Cic.Name ("DemEq"^ Utils.string_of_pos pos)
772            | _ -> assert false
773          in
774          let pred = 
775            match pred with
776            | Cic.Lambda (_,a,b) -> Cic.Lambda (varname,a,b)
777            | _ -> assert false
778          in
779          let p = build_proof_step eq lift subst p1 p2 pos l r pred in
780 (*         let cond =  (not (List.mem 302 (Utils.metas_of_term p)) || id1 = 8 || id1 = 132) in
781            if not cond then
782              prerr_endline ("ERROR " ^ string_of_int id1 ^ " " ^ string_of_int id2);
783            assert cond;*)
784            p
785   in
786    aux proof
787 ;;
788
789 let build_goal_proof bag eq l initial ty se context menv =
790   let se = List.map (fun i -> Cic.Meta (i,[])) se in 
791   let lets = get_duplicate_step_in_wfo bag l initial in
792   let letsno = List.length lets in
793   let lift_list l = List.map (fun (i,t) -> i,CicSubstitution.lift 1 t) l in
794   let lets,_,h = 
795     List.fold_left
796       (fun (acc,n,h) id -> 
797         let p,l,r = proof_of_id bag id in
798         let cic = build_proof_term bag eq h n p in
799         let real_cic,instance = 
800           parametrize_proof cic l r 
801         in
802         let h = (id, instance)::lift_list h in
803         acc@[id,real_cic],n+1,h) 
804       ([],0,[]) lets
805   in
806   let lets =
807    List.map (fun (id,cic) -> id,cic,Cic.Implicit (Some `Type)) lets
808   in
809   let proof,se = 
810     let rec aux se current_proof = function
811       | [] -> current_proof,se
812       | (rule,pos,id,subst,pred)::tl ->
813           let p,l,r = proof_of_id bag id in
814            let p = build_proof_term bag eq h letsno p in
815            let pos = if pos = Utils.Left then Utils.Right else Utils.Left in
816          let varname = 
817            match rule with
818            | SuperpositionLeft -> Cic.Name ("SupL" ^ Utils.string_of_pos pos) 
819            | Demodulation -> Cic.Name ("DemG"^ Utils.string_of_pos pos)
820            | _ -> assert false
821          in
822          let pred = 
823            match pred with
824            | Cic.Lambda (_,a,b) -> Cic.Lambda (varname,a,b)
825            | _ -> assert false
826          in
827            let proof = 
828              build_proof_step eq letsno subst current_proof p pos l r pred
829            in
830            let proof,se = aux se proof tl in
831            Subst.apply_subst_lift letsno subst proof,
832            List.map (fun x -> Subst.apply_subst(*_lift letsno*) subst x) se
833     in
834     aux se (build_proof_term bag eq h letsno initial) l
835   in
836   let n,proof = 
837     let initial = proof in
838     List.fold_right
839       (fun (id,cic,ty) (n,p) -> 
840         n-1,
841         Cic.LetIn (
842           Cic.Name ("H"^string_of_int id),
843           cic,
844           ty,
845           p))
846     lets (letsno-1,initial)
847   in
848    canonical 
849      (contextualize_rewrites proof (CicSubstitution.lift letsno ty))
850      context menv,
851    se 
852 ;;
853
854 let refl_proof eq_uri ty term = 
855   Cic.Appl [Cic.MutConstruct (eq_uri, 0, 1, []); ty; term]
856 ;;
857
858 let metas_of_proof bag p =
859   let eq = 
860     match LibraryObjects.eq_URI () with
861     | Some u -> u 
862     | None -> 
863         raise 
864           (ProofEngineTypes.Fail 
865             (lazy "No default equality defined when calling metas_of_proof"))
866   in
867   let p = build_proof_term bag eq [] 0 p in
868   Utils.metas_of_term p
869 ;;
870
871 let remove_local_context eq =
872    let w, p, (ty, left, right, o), menv,id = open_equality eq in
873    let p = Utils.remove_local_context p in
874    let ty = Utils.remove_local_context ty in
875    let left = Utils.remove_local_context left in
876    let right = Utils.remove_local_context right in
877    w, p, (ty, left, right, o), menv, id
878 ;;
879
880 let relocate newmeta menv to_be_relocated =
881   let subst, newmetasenv, newmeta = 
882     List.fold_right 
883       (fun i (subst, metasenv, maxmeta) ->         
884         let _,context,ty = CicUtil.lookup_meta i menv in
885         let irl = [] in
886         let newmeta = Cic.Meta(maxmeta,irl) in
887         let newsubst = Subst.buildsubst i context newmeta ty subst in
888         newsubst, (maxmeta,context,ty)::metasenv, maxmeta+1) 
889       to_be_relocated (Subst.empty_subst, [], newmeta+1)
890   in
891   let menv = Subst.apply_subst_metasenv subst menv @ newmetasenv in
892   subst, menv, newmeta
893
894 let fix_metas_goal newmeta goal =
895   let (proof, menv, ty) = goal in
896   let to_be_relocated = 
897     HExtlib.list_uniq (List.sort Pervasives.compare (Utils.metas_of_term ty))
898   in
899   let subst, menv, newmeta = relocate newmeta menv to_be_relocated in
900   let ty = Subst.apply_subst subst ty in
901   let proof = 
902     match proof with
903     | [] -> assert false (* is a nonsense to relocate the initial goal *)
904     | (r,pos,id,s,p) :: tl -> (r,pos,id,Subst.concat subst s,p) :: tl
905   in
906   newmeta+1,(proof, menv, ty)
907 ;;
908
909 let fix_metas bag newmeta eq = 
910   let w, p, (ty, left, right, o), menv,_ = open_equality eq in
911   let to_be_relocated = 
912 (* List.map (fun i ,_,_ -> i) menv *)
913     HExtlib.list_uniq 
914       (List.sort Pervasives.compare 
915          (Utils.metas_of_term left @ Utils.metas_of_term right @
916          Utils.metas_of_term ty)) 
917   in
918   let subst, metasenv, newmeta = relocate newmeta menv to_be_relocated in
919   let ty = Subst.apply_subst subst ty in
920   let left = Subst.apply_subst subst left in
921   let right = Subst.apply_subst subst right in
922   let fix_proof = function
923     | Exact p -> Exact (Subst.apply_subst subst p)
924     | Step (s,(r,id1,(pos,id2),pred)) -> 
925         Step (Subst.concat s subst,(r,id1,(pos,id2), pred))
926   in
927   let p = fix_proof p in
928   let eq' = mk_equality bag (w, p, (ty, left, right, o), metasenv) in
929   newmeta+1, eq'  
930
931 exception NotMetaConvertible;;
932
933 let meta_convertibility_aux table t1 t2 =
934   let module C = Cic in
935   let rec aux ((table_l,table_r) as table) t1 t2 =
936     match t1, t2 with
937     | C.Meta (m1, tl1), C.Meta (m2, tl2) when m1 = m2 -> table
938     | C.Meta (m1, tl1), C.Meta (m2, tl2) when m1 < m2 -> aux table t2 t1
939     | C.Meta (m1, tl1), C.Meta (m2, tl2) ->
940         let m1_binding, table_l =
941           try List.assoc m1 table_l, table_l
942           with Not_found -> m2, (m1, m2)::table_l
943         and m2_binding, table_r =
944           try List.assoc m2 table_r, table_r
945           with Not_found -> m1, (m2, m1)::table_r
946         in
947         if (m1_binding <> m2) || (m2_binding <> m1) then
948           raise NotMetaConvertible
949         else table_l,table_r
950     | C.Var (u1, ens1), C.Var (u2, ens2)
951     | C.Const (u1, ens1), C.Const (u2, ens2) when (UriManager.eq u1 u2) ->
952         aux_ens table ens1 ens2
953     | C.Cast (s1, t1), C.Cast (s2, t2)
954     | C.Prod (_, s1, t1), C.Prod (_, s2, t2)
955     | C.Lambda (_, s1, t1), C.Lambda (_, s2, t2) ->
956         let table = aux table s1 s2 in
957         aux table t1 t2
958     | C.LetIn (_, s1, ty1, t1), C.LetIn (_, s2, ty2, t2) ->
959         let table = aux table s1 s2 in
960         let table = aux table ty1 ty2 in
961         aux table t1 t2
962     | C.Appl l1, C.Appl l2 -> (
963         try List.fold_left2 (fun res t1 t2 -> (aux res t1 t2)) table l1 l2
964         with Invalid_argument _ -> raise NotMetaConvertible
965       )
966     | C.MutInd (u1, i1, ens1), C.MutInd (u2, i2, ens2)
967         when (UriManager.eq u1 u2) && i1 = i2 -> aux_ens table ens1 ens2
968     | C.MutConstruct (u1, i1, j1, ens1), C.MutConstruct (u2, i2, j2, ens2)
969         when (UriManager.eq u1 u2) && i1 = i2 && j1 = j2 ->
970         aux_ens table ens1 ens2
971     | C.MutCase (u1, i1, s1, t1, l1), C.MutCase (u2, i2, s2, t2, l2)
972         when (UriManager.eq u1 u2) && i1 = i2 ->
973         let table = aux table s1 s2 in
974         let table = aux table t1 t2 in (
975           try List.fold_left2 (fun res t1 t2 -> (aux res t1 t2)) table l1 l2
976           with Invalid_argument _ -> raise NotMetaConvertible
977         )
978     | C.Fix (i1, il1), C.Fix (i2, il2) when i1 = i2 -> (
979         try
980           List.fold_left2
981             (fun res (n1, i1, s1, t1) (n2, i2, s2, t2) ->
982                if i1 <> i2 then raise NotMetaConvertible
983                else
984                  let res = (aux res s1 s2) in aux res t1 t2)
985             table il1 il2
986         with Invalid_argument _ -> raise NotMetaConvertible
987       )
988     | C.CoFix (i1, il1), C.CoFix (i2, il2) when i1 = i2 -> (
989         try
990           List.fold_left2
991             (fun res (n1, s1, t1) (n2, s2, t2) ->
992                let res = aux res s1 s2 in aux res t1 t2)
993             table il1 il2
994         with Invalid_argument _ -> raise NotMetaConvertible
995       )
996     | t1, t2 when t1 = t2 -> table
997     | _, _ -> raise NotMetaConvertible
998         
999   and aux_ens table ens1 ens2 =
1000     let cmp (u1, t1) (u2, t2) =
1001       Pervasives.compare (UriManager.string_of_uri u1) (UriManager.string_of_uri u2)
1002     in
1003     let ens1 = List.sort cmp ens1
1004     and ens2 = List.sort cmp ens2 in
1005     try
1006       List.fold_left2
1007         (fun res (u1, t1) (u2, t2) ->
1008            if not (UriManager.eq u1 u2) then raise NotMetaConvertible
1009            else aux res t1 t2)
1010         table ens1 ens2
1011     with Invalid_argument _ -> raise NotMetaConvertible
1012   in
1013   aux table t1 t2
1014 ;;
1015
1016
1017 let meta_convertibility_eq eq1 eq2 =
1018   let _, _, (ty, left, right, _), _,_ = open_equality eq1 in
1019   let _, _, (ty', left', right', _), _,_ = open_equality eq2 in
1020   if ty <> ty' then
1021     false
1022   else if (left = left') && (right = right') then
1023     true
1024   else if (left = right') && (right = left') then
1025     true
1026   else
1027     try
1028       let table = meta_convertibility_aux ([],[]) left left' in
1029       let _ = meta_convertibility_aux table right right' in
1030       true
1031     with NotMetaConvertible ->
1032       try
1033         let table = meta_convertibility_aux ([],[]) left right' in
1034         let _ = meta_convertibility_aux table right left' in
1035         true
1036       with NotMetaConvertible ->
1037         false
1038 ;;
1039
1040 let meta_convertibility t1 t2 =
1041   if t1 = t2 then
1042     true
1043   else
1044     try
1045       ignore(meta_convertibility_aux ([],[]) t1 t2);
1046       true
1047     with NotMetaConvertible ->
1048       false
1049 ;;
1050
1051 let meta_convertibility_subst t1 t2 menv =
1052   if t1 = t2 then
1053     Some([])
1054   else
1055     try
1056       let (l,_) = meta_convertibility_aux ([],[]) t1 t2 in
1057       let subst =
1058         List.map
1059           (fun (x,y) ->
1060              try 
1061                let (_,c,t) = CicUtil.lookup_meta x menv in
1062                let irl = 
1063                  CicMkImplicit.identity_relocation_list_for_metavariable c in
1064                (y,(c,Cic.Meta(x,irl),t))
1065              with CicUtil.Meta_not_found _ ->
1066                try 
1067                  let (_,c,t) = CicUtil.lookup_meta y menv in
1068                  let irl =  
1069                    CicMkImplicit.identity_relocation_list_for_metavariable c in
1070                    (x,(c,Cic.Meta(y,irl),t))
1071                with CicUtil.Meta_not_found _ -> assert false) l in   
1072         Some subst
1073     with NotMetaConvertible ->
1074       None
1075 ;;
1076
1077 exception TermIsNotAnEquality;;
1078
1079 let term_is_equality term =
1080   match term with
1081   | Cic.Appl [Cic.MutInd (uri, _, _); _; _; _] 
1082     when LibraryObjects.is_eq_URI uri -> true
1083   | _ -> false
1084 ;;
1085
1086 let equality_of_term bag proof term =
1087   match term with
1088   | Cic.Appl [Cic.MutInd (uri, _, _); ty; t1; t2] 
1089     when LibraryObjects.is_eq_URI uri ->
1090       let o = !Utils.compare_terms t1 t2 in
1091       let stat = (ty,t1,t2,o) in
1092       let w = Utils.compute_equality_weight stat in
1093       let e = mk_equality bag (w, Exact proof, stat,[]) in
1094       e
1095   | _ ->
1096       raise TermIsNotAnEquality
1097 ;;
1098
1099 let is_weak_identity eq = 
1100   let _,_,(_,left, right,_),_,_ = open_equality eq in
1101    left = right 
1102    (* doing metaconv here is meaningless *)
1103 ;;
1104
1105 let is_identity (_, context, ugraph) eq = 
1106   let _,_,(ty,left,right,_),menv,_ = open_equality eq in
1107   (* doing metaconv here is meaningless *)
1108   left = right
1109 (*   fst (CicReduction.are_convertible ~metasenv:menv context left right ugraph)
1110  *   *)
1111 ;;
1112
1113
1114 let term_of_equality eq_uri equality =
1115   let _, _, (ty, left, right, _), menv, _= open_equality equality in
1116   let eq i = function Cic.Meta (j, _) -> i = j | _ -> false in
1117   let argsno = List.length menv in
1118   let t =
1119     CicSubstitution.lift argsno
1120       (Cic.Appl [Cic.MutInd (eq_uri, 0, []); ty; left; right])
1121   in
1122   snd (
1123     List.fold_right
1124       (fun (i,_,ty) (n, t) ->
1125          let name = Cic.Name ("X" ^ (string_of_int n)) in
1126          let ty = CicSubstitution.lift (n-1) ty in
1127          let t = 
1128            ProofEngineReduction.replace
1129              ~equality:eq ~what:[i]
1130              ~with_what:[Cic.Rel (argsno - (n - 1))] ~where:t
1131          in
1132            (n-1, Cic.Prod (name, ty, t)))
1133       menv (argsno, t))
1134 ;;
1135
1136 let symmetric bag eq_ty l id uri m =
1137   let eq = Cic.MutInd(uri,0,[]) in
1138   let pred = 
1139     Cic.Lambda (Cic.Name "Sym",eq_ty,
1140      Cic.Appl [CicSubstitution.lift 1 eq ;
1141                CicSubstitution.lift 1 eq_ty;
1142                Cic.Rel 1;CicSubstitution.lift 1 l]) 
1143   in
1144   let prefl = 
1145     Exact (Cic.Appl
1146       [Cic.MutConstruct(uri,0,1,[]);eq_ty;l]) 
1147   in
1148   let id1 = 
1149     let eq = mk_equality bag (0,prefl,(eq_ty,l,l,Utils.Eq),m) in
1150     let (_,_,_,_,id) = open_equality eq in
1151     id
1152   in
1153   Step(Subst.empty_subst,
1154     (Demodulation,id1,(Utils.Left,id),pred))
1155 ;;
1156
1157 module IntOT = struct
1158   type t = int
1159   let compare = Pervasives.compare
1160 end
1161
1162 module IntSet = Set.Make(IntOT);;
1163
1164 let n_purged = ref 0;;
1165
1166 let collect ((id_to_eq,_) as bag) alive1 alive2 alive3 =
1167 (*   let _ = <:start<collect>> in *)
1168   let deps_of id = 
1169     let p,_,_ = proof_of_id bag id in  
1170     match p with
1171     | Exact _ -> IntSet.empty
1172     | Step (_,(_,id1,(_,id2),_)) ->
1173           IntSet.add id1 (IntSet.add id2 IntSet.empty)
1174   in
1175   let rec close s = 
1176     let news = IntSet.fold (fun id s -> IntSet.union (deps_of id) s) s s in
1177     if IntSet.equal news s then s else close news
1178   in
1179   let l_to_s s l = List.fold_left (fun s x -> IntSet.add x s) s l in
1180   let alive_set = l_to_s (l_to_s (l_to_s IntSet.empty alive2) alive1) alive3 in
1181   let closed_alive_set = close alive_set in
1182   let to_purge = 
1183     Hashtbl.fold 
1184       (fun k _ s -> 
1185         if not (IntSet.mem k closed_alive_set) then
1186           k::s else s) id_to_eq []
1187   in
1188   n_purged := !n_purged + List.length to_purge;
1189   List.iter (Hashtbl.remove id_to_eq) to_purge;
1190 (*   let _ = <:stop<collect>> in ()   *)
1191 ;;
1192
1193 let id_of e = 
1194   let _,_,_,_,id = open_equality e in id
1195 ;;
1196
1197 let get_stats () = "" 
1198 (*
1199   <:show<Equality.>> ^ 
1200   "# of purged eq by the collector: " ^ string_of_int !n_purged ^ "\n"
1201 *)
1202 ;;
1203
1204 let rec pp_proofterm name t context = 
1205   let rec skip_lambda tys ctx = function
1206     | Cic.Lambda (n,s,t) -> skip_lambda (s::tys) ((Some n)::ctx) t
1207     | t -> ctx,tys,t
1208   in
1209   let rename s name = 
1210     match name with 
1211     | Cic.Name s1 -> Cic.Name (s ^ s1)
1212     | _ -> assert false
1213   in
1214   let rec skip_letin ctx = function
1215     | Cic.LetIn (n,b,_,t) -> 
1216         pp_proofterm (Some (rename "Lemma " n)) b ctx:: 
1217           skip_letin ((Some n)::ctx) t
1218     | t -> 
1219         let ppterm t = CicPp.pp t ctx in
1220         let rec pp inner = function
1221           | Cic.Appl [Cic.Const (uri,[]);_;l;m;r;p1;p2] 
1222               when Pcre.pmatch ~pat:"trans_eq" (UriManager.string_of_uri uri)->
1223                 if not inner then
1224                   ("     " ^ ppterm l) :: pp true p1 @ 
1225                             [ "   = " ^ ppterm m ] @ pp true p2 @ 
1226                             [ "   = " ^ ppterm r ]
1227                 else
1228                    pp true p1 @ 
1229                             [ "   = " ^ ppterm m ] @ pp true p2 
1230           | Cic.Appl [Cic.Const (uri,[]);_;l;m;p] 
1231               when Pcre.pmatch ~pat:"sym_eq" (UriManager.string_of_uri uri)->
1232                 pp true p
1233           | Cic.Appl [Cic.Const (uri,[]);_;_;_;_;_;p] 
1234               when Pcre.pmatch ~pat:"eq_f" (UriManager.string_of_uri uri)->
1235                 pp true p
1236           | Cic.Appl [Cic.Const (uri,[]);_;_;_;_;_;p] 
1237               when Pcre.pmatch ~pat:"eq_OF_eq" (UriManager.string_of_uri uri)->
1238                 pp true p
1239           | Cic.Appl [Cic.MutConstruct (uri,_,_,[]);_;_;t;p] 
1240               when Pcre.pmatch ~pat:"ex.ind" (UriManager.string_of_uri uri)->
1241                       [ "witness " ^ ppterm t ] @ pp true p
1242           | Cic.Appl (t::_) ->[ " [by " ^ ppterm t ^ "]"]
1243           | t ->[ " [by " ^ ppterm t ^ "]"]
1244         in
1245         let rec compat = function
1246           | a::b::tl -> (b ^ a) :: compat tl
1247           | h::[] -> [h]
1248           | [] -> []
1249         in
1250         let compat l = List.hd l :: compat (List.tl l) in
1251         compat (pp false t) @ ["";""]
1252   in      
1253   let names, tys, body = skip_lambda [] context t in
1254   let ppname name = (match name with Some (Cic.Name s) -> s | _ -> "") in
1255   ppname name ^ ":\n" ^
1256   (if context = [] then
1257      let rec pp_l ctx = function
1258           | (t,name)::tl -> 
1259               "   " ^ ppname name ^ ": " ^ CicPp.pp t ctx ^ "\n" ^ 
1260               pp_l (name::ctx) tl
1261           | [] -> "\n\n"
1262      in
1263        pp_l [] (List.rev (List.combine tys names))
1264    else "")
1265     ^
1266   String.concat "\n" (skip_letin names body)
1267 ;;
1268
1269 let pp_proofterm t = 
1270   "\n\n" ^ 
1271   pp_proofterm (Some (Cic.Name "Hypothesis")) t []
1272 ;;
1273
1274 let initial_nameset_list = [
1275  "x"; "y"; "z"; "t"; "u"; "v"; "a"; "b"; "c"; "d"; 
1276  "e"; "l"; "m"; "n"; "o"; "p"; "q"; "r"; 
1277 ]
1278
1279 module S = Set.Make(String)
1280
1281 let initial_nameset = List.fold_right S.add initial_nameset_list S.empty, [];;
1282
1283 let freshname (nameset, subst) term = 
1284   let m = CicUtil.metas_of_term term in
1285   let nameset, subst = 
1286     List.fold_left 
1287       (fun (set,rc) (m,_) -> 
1288         if List.mem_assoc m rc then set,rc else
1289         let name = S.choose set in
1290         let set = S.remove name set in
1291         set, 
1292         (m,Cic.Const(UriManager.uri_of_string 
1293              ("cic:/"^name^".con"),[]))::rc)
1294       (nameset,subst) m
1295   in
1296   let term = 
1297    ProofEngineReduction.replace
1298     ~equality:(fun i t -> match t with Cic.Meta (j,_) -> i=j| _ -> false) 
1299     ~what:(List.map fst subst) 
1300     ~with_what:(List.map snd subst) ~where:term
1301   in
1302   (nameset, subst), term
1303 ;;
1304
1305 let remove_names_in_context (set,subst) names =
1306   List.fold_left
1307     (fun s n -> 
1308       match n with Some (Cic.Name n) -> S.remove n s | _ -> s) 
1309     set names, subst
1310 ;;
1311
1312 let string_of_id2 (id_to_eq,_) names nameset id = 
1313   if id = 0 then "" else 
1314   try
1315     let (_,_,(_,l,r,_),_,_) = open_equality (Hashtbl.find id_to_eq id) in
1316     let nameset, l = freshname nameset l in
1317     let nameset, r = freshname nameset r in
1318     Printf.sprintf "%s = %s" (CicPp.pp l names) (CicPp.pp r names)
1319   with
1320       Not_found -> assert false
1321 ;;
1322
1323 let draw_proof bag names goal_proof proof id =
1324   let b = Buffer.create 100 in
1325   let fmt = Format.formatter_of_buffer b in 
1326   let sint = string_of_int in
1327   let fst3 (x,_,_) = x in
1328   let visited = ref [] in
1329   let nameset = remove_names_in_context initial_nameset names in
1330   let rec fact id = function
1331     | Exact t -> 
1332         if not (List.mem id !visited) then
1333           begin
1334           visited := id :: !visited;
1335           let nameset, t = freshname nameset t in
1336           let t = CicPp.pp t names in
1337           GraphvizPp.Dot.node (sint id) 
1338           ~attrs:["label",t^":"^string_of_id2 bag names nameset id;
1339           "shape","rectangle"] fmt;
1340           end
1341     | Step (_,(_,id1,(_,id2),_)) ->
1342         GraphvizPp.Dot.edge (sint id) (sint id1) fmt;
1343         GraphvizPp.Dot.edge (sint id) (sint id2) fmt;
1344         let p1,_,_ = proof_of_id bag id1 in
1345         let p2,_,_ = proof_of_id bag id2 in
1346         fact id1 p1;
1347         fact id2 p2;
1348         if not (List.mem id !visited); then
1349           begin
1350           visited := id :: !visited;
1351           GraphvizPp.Dot.node (sint id) 
1352           ~attrs:["label",sint id^":"^string_of_id2 bag names nameset id;
1353                   "shape","ellipse"] fmt
1354           end
1355   in
1356   let sleft acc (_,_,id,_,_) =
1357     if acc != 0 then GraphvizPp.Dot.edge (sint acc) (sint id) fmt;
1358     fact id (fst3 (proof_of_id bag id));
1359     id
1360   in
1361   GraphvizPp.Dot.header ~node_attrs:["fontsize","10"; ] fmt;
1362   ignore(List.fold_left sleft id goal_proof);
1363   GraphvizPp.Dot.trailer fmt;
1364   let oc = open_out "/tmp/matita_paramod.dot" in
1365   Buffer.output_buffer oc b;
1366   close_out oc;
1367   Utils.debug_print (lazy "dot!");
1368   ignore(Unix.system 
1369     "dot -Tps -o /tmp/matita_paramod.eps /tmp/matita_paramod.dot"
1370 (* "cat /tmp/matita_paramod.dot| tred | dot -Tps -o /tmp/matita_paramod.eps" *)
1371   );
1372   ignore(Unix.system "gv /tmp/matita_paramod.eps");
1373 ;;
1374