]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/paramodulation/equality.ml
4414d2f435f3af14a1d8cc1d32c131bd0b241db7
[helm.git] / components / tactics / paramodulation / equality.ml
1 (* cOpyright (C) 2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 let _profiler = <:profiler<_profiler>>;;
27
28 (* $Id: inference.ml 6245 2006-04-05 12:07:51Z tassi $ *)
29
30 type rule = SuperpositionRight | SuperpositionLeft | Demodulation
31 type uncomparable = int -> int 
32 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 let head_of_apply = function | Cic.Appl (hd::_) -> hd | t -> t;;
241 let tail_of_apply = function | Cic.Appl (_::tl) -> tl | t -> [];;
242 let count_args t = List.length (tail_of_apply t);;
243 let rec build_nat = 
244   let u = UriManager.uri_of_string "cic:/matita/nat/nat/nat.ind" in
245   function
246     | 0 -> Cic.MutConstruct(u,0,1,[])
247     | n -> 
248         Cic.Appl [Cic.MutConstruct(u,0,2,[]);build_nat (n-1)]
249 ;;
250 let tyof context menv t =
251   try
252     fst(CicTypeChecker.type_of_aux' menv context t CicUniv.empty_ugraph)
253   with
254   | CicTypeChecker.TypeCheckerFailure _
255   | CicTypeChecker.AssertFailure _ -> assert false
256 ;;
257 let rec lambdaof left context = function
258   | Cic.Prod (n,s,t) ->
259       Cic.Lambda (n,s,lambdaof left context t)
260   | Cic.Appl [Cic.MutInd (uri, 0,_);ty;l;r] 
261       when LibraryObjects.is_eq_URI uri -> if left then l else r
262   | t -> 
263       let names = Utils.names_of_context context in
264       prerr_endline ("lambdaof: " ^ (CicPp.pp t names));
265       assert false
266 ;;
267
268 let canonical t context menv = 
269   let rec remove_refl t =
270     match t with
271     | Cic.Appl (((Cic.Const(uri_trans,ens))::tl) as args)
272           when LibraryObjects.is_trans_eq_URI uri_trans ->
273           let ty,l,m,r,p1,p2 = open_trans ens tl in
274             (match p1,p2 with
275               | Cic.Appl [Cic.MutConstruct (uri, 0, 1,_);_;_],p2 -> 
276                   remove_refl p2
277               | p1,Cic.Appl [Cic.MutConstruct (uri, 0, 1,_);_;_] -> 
278                   remove_refl p1
279               | _ -> Cic.Appl (List.map remove_refl args))
280     | Cic.Appl l -> Cic.Appl (List.map remove_refl l)
281     | Cic.LetIn (name,bo,rest) ->
282         Cic.LetIn (name,remove_refl bo,remove_refl rest)
283     | _ -> t
284   in
285   let rec canonical context t =
286     match t with
287       | Cic.LetIn(name,bo,rest) -> 
288           let context' = (Some (name,Cic.Def (bo,None)))::context in
289           Cic.LetIn(name,canonical context bo,canonical context' rest)
290       | Cic.Appl (((Cic.Const(uri_sym,ens))::tl) as args)
291           when LibraryObjects.is_sym_eq_URI uri_sym ->
292           (match p_of_sym ens tl with
293              | Cic.Appl ((Cic.Const(uri,ens))::tl)
294                  when LibraryObjects.is_sym_eq_URI uri -> 
295                    canonical context (p_of_sym ens tl)
296              | Cic.Appl ((Cic.Const(uri_trans,ens))::tl)
297                  when LibraryObjects.is_trans_eq_URI uri_trans ->
298                  let ty,l,m,r,p1,p2 = open_trans ens tl in
299                    mk_trans uri_trans ty r m l 
300                      (canonical context (mk_sym uri_sym ty m r p2)) 
301                      (canonical context (mk_sym uri_sym ty l m p1))
302              | Cic.Appl (([Cic.Const(uri_feq,ens);ty1;ty2;f;x;y;p])) ->
303                  
304                  let eq_f_sym = 
305                    Cic.Const (UriManager.uri_of_string
306                      "cic:/matita/logic/equality/eq_f1.con",[]) 
307                  in
308                  Cic.Appl (([eq_f_sym;ty1;ty2;f;x;y;p]))  
309
310 (*
311                  let sym_eq = Cic.Const(uri_sym,ens) in
312                  let eq_f = Cic.Const(uri_feq,[]) in
313                  let b = Cic.MutConstruct (UriManager.uri_of_string
314                    "cic:/matita/datatypes/bool/bool.ind",0,1,[])
315                  in
316                  let u = ty1 in
317                  let ctx = f in
318                  let n = build_nat (count_args p) in
319                  let h = head_of_apply p in
320                  let predl = lambdaof true context (tyof context menv h) in 
321                  let predr = lambdaof false context (tyof context menv h) in
322                  let args = tail_of_apply p in
323                  let appl = 
324                    Cic.Appl
325                     ([Cic.Const(UriManager.uri_of_string
326                       "cic:/matita/paramodulation/rewrite.con",[]);
327                       eq; sym_eq; eq_f; b; u; ctx; n; predl; predr; h] @
328                       args)
329                  in
330                  appl
331 *)
332 (*
333              | Cic.Appl (((Cic.Const(uri_ind,ens)) as he)::tl) 
334                  when LibraryObjects.is_eq_ind_URI uri_ind || 
335                       LibraryObjects.is_eq_ind_r_URI uri_ind ->
336                  let ty, what, pred, p1, other, p2 =
337                    match tl with
338                    | [ty;what;pred;p1;other;p2] -> ty, what, pred, p1, other, p2
339                    | _ -> assert false
340                  in
341                  let pred,l,r = 
342                    match pred with
343                    | Cic.Lambda (name,s,Cic.Appl [Cic.MutInd(uri,0,ens);ty;l;r])
344                        when LibraryObjects.is_eq_URI uri ->
345                          Cic.Lambda 
346                            (name,s,Cic.Appl [Cic.MutInd(uri,0,ens);ty;r;l]),l,r
347                    | _ -> 
348                        prerr_endline (CicPp.ppterm pred);
349                        assert false
350                  in
351                  let l = CicSubstitution.subst what l in
352                  let r = CicSubstitution.subst what r in
353                  Cic.Appl 
354                    [he;ty;what;pred;
355                     canonical (mk_sym uri_sym ty l r p1);other;canonical p2]
356 *)
357              | Cic.Appl [Cic.MutConstruct (uri, 0, 1,_);_;_] as t
358                  when LibraryObjects.is_eq_URI uri -> t
359              | _ -> Cic.Appl (List.map (canonical context) args))
360       | Cic.Appl l -> Cic.Appl (List.map (canonical context) l)
361       | _ -> t
362   in
363   remove_refl (canonical context t)
364 ;;
365   
366 let ty_of_lambda = function
367   | Cic.Lambda (_,ty,_) -> ty
368   | _ -> assert false 
369 ;;
370
371 let compose_contexts ctx1 ctx2 = 
372   ProofEngineReduction.replace_lifting 
373     ~equality:(=) ~what:[Cic.Implicit(Some `Hole)] ~with_what:[ctx2] ~where:ctx1
374 ;;
375
376 let put_in_ctx ctx t = 
377   ProofEngineReduction.replace_lifting
378     ~equality:(=) ~what:[Cic.Implicit (Some `Hole)] ~with_what:[t] ~where:ctx
379 ;;
380
381 let mk_eq uri ty l r =
382   Cic.Appl [Cic.MutInd(uri,0,[]);ty;l;r]
383 ;;
384
385 let mk_refl uri ty t = 
386   Cic.Appl [Cic.MutConstruct(uri,0,1,[]);ty;t]
387 ;;
388
389 let open_eq = function 
390   | Cic.Appl [Cic.MutInd(uri,0,[]);ty;l;r] when LibraryObjects.is_eq_URI uri ->
391       uri, ty, l ,r
392   | _ -> assert false
393 ;;
394
395 let mk_feq uri_feq ty ty1 left pred right t = 
396   Cic.Appl [Cic.Const(uri_feq,[]);ty;ty1;pred;left;right;t]
397 ;;
398
399 let contextualize uri ty left right t = 
400   let hole = Cic.Implicit (Some `Hole) in
401   (* aux [uri] [ty] [left] [right] [ctx] [t] 
402    * 
403    * the parameters validate this invariant  
404    *   t: eq(uri) ty left right
405    * that is used only by the base case
406    *
407    * ctx is a term with an hole. Cic.Implicit(Some `Hole) is the empty context
408    * ty_ctx is the type of ctx_d
409    *)
410     let rec aux uri ty left right ctx_d ctx_ty = function
411       | Cic.Appl ((Cic.Const(uri_sym,ens))::tl) 
412         when LibraryObjects.is_sym_eq_URI uri_sym  ->
413           let ty,l,r,p = open_sym ens tl in
414           mk_sym uri_sym ty l r (aux uri ty l r ctx_d ctx_ty p)
415       | Cic.LetIn (name,body,rest) ->
416           (* we should go in body *)
417           Cic.LetIn (name,body,aux uri ty left right ctx_d ctx_ty rest)
418       | Cic.Appl ((Cic.Const(uri_ind,ens))::tl)
419         when LibraryObjects.is_eq_ind_URI uri_ind || 
420              LibraryObjects.is_eq_ind_r_URI uri_ind ->
421           let ty1,what,pred,p1,other,p2 = open_eq_ind tl in
422           let ty2,eq,lp,rp = open_pred pred in 
423           let uri_trans = LibraryObjects.trans_eq_URI ~eq:uri in
424           let uri_sym = LibraryObjects.sym_eq_URI ~eq:uri in
425           let is_not_fixed_lp = is_not_fixed lp in
426           let avoid_eq_ind = LibraryObjects.is_eq_ind_URI uri_ind in
427           (* extract the context and the fixed term from the predicate *)
428           let m, ctx_c, ty2 = 
429             let m, ctx_c = if is_not_fixed_lp then rp,lp else lp,rp in
430             (* they were under a lambda *)
431             let m =  CicSubstitution.subst hole m in
432             let ctx_c = CicSubstitution.subst hole ctx_c in
433             let ty2 = CicSubstitution.subst hole ty2 in
434             m, ctx_c, ty2          
435           in
436           (* create the compound context and put the terms under it *)
437           let ctx_dc = compose_contexts ctx_d ctx_c in
438           let dc_what = put_in_ctx ctx_dc what in
439           let dc_other = put_in_ctx ctx_dc other in
440           (* m is already in ctx_c so it is put in ctx_d only *)
441           let d_m = put_in_ctx ctx_d m in
442           (* we also need what in ctx_c *)
443           let c_what = put_in_ctx ctx_c what in
444           (* now put the proofs in the compound context *)
445           let p1 = (* p1: dc_what = d_m *)
446             if is_not_fixed_lp then 
447               aux uri ty2 c_what m ctx_d ctx_ty p1 
448             else
449               mk_sym uri_sym ctx_ty d_m dc_what
450                 (aux uri ty2 m c_what ctx_d ctx_ty p1)
451           in
452           let p2 = (* p2: dc_other = dc_what *)
453             if avoid_eq_ind then
454               mk_sym uri_sym ctx_ty dc_what dc_other
455                 (aux uri ty1 what other ctx_dc ctx_ty p2)
456             else
457               aux uri ty1 other what ctx_dc ctx_ty p2
458           in
459           (* if pred = \x.C[x]=m --> t : C[other]=m --> trans other what m
460              if pred = \x.m=C[x] --> t : m=C[other] --> trans m what other *)
461           let a,b,c,paeqb,pbeqc =
462             if is_not_fixed_lp then
463               dc_other,dc_what,d_m,p2,p1
464             else
465               d_m,dc_what,dc_other,
466                 (mk_sym uri_sym ctx_ty dc_what d_m p1),
467                 (mk_sym uri_sym ctx_ty dc_other dc_what p2)
468           in
469           mk_trans uri_trans ctx_ty a b c paeqb pbeqc
470     | t when ctx_d = hole -> t 
471     | t -> 
472 (*         let uri_sym = LibraryObjects.sym_eq_URI ~eq:uri in *)
473 (*         let uri_ind = LibraryObjects.eq_ind_URI ~eq:uri in *)
474         let uri_feq = 
475           UriManager.uri_of_string "cic:/matita/logic/equality/eq_f.con"
476         in
477         let pred = 
478 (*           let r = CicSubstitution.lift 1 (put_in_ctx ctx_d left) in *)
479           let l = 
480             let ctx_d = CicSubstitution.lift 1 ctx_d in
481             put_in_ctx ctx_d (Cic.Rel 1)
482           in
483 (*           let lty = CicSubstitution.lift 1 ctx_ty in  *)
484 (*           Cic.Lambda (Cic.Name "foo",ty,(mk_eq uri lty l r)) *)
485           Cic.Lambda (Cic.Name "foo",ty,l)
486         in
487 (*         let d_left = put_in_ctx ctx_d left in *)
488 (*         let d_right = put_in_ctx ctx_d right in *)
489 (*         let refl_eq = mk_refl uri ctx_ty d_left in *)
490 (*         mk_sym uri_sym ctx_ty d_right d_left *)
491 (*           (mk_eq_ind uri_ind ty left pred refl_eq right t) *)
492           (mk_feq uri_feq ty ctx_ty left pred right t)
493   in
494   aux uri ty left right hole ty t
495 ;;
496
497 let contextualize_rewrites t ty = 
498   let eq,ty,l,r = open_eq ty in
499   contextualize eq ty l r t
500 ;;
501
502 let add_subst subst =
503   function
504     | Exact t -> Exact (Subst.apply_subst subst t)
505     | Step (s,(rule, id1, (pos,id2), pred)) -> 
506         Step (Subst.concat subst s,(rule, id1, (pos,id2), pred))
507 ;;
508         
509 let build_proof_step eq lift subst p1 p2 pos l r pred =
510   let p1 = Subst.apply_subst_lift lift subst p1 in
511   let p2 = Subst.apply_subst_lift lift subst p2 in
512   let l  = CicSubstitution.lift lift l in
513   let l = Subst.apply_subst_lift lift subst l in
514   let r  = CicSubstitution.lift lift r in
515   let r = Subst.apply_subst_lift lift subst r in
516   let pred = CicSubstitution.lift lift pred in
517   let pred = Subst.apply_subst_lift lift subst pred in
518   let ty,body = 
519     match pred with
520       | Cic.Lambda (_,ty,body) -> ty,body 
521       | _ -> assert false
522   in
523   let what, other = 
524     if pos = Utils.Left then l,r else r,l
525   in
526   let p =
527     match pos with
528       | Utils.Left ->
529         mk_eq_ind (LibraryObjects.eq_ind_URI ~eq) ty what pred p1 other p2
530       | Utils.Right ->
531         mk_eq_ind (LibraryObjects.eq_ind_r_URI ~eq) ty what pred p1 other p2
532   in
533     p
534 ;;
535
536 let parametrize_proof p l r ty = 
537   let uniq l = HExtlib.list_uniq (List.sort Pervasives.compare l) in
538   let mot = CicUtil.metas_of_term_set in
539   let parameters = uniq (mot p @ mot l @ mot r) in 
540   (* ?if they are under a lambda? *)
541   let parameters = 
542     HExtlib.list_uniq (List.sort Pervasives.compare parameters) 
543   in
544   let what = List.map (fun (i,l) -> Cic.Meta (i,l)) parameters in 
545   let with_what, lift_no = 
546     List.fold_right (fun _ (acc,n) -> ((Cic.Rel n)::acc),n+1) what ([],1) 
547   in
548   let p = CicSubstitution.lift (lift_no-1) p in
549   let p = 
550     ProofEngineReduction.replace_lifting
551     ~equality:(fun t1 t2 -> 
552       match t1,t2 with Cic.Meta (i,_),Cic.Meta(j,_) -> i=j | _ -> false) 
553     ~what ~with_what ~where:p
554   in
555   let ty_of_m _ = ty (*function 
556     | Cic.Meta (i,_) -> List.assoc i menv 
557     | _ -> assert false *)
558   in
559   let args, proof,_ = 
560     List.fold_left 
561       (fun (instance,p,n) m -> 
562         (instance@[m],
563         Cic.Lambda 
564           (Cic.Name ("x"^string_of_int n),
565           CicSubstitution.lift (lift_no - n - 1) (ty_of_m m),
566           p),
567         n+1)) 
568       ([Cic.Rel 1],p,1) 
569       what
570   in
571   let instance = match args with | [x] -> x | _ -> Cic.Appl args in
572   proof, instance
573 ;;
574
575 let wfo goalproof proof id =
576   let rec aux acc id =
577     let p,_,_ = proof_of_id id in
578     match p with
579     | Exact _ -> if (List.mem id acc) then acc else id :: acc
580     | Step (_,(_,id1, (_,id2), _)) -> 
581         let acc = if not (List.mem id1 acc) then aux acc id1 else acc in
582         let acc = if not (List.mem id2 acc) then aux acc id2 else acc in
583         id :: acc
584   in
585   let acc = 
586     match proof with
587       | Exact _ -> [id]
588       | Step (_,(_,id1, (_,id2), _)) -> aux (aux [id] id1) id2
589   in 
590   List.fold_left (fun acc (_,_,id,_,_) -> aux acc id) acc goalproof
591 ;;
592
593 let string_of_id names id = 
594   if id = 0 then "" else 
595   try
596     let (_,p,(_,l,r,_),m,_) = open_equality (Hashtbl.find id_to_eq id) in
597     match p with
598     | Exact t -> 
599         Printf.sprintf "%d = %s: %s = %s [%s]" id
600           (CicPp.pp t names) (CicPp.pp l names) (CicPp.pp r names)
601         (String.concat ", " (List.map (fun (i,_,_) -> string_of_int i) m))
602     | Step (_,(step,id1, (_,id2), _) ) ->
603         Printf.sprintf "%6d: %s %6d %6d   %s = %s [%s]" id
604           (string_of_rule step)
605           id1 id2 (CicPp.pp l names) (CicPp.pp r names)
606         (String.concat ", " (List.map (fun (i,_,_) -> string_of_int i) m))
607   with
608       Not_found -> assert false
609
610 let pp_proof names goalproof proof subst id initial_goal =
611   String.concat "\n" (List.map (string_of_id names) (wfo goalproof proof id)) ^ 
612   "\ngoal:\n   " ^ 
613     (String.concat "\n   " 
614       (fst (List.fold_right
615         (fun (r,pos,i,s,pred) (acc,g) -> 
616           let _,_,left,right = open_eq g in
617           let ty = 
618             match pos with 
619             | Utils.Left -> CicReduction.head_beta_reduce (Cic.Appl[pred;right])
620             | Utils.Right -> CicReduction.head_beta_reduce (Cic.Appl[pred;left])
621           in
622           let ty = Subst.apply_subst s ty in
623           ("("^ string_of_rule r ^ " " ^ string_of_int i^") -> "
624           ^ CicPp.pp ty names) :: acc,ty) goalproof ([],initial_goal)))) ^
625   "\nand then subsumed by " ^ string_of_int id ^ " when " ^ Subst.ppsubst subst
626 ;;
627
628 module OT = 
629   struct
630     type t = int
631     let compare = Pervasives.compare
632   end
633
634 module M = Map.Make(OT)
635
636 let rec find_deps m i = 
637   if M.mem i m then m
638   else 
639     let p,_,_ = proof_of_id i in
640     match p with
641     | Exact _ -> M.add i [] m
642     | Step (_,(_,id1,(_,id2),_)) -> 
643         let m = find_deps m id1 in
644         let m = find_deps m id2 in
645         (* without the uniq there is a stack overflow doing concatenation *)
646         let xxx = [id1;id2] @ M.find id1 m @ M.find id2 m in 
647         let xxx = HExtlib.list_uniq (List.sort Pervasives.compare xxx) in
648         M.add i xxx m
649 ;;
650
651 let topological_sort l = 
652   (* build the partial order relation *)
653   let m = List.fold_left (fun m i -> find_deps m i) M.empty l in
654   let m = (* keep only deps inside l *) 
655     List.fold_left 
656       (fun m' i ->
657         M.add i (List.filter (fun x -> List.mem x l) (M.find i m)) m') 
658       M.empty l 
659   in
660   let m = M.map (fun x -> Some x) m in
661   (* utils *)
662   let keys m = M.fold (fun i _ acc -> i::acc) m [] in
663   let split l m = List.filter (fun i -> M.find i m = Some []) l in
664   let purge l m = 
665     M.mapi 
666       (fun k v -> if List.mem k l then None else 
667          match v with
668          | None -> None
669          | Some ll -> Some (List.filter (fun i -> not (List.mem i l)) ll)) 
670       m
671   in
672   let rec aux m res = 
673       let keys = keys m in
674       let ok = split keys m in
675       let m = purge ok m in
676       let res = ok @ res in
677       if ok = [] then res else aux m res
678   in
679   let rc = List.rev (aux m []) in
680   rc
681 ;;
682   
683
684 (* returns the list of ids that should be factorized *)
685 let get_duplicate_step_in_wfo l p =
686   let ol = List.rev l in
687   let h = Hashtbl.create 13 in
688   (* NOTE: here the n parameter is an approximation of the dependency 
689      between equations. To do things seriously we should maintain a 
690      dependency graph. This approximation is not perfect. *)
691   let add i = 
692     let p,_,_ = proof_of_id i in 
693     match p with 
694     | Exact _ -> true
695     | _ -> 
696         try 
697           let no = Hashtbl.find h i in
698           Hashtbl.replace h i (no+1);
699           false
700         with Not_found -> Hashtbl.add h i 1;true
701   in
702   let rec aux = function
703     | Exact _ -> ()
704     | Step (_,(_,i1,(_,i2),_)) -> 
705         let go_on_1 = add i1 in
706         let go_on_2 = add i2 in
707         if go_on_1 then aux (let p,_,_ = proof_of_id i1 in p);
708         if go_on_2 then aux (let p,_,_ = proof_of_id i2 in p)
709   in
710   aux p;
711   List.iter
712     (fun (_,_,id,_,_) -> aux (let p,_,_ = proof_of_id id in p))
713     ol;
714   (* now h is complete *)
715   let proofs = Hashtbl.fold (fun k count acc-> (k,count)::acc) h [] in
716   let proofs = List.filter (fun (_,c) -> c > 1) proofs in
717   let res = topological_sort (List.map (fun (i,_) -> i) proofs) in
718   res
719 ;;
720
721 let build_proof_term eq h lift proof =
722   let proof_of_id aux id =
723     let p,l,r = proof_of_id id in
724     try List.assoc id h,l,r with Not_found -> aux p, l, r
725   in
726   let rec aux = function
727      | Exact term -> 
728          CicSubstitution.lift lift term
729      | Step (subst,(rule, id1, (pos,id2), pred)) ->
730          let p1,_,_ = proof_of_id aux id1 in
731          let p2,l,r = proof_of_id aux id2 in
732          let varname = 
733            match rule with
734            | SuperpositionRight -> Cic.Name ("SupR" ^ Utils.string_of_pos pos) 
735            | Demodulation -> Cic.Name ("DemEq"^ Utils.string_of_pos pos)
736            | _ -> assert false
737          in
738          let pred = 
739            match pred with
740            | Cic.Lambda (_,a,b) -> Cic.Lambda (varname,a,b)
741            | _ -> assert false
742          in
743          let p = build_proof_step eq lift subst p1 p2 pos l r pred in
744 (*         let cond =  (not (List.mem 302 (Utils.metas_of_term p)) || id1 = 8 || id1 = 132) in
745            if not cond then
746              prerr_endline ("ERROR " ^ string_of_int id1 ^ " " ^ string_of_int id2);
747            assert cond;*)
748            p
749   in
750    aux proof
751 ;;
752
753 let build_goal_proof eq l initial ty se context menv =
754   let se = List.map (fun i -> Cic.Meta (i,[])) se in 
755   let lets = get_duplicate_step_in_wfo l initial in
756   let letsno = List.length lets in
757   let _,mty,_,_ = open_eq ty in
758   let lift_list l = List.map (fun (i,t) -> i,CicSubstitution.lift 1 t) l in
759   let lets,_,h = 
760     List.fold_left
761       (fun (acc,n,h) id -> 
762         let p,l,r = proof_of_id id in
763         let cic = build_proof_term eq h n p in
764         let real_cic,instance = 
765           parametrize_proof cic l r (CicSubstitution.lift n mty)
766         in
767         let h = (id, instance)::lift_list h in
768         acc@[id,real_cic],n+1,h) 
769       ([],0,[]) lets
770   in
771   let proof,se = 
772     let rec aux se current_proof = function
773       | [] -> current_proof,se
774       | (rule,pos,id,subst,pred)::tl ->
775           let p,l,r = proof_of_id id in
776            let p = build_proof_term eq h letsno p in
777            let pos = if pos = Utils.Left then Utils.Right else Utils.Left in
778          let varname = 
779            match rule with
780            | SuperpositionLeft -> Cic.Name ("SupL" ^ Utils.string_of_pos pos) 
781            | Demodulation -> Cic.Name ("DemG"^ Utils.string_of_pos pos)
782            | _ -> assert false
783          in
784          let pred = 
785            match pred with
786            | Cic.Lambda (_,a,b) -> Cic.Lambda (varname,a,b)
787            | _ -> assert false
788          in
789            let proof = 
790              build_proof_step eq letsno subst current_proof p pos l r pred
791            in
792            let proof,se = aux se proof tl in
793            Subst.apply_subst_lift letsno subst proof,
794            List.map (fun x -> Subst.apply_subst_lift letsno subst x) se
795     in
796     aux se (build_proof_term eq h letsno initial) l
797   in
798   let n,proof = 
799     let initial = proof in
800     List.fold_right
801       (fun (id,cic) (n,p) -> 
802         n-1,
803         Cic.LetIn (
804           Cic.Name ("H"^string_of_int id),
805           cic, p))
806     lets (letsno-1,initial)
807   in
808    canonical 
809      (contextualize_rewrites proof (CicSubstitution.lift letsno ty))
810      context menv,
811    se 
812 ;;
813
814 let refl_proof eq_uri ty term = 
815   Cic.Appl [Cic.MutConstruct (eq_uri, 0, 1, []); ty; term]
816 ;;
817
818 let metas_of_proof p =
819   let eq = 
820     match LibraryObjects.eq_URI () with
821     | Some u -> u 
822     | None -> 
823         raise 
824           (ProofEngineTypes.Fail 
825             (lazy "No default equality defined when calling metas_of_proof"))
826   in
827   let p = build_proof_term eq [] 0 p in
828   Utils.metas_of_term p
829 ;;
830
831 let remove_local_context eq =
832    let w, p, (ty, left, right, o), menv,id = open_equality eq in
833    let p = Utils.remove_local_context p in
834    let ty = Utils.remove_local_context ty in
835    let left = Utils.remove_local_context left in
836    let right = Utils.remove_local_context right in
837    w, p, (ty, left, right, o), menv, id
838 ;;
839
840 let relocate newmeta menv to_be_relocated =
841   let subst, newmetasenv, newmeta = 
842     List.fold_right 
843       (fun i (subst, metasenv, maxmeta) ->         
844         let _,context,ty = CicUtil.lookup_meta i menv in
845         let irl = [] in
846         let newmeta = Cic.Meta(maxmeta,irl) in
847         let newsubst = Subst.buildsubst i context newmeta ty subst in
848         newsubst, (maxmeta,context,ty)::metasenv, maxmeta+1) 
849       to_be_relocated (Subst.empty_subst, [], newmeta+1)
850   in
851   let menv = Subst.apply_subst_metasenv subst menv @ newmetasenv in
852   subst, menv, newmeta
853
854 let fix_metas_goal newmeta goal =
855   let (proof, menv, ty) = goal in
856   let to_be_relocated = 
857     HExtlib.list_uniq (List.sort Pervasives.compare (Utils.metas_of_term ty))
858   in
859   let subst, menv, newmeta = relocate newmeta menv to_be_relocated in
860   let ty = Subst.apply_subst subst ty in
861   let proof = 
862     match proof with
863     | [] -> assert false (* is a nonsense to relocate the initial goal *)
864     | (r,pos,id,s,p) :: tl -> (r,pos,id,Subst.concat subst s,p) :: tl
865   in
866   newmeta+1,(proof, menv, ty)
867 ;;
868
869 let fix_metas newmeta eq = 
870   let w, p, (ty, left, right, o), menv,_ = open_equality eq in
871   let to_be_relocated = 
872 (* List.map (fun i ,_,_ -> i) menv *)
873     HExtlib.list_uniq 
874       (List.sort Pervasives.compare 
875          (Utils.metas_of_term left @ Utils.metas_of_term right)) 
876   in
877   let subst, metasenv, newmeta = relocate newmeta menv to_be_relocated in
878   let ty = Subst.apply_subst subst ty in
879   let left = Subst.apply_subst subst left in
880   let right = Subst.apply_subst subst right in
881   let fix_proof = function
882     | Exact p -> Exact (Subst.apply_subst subst p)
883     | Step (s,(r,id1,(pos,id2),pred)) -> 
884         Step (Subst.concat s subst,(r,id1,(pos,id2), pred))
885   in
886   let p = fix_proof p in
887   let eq' = mk_equality (w, p, (ty, left, right, o), metasenv) in
888   newmeta+1, eq'  
889
890 exception NotMetaConvertible;;
891
892 let meta_convertibility_aux table t1 t2 =
893   let module C = Cic in
894   let rec aux ((table_l, table_r) as table) t1 t2 =
895     match t1, t2 with
896     | C.Meta (m1, tl1), C.Meta (m2, tl2) ->
897         let tl1, tl2 = [],[] in
898         let m1_binding, table_l =
899           try List.assoc m1 table_l, table_l
900           with Not_found -> m2, (m1, m2)::table_l
901         and m2_binding, table_r =
902           try List.assoc m2 table_r, table_r
903           with Not_found -> m1, (m2, m1)::table_r
904         in
905         if (m1_binding <> m2) || (m2_binding <> m1) then
906           raise NotMetaConvertible
907         else (
908           try
909             List.fold_left2
910               (fun res t1 t2 ->
911                  match t1, t2 with
912                  | None, Some _ | Some _, None -> raise NotMetaConvertible
913                  | None, None -> res
914                  | Some t1, Some t2 -> (aux res t1 t2))
915               (table_l, table_r) tl1 tl2
916           with Invalid_argument _ ->
917             raise NotMetaConvertible
918         )
919     | C.Var (u1, ens1), C.Var (u2, ens2)
920     | C.Const (u1, ens1), C.Const (u2, ens2) when (UriManager.eq u1 u2) ->
921         aux_ens table ens1 ens2
922     | C.Cast (s1, t1), C.Cast (s2, t2)
923     | C.Prod (_, s1, t1), C.Prod (_, s2, t2)
924     | C.Lambda (_, s1, t1), C.Lambda (_, s2, t2)
925     | C.LetIn (_, s1, t1), C.LetIn (_, s2, t2) ->
926         let table = aux table s1 s2 in
927         aux table t1 t2
928     | C.Appl l1, C.Appl l2 -> (
929         try List.fold_left2 (fun res t1 t2 -> (aux res t1 t2)) table l1 l2
930         with Invalid_argument _ -> raise NotMetaConvertible
931       )
932     | C.MutInd (u1, i1, ens1), C.MutInd (u2, i2, ens2)
933         when (UriManager.eq u1 u2) && i1 = i2 -> aux_ens table ens1 ens2
934     | C.MutConstruct (u1, i1, j1, ens1), C.MutConstruct (u2, i2, j2, ens2)
935         when (UriManager.eq u1 u2) && i1 = i2 && j1 = j2 ->
936         aux_ens table ens1 ens2
937     | C.MutCase (u1, i1, s1, t1, l1), C.MutCase (u2, i2, s2, t2, l2)
938         when (UriManager.eq u1 u2) && i1 = i2 ->
939         let table = aux table s1 s2 in
940         let table = aux table t1 t2 in (
941           try List.fold_left2 (fun res t1 t2 -> (aux res t1 t2)) table l1 l2
942           with Invalid_argument _ -> raise NotMetaConvertible
943         )
944     | C.Fix (i1, il1), C.Fix (i2, il2) when i1 = i2 -> (
945         try
946           List.fold_left2
947             (fun res (n1, i1, s1, t1) (n2, i2, s2, t2) ->
948                if i1 <> i2 then raise NotMetaConvertible
949                else
950                  let res = (aux res s1 s2) in aux res t1 t2)
951             table il1 il2
952         with Invalid_argument _ -> raise NotMetaConvertible
953       )
954     | C.CoFix (i1, il1), C.CoFix (i2, il2) when i1 = i2 -> (
955         try
956           List.fold_left2
957             (fun res (n1, s1, t1) (n2, s2, t2) ->
958                let res = aux res s1 s2 in aux res t1 t2)
959             table il1 il2
960         with Invalid_argument _ -> raise NotMetaConvertible
961       )
962     | t1, t2 when t1 = t2 -> table
963     | _, _ -> raise NotMetaConvertible
964         
965   and aux_ens table ens1 ens2 =
966     let cmp (u1, t1) (u2, t2) =
967       Pervasives.compare (UriManager.string_of_uri u1) (UriManager.string_of_uri u2)
968     in
969     let ens1 = List.sort cmp ens1
970     and ens2 = List.sort cmp ens2 in
971     try
972       List.fold_left2
973         (fun res (u1, t1) (u2, t2) ->
974            if not (UriManager.eq u1 u2) then raise NotMetaConvertible
975            else aux res t1 t2)
976         table ens1 ens2
977     with Invalid_argument _ -> raise NotMetaConvertible
978   in
979   aux table t1 t2
980 ;;
981
982
983 let meta_convertibility_eq eq1 eq2 =
984   let _, _, (ty, left, right, _), _,_ = open_equality eq1 in
985   let _, _, (ty', left', right', _), _,_ = open_equality eq2 in
986   if ty <> ty' then
987     false
988   else if (left = left') && (right = right') then
989     true
990   else if (left = right') && (right = left') then
991     true
992   else
993     try
994       let table = meta_convertibility_aux ([], []) left left' in
995       let _ = meta_convertibility_aux table right right' in
996       true
997     with NotMetaConvertible ->
998       try
999         let table = meta_convertibility_aux ([], []) left right' in
1000         let _ = meta_convertibility_aux table right left' in
1001         true
1002       with NotMetaConvertible ->
1003         false
1004 ;;
1005
1006
1007 let meta_convertibility t1 t2 =
1008   if t1 = t2 then
1009     true
1010   else
1011     try
1012       ignore(meta_convertibility_aux ([], []) t1 t2);
1013       true
1014     with NotMetaConvertible ->
1015       false
1016 ;;
1017
1018 exception TermIsNotAnEquality;;
1019
1020 let term_is_equality term =
1021   match term with
1022   | Cic.Appl [Cic.MutInd (uri, _, _); _; _; _] 
1023     when LibraryObjects.is_eq_URI uri -> true
1024   | _ -> false
1025 ;;
1026
1027 let equality_of_term proof term =
1028   match term with
1029   | Cic.Appl [Cic.MutInd (uri, _, _); ty; t1; t2] 
1030     when LibraryObjects.is_eq_URI uri ->
1031       let o = !Utils.compare_terms t1 t2 in
1032       let stat = (ty,t1,t2,o) in
1033       let w = Utils.compute_equality_weight stat in
1034       let e = mk_equality (w, Exact proof, stat,[]) in
1035       e
1036   | _ ->
1037       raise TermIsNotAnEquality
1038 ;;
1039
1040 let is_weak_identity eq = 
1041   let _,_,(_,left, right,_),_,_ = open_equality eq in
1042   left = right || meta_convertibility left right 
1043 ;;
1044
1045 let is_identity (_, context, ugraph) eq = 
1046   let _,_,(ty,left,right,_),menv,_ = open_equality eq in
1047   left = right ||
1048   (* (meta_convertibility left right)) *)
1049   fst (CicReduction.are_convertible ~metasenv:menv context left right ugraph)
1050 ;;
1051
1052
1053 let term_of_equality eq_uri equality =
1054   let _, _, (ty, left, right, _), menv, _= open_equality equality in
1055   let eq i = function Cic.Meta (j, _) -> i = j | _ -> false in
1056   let argsno = List.length menv in
1057   let t =
1058     CicSubstitution.lift argsno
1059       (Cic.Appl [Cic.MutInd (eq_uri, 0, []); ty; left; right])
1060   in
1061   snd (
1062     List.fold_right
1063       (fun (i,_,ty) (n, t) ->
1064          let name = Cic.Name ("X" ^ (string_of_int n)) in
1065          let ty = CicSubstitution.lift (n-1) ty in
1066          let t = 
1067            ProofEngineReduction.replace
1068              ~equality:eq ~what:[i]
1069              ~with_what:[Cic.Rel (argsno - (n - 1))] ~where:t
1070          in
1071            (n-1, Cic.Prod (name, ty, t)))
1072       menv (argsno, t))
1073 ;;
1074
1075 let symmetric eq_ty l id uri m =
1076   let eq = Cic.MutInd(uri,0,[]) in
1077   let pred = 
1078     Cic.Lambda (Cic.Name "Sym",eq_ty,
1079      Cic.Appl [CicSubstitution.lift 1 eq ;
1080                CicSubstitution.lift 1 eq_ty;
1081                Cic.Rel 1;CicSubstitution.lift 1 l]) 
1082   in
1083   let prefl = 
1084     Exact (Cic.Appl
1085       [Cic.MutConstruct(uri,0,1,[]);eq_ty;l]) 
1086   in
1087   let id1 = 
1088     let eq = mk_equality (0,prefl,(eq_ty,l,l,Utils.Eq),m) in
1089     let (_,_,_,_,id) = open_equality eq in
1090     id
1091   in
1092   Step(Subst.empty_subst,
1093     (Demodulation,id1,(Utils.Left,id),pred))
1094 ;;
1095
1096 module IntOT = struct
1097   type t = int
1098   let compare = Pervasives.compare
1099 end
1100
1101 module IntSet = Set.Make(IntOT);;
1102
1103 let n_purged = ref 0;;
1104
1105 let collect alive1 alive2 alive3 =
1106   let _ = <:start<collect>> in
1107   let deps_of id = 
1108     let p,_,_ = proof_of_id id in  
1109     match p with
1110     | Exact _ -> IntSet.empty
1111     | Step (_,(_,id1,(_,id2),_)) ->
1112           IntSet.add id1 (IntSet.add id2 IntSet.empty)
1113   in
1114   let rec close s = 
1115     let news = IntSet.fold (fun id s -> IntSet.union (deps_of id) s) s s in
1116     if IntSet.equal news s then s else close news
1117   in
1118   let l_to_s s l = List.fold_left (fun s x -> IntSet.add x s) s l in
1119   let alive_set = l_to_s (l_to_s (l_to_s IntSet.empty alive2) alive1) alive3 in
1120   let closed_alive_set = close alive_set in
1121   let to_purge = 
1122     Hashtbl.fold 
1123       (fun k _ s -> 
1124         if not (IntSet.mem k closed_alive_set) then
1125           k::s else s) id_to_eq []
1126   in
1127   n_purged := !n_purged + List.length to_purge;
1128   List.iter (Hashtbl.remove id_to_eq) to_purge;
1129   let _ = <:stop<collect>> in ()  
1130 ;;
1131
1132 let id_of e = 
1133   let _,_,_,_,id = open_equality e in id
1134 ;;
1135
1136 let get_stats () = 
1137   <:show<Equality.>> ^ 
1138   "# of purged eq by the collector: " ^ string_of_int !n_purged ^ "\n"
1139 ;;