]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/paramodulation/equality.ml
1) variables occurring only in proofs anre not relocated
[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 (* $Id: inference.ml 6245 2006-04-05 12:07:51Z tassi $ *)
27
28 type rule = SuperpositionRight | SuperpositionLeft | Demodulation
29 type uncomparable = int -> int 
30 type equality =
31     uncomparable *       (* trick to break structural equality *)
32     int  *               (* weight *)
33     proof * 
34     (Cic.term *          (* type *)
35      Cic.term *          (* left side *)
36      Cic.term *          (* right side *)
37      Utils.comparison) * (* ordering *)  
38     Cic.metasenv  *      (* environment for metas *)
39     int                  (* id *)
40 and proof = 
41   | Exact of Cic.term
42   | Step of Subst.substitution * (rule * int*(Utils.pos*int)* Cic.term) 
43             (* subst, (rule,eq1, eq2,predicate) *)  
44 and goal_proof = (Utils.pos * int * Subst.substitution * Cic.term) list
45 ;;
46
47 (* globals *)
48 let maxid = ref 0;;
49 let id_to_eq = Hashtbl.create 1024;;
50
51 let freshid () =
52   incr maxid; !maxid
53 ;;
54
55 let reset () = 
56   maxid := 0;
57   Hashtbl.clear  id_to_eq
58 ;;
59
60 let uncomparable = fun _ -> 0
61
62 let mk_equality (weight,p,(ty,l,r,o),m) =
63   let id = freshid () in
64   let eq = (uncomparable,weight,p,(ty,l,r,o),m,id) in
65   Hashtbl.add id_to_eq id eq;
66   eq
67 ;;
68
69 let mk_tmp_equality (weight,(ty,l,r,o),m) =
70   let id = -1 in
71   uncomparable,weight,Exact (Cic.Implicit None),(ty,l,r,o),m,id
72 ;;
73
74
75 let open_equality (_,weight,proof,(ty,l,r,o),m,id) = 
76   (weight,proof,(ty,l,r,o),m,id)
77
78 let string_of_equality ?env eq =
79   match env with
80   | None ->
81       let w, _, (ty, left, right, o), m , id = open_equality eq in
82       Printf.sprintf "Id: %d, Weight: %d, {%s}: %s =(%s) %s [%s]" 
83               id w (CicPp.ppterm ty)
84               (CicPp.ppterm left) 
85               (Utils.string_of_comparison o) (CicPp.ppterm right)
86         (String.concat ", " (List.map (fun (i,_,_) -> string_of_int i) m))
87   | Some (_, context, _) -> 
88       let names = Utils.names_of_context context in
89       let w, _, (ty, left, right, o), m , id = open_equality eq in
90       Printf.sprintf "Id: %d, Weight: %d, {%s}: %s =(%s) %s [%s]" 
91               id w (CicPp.pp ty names)
92               (CicPp.pp left names) (Utils.string_of_comparison o)
93               (CicPp.pp right names)
94         (String.concat ", " (List.map (fun (i,_,_) -> string_of_int i) m))
95 ;;
96
97 let compare (_,_,_,s1,_,_) (_,_,_,s2,_,_) =
98   Pervasives.compare s1 s2
99 ;;
100
101 let proof_of_id id =
102   try
103     let (_,p,(_,l,r,_),_,_) = open_equality (Hashtbl.find id_to_eq id) in
104       p,l,r
105   with
106       Not_found -> assert false
107
108
109 let string_of_proof ?(names=[]) p gp = 
110   let str_of_rule = function
111     | SuperpositionRight -> "SupR"
112     | SuperpositionLeft -> "SupL"
113     | Demodulation -> "Demod"
114   in
115   let str_of_pos = function
116     | Utils.Left -> "left"
117     | Utils.Right -> "right"
118   in
119   let fst3 (x,_,_) = x in
120   let rec aux margin name = 
121     let prefix = String.make margin ' ' ^ name ^ ": " in function 
122     | Exact t -> 
123         Printf.sprintf "%sExact (%s)\n" 
124           prefix (CicPp.pp t names)
125     | Step (subst,(rule,eq1,(pos,eq2),pred)) -> 
126         Printf.sprintf "%s%s(%s|%d with %d dir %s pred %s))\n"
127           prefix (str_of_rule rule) (Subst.ppsubst ~names subst) eq1 eq2 (str_of_pos pos) 
128           (CicPp.pp pred names)^ 
129         aux (margin+1) (Printf.sprintf "%d" eq1) (fst3 (proof_of_id eq1)) ^ 
130         aux (margin+1) (Printf.sprintf "%d" eq2) (fst3 (proof_of_id eq2)) 
131   in
132   aux 0 "" p ^ 
133   String.concat "\n" 
134     (List.map 
135       (fun (pos,i,s,t) -> 
136         (Printf.sprintf 
137           "GOAL: %s %d %s %s\n" 
138             (str_of_pos pos) i (Subst.ppsubst ~names s) (CicPp.pp t names)) ^ 
139         aux 1 (Printf.sprintf "%d " i) (fst3 (proof_of_id i)))
140       gp)
141 ;;
142
143 let rec depend eq id =
144   let (_,p,(_,_,_,_),_,ideq) = open_equality eq in
145   if id = ideq then true else  
146   match p with
147       Exact _ -> false
148     | Step (_,(_,id1,(_,id2),_)) ->
149         let eq1 = Hashtbl.find id_to_eq id1 in
150         let eq2 = Hashtbl.find id_to_eq id2 in  
151         depend eq1 id || depend eq2 id
152 ;;
153
154 let ppsubst = Subst.ppsubst ~names:[];;
155
156 (* returns an explicit named subst and a list of arguments for sym_eq_URI *)
157 let build_ens uri termlist =
158   let obj, _ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
159   match obj with
160   | Cic.Constant (_, _, _, uris, _) ->
161       assert (List.length uris <= List.length termlist);
162       let rec aux = function
163         | [], tl -> [], tl
164         | (uri::uris), (term::tl) ->
165             let ens, args = aux (uris, tl) in
166             (uri, term)::ens, args
167         | _, _ -> assert false
168       in
169       aux (uris, termlist)
170   | _ -> assert false
171 ;;
172
173 let mk_sym uri ty t1 t2 p =
174   let ens, args =  build_ens uri [ty;t1;t2;p] in
175     Cic.Appl (Cic.Const(uri, ens) :: args)
176 ;;
177
178 let mk_trans uri ty t1 t2 t3 p12 p23 =
179   let ens, args = build_ens uri [ty;t1;t2;t3;p12;p23] in
180     Cic.Appl (Cic.Const (uri, ens) :: args)
181 ;;
182
183 let mk_eq_ind uri ty what pred p1 other p2 =
184  Cic.Appl [Cic.Const (uri, []); ty; what; pred; p1; other; p2]
185 ;;
186
187 let p_of_sym ens tl =
188   let args = List.map snd ens @ tl in
189   match args with 
190     | [_;_;_;p] -> p 
191     | _ -> assert false 
192 ;;
193
194 let open_trans ens tl =
195   let args = List.map snd ens @ tl in
196   match args with 
197     | [ty;l;m;r;p1;p2] -> ty,l,m,r,p1,p2
198     | _ -> assert false   
199 ;;
200
201 let open_eq_ind args =
202   match args with 
203   | [ty;l;pred;pl;r;pleqr] -> ty,l,pred,pl,r,pleqr
204   | _ -> assert false   
205 ;;
206
207 let open_pred pred =
208   match pred with 
209   | Cic.Lambda (_,ty,(Cic.Appl [Cic.MutInd (uri, 0,_);_;l;r])) 
210      when LibraryObjects.is_eq_URI uri -> ty,uri,l,r
211   | _ -> prerr_endline (CicPp.ppterm pred); assert false   
212 ;;
213
214 let is_not_fixed t =
215    CicSubstitution.subst (Cic.Implicit None) t <>
216    CicSubstitution.subst (Cic.Rel 1) t
217 ;;
218
219
220 let canonical t = 
221   let rec remove_refl t =
222     match t with
223     | Cic.Appl (((Cic.Const(uri_trans,ens))::tl) as args)
224           when LibraryObjects.is_trans_eq_URI uri_trans ->
225           let ty,l,m,r,p1,p2 = open_trans ens tl in
226             (match p1,p2 with
227               | Cic.Appl [Cic.MutConstruct (uri, 0, 1,_);_;_],p2 -> 
228                   remove_refl p2
229               | p1,Cic.Appl [Cic.MutConstruct (uri, 0, 1,_);_;_] -> 
230                   remove_refl p1
231               | _ -> Cic.Appl (List.map remove_refl args))
232     | Cic.Appl l -> Cic.Appl (List.map remove_refl l)
233     | Cic.LetIn (name,bo,rest) ->
234         Cic.LetIn (name,remove_refl bo,remove_refl rest)
235     | _ -> t
236   in
237   let rec canonical t =
238     match t with
239       | Cic.LetIn(name,bo,rest) -> Cic.LetIn(name,canonical bo,canonical rest)
240       | Cic.Appl (((Cic.Const(uri_sym,ens))::tl) as args)
241           when LibraryObjects.is_sym_eq_URI uri_sym ->
242           (match p_of_sym ens tl with
243              | Cic.Appl ((Cic.Const(uri,ens))::tl)
244                  when LibraryObjects.is_sym_eq_URI uri -> 
245                    canonical (p_of_sym ens tl)
246              | Cic.Appl ((Cic.Const(uri_trans,ens))::tl)
247                  when LibraryObjects.is_trans_eq_URI uri_trans ->
248                  let ty,l,m,r,p1,p2 = open_trans ens tl in
249                    mk_trans uri_trans ty r m l 
250                      (canonical (mk_sym uri_sym ty m r p2)) 
251                      (canonical (mk_sym uri_sym ty l m p1))
252              | Cic.Appl (((Cic.Const(uri_ind,ens)) as he)::tl) 
253                  when LibraryObjects.is_eq_ind_URI uri_ind || 
254                       LibraryObjects.is_eq_ind_r_URI uri_ind ->
255                  let ty, what, pred, p1, other, p2 =
256                    match tl with
257                    | [ty;what;pred;p1;other;p2] -> ty, what, pred, p1, other, p2
258                    | _ -> assert false
259                  in
260                  let pred,l,r = 
261                    match pred with
262                    | Cic.Lambda (name,s,Cic.Appl [Cic.MutInd(uri,0,ens);ty;l;r])
263                        when LibraryObjects.is_eq_URI uri ->
264                          Cic.Lambda 
265                            (name,s,Cic.Appl [Cic.MutInd(uri,0,ens);ty;r;l]),l,r
266                    | _ -> 
267                        prerr_endline (CicPp.ppterm pred);
268                        assert false
269                  in
270                  let l = CicSubstitution.subst what l in
271                  let r = CicSubstitution.subst what r in
272                  Cic.Appl 
273                    [he;ty;what;pred;
274                     canonical (mk_sym uri_sym ty l r p1);other;canonical p2]
275              | Cic.Appl [Cic.MutConstruct (uri, 0, 1,_);_;_] as t
276                  when LibraryObjects.is_eq_URI uri -> t
277              | _ -> Cic.Appl (List.map canonical args))
278       | Cic.Appl l -> Cic.Appl (List.map canonical l)
279       | _ -> t
280   in
281   remove_refl (canonical t)
282 ;;
283   
284 let ty_of_lambda = function
285   | Cic.Lambda (_,ty,_) -> ty
286   | _ -> assert false 
287 ;;
288
289 let compose_contexts ctx1 ctx2 = 
290   ProofEngineReduction.replace_lifting 
291     ~equality:(=) ~what:[Cic.Rel 1] ~with_what:[ctx2] ~where:ctx1
292 ;;
293
294 let put_in_ctx ctx t = 
295   ProofEngineReduction.replace_lifting
296     ~equality:(=) ~what:[Cic.Rel 1] ~with_what:[t] ~where:ctx
297 ;;
298
299 let mk_eq uri ty l r =
300   Cic.Appl [Cic.MutInd(uri,0,[]);ty;l;r]
301 ;;
302
303 let mk_refl uri ty t = 
304   Cic.Appl [Cic.MutConstruct(uri,0,1,[]);ty;t]
305 ;;
306
307 let open_eq = function 
308   | Cic.Appl [Cic.MutInd(uri,0,[]);ty;l;r] when LibraryObjects.is_eq_URI uri ->
309       uri, ty, l ,r
310   | _ -> assert false
311 ;;
312
313 let contextualize uri ty left right t = 
314   (* aux [uri] [ty] [left] [right] [ctx] [t] 
315    * 
316    * the parameters validate this invariant  
317    *   t: eq(uri) ty left right
318    * that is used only by the base case
319    *
320    * ctx is a term with an open (Rel 1). (Rel 1) is the empty context
321    *)
322     let rec aux uri ty left right ctx_d = function
323       | Cic.LetIn (name,body,rest) ->
324           (* we should go in body *)
325           Cic.LetIn (name,body,aux uri ty left right ctx_d rest)
326       | Cic.Appl ((Cic.Const(uri_ind,ens))::tl)
327         when LibraryObjects.is_eq_ind_URI uri_ind || 
328              LibraryObjects.is_eq_ind_r_URI uri_ind ->
329           let ty1,what,pred,p1,other,p2 = open_eq_ind tl in
330           let ty2,eq,lp,rp = open_pred pred in 
331           let uri_trans = LibraryObjects.trans_eq_URI ~eq:uri in
332           let uri_sym = LibraryObjects.sym_eq_URI ~eq:uri in
333           let is_not_fixed_lp = is_not_fixed lp in
334           let avoid_eq_ind = LibraryObjects.is_eq_ind_URI uri_ind in
335           (* extract the context and the fixed term from the predicate *)
336           let m, ctx_c = 
337             let m, ctx_c = if is_not_fixed_lp then rp,lp else lp,rp in
338             (* they were under a lambda *)
339             let m =  CicSubstitution.subst (Cic.Implicit None) m in
340             let ctx_c = CicSubstitution.subst (Cic.Rel 1) ctx_c in
341             m, ctx_c          
342           in
343           (* create the compound context and put the terms under it *)
344           let ctx_dc = compose_contexts ctx_d ctx_c in
345           let dc_what = put_in_ctx ctx_dc what in
346           let dc_other = put_in_ctx ctx_dc other in
347           (* m is already in ctx_c so it is put in ctx_d only *)
348           let d_m = put_in_ctx ctx_d m in
349           (* we also need what in ctx_c *)
350           let c_what = put_in_ctx ctx_c what in
351           (* now put the proofs in the compound context *)
352           let p1 = (* p1: dc_what = d_m *)
353             if is_not_fixed_lp then 
354               aux uri ty1 c_what m ctx_d p1 
355             else
356               mk_sym uri_sym ty d_m dc_what
357                 (aux uri ty1 m c_what ctx_d p1)
358           in
359           let p2 = (* p2: dc_other = dc_what *)
360             if avoid_eq_ind then
361               mk_sym uri_sym ty dc_what dc_other
362                 (aux uri ty1 what other ctx_dc p2)
363             else
364               aux uri ty1 other what ctx_dc p2
365           in
366           (* if pred = \x.C[x]=m --> t : C[other]=m --> trans other what m
367              if pred = \x.m=C[x] --> t : m=C[other] --> trans m what other *)
368           let a,b,c,paeqb,pbeqc =
369             if is_not_fixed_lp then
370               dc_other,dc_what,d_m,p2,p1
371             else
372               d_m,dc_what,dc_other,
373                 (mk_sym uri_sym ty dc_what d_m p1),
374                 (mk_sym uri_sym ty dc_other dc_what p2)
375           in
376           mk_trans uri_trans ty a b c paeqb pbeqc
377     | t -> 
378         let uri_sym = LibraryObjects.sym_eq_URI ~eq:uri in
379         let uri_ind = LibraryObjects.eq_ind_URI ~eq:uri in
380         let pred = 
381           (* ctx_d will go under a lambda, but put_in_ctx substitutes Rel 1 *)
382           let ctx_d = CicSubstitution.lift_from 2 1 ctx_d in (* bleah *)
383           let r = put_in_ctx ctx_d (CicSubstitution.lift 1 left) in
384           let l = ctx_d in
385           let lty = CicSubstitution.lift 1 ty in 
386           Cic.Lambda (Cic.Name "foo",ty,(mk_eq uri lty l r))
387         in
388         let d_left = put_in_ctx ctx_d left in
389         let d_right = put_in_ctx ctx_d right in
390         let refl_eq = mk_refl uri ty d_left in
391         mk_sym uri_sym ty d_right d_left
392           (mk_eq_ind uri_ind ty left pred refl_eq right t)
393   in
394   let empty_context = Cic.Rel 1 in
395   aux uri ty left right empty_context t
396 ;;
397
398 let contextualize_rewrites t ty = 
399   let eq,ty,l,r = open_eq ty in
400   contextualize eq ty l r t
401 ;;
402   
403 let build_proof_step lift subst p1 p2 pos l r pred =
404   let p1 = Subst.apply_subst_lift lift subst p1 in
405   let p2 = Subst.apply_subst_lift lift subst p2 in
406   let l  = CicSubstitution.lift lift l in
407   let l = Subst.apply_subst_lift lift subst l in
408   let r  = CicSubstitution.lift lift r in
409   let r = Subst.apply_subst_lift lift subst r in
410   let pred = CicSubstitution.lift lift pred in
411   let pred = Subst.apply_subst_lift lift subst pred in
412   let ty,body = 
413     match pred with
414       | Cic.Lambda (_,ty,body) -> ty,body 
415       | _ -> assert false
416   in
417   let what, other = 
418     if pos = Utils.Left then l,r else r,l
419   in
420     match pos with
421       | Utils.Left ->
422         mk_eq_ind (Utils.eq_ind_URI ()) ty what pred p1 other p2
423       | Utils.Right ->
424         mk_eq_ind (Utils.eq_ind_r_URI ()) ty what pred p1 other p2
425 ;;
426
427 let parametrize_proof p l r ty = 
428   let parameters = CicUtil.metas_of_term p 
429 @ CicUtil.metas_of_term l 
430 @ CicUtil.metas_of_term r
431 in (* ?if they are under a lambda? *)
432   let parameters = 
433     HExtlib.list_uniq (List.sort Pervasives.compare parameters) 
434   in
435   let what = List.map (fun (i,l) -> Cic.Meta (i,l)) parameters in 
436   let with_what, lift_no = 
437     List.fold_right (fun _ (acc,n) -> ((Cic.Rel n)::acc),n+1) what ([],1) 
438   in
439   let p = CicSubstitution.lift (lift_no-1) p in
440   let p = 
441     ProofEngineReduction.replace_lifting
442     ~equality:(fun t1 t2 -> match t1,t2 with Cic.Meta (i,_),Cic.Meta(j,_) -> i=j | _ -> false) ~what ~with_what ~where:p
443   in
444   let ty_of_m _ = ty (*function 
445     | Cic.Meta (i,_) -> List.assoc i menv 
446     | _ -> assert false *)
447   in
448   let args, proof,_ = 
449     List.fold_left 
450       (fun (instance,p,n) m -> 
451         (instance@[m],
452         Cic.Lambda 
453           (Cic.Name ("x"^string_of_int n),
454           CicSubstitution.lift (lift_no - n - 1) (ty_of_m m),
455           p),
456         n+1)) 
457       ([Cic.Rel 1],p,1) 
458       what
459   in
460   let instance = match args with | [x] -> x | _ -> Cic.Appl args in
461   proof, instance
462 ;;
463
464 let wfo goalproof proof =
465   let rec aux acc id =
466     let p,_,_ = proof_of_id id in
467     match p with
468     | Exact _ -> if (List.mem id acc) then acc else id :: acc
469     | Step (_,(_,id1, (_,id2), _)) -> 
470         let acc = if not (List.mem id1 acc) then aux acc id1 else acc in
471         let acc = if not (List.mem id2 acc) then aux acc id2 else acc in
472         id :: acc
473   in
474   let acc = 
475     match proof with
476       | Exact _ -> []
477       | Step (_,(_,id1, (_,id2), _)) -> aux (aux [] id1) id2
478   in 
479   List.fold_left (fun acc (_,id,_,_) -> aux acc id) acc goalproof
480 ;;
481
482 let string_of_id names id = 
483   try
484     let (_,p,(_,l,r,_),m,_) = open_equality (Hashtbl.find id_to_eq id) in
485     match p with
486     | Exact t -> 
487         Printf.sprintf "%d = %s: %s = %s [%s]" id
488           (CicPp.pp t names) (CicPp.pp l names) (CicPp.pp r names)
489         (String.concat ", " (List.map (fun (i,_,_) -> string_of_int i) m))
490     | Step (_,(step,id1, (_,id2), _) ) ->
491         Printf.sprintf "%6d: %s %6d %6d   %s = %s [%s]" id
492           (if step = SuperpositionRight then "SupR" else "Demo") 
493           id1 id2 (CicPp.pp l names) (CicPp.pp r names)
494         (String.concat ", " (List.map (fun (i,_,_) -> string_of_int i) m))
495   with
496       Not_found -> assert false
497
498 let pp_proof names goalproof proof =
499   String.concat "\n" (List.map (string_of_id names) (wfo goalproof proof)) ^ 
500   "\ngoal is demodulated with " ^ 
501     (String.concat " " 
502       ((List.map (fun (_,i,_,_) -> string_of_int i) goalproof)))
503 ;;
504
505 (* returns the list of ids that should be factorized *)
506 let get_duplicate_step_in_wfo l p =
507   let ol = List.rev l in
508   let h = Hashtbl.create 13 in
509   (* NOTE: here the n parameter is an approximation of the dependency 
510      between equations. To do things seriously we should maintain a 
511      dependency graph. This approximation is not perfect. *)
512   let add i n = 
513     let p,_,_ = proof_of_id i in 
514     match p with 
515     | Exact _ -> true
516     | _ -> 
517         try let (pos,no) = Hashtbl.find h i in Hashtbl.replace h i (pos,no+1);false
518         with Not_found -> Hashtbl.add h i (n,1);true
519   in
520   let rec aux n = function
521     | Exact _ -> n
522     | Step (_,(_,i1,(_,i2),_)) -> 
523         let go_on_1 = add i1 n in
524         let go_on_2 = add i2 n in
525         max 
526          (if go_on_1 then aux (n+1) (let p,_,_ = proof_of_id i1 in p) else n+1)
527          (if go_on_2 then aux (n+1) (let p,_,_ = proof_of_id i2 in p) else n+1)
528   in
529   let i = aux 0 p in 
530   let _ = 
531     List.fold_left 
532       (fun acc (_,id,_,_) -> aux acc (let p,_,_ = proof_of_id id in p))
533       i ol
534   in
535   (* now h is complete *)
536   let proofs = Hashtbl.fold (fun k (pos,count) acc->(k,pos,count)::acc) h [] in
537   let proofs = List.filter (fun (_,_,c) -> c > 1) proofs in
538   let proofs = 
539     List.sort (fun (_,c1,_) (_,c2,_) -> Pervasives.compare c2 c1) proofs 
540   in
541   List.map (fun (i,_,_) -> i) proofs
542 ;;
543
544 let build_proof_term h lift proof =
545   let proof_of_id aux id =
546     let p,l,r = proof_of_id id in
547     try List.assoc id h,l,r with Not_found -> aux p, l, r
548   in
549   let rec aux = function
550      | Exact term -> CicSubstitution.lift lift term
551      | Step (subst,(_, id1, (pos,id2), pred)) ->
552          if Subst.is_in_subst 302 subst then
553            prerr_endline ("TROVATA in " ^ string_of_int id1 ^ " " ^ string_of_int id2);
554
555          let p1,_,_ = proof_of_id aux id1 in
556          let p2,l,r = proof_of_id aux id2 in
557          let p =   build_proof_step lift subst p1 p2 pos l r pred in
558 (*       let cond =  (not (List.mem 302 (Utils.metas_of_term p)) || id1 = 8 || id1 = 132) in
559            if not cond then
560              prerr_endline ("ERROR " ^ string_of_int id1 ^ " " ^ string_of_int id2);
561            assert cond;*)
562            p
563   in
564    aux proof
565 ;;
566
567 let build_goal_proof l initial ty se =
568   let se = List.map (fun i -> Cic.Meta (i,[])) se in 
569   let lets = get_duplicate_step_in_wfo l initial in
570   let letsno = List.length lets in
571   let _,mty,_,_ = open_eq ty in
572   let lift_list l = List.map (fun (i,t) -> i,CicSubstitution.lift 1 t) l 
573   in
574   let lets,_,h = 
575     List.fold_left
576       (fun (acc,n,h) id -> 
577         let p,l,r = proof_of_id id in
578         let cic = build_proof_term h n p in
579         let real_cic,instance = 
580           parametrize_proof cic l r (CicSubstitution.lift n mty)
581         in
582         let h = (id, instance)::lift_list h in
583         acc@[id,real_cic],n+1,h) 
584       ([],0,[]) lets
585   in
586   let proof,se = 
587     let rec aux se current_proof = function
588       | [] -> current_proof,se
589       | (pos,id,subst,pred)::tl ->
590          if Subst.is_in_subst 302 subst then
591            prerr_endline ("TROVATA in " ^ string_of_int id );
592
593           let p,l,r = proof_of_id id in
594            let p = build_proof_term h letsno p in
595            let pos = if pos = Utils.Left then Utils.Right else Utils.Left in
596            let proof = 
597              build_proof_step letsno subst current_proof p pos l r pred 
598            in
599            let proof,se = aux se proof tl in
600            Subst.apply_subst_lift letsno subst proof,
601            List.map (fun x -> Subst.apply_subst_lift letsno subst x) se
602     in
603     aux se (build_proof_term h letsno initial) l
604   in
605   let n,proof = 
606     let initial = proof in
607     List.fold_right
608       (fun (id,cic) (n,p) -> 
609         n-1,
610         Cic.LetIn (
611           Cic.Name ("H"^string_of_int id),
612           cic, p))
613     lets (letsno-1,initial)
614   in
615   (*canonical (contextualize_rewrites proof (CicSubstitution.lift letsno ty))*)proof, se
616 ;;
617
618 let refl_proof ty term = 
619   Cic.Appl 
620     [Cic.MutConstruct 
621        (LibraryObjects.eq_URI (), 0, 1, []);
622        ty; term]
623 ;;
624
625 let metas_of_proof p =
626   let p = build_proof_term [] 0 p in
627   Utils.metas_of_term p
628 ;;
629
630 let relocate newmeta menv to_be_relocated =
631   let subst, newmetasenv, newmeta = 
632     List.fold_right 
633       (fun i (subst, metasenv, maxmeta) ->         
634         let _,context,ty = CicUtil.lookup_meta i menv in
635         let irl = [] in
636         let newmeta = Cic.Meta(maxmeta,irl) in
637         let newsubst = Subst.buildsubst i context newmeta ty subst in
638         newsubst, (maxmeta,context,ty)::metasenv, maxmeta+1) 
639       to_be_relocated (Subst.empty_subst, [], newmeta+1)
640   in
641   let menv = Subst.apply_subst_metasenv subst menv @ newmetasenv in
642   subst, menv, newmeta
643
644
645 let fix_metas newmeta eq = 
646   let w, p, (ty, left, right, o), menv,_ = open_equality eq in
647   let to_be_relocated = 
648     HExtlib.list_uniq 
649       (List.sort Pervasives.compare 
650          (Utils.metas_of_term left @ Utils.metas_of_term right)) 
651   in
652   let subst, metasenv, newmeta = relocate newmeta menv to_be_relocated in
653   let ty = Subst.apply_subst subst ty in
654   let left = Subst.apply_subst subst left in
655   let right = Subst.apply_subst subst right in
656   let fix_proof = function
657     | Exact p -> Exact (Subst.apply_subst subst p)
658     | Step (s,(r,id1,(pos,id2),pred)) -> 
659         Step (Subst.concat s subst,(r,id1,(pos,id2), pred))
660   in
661   let p = fix_proof p in
662   let eq' = mk_equality (w, p, (ty, left, right, o), metasenv) in
663   newmeta+1, eq'  
664
665 exception NotMetaConvertible;;
666
667 let meta_convertibility_aux table t1 t2 =
668   let module C = Cic in
669   let rec aux ((table_l, table_r) as table) t1 t2 =
670     match t1, t2 with
671     | C.Meta (m1, tl1), C.Meta (m2, tl2) ->
672         let m1_binding, table_l =
673           try List.assoc m1 table_l, table_l
674           with Not_found -> m2, (m1, m2)::table_l
675         and m2_binding, table_r =
676           try List.assoc m2 table_r, table_r
677           with Not_found -> m1, (m2, m1)::table_r
678         in
679         if (m1_binding <> m2) || (m2_binding <> m1) then
680           raise NotMetaConvertible
681         else (
682           try
683             List.fold_left2
684               (fun res t1 t2 ->
685                  match t1, t2 with
686                  | None, Some _ | Some _, None -> raise NotMetaConvertible
687                  | None, None -> res
688                  | Some t1, Some t2 -> (aux res t1 t2))
689               (table_l, table_r) tl1 tl2
690           with Invalid_argument _ ->
691             raise NotMetaConvertible
692         )
693     | C.Var (u1, ens1), C.Var (u2, ens2)
694     | C.Const (u1, ens1), C.Const (u2, ens2) when (UriManager.eq u1 u2) ->
695         aux_ens table ens1 ens2
696     | C.Cast (s1, t1), C.Cast (s2, t2)
697     | C.Prod (_, s1, t1), C.Prod (_, s2, t2)
698     | C.Lambda (_, s1, t1), C.Lambda (_, s2, t2)
699     | C.LetIn (_, s1, t1), C.LetIn (_, s2, t2) ->
700         let table = aux table s1 s2 in
701         aux table t1 t2
702     | C.Appl l1, C.Appl l2 -> (
703         try List.fold_left2 (fun res t1 t2 -> (aux res t1 t2)) table l1 l2
704         with Invalid_argument _ -> raise NotMetaConvertible
705       )
706     | C.MutInd (u1, i1, ens1), C.MutInd (u2, i2, ens2)
707         when (UriManager.eq u1 u2) && i1 = i2 -> aux_ens table ens1 ens2
708     | C.MutConstruct (u1, i1, j1, ens1), C.MutConstruct (u2, i2, j2, ens2)
709         when (UriManager.eq u1 u2) && i1 = i2 && j1 = j2 ->
710         aux_ens table ens1 ens2
711     | C.MutCase (u1, i1, s1, t1, l1), C.MutCase (u2, i2, s2, t2, l2)
712         when (UriManager.eq u1 u2) && i1 = i2 ->
713         let table = aux table s1 s2 in
714         let table = aux table t1 t2 in (
715           try List.fold_left2 (fun res t1 t2 -> (aux res t1 t2)) table l1 l2
716           with Invalid_argument _ -> raise NotMetaConvertible
717         )
718     | C.Fix (i1, il1), C.Fix (i2, il2) when i1 = i2 -> (
719         try
720           List.fold_left2
721             (fun res (n1, i1, s1, t1) (n2, i2, s2, t2) ->
722                if i1 <> i2 then raise NotMetaConvertible
723                else
724                  let res = (aux res s1 s2) in aux res t1 t2)
725             table il1 il2
726         with Invalid_argument _ -> raise NotMetaConvertible
727       )
728     | C.CoFix (i1, il1), C.CoFix (i2, il2) when i1 = i2 -> (
729         try
730           List.fold_left2
731             (fun res (n1, s1, t1) (n2, s2, t2) ->
732                let res = aux res s1 s2 in aux res t1 t2)
733             table il1 il2
734         with Invalid_argument _ -> raise NotMetaConvertible
735       )
736     | t1, t2 when t1 = t2 -> table
737     | _, _ -> raise NotMetaConvertible
738         
739   and aux_ens table ens1 ens2 =
740     let cmp (u1, t1) (u2, t2) =
741       Pervasives.compare (UriManager.string_of_uri u1) (UriManager.string_of_uri u2)
742     in
743     let ens1 = List.sort cmp ens1
744     and ens2 = List.sort cmp ens2 in
745     try
746       List.fold_left2
747         (fun res (u1, t1) (u2, t2) ->
748            if not (UriManager.eq u1 u2) then raise NotMetaConvertible
749            else aux res t1 t2)
750         table ens1 ens2
751     with Invalid_argument _ -> raise NotMetaConvertible
752   in
753   aux table t1 t2
754 ;;
755
756
757 let meta_convertibility_eq eq1 eq2 =
758   let _, _, (ty, left, right, _), _,_ = open_equality eq1 in
759   let _, _, (ty', left', right', _), _,_ = open_equality eq2 in
760   if ty <> ty' then
761     false
762   else if (left = left') && (right = right') then
763     true
764   else if (left = right') && (right = left') then
765     true
766   else
767     try
768       let table = meta_convertibility_aux ([], []) left left' in
769       let _ = meta_convertibility_aux table right right' in
770       true
771     with NotMetaConvertible ->
772       try
773         let table = meta_convertibility_aux ([], []) left right' in
774         let _ = meta_convertibility_aux table right left' in
775         true
776       with NotMetaConvertible ->
777         false
778 ;;
779
780
781 let meta_convertibility t1 t2 =
782   if t1 = t2 then
783     true
784   else
785     try
786       ignore(meta_convertibility_aux ([], []) t1 t2);
787       true
788     with NotMetaConvertible ->
789       false
790 ;;
791
792 exception TermIsNotAnEquality;;
793
794 let term_is_equality term =
795   let iseq uri = UriManager.eq uri (LibraryObjects.eq_URI ()) in
796   match term with
797   | Cic.Appl [Cic.MutInd (uri, _, _); _; _; _] when iseq uri -> true
798   | _ -> false
799 ;;
800
801 let equality_of_term proof term =
802   let eq_uri = LibraryObjects.eq_URI () in
803   let iseq uri = UriManager.eq uri eq_uri in
804   match term with
805   | Cic.Appl [Cic.MutInd (uri, _, _); ty; t1; t2] when iseq uri ->
806       let o = !Utils.compare_terms t1 t2 in
807       let stat = (ty,t1,t2,o) in
808       let w = Utils.compute_equality_weight stat in
809       let e = mk_equality (w, Exact proof, stat,[]) in
810       e
811   | _ ->
812       raise TermIsNotAnEquality
813 ;;
814
815 let is_weak_identity eq = 
816   let _,_,(_,left, right,_),_,_ = open_equality eq in
817   left = right || meta_convertibility left right 
818 ;;
819
820 let is_identity (_, context, ugraph) eq = 
821   let _,_,(ty,left,right,_),menv,_ = open_equality eq in
822   left = right ||
823   (* (meta_convertibility left right)) *)
824   fst (CicReduction.are_convertible ~metasenv:menv context left right ugraph)
825 ;;
826
827
828 let term_of_equality equality =
829   let _, _, (ty, left, right, _), menv, _= open_equality equality in
830   let eq i = function Cic.Meta (j, _) -> i = j | _ -> false in
831   let argsno = List.length menv in
832   let t =
833     CicSubstitution.lift argsno
834       (Cic.Appl [Cic.MutInd (LibraryObjects.eq_URI (), 0, []); ty; left; right])
835   in
836   snd (
837     List.fold_right
838       (fun (i,_,ty) (n, t) ->
839          let name = Cic.Name ("X" ^ (string_of_int n)) in
840          let ty = CicSubstitution.lift (n-1) ty in
841          let t = 
842            ProofEngineReduction.replace
843              ~equality:eq ~what:[i]
844              ~with_what:[Cic.Rel (argsno - (n - 1))] ~where:t
845          in
846            (n-1, Cic.Prod (name, ty, t)))
847       menv (argsno, t))
848 ;;
849