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