]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/paramodulation/inference.ml
Snapshot.
[helm.git] / components / tactics / paramodulation / inference.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$ *)
27
28 open Utils;;
29
30 let metas_of_proof_time = ref 0.;;
31 let metas_of_term_time = ref 0.;;
32
33 type 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     Cic.term list        (* arguments *)
42
43 and proof =
44   | NoProof (* term is the goal missing a proof *)
45   | BasicProof of Cic.term
46   | ProofBlock of
47       Cic.substitution * UriManager.uri *
48         (Cic.name * Cic.term) * Cic.term * (Utils.pos * equality) * proof
49   | ProofGoalBlock of proof * proof 
50   | ProofSymBlock of Cic.term list * proof
51   | SubProof of Cic.term * int * proof
52 ;;
53
54 let string_of_equality ?env =
55   match env with
56   | None -> (
57       function
58         | w, _, (ty, left, right, o), _, _ ->
59             Printf.sprintf "Weight: %d, {%s}: %s =(%s) %s" w (CicPp.ppterm ty)
60               (CicPp.ppterm left) (string_of_comparison o) (CicPp.ppterm right)
61     )
62   | Some (_, context, _) -> (
63       let names = names_of_context context in
64       function
65         | w, _, (ty, left, right, o), _, _ ->
66             Printf.sprintf "Weight: %d, {%s}: %s =(%s) %s" w (CicPp.pp ty names)
67               (CicPp.pp left names) (string_of_comparison o)
68               (CicPp.pp right names)
69     )
70 ;;
71
72
73 let rec string_of_proof = function
74   | NoProof -> "NoProof " 
75   | BasicProof t -> "BasicProof " ^ (CicPp.ppterm t)
76   | SubProof (t, i, p) ->
77       Printf.sprintf "SubProof(%s, %s, %s)"
78         (CicPp.ppterm t) (string_of_int i) (string_of_proof p)
79   | ProofSymBlock _ -> "ProofSymBlock"
80   | ProofBlock (subst, _, _, _ ,_,_) -> 
81       "ProofBlock" ^ (CicMetaSubst.ppsubst subst)
82   | ProofGoalBlock (p1, p2) ->
83       Printf.sprintf "ProofGoalBlock(%s, %s)"
84         (string_of_proof p1) (string_of_proof p2)
85 ;;
86
87
88 let check_disjoint_invariant subst metasenv msg =
89   if (List.exists 
90         (fun (i,_,_) -> (List.exists (fun (j,_) -> i=j) subst)) metasenv)
91   then 
92     begin 
93       prerr_endline ("not disjoint: " ^ msg);
94       assert false
95     end
96 ;;
97
98 (* filter out from metasenv the variables in substs *)
99 let filter subst metasenv =
100   List.filter
101     (fun (m, _, _) ->
102          try let _ = List.find (fun (i, _) -> m = i) subst in false
103          with Not_found -> true)
104     metasenv
105 ;;
106
107 (* returns an explicit named subst and a list of arguments for sym_eq_URI *)
108 let build_ens_for_sym_eq sym_eq_URI termlist =
109   let obj, _ = CicEnvironment.get_obj CicUniv.empty_ugraph sym_eq_URI in
110   match obj with
111   | Cic.Constant (_, _, _, uris, _) ->
112       assert (List.length uris <= List.length termlist);
113       let rec aux = function
114         | [], tl -> [], tl
115         | (uri::uris), (term::tl) ->
116             let ens, args = aux (uris, tl) in
117             (uri, term)::ens, args
118         | _, _ -> assert false
119       in
120       aux (uris, termlist)
121   | _ -> assert false
122 ;;
123
124
125 let build_proof_term ?(noproof=Cic.Implicit None) proof =
126   let rec do_build_proof proof = 
127     match proof with
128     | NoProof ->
129         Printf.fprintf stderr "WARNING: no proof!\n";
130         noproof
131     | BasicProof term -> term
132     | ProofGoalBlock (proofbit, proof) ->
133         print_endline "found ProofGoalBlock, going up...";
134         do_build_goal_proof proofbit proof
135     | ProofSymBlock (termlist, proof) ->
136         let proof = do_build_proof proof in
137         let ens, args = build_ens_for_sym_eq (Utils.sym_eq_URI ()) termlist in
138         Cic.Appl ([Cic.Const (Utils.sym_eq_URI (), ens)] @ args @ [proof])
139     | ProofBlock (subst, eq_URI, (name, ty), bo, (pos, eq), eqproof) ->
140         let t' = Cic.Lambda (name, ty, bo) in
141         let proof' =
142           let _, proof', _, _, _ = eq in
143           do_build_proof proof'
144         in
145         let eqproof = do_build_proof eqproof in
146         let _, _, (ty, what, other, _), menv', args' = eq in
147         let what, other =
148           if pos = Utils.Left then what, other else other, what
149         in
150         CicMetaSubst.apply_subst subst
151           (Cic.Appl [Cic.Const (eq_URI, []); ty;
152                      what; t'; eqproof; other; proof'])
153     | SubProof (term, meta_index, proof) ->
154         let proof = do_build_proof proof in
155         let eq i = function
156           | Cic.Meta (j, _) -> i = j
157           | _ -> false
158         in
159         ProofEngineReduction.replace
160           ~equality:eq ~what:[meta_index] ~with_what:[proof] ~where:term
161
162   and do_build_goal_proof proofbit proof =
163     match proof with
164     | ProofGoalBlock (pb, p) ->
165         do_build_proof (ProofGoalBlock (replace_proof proofbit pb, p))
166     | _ -> do_build_proof (replace_proof proofbit proof)
167
168   and replace_proof newproof = function
169     | ProofBlock (subst, eq_URI, namety, bo, poseq, eqproof) ->
170         let eqproof' = replace_proof newproof eqproof in
171         ProofBlock (subst, eq_URI, namety, bo, poseq, eqproof')
172     | ProofGoalBlock (pb, p) ->
173         let pb' = replace_proof newproof pb in
174         ProofGoalBlock (pb', p)
175     | BasicProof _ -> newproof
176     | SubProof (term, meta_index, p) ->
177         SubProof (term, meta_index, replace_proof newproof p)
178     | p -> p
179   in
180   do_build_proof proof
181 ;;
182
183
184 let rec metas_of_term = function
185   | Cic.Meta (i, c) -> [i]
186   | Cic.Var (_, ens) 
187   | Cic.Const (_, ens) 
188   | Cic.MutInd (_, _, ens) 
189   | Cic.MutConstruct (_, _, _, ens) ->
190       List.flatten (List.map (fun (u, t) -> metas_of_term t) ens)
191   | Cic.Cast (s, t)
192   | Cic.Prod (_, s, t)
193   | Cic.Lambda (_, s, t)
194   | Cic.LetIn (_, s, t) -> (metas_of_term s) @ (metas_of_term t)
195   | Cic.Appl l -> List.flatten (List.map metas_of_term l)
196   | Cic.MutCase (uri, i, s, t, l) ->
197       (metas_of_term s) @ (metas_of_term t) @
198         (List.flatten (List.map metas_of_term l))
199   | Cic.Fix (i, il) ->
200       List.flatten
201         (List.map (fun (s, i, t1, t2) ->
202                      (metas_of_term t1) @ (metas_of_term t2)) il)
203   | Cic.CoFix (i, il) ->
204       List.flatten
205         (List.map (fun (s, t1, t2) ->
206                      (metas_of_term t1) @ (metas_of_term t2)) il)
207   | _ -> []
208 ;;      
209
210 let rec metas_of_proof p = 
211   if Utils.debug then
212     let t1 = Unix.gettimeofday () in
213     let res = metas_of_term (build_proof_term p) in
214     let t2 = Unix.gettimeofday () in
215     metas_of_proof_time := !metas_of_proof_time  +. (t2 -. t1);
216     res
217   else 
218     metas_of_term (build_proof_term p)
219 ;;
220
221 exception NotMetaConvertible;;
222
223 let meta_convertibility_aux table t1 t2 =
224   let module C = Cic in
225   let rec aux ((table_l, table_r) as table) t1 t2 =
226     match t1, t2 with
227     | C.Meta (m1, tl1), C.Meta (m2, tl2) ->
228         let m1_binding, table_l =
229           try List.assoc m1 table_l, table_l
230           with Not_found -> m2, (m1, m2)::table_l
231         and m2_binding, table_r =
232           try List.assoc m2 table_r, table_r
233           with Not_found -> m1, (m2, m1)::table_r
234         in
235         if (m1_binding <> m2) || (m2_binding <> m1) then
236           raise NotMetaConvertible
237         else (
238           try
239             List.fold_left2
240               (fun res t1 t2 ->
241                  match t1, t2 with
242                  | None, Some _ | Some _, None -> raise NotMetaConvertible
243                  | None, None -> res
244                  | Some t1, Some t2 -> (aux res t1 t2))
245               (table_l, table_r) tl1 tl2
246           with Invalid_argument _ ->
247             raise NotMetaConvertible
248         )
249     | C.Var (u1, ens1), C.Var (u2, ens2)
250     | C.Const (u1, ens1), C.Const (u2, ens2) when (UriManager.eq u1 u2) ->
251         aux_ens table ens1 ens2
252     | C.Cast (s1, t1), C.Cast (s2, t2)
253     | C.Prod (_, s1, t1), C.Prod (_, s2, t2)
254     | C.Lambda (_, s1, t1), C.Lambda (_, s2, t2)
255     | C.LetIn (_, s1, t1), C.LetIn (_, s2, t2) ->
256         let table = aux table s1 s2 in
257         aux table t1 t2
258     | C.Appl l1, C.Appl l2 -> (
259         try List.fold_left2 (fun res t1 t2 -> (aux res t1 t2)) table l1 l2
260         with Invalid_argument _ -> raise NotMetaConvertible
261       )
262     | C.MutInd (u1, i1, ens1), C.MutInd (u2, i2, ens2)
263         when (UriManager.eq u1 u2) && i1 = i2 -> aux_ens table ens1 ens2
264     | C.MutConstruct (u1, i1, j1, ens1), C.MutConstruct (u2, i2, j2, ens2)
265         when (UriManager.eq u1 u2) && i1 = i2 && j1 = j2 ->
266         aux_ens table ens1 ens2
267     | C.MutCase (u1, i1, s1, t1, l1), C.MutCase (u2, i2, s2, t2, l2)
268         when (UriManager.eq u1 u2) && i1 = i2 ->
269         let table = aux table s1 s2 in
270         let table = aux table t1 t2 in (
271           try List.fold_left2 (fun res t1 t2 -> (aux res t1 t2)) table l1 l2
272           with Invalid_argument _ -> raise NotMetaConvertible
273         )
274     | C.Fix (i1, il1), C.Fix (i2, il2) when i1 = i2 -> (
275         try
276           List.fold_left2
277             (fun res (n1, i1, s1, t1) (n2, i2, s2, t2) ->
278                if i1 <> i2 then raise NotMetaConvertible
279                else
280                  let res = (aux res s1 s2) in aux res t1 t2)
281             table il1 il2
282         with Invalid_argument _ -> raise NotMetaConvertible
283       )
284     | C.CoFix (i1, il1), C.CoFix (i2, il2) when i1 = i2 -> (
285         try
286           List.fold_left2
287             (fun res (n1, s1, t1) (n2, s2, t2) ->
288                let res = aux res s1 s2 in aux res t1 t2)
289             table il1 il2
290         with Invalid_argument _ -> raise NotMetaConvertible
291       )
292     | t1, t2 when t1 = t2 -> table
293     | _, _ -> raise NotMetaConvertible
294         
295   and aux_ens table ens1 ens2 =
296     let cmp (u1, t1) (u2, t2) =
297       compare (UriManager.string_of_uri u1) (UriManager.string_of_uri u2)
298     in
299     let ens1 = List.sort cmp ens1
300     and ens2 = List.sort cmp ens2 in
301     try
302       List.fold_left2
303         (fun res (u1, t1) (u2, t2) ->
304            if not (UriManager.eq u1 u2) then raise NotMetaConvertible
305            else aux res t1 t2)
306         table ens1 ens2
307     with Invalid_argument _ -> raise NotMetaConvertible
308   in
309   aux table t1 t2
310 ;;
311
312
313 let meta_convertibility_eq eq1 eq2 =
314   let _, _, (ty, left, right, _), _, _ = eq1
315   and _, _, (ty', left', right', _), _, _ = eq2 in
316   if ty <> ty' then
317     false
318   else if (left = left') && (right = right') then
319     true
320   else if (left = right') && (right = left') then
321     true
322   else
323     try
324       let table = meta_convertibility_aux ([], []) left left' in
325       let _ = meta_convertibility_aux table right right' in
326       true
327     with NotMetaConvertible ->
328       try
329         let table = meta_convertibility_aux ([], []) left right' in
330         let _ = meta_convertibility_aux table right left' in
331         true
332       with NotMetaConvertible ->
333         false
334 ;;
335
336
337 let meta_convertibility t1 t2 =
338   if t1 = t2 then
339     true
340   else
341     try
342       ignore(meta_convertibility_aux ([], []) t1 t2);
343       true
344     with NotMetaConvertible ->
345       false
346 ;;
347
348
349 let rec check_irl start = function
350   | [] -> true
351   | None::tl -> check_irl (start+1) tl
352   | (Some (Cic.Rel x))::tl ->
353       if x = start then check_irl (start+1) tl else false
354   | _ -> false
355 ;;
356
357
358 let rec is_simple_term = function
359   | Cic.Appl ((Cic.Meta _)::_) -> false
360   | Cic.Appl l -> List.for_all is_simple_term l
361   | Cic.Meta (i, l) -> check_irl 1 l
362   | Cic.Rel _ -> true
363   | Cic.Const _ -> true
364   | Cic.MutInd (_, _, []) -> true
365   | Cic.MutConstruct (_, _, _, []) -> true
366   | _ -> false
367 ;;
368
369
370 let lookup_subst meta subst =
371   match meta with
372   | Cic.Meta (i, _) -> (
373       try let _, (_, t, _) = List.find (fun (m, _) -> m = i) subst in t
374       with Not_found -> meta
375     )
376   | _ -> assert false
377 ;;
378
379
380 let unification_simple metasenv context t1 t2 ugraph =
381   let module C = Cic in
382   let module M = CicMetaSubst in
383   let module U = CicUnification in
384   let lookup = lookup_subst in
385   let rec occurs_check subst what where =
386     match where with
387     | t when what = t -> true
388     | C.Appl l -> List.exists (occurs_check subst what) l
389     | C.Meta _ ->
390         let t = lookup where subst in
391         if t <> where then occurs_check subst what t else false
392     | _ -> false
393   in
394   let rec unif subst menv s t =
395     let s = match s with C.Meta _ -> lookup s subst | _ -> s
396     and t = match t with C.Meta _ -> lookup t subst | _ -> t
397     in
398     match s, t with
399     | s, t when s = t -> subst, menv
400     | C.Meta (i, _), C.Meta (j, _) when i > j ->
401         unif subst menv t s
402     | C.Meta _, t when occurs_check subst s t ->
403         raise
404           (U.UnificationFailure (lazy "Inference.unification.unif"))
405     | C.Meta (i, l), t -> (
406         try
407           let _, _, ty = CicUtil.lookup_meta i menv in
408           assert (not (List.mem_assoc i subst));
409           let subst = (i, (context, t, ty))::subst in
410           let menv = menv in (* List.filter (fun (m, _, _) -> i <> m) menv in *)
411           subst, menv
412         with CicUtil.Meta_not_found m ->
413           let names = names_of_context context in
414           debug_print
415             (lazy
416                (Printf.sprintf "Meta_not_found %d!: %s %s\n%s\n\n%s" m
417                   (CicPp.pp t1 names) (CicPp.pp t2 names)
418                   (print_metasenv menv) (print_metasenv metasenv)));
419           assert false
420       )
421     | _, C.Meta _ -> unif subst menv t s
422     | C.Appl (hds::_), C.Appl (hdt::_) when hds <> hdt ->
423         raise (U.UnificationFailure (lazy "Inference.unification.unif"))
424     | C.Appl (hds::tls), C.Appl (hdt::tlt) -> (
425         try
426           List.fold_left2
427             (fun (subst', menv) s t -> unif subst' menv s t)
428             (subst, menv) tls tlt
429         with Invalid_argument _ ->
430           raise (U.UnificationFailure (lazy "Inference.unification.unif"))
431       )
432     | _, _ ->
433         raise (U.UnificationFailure (lazy "Inference.unification.unif"))
434   in
435   let subst, menv = unif [] metasenv t1 t2 in
436   let menv = filter subst menv in
437   List.rev subst, menv, ugraph
438 ;;
439
440
441 let unification metasenv1 metasenv2 context t1 t2 ugraph =
442   let metasenv = metasenv1 metasenv2 in
443   let subst, menv, ug =
444     if not (is_simple_term t1) || not (is_simple_term t2) then (
445       debug_print
446         (lazy
447            (Printf.sprintf "NOT SIMPLE TERMS: %s %s"
448               (CicPp.ppterm t1) (CicPp.ppterm t2)));
449       CicUnification.fo_unif metasenv context t1 t2 ugraph
450     ) else
451       unification_simple metasenv context t1 t2 ugraph
452   in
453   if Utils.debug_res then
454             ignore(check_disjoint_invariant subst menv "unif");
455   let subst =
456     List.map
457       (fun (i, (context, term, ty)) ->
458          let context = CicMetaSubst.apply_subst_context subst context in
459          let term = CicMetaSubst.apply_subst subst term in
460          let ty = CicMetaSubst.apply_subst subst ty in  
461            (i, (context, term, ty))) subst in
462 (*
463   let rec fix_term = function
464     | (Cic.Meta (i, l) as t) ->
465         let t' = lookup_subst t subst in
466         if t <> t' then fix_term t' else t
467     | Cic.Appl l -> Cic.Appl (List.map fix_term l)
468     | t -> t
469   in
470   let rec fix_subst = function
471     | [] -> []
472     | (i, (c, t, ty))::tl -> (i, (c, fix_term t, fix_term ty))::(fix_subst tl)
473   in 
474   fix_subst subst, menv, ug *)
475   subst, menv, ug
476 ;;
477
478
479 let unification metasenv1 metasenv2 context t1 t2 ugraph = 
480   let (subst, metasenv, ugraph) = 
481     CicUnification.fo_unif (metasenv1@metasenv2) context t1 t2 ugraph in
482   if Utils.debug_res then
483             ignore(check_disjoint_invariant subst metasenv "fo_unif");
484   (subst, metasenv, ugraph)
485     
486 ;;
487
488 exception MatchingFailure;;
489
490
491 (*
492 let matching_simple metasenv context t1 t2 ugraph =
493   let module C = Cic in
494   let module M = CicMetaSubst in
495   let module U = CicUnification in
496   let lookup meta subst =
497     match meta with
498     | C.Meta (i, _) -> (
499         try let _, (_, t, _) = List.find (fun (m, _) -> m = i) subst in t
500         with Not_found -> meta
501       )
502     | _ -> assert false
503   in
504   let rec do_match subst menv s t =
505     match s, t with
506     | s, t when s = t -> subst, menv
507     | s, C.Meta (i, l) ->
508         let filter_menv i menv =
509           List.filter (fun (m, _, _) -> i <> m) menv
510         in
511         let subst, menv =
512           let value = lookup t subst in
513           match value with
514           | value when value = t ->
515               let _, _, ty = CicUtil.lookup_meta i menv in
516               (i, (context, s, ty))::subst, filter_menv i menv
517           | value when value <> s ->
518               raise MatchingFailure
519           | value -> do_match subst menv s value
520         in
521         subst, menv
522     | C.Appl ls, C.Appl lt -> (
523         try
524           List.fold_left2
525             (fun (subst, menv) s t -> do_match subst menv s t)
526             (subst, menv) ls lt
527         with Invalid_argument _ ->
528           raise MatchingFailure
529       )
530     | _, _ ->
531         raise MatchingFailure
532   in
533   let subst, menv = do_match [] metasenv t1 t2 in
534   subst, menv, ugraph
535 ;;
536 *)
537
538 (*
539 let matching metasenv context t1 t2 ugraph =
540     try
541       let subst, metasenv, ugraph =
542         try
543           unification metasenv context t1 t2 ugraph
544         with CicUtil.Meta_not_found _ as exn ->
545           Printf.eprintf "t1 == %s\nt2 = %s\nmetasenv == %s\n%!"
546             (CicPp.ppterm t1) (CicPp.ppterm t2) 
547             (CicMetaSubst.ppmetasenv [] metasenv);
548           raise exn
549       in
550       if Utils.debug_res then
551             ignore(check_disjoint_invariant subst metasenv "qua-2");
552       let t' = CicMetaSubst.apply_subst subst t1 in
553       if not (meta_convertibility t1 t') then
554         raise MatchingFailure
555       else
556         if Utils.debug_res then
557             ignore(check_disjoint_invariant subst metasenv "qua-1");
558         let metas = metas_of_term t1 in
559         let subst =
560           List.map
561             (fun (i, (context, term, ty)) ->
562                let context = CicMetaSubst.apply_subst_context subst context in
563                let term = CicMetaSubst.apply_subst subst term in
564                let ty = CicMetaSubst.apply_subst subst ty in  
565                  (i, (context, term, ty))) subst in
566           if Utils.debug_res then
567             ignore(check_disjoint_invariant subst metasenv "qua0");
568           
569           let subst, metasenv =
570           List.fold_left
571             (fun 
572                (subst,metasenv) s ->
573                  match s with
574                    | (i, (c, Cic.Meta (j, lc), ty)) when List.mem i metas ->
575                        let metasenv' =
576                          List.filter (fun (x, _, _) -> x<>j) metasenv 
577                        in
578                          ((j, (c, Cic.Meta (i, lc), ty))::subst,
579                           (i,c,ty)::metasenv')
580                    |_ -> s::subst,metasenv) ([],metasenv) subst
581         in
582         if Utils.debug_res then
583           ignore(check_disjoint_invariant subst metasenv "qua1");
584 (*
585         let fix_subst = function
586           | (i, (c, Cic.Meta (j, lc), ty)) when List.mem i metas ->
587               (j, (c, Cic.Meta (i, lc), ty))
588           | s -> s
589         in
590         let subst = List.map fix_subst subst in *)
591         if CicMetaSubst.apply_subst subst t1 = t1 then
592           subst, metasenv, ugraph
593         else
594           (prerr_endline "mah"; raise MatchingFailure)
595     with
596     | CicUnification.UnificationFailure _
597     | CicUnification.Uncertain _ ->
598       raise MatchingFailure
599 ;;
600 *)
601
602 (** matching takes in input the _disjoint_ metasenv of t1 and  t2;
603 it perform unification in the union metasenv, then check that
604 the first metasenv has not changed *)
605
606 let matching metasenv1 metasenv2 context t1 t2 ugraph =
607       let subst, metasenv, ugraph =
608         try
609           unification metasenv1 metasenv2 context t1 t2 ugraph
610         with 
611             CicUtil.Meta_not_found _ as exn ->
612               Printf.eprintf "t1 == %s\nt2 = %s\nmetasenv == %s\n%!"
613                 (CicPp.ppterm t1) (CicPp.ppterm t2) 
614                 (CicMetaSubst.ppmetasenv [] (metasenv1@metasenv2));
615               raise exn
616           | CicUnification.UnificationFailure _
617           | CicUnification.Uncertain _ ->
618               raise MatchingFailure    
619       in
620       if Utils.debug_res then
621             ignore(check_disjoint_invariant subst metasenv "qua-2");
622       (* let us unfold subst *)
623       if metasenv = metasenv1 then 
624         subst, metasenv, ugraph (* everything is fine *)
625       else
626         (* let us unfold subst *)
627         let subst =
628           List.map
629             (fun (i, (context, term, ty)) ->
630                let context = CicMetaSubst.apply_subst_context subst context in
631                let term = CicMetaSubst.apply_subst subst term in
632                let ty = CicMetaSubst.apply_subst subst ty in  
633                  (i, (context, term, ty))) subst in
634           (* let us revert Meta-Meta in subst privileging metasenv1 *)
635         let subst, metasenv =
636           List.fold_left
637             (fun 
638                (subst,metasenv) s ->
639                  match s with
640                    | (i, (c, Cic.Meta (j, lc), ty)) 
641                        when (List.exists (fun (x, _, _)  -> x=i) metasenv1) &&
642                          not (List.exists (fun (x, _)  -> x=j) subst) ->
643                        let metasenv' =
644                          List.filter (fun (x, _, _) -> x<>j) metasenv 
645                        in
646                          ((j, (c, Cic.Meta (i, lc), ty))::subst,
647                           (i,c,ty)::metasenv')
648                    |_ -> s::subst,metasenv) ([],metasenv) subst
649         in
650         (* finally, let us chek again that metasenv = metasenv1 *)
651         if metasenv = metasenv1 then 
652           subst, metasenv, ugraph
653         else raise MatchingFailure  
654 ;;
655
656 let check_eq context msg eq =
657   let w, proof, (eq_ty, left, right, order), metas, args = eq in
658   if not (fst (CicReduction.are_convertible ~metasenv:metas context eq_ty
659    (fst (CicTypeChecker.type_of_aux' metas context  left CicUniv.empty_ugraph))
660    CicUniv.empty_ugraph))
661   then
662     begin
663       prerr_endline msg;
664       assert false;
665     end
666   else ()
667 ;;
668
669 let find_equalities context proof =
670   let module C = Cic in
671   let module S = CicSubstitution in
672   let module T = CicTypeChecker in
673   let eq_uri = LibraryObjects.eq_URI () in
674   let newmeta = ProofEngineHelpers.new_meta_of_proof ~proof in
675   let ok_types ty menv =
676     List.for_all (fun (_, _, mt) -> mt = ty) menv
677   in
678   let rec aux index newmeta = function
679     | [] -> [], newmeta
680     | (Some (_, C.Decl (term)))::tl ->
681         let do_find context term =
682           match term with
683           | C.Prod (name, s, t) ->
684               let (head, newmetas, args, newmeta) =
685                 ProofEngineHelpers.saturate_term newmeta []
686                   context (S.lift index term) 0
687               in
688               let p =
689                 if List.length args = 0 then
690                   C.Rel index
691                 else
692                   C.Appl ((C.Rel index)::args)
693               in (
694                 match head with
695                 | C.Appl [C.MutInd (uri, _, _); ty; t1; t2]
696                     when (UriManager.eq uri eq_uri) && (ok_types ty newmetas) ->
697                     debug_print
698                       (lazy
699                          (Printf.sprintf "OK: %s" (CicPp.ppterm term)));
700                     let o = !Utils.compare_terms t1 t2 in
701                     let w = compute_equality_weight ty t1 t2 in
702                     let proof = BasicProof p in
703                     let e = (w, proof, (ty, t1, t2, o), newmetas, args) in
704                     Some e, (newmeta+1)
705                 | _ -> None, newmeta
706               )
707           | C.Appl [C.MutInd (uri, _, _); ty; t1; t2]
708               when UriManager.eq uri eq_uri ->
709               let ty = S.lift index ty in
710               let t1 = S.lift index t1 in
711               let t2 = S.lift index t2 in
712               let o = !Utils.compare_terms t1 t2 in
713               let w = compute_equality_weight ty t1 t2 in
714               let e = (w, BasicProof (C.Rel index), (ty, t1, t2, o), [], []) in
715               Some e, (newmeta+1)
716           | _ -> None, newmeta
717         in (
718           match do_find context term with
719           | Some p, newmeta ->
720               let tl, newmeta' = (aux (index+1) newmeta tl) in
721               if newmeta' < newmeta then 
722                 prerr_endline "big trouble";
723               (index, p)::tl, newmeta' (* max???? *)
724           | None, _ ->
725               aux (index+1) newmeta tl
726         )
727     | _::tl ->
728         aux (index+1) newmeta tl
729   in
730   let il, maxm = aux 1 newmeta context in
731   let indexes, equalities = List.split il in
732   ignore (List.iter (check_eq context "find") equalities);
733   indexes, equalities, maxm
734 ;;
735
736
737 (*
738 let equations_blacklist =
739   List.fold_left
740     (fun s u -> UriManager.UriSet.add (UriManager.uri_of_string u) s)
741     UriManager.UriSet.empty [
742       "cic:/Coq/Init/Logic/eq.ind#xpointer(1/1/1)";
743       "cic:/Coq/Init/Logic/trans_eq.con";
744       "cic:/Coq/Init/Logic/f_equal.con";
745       "cic:/Coq/Init/Logic/f_equal2.con";
746       "cic:/Coq/Init/Logic/f_equal3.con";
747       "cic:/Coq/Init/Logic/f_equal4.con";
748       "cic:/Coq/Init/Logic/f_equal5.con";
749       "cic:/Coq/Init/Logic/sym_eq.con";
750       "cic:/Coq/Init/Logic/eq_ind.con";
751       "cic:/Coq/Init/Logic/eq_ind_r.con";
752       "cic:/Coq/Init/Logic/eq_rec.con";
753       "cic:/Coq/Init/Logic/eq_rec_r.con";
754       "cic:/Coq/Init/Logic/eq_rect.con";
755       "cic:/Coq/Init/Logic/eq_rect_r.con";
756       "cic:/Coq/Logic/Eqdep/UIP.con";
757       "cic:/Coq/Logic/Eqdep/UIP_refl.con";
758       "cic:/Coq/Logic/Eqdep_dec/eq2eqT.con";
759       "cic:/Coq/ZArith/Zcompare/rename.con";
760       (* ALB !!!! questo e` imbrogliare, ma x ora lo lasciamo cosi`...
761          perche' questo cacchio di teorema rompe le scatole :'( *)
762       "cic:/Rocq/SUBST/comparith/mult_n_2.con";
763
764       "cic:/matita/logic/equality/eq_f.con";
765       "cic:/matita/logic/equality/eq_f2.con";
766       "cic:/matita/logic/equality/eq_rec.con";
767       "cic:/matita/logic/equality/eq_rect.con";
768     ]
769 ;;
770 *)
771 let equations_blacklist = UriManager.UriSet.empty;;
772
773
774 let find_library_equalities dbd context status maxmeta = 
775   let module C = Cic in
776   let module S = CicSubstitution in
777   let module T = CicTypeChecker in
778   let blacklist =
779     List.fold_left
780       (fun s u -> UriManager.UriSet.add u s)
781       equations_blacklist
782       [eq_XURI (); sym_eq_URI (); trans_eq_URI (); eq_ind_URI ();
783        eq_ind_r_URI ()]
784   in
785   let candidates =
786     List.fold_left
787       (fun l uri ->
788          if UriManager.UriSet.mem uri blacklist then
789            l
790          else
791            let t = CicUtil.term_of_uri uri in
792            let ty, _ =
793              CicTypeChecker.type_of_aux' [] context t CicUniv.empty_ugraph
794            in
795            (uri, t, ty)::l)
796       []
797       (let t1 = Unix.gettimeofday () in
798        let eqs = (MetadataQuery.equations_for_goal ~dbd status) in
799        let t2 = Unix.gettimeofday () in
800        (debug_print
801           (lazy
802              (Printf.sprintf "Tempo di MetadataQuery.equations_for_goal: %.9f\n"
803                 (t2 -. t1))));
804        eqs)
805   in
806   let eq_uri1 = eq_XURI ()
807   and eq_uri2 = LibraryObjects.eq_URI () in
808   let iseq uri =
809     (UriManager.eq uri eq_uri1) || (UriManager.eq uri eq_uri2)
810   in
811   let ok_types ty menv =
812     List.for_all (fun (_, _, mt) -> mt = ty) menv
813   in
814   let rec has_vars = function
815     | C.Meta _ | C.Rel _ | C.Const _ -> false
816     | C.Var _ -> true
817     | C.Appl l -> List.exists has_vars l
818     | C.Prod (_, s, t) | C.Lambda (_, s, t)
819     | C.LetIn (_, s, t) | C.Cast (s, t) ->
820         (has_vars s) || (has_vars t)
821     | _ -> false
822   in
823   let rec aux newmeta = function
824     | [] -> [], newmeta
825     | (uri, term, termty)::tl ->
826         debug_print
827           (lazy
828              (Printf.sprintf "Examining: %s (%s)"
829                 (CicPp.ppterm term) (CicPp.ppterm termty)));
830         let res, newmeta = 
831           match termty with
832           | C.Prod (name, s, t) when not (has_vars termty) ->
833               let head, newmetas, args, newmeta =
834                 ProofEngineHelpers.saturate_term newmeta [] context termty 0
835               in
836               let p =
837                 if List.length args = 0 then
838                   term
839                 else
840                   C.Appl (term::args)
841               in (
842                 match head with
843                 | C.Appl [C.MutInd (uri, _, _); ty; t1; t2]
844                     when (iseq uri) && (ok_types ty newmetas) ->
845                     debug_print
846                       (lazy
847                          (Printf.sprintf "OK: %s" (CicPp.ppterm term)));
848                     let o = !Utils.compare_terms t1 t2 in
849                     let w = compute_equality_weight ty t1 t2 in
850                     let proof = BasicProof p in
851                     let e = (w, proof, (ty, t1, t2, o), newmetas, args) in
852                     Some e, (newmeta+1)
853                 | _ -> None, newmeta
854               )
855           | C.Appl [C.MutInd (uri, _, _); ty; t1; t2]
856               when iseq uri && not (has_vars termty) ->
857               let o = !Utils.compare_terms t1 t2 in
858               let w = compute_equality_weight ty t1 t2 in
859               let e = (w, BasicProof term, (ty, t1, t2, o), [], []) in
860               Some e, (newmeta+1)
861           | _ -> None, newmeta
862         in
863         match res with
864         | Some e ->
865             let tl, newmeta' = aux newmeta tl in
866               if newmeta' < newmeta then 
867                 prerr_endline "big trouble";
868               (uri, e)::tl, newmeta' (* max???? *)
869         | None ->
870             aux newmeta tl
871   in
872   let found, maxm = aux maxmeta candidates in
873   let uriset, eqlist = 
874     (List.fold_left
875        (fun (s, l) (u, e) ->
876           if List.exists (meta_convertibility_eq e) (List.map snd l) then (
877             debug_print
878               (lazy
879                  (Printf.sprintf "NO!! %s already there!"
880                     (string_of_equality e)));
881             (UriManager.UriSet.add u s, l)
882           ) else (UriManager.UriSet.add u s, (u, e)::l))
883        (UriManager.UriSet.empty, []) found)
884   in
885   uriset, eqlist, maxm
886 ;;
887
888
889 let find_library_theorems dbd env status equalities_uris =
890   let module C = Cic in
891   let module S = CicSubstitution in
892   let module T = CicTypeChecker in
893   let blacklist =
894     let refl_equal =
895       UriManager.uri_of_string "cic:/Coq/Init/Logic/eq.ind#xpointer(1/1/1)" in
896     let s =
897       UriManager.UriSet.remove refl_equal
898         (UriManager.UriSet.union equalities_uris equations_blacklist)
899     in
900     List.fold_left
901       (fun s u -> UriManager.UriSet.add u s)
902       s [eq_XURI () ;sym_eq_URI (); trans_eq_URI (); eq_ind_URI ();
903          eq_ind_r_URI ()]
904   in
905   let metasenv, context, ugraph = env in
906   let candidates =
907     List.fold_left
908       (fun l uri ->
909          if UriManager.UriSet.mem uri blacklist then l
910          else
911            let t = CicUtil.term_of_uri uri in
912            let ty, _ = CicTypeChecker.type_of_aux' metasenv context t ugraph in
913            (t, ty, [])::l)
914       [] (MetadataQuery.signature_of_goal ~dbd status)
915   in
916   let refl_equal =
917     let u = eq_XURI () in
918     let t = CicUtil.term_of_uri u in
919     let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
920     (t, ty, [])
921   in
922   refl_equal::candidates
923 ;;
924
925
926 let find_context_hypotheses env equalities_indexes =
927   let metasenv, context, ugraph = env in
928   let _, res = 
929     List.fold_left
930       (fun (n, l) entry ->
931          match entry with
932          | None -> (n+1, l)
933          | Some _ ->
934              if List.mem n equalities_indexes then
935                (n+1, l)
936              else
937                let t = Cic.Rel n in
938                let ty, _ =
939                  CicTypeChecker.type_of_aux' metasenv context t ugraph in 
940                (n+1, (t, ty, [])::l))
941       (1, []) context
942   in
943   res
944 ;;
945
946
947 let fix_metas_old newmeta (w, p, (ty, left, right, o), menv, args) =
948   let table = Hashtbl.create (List.length args) in
949
950   let newargs, newmeta =
951     List.fold_right
952       (fun t (newargs, index) ->
953          match t with
954          | Cic.Meta (i, l) ->
955              if Hashtbl.mem table i then
956                let idx = Hashtbl.find table i in
957                ((Cic.Meta (idx, l))::newargs, index+1)
958              else
959                let _ = Hashtbl.add table i index in
960                ((Cic.Meta (index, l))::newargs, index+1)
961          | _ -> assert false)
962       args ([], newmeta+1)
963   in
964
965   let repl where =
966     ProofEngineReduction.replace ~equality:(=) ~what:args ~with_what:newargs
967       ~where
968   in
969   let menv' =
970     List.fold_right
971       (fun (i, context, term) menv ->
972          try
973            let index = Hashtbl.find table i in
974            (index, context, term)::menv
975          with Not_found ->
976            (i, context, term)::menv)
977       menv []
978   in
979   let ty = repl ty
980   and left = repl left
981   and right = repl right in
982   let metas = 
983     (metas_of_term left) @ 
984       (metas_of_term right) @ 
985       (metas_of_term ty) @ (metas_of_proof p) in
986   let menv' = List.filter (fun (i, _, _) -> List.mem i metas) menv' in
987   let newargs =
988     List.filter
989       (function Cic.Meta (i, _) -> List.mem i metas | _ -> assert false) newargs
990   in
991   let _ =
992     if List.length metas > 0 then 
993       let first = List.hd metas in
994       (* this new equality might have less variables than its parents: here
995          we fill the gap with a dummy arg. Example:
996          with (f X Y) = X we can simplify
997          (g X) = (f X Y) in
998          (g X) = X. 
999          So the new equation has only one variable, but it still has type like
1000          \lambda X,Y:..., so we need to pass a dummy arg for Y
1001          (I hope this makes some sense...)
1002       *)
1003       Hashtbl.iter
1004         (fun k v ->
1005            if not (List.exists
1006                      (function Cic.Meta (i, _) -> i = v | _ -> assert false)
1007                      newargs) then
1008              Hashtbl.replace table k first)
1009         (Hashtbl.copy table)
1010   in
1011   let rec fix_proof = function
1012     | NoProof -> NoProof 
1013     | BasicProof term -> BasicProof (repl term)
1014     | ProofBlock (subst, eq_URI, namety, bo, (pos, eq), p) ->
1015         let subst' =
1016           List.fold_left
1017             (fun s arg ->
1018                match arg with
1019                | Cic.Meta (i, l) -> (
1020                    try
1021                      let j = Hashtbl.find table i in
1022                      if List.mem_assoc i subst then
1023                        s
1024                      else
1025                        let _, context, ty = CicUtil.lookup_meta i menv in
1026                        (i, (context, Cic.Meta (j, l), ty))::s
1027                    with Not_found | CicUtil.Meta_not_found _ ->
1028                      s
1029                  )
1030                | _ -> assert false)
1031             [] args
1032         in
1033         ProofBlock (subst' @ subst, eq_URI, namety, bo(* t' *), (pos, eq), p)
1034     | p -> assert false
1035   in
1036   let neweq = (w, fix_proof p, (ty, left, right, o), menv', newargs) in
1037   (newmeta +1, neweq)
1038 ;;
1039
1040
1041 let relocate newmeta menv =
1042   let subst, metasenv, newmeta = 
1043     List.fold_right 
1044       (fun (i, context, ty) (subst, menv, maxmeta) -> 
1045         let irl=CicMkImplicit.identity_relocation_list_for_metavariable context in
1046         let newsubst = (i, (context, (Cic.Meta (maxmeta, irl)), ty)) in
1047         let newmeta = maxmeta, context, ty in
1048         newsubst::subst, newmeta::menv, maxmeta+1) 
1049       menv ([], [], newmeta+1)
1050   in
1051   let metasenv = CicMetaSubst.apply_subst_metasenv subst metasenv in
1052   let subst =
1053     List.map
1054       (fun (i, (context, term, ty)) ->
1055          let context = CicMetaSubst.apply_subst_context subst context in
1056          let term = CicMetaSubst.apply_subst subst term in
1057          let ty = CicMetaSubst.apply_subst subst ty in  
1058          (i, (context, term, ty))) subst in
1059   subst, metasenv, newmeta
1060
1061
1062 let fix_metas newmeta (w, p, (ty, left, right, o), menv, args) =
1063   (*
1064   let metas = (metas_of_term left)@(metas_of_term right)
1065     @(metas_of_term ty)@(metas_of_proof p) in
1066   let menv = List.filter (fun (i, _, _) -> List.mem i metas) menv in
1067   *)
1068   (* debug 
1069   let _ , eq = 
1070     fix_metas_old newmeta (w, p, (ty, left, right, o), menv, args) in
1071   prerr_endline (string_of_equality eq); *)
1072   let subst, metasenv, newmeta = relocate newmeta menv in
1073   let ty = CicMetaSubst.apply_subst subst ty in
1074   let left = CicMetaSubst.apply_subst subst left in
1075   let right = CicMetaSubst.apply_subst subst right in
1076   let args = List.map (CicMetaSubst.apply_subst subst) args in
1077   let rec fix_proof = function
1078     | NoProof -> NoProof 
1079     | BasicProof term -> BasicProof (CicMetaSubst.apply_subst subst term)
1080     | ProofBlock (subst', eq_URI, namety, bo, (pos, eq), p) ->
1081         (*
1082         let newsubst = 
1083           List.map
1084             (fun (i, (context, term, ty)) ->
1085                let context = CicMetaSubst.apply_subst_context subst context in
1086                let term = CicMetaSubst.apply_subst subst term in
1087                let ty = CicMetaSubst.apply_subst subst ty in  
1088                  (i, (context, term, ty))) subst' in *)
1089           ProofBlock (subst@subst', eq_URI, namety, bo, (pos, eq), p)
1090     | p -> assert false
1091   in
1092   let p = fix_proof p in
1093   (*
1094   let metas = (metas_of_term left)@(metas_of_term right)
1095     @(metas_of_term ty)@(metas_of_proof p) in
1096   let metasenv = List.filter (fun (i, _, _) -> List.mem i metas) metasenv in
1097   *)
1098   let eq = (w, p, (ty, left, right, o), metasenv, args) in
1099   (* debug prerr_endline (string_of_equality eq); *)
1100   newmeta+1, eq  
1101
1102 let term_is_equality term =
1103   let iseq uri = UriManager.eq uri (LibraryObjects.eq_URI ()) in
1104   match term with
1105   | Cic.Appl [Cic.MutInd (uri, _, _); _; _; _] when iseq uri -> true
1106   | _ -> false
1107 ;;
1108
1109
1110 exception TermIsNotAnEquality;;
1111
1112 let equality_of_term proof term =
1113   let eq_uri = LibraryObjects.eq_URI () in
1114   let iseq uri = UriManager.eq uri eq_uri in
1115   match term with
1116   | Cic.Appl [Cic.MutInd (uri, _, _); ty; t1; t2] when iseq uri ->
1117       let o = !Utils.compare_terms t1 t2 in
1118       let w = compute_equality_weight ty t1 t2 in
1119       let e = (w, BasicProof proof, (ty, t1, t2, o), [], []) in
1120       e
1121   | _ ->
1122       raise TermIsNotAnEquality
1123 ;;
1124
1125
1126 type environment = Cic.metasenv * Cic.context * CicUniv.universe_graph;;
1127
1128 let is_weak_identity (metasenv, context, ugraph) = function
1129   | (_, _, (ty, left, right, _), menv, _) -> 
1130        (left = right ||
1131           (meta_convertibility left right)) 
1132            (* the test below is not a good idea since it stops
1133               demodulation too early *)
1134            (* (fst (CicReduction.are_convertible 
1135                   ~metasenv:(metasenv @ menv) context left right ugraph)))*)
1136 ;;
1137
1138 let is_identity (metasenv, context, ugraph) = function
1139   | (_, _, (ty, left, right, _), menv, _) ->
1140        (left = right ||
1141           (* (meta_convertibility left right)) *)
1142            (fst (CicReduction.are_convertible 
1143                   ~metasenv:(metasenv @ menv) context left right ugraph)))
1144 ;;
1145
1146
1147 let term_of_equality equality =
1148   let _, _, (ty, left, right, _), menv, _ = equality in
1149   let eq i = function Cic.Meta (j, _) -> i = j | _ -> false in
1150   let argsno = List.length menv in
1151   let t =
1152     CicSubstitution.lift argsno
1153       (Cic.Appl [Cic.MutInd (LibraryObjects.eq_URI (), 0, []); ty; left; right])
1154   in
1155   snd (
1156     List.fold_right
1157       (fun (i,_,ty) (n, t) ->
1158          let name = Cic.Name ("X" ^ (string_of_int n)) in
1159          let ty = CicSubstitution.lift (n-1) ty in
1160          let t = 
1161            ProofEngineReduction.replace
1162              ~equality:eq ~what:[i]
1163              ~with_what:[Cic.Rel (argsno - (n - 1))] ~where:t
1164          in
1165            (n-1, Cic.Prod (name, ty, t)))
1166       menv (argsno, t))
1167 ;;