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