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