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