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