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