]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/paramodulation/inference.ml
added some typechecks to avoid using equations with the wrong type
[helm.git] / helm / ocaml / paramodulation / inference.ml
1 open Utils;;
2
3
4 type equality =
5     int  *               (* weight *)
6     proof * 
7     (Cic.term *          (* type *)
8      Cic.term *          (* left side *)
9      Cic.term *          (* right side *)
10      Utils.comparison) * (* ordering *)  
11     Cic.metasenv *       (* environment for metas *)
12     Cic.term list        (* arguments *)
13
14 and proof =
15   | NoProof
16   | BasicProof of Cic.term
17   | ProofBlock of
18       Cic.substitution * UriManager.uri *
19         (* name, ty, eq_ty, left, right *)
20         (Cic.name * Cic.term * Cic.term * Cic.term * Cic.term) * 
21         (Utils.pos * equality) * proof
22   | ProofGoalBlock of proof * equality
23   | ProofSymBlock of Cic.term Cic.explicit_named_substitution * proof
24 ;;
25
26
27 let string_of_equality ?env =
28   match env with
29   | None -> (
30       function
31         | w, _, (ty, left, right, o), _, _ ->
32             Printf.sprintf "Weight: %d, {%s}: %s =(%s) %s" w (CicPp.ppterm ty)
33               (CicPp.ppterm left) (string_of_comparison o) (CicPp.ppterm right)
34     )
35   | Some (_, context, _) -> (
36       let names = names_of_context context in
37       function
38         | w, _, (ty, left, right, o), _, _ ->
39             Printf.sprintf "Weight: %d, {%s}: %s =(%s) %s" w (CicPp.pp ty names)
40               (CicPp.pp left names) (string_of_comparison o)
41               (CicPp.pp right names)
42     )
43 ;;
44
45
46 let build_proof_term equality =
47 (*   Printf.printf "build_term_proof %s" (string_of_equality equality); *)
48 (*   print_newline (); *)
49
50   let indent = ref 0 in
51   
52   let rec do_build_proof proof = 
53     match proof with
54     | NoProof ->
55         Printf.fprintf stderr "WARNING: no proof!\n";
56 (*           (string_of_equality equality); *)
57         Cic.Implicit None
58     | BasicProof term -> term
59     | ProofGoalBlock (proofbit, equality) ->
60         print_endline "found ProofGoalBlock, going up...";
61         let _, proof, _, _, _ = equality in
62         do_build_goal_proof proofbit proof
63     | ProofSymBlock (ens, proof) ->
64         let proof = do_build_proof proof in
65         Cic.Appl [
66           Cic.Const (HelmLibraryObjects.Logic.sym_eq_URI, ens); (* symmetry *)
67           proof
68         ]
69     | ProofBlock (subst, eq_URI, t', (pos, eq), eqproof) ->
70 (*         Printf.printf "\nsubst:\n%s\n" (print_subst subst); *)
71 (*         print_newline (); *)
72
73         let name, ty, eq_ty, left, right = t' in
74         let bo =
75           Cic.Appl [Cic.MutInd (HelmLibraryObjects.Logic.eq_URI, 0, []);
76                     eq_ty; left; right]
77         in
78         let t' = Cic.Lambda (name, ty, (* CicSubstitution.lift 1 *) bo) in
79         (*       Printf.printf "   ProofBlock: eq = %s, eq' = %s" *)
80         (*         (string_of_equality eq) (string_of_equality eq'); *)
81         (*       print_newline (); *)
82
83 (*         let s = String.make !indent ' ' in *)
84 (*         incr indent; *)
85         
86 (*         print_endline (s ^ "build proof'------------"); *)
87         
88         let proof' =
89           let _, proof', _, _, _ = eq in
90           do_build_proof proof'
91         in
92 (*         print_endline (s ^ "END proof'"); *)
93
94 (*         print_endline (s ^ "build eqproof-----------"); *)
95
96         let eqproof = do_build_proof eqproof in
97
98 (*         print_endline (s ^ "END eqproof"); *)
99 (*         decr indent; *)
100         
101         
102         let _, _, (ty, what, other, _), menv', args' = eq in
103         let what, other =
104           if pos = Utils.Left then what, other else other, what
105         in
106         CicMetaSubst.apply_subst subst
107           (Cic.Appl [Cic.Const (eq_URI, []); ty;
108                      what; t'; eqproof; other; proof'])
109
110   and do_build_goal_proof proofbit proof =
111 (*     match proofbit with *)
112 (*     | BasicProof _ -> do_build_proof proof *)
113 (*     | proofbit -> *)
114         match proof with
115         | ProofGoalBlock (pb, eq) ->
116             do_build_proof (ProofGoalBlock (replace_proof proofbit pb, eq))
117 (*             let _, proof, _, _, _  = eq in *)
118 (*             let newproof = replace_proof proofbit proof in *)
119 (*             do_build_proof newproof *)
120
121 (*         | ProofBlock (subst, eq_URI, t', poseq, eqproof) -> *)
122 (*             let eqproof' = replace_proof proofbit eqproof in *)
123 (*             do_build_proof (ProofBlock (subst, eq_URI, t', poseq, eqproof')) *)
124         | _ -> do_build_proof (replace_proof proofbit proof) (* assert false *)
125
126   and replace_proof newproof = function
127     | ProofBlock (subst, eq_URI, t', poseq, eqproof) ->
128         let uri = eq_URI in
129 (*           if eq_URI = HelmLibraryObjects.Logic.eq_ind_URI then *)
130 (*             HelmLibraryObjects.Logic.eq_ind_r_URI *)
131 (*           else *)
132 (*             HelmLibraryObjects.Logic.eq_ind_URI *)
133 (*         in *)
134         let eqproof' = replace_proof newproof eqproof in
135         ProofBlock (subst, uri(* eq_URI *), t', poseq, eqproof')
136 (*         ProofBlock (subst, eq_URI, t', poseq, newproof) *)
137     | ProofGoalBlock (pb, equality) ->
138         let pb' = replace_proof newproof pb in
139         ProofGoalBlock (pb', equality)
140 (*         let w, proof, t, menv, args = equality in *)
141 (*         let proof' = replace_proof newproof proof in *)
142 (*         ProofGoalBlock (pb, (w, proof', t, menv, args)) *)
143     | BasicProof _ -> newproof
144     | p -> p
145   in
146   let _, proof, _, _, _ = equality in
147   do_build_proof proof
148 ;;
149
150
151 let rec metas_of_term = function
152   | Cic.Meta (i, c) -> [i]
153   | Cic.Var (_, ens) 
154   | Cic.Const (_, ens) 
155   | Cic.MutInd (_, _, ens) 
156   | Cic.MutConstruct (_, _, _, ens) ->
157       List.flatten (List.map (fun (u, t) -> metas_of_term t) ens)
158   | Cic.Cast (s, t)
159   | Cic.Prod (_, s, t)
160   | Cic.Lambda (_, s, t)
161   | Cic.LetIn (_, s, t) -> (metas_of_term s) @ (metas_of_term t)
162   | Cic.Appl l -> List.flatten (List.map metas_of_term l)
163   | Cic.MutCase (uri, i, s, t, l) ->
164       (metas_of_term s) @ (metas_of_term t) @
165         (List.flatten (List.map metas_of_term l))
166   | Cic.Fix (i, il) ->
167       List.flatten
168         (List.map (fun (s, i, t1, t2) ->
169                      (metas_of_term t1) @ (metas_of_term t2)) il)
170   | Cic.CoFix (i, il) ->
171       List.flatten
172         (List.map (fun (s, t1, t2) ->
173                      (metas_of_term t1) @ (metas_of_term t2)) il)
174   | _ -> []
175 ;;      
176
177
178 exception NotMetaConvertible;;
179
180 let meta_convertibility_aux table t1 t2 =
181   let module C = Cic in
182   let print_table t =
183     String.concat ", "
184       (List.map
185          (fun (k, v) -> Printf.sprintf "(%d, %d)" k v) t)
186   in
187   let rec aux ((table_l, table_r) as table) t1 t2 =
188 (*     Printf.printf "aux %s, %s\ntable_l: %s, table_r: %s\n" *)
189 (*       (CicPp.ppterm t1) (CicPp.ppterm t2) *)
190 (*       (print_table table_l) (print_table table_r); *)
191     match t1, t2 with
192     | C.Meta (m1, tl1), C.Meta (m2, tl2) ->
193         let m1_binding, table_l =
194           try List.assoc m1 table_l, table_l
195           with Not_found -> m2, (m1, m2)::table_l
196         and m2_binding, table_r =
197           try List.assoc m2 table_r, table_r
198           with Not_found -> m1, (m2, m1)::table_r
199         in
200 (*         let m1_binding, m2_binding, table = *)
201 (*           let m1b, table =  *)
202 (*             try List.assoc m1 table, table *)
203 (*             with Not_found -> m2, (m1, m2)::table *)
204 (*           in *)
205 (*           let m2b, table =  *)
206 (*             try List.assoc m2 table, table *)
207 (*             with Not_found -> m1, (m2, m1)::table *)
208 (*           in *)
209 (*           m1b, m2b, table *)
210 (*         in *)
211 (*         Printf.printf "table_l: %s\ntable_r: %s\n\n" *)
212 (*           (print_table table_l) (print_table table_r); *)
213         if (m1_binding <> m2) || (m2_binding <> m1) then
214           raise NotMetaConvertible
215         else (
216           try
217             List.fold_left2
218               (fun res t1 t2 ->
219                  match t1, t2 with
220                  | None, Some _ | Some _, None -> raise NotMetaConvertible
221                  | None, None -> res
222                  | Some t1, Some t2 -> (aux res t1 t2))
223               (table_l, table_r) tl1 tl2
224           with Invalid_argument _ ->
225             raise NotMetaConvertible
226         )
227     | C.Var (u1, ens1), C.Var (u2, ens2)
228     | C.Const (u1, ens1), C.Const (u2, ens2) when (UriManager.eq u1 u2) ->
229         aux_ens table ens1 ens2
230     | C.Cast (s1, t1), C.Cast (s2, t2)
231     | C.Prod (_, s1, t1), C.Prod (_, s2, t2)
232     | C.Lambda (_, s1, t1), C.Lambda (_, s2, t2)
233     | C.LetIn (_, s1, t1), C.LetIn (_, s2, t2) ->
234         let table = aux table s1 s2 in
235         aux table t1 t2
236     | C.Appl l1, C.Appl l2 -> (
237         try List.fold_left2 (fun res t1 t2 -> (aux res t1 t2)) table l1 l2
238         with Invalid_argument _ -> raise NotMetaConvertible
239       )
240     | C.MutInd (u1, i1, ens1), C.MutInd (u2, i2, ens2)
241         when (UriManager.eq u1 u2) && i1 = i2 -> aux_ens table ens1 ens2
242     | C.MutConstruct (u1, i1, j1, ens1), C.MutConstruct (u2, i2, j2, ens2)
243         when (UriManager.eq u1 u2) && i1 = i2 && j1 = j2 ->
244         aux_ens table ens1 ens2
245     | C.MutCase (u1, i1, s1, t1, l1), C.MutCase (u2, i2, s2, t2, l2)
246         when (UriManager.eq u1 u2) && i1 = i2 ->
247         let table = aux table s1 s2 in
248         let table = aux table t1 t2 in (
249           try List.fold_left2 (fun res t1 t2 -> (aux res t1 t2)) table l1 l2
250           with Invalid_argument _ -> raise NotMetaConvertible
251         )
252     | C.Fix (i1, il1), C.Fix (i2, il2) when i1 = i2 -> (
253         try
254           List.fold_left2
255             (fun res (n1, i1, s1, t1) (n2, i2, s2, t2) ->
256                if i1 <> i2 then raise NotMetaConvertible
257                else
258                  let res = (aux res s1 s2) in aux res t1 t2)
259             table il1 il2
260         with Invalid_argument _ -> raise NotMetaConvertible
261       )
262     | C.CoFix (i1, il1), C.CoFix (i2, il2) when i1 = i2 -> (
263         try
264           List.fold_left2
265             (fun res (n1, s1, t1) (n2, s2, t2) ->
266                let res = aux res s1 s2 in aux res t1 t2)
267             table il1 il2
268         with Invalid_argument _ -> raise NotMetaConvertible
269       )
270     | t1, t2 when t1 = t2 -> table
271     | _, _ -> raise NotMetaConvertible
272         
273   and aux_ens table ens1 ens2 =
274     let cmp (u1, t1) (u2, t2) =
275       compare (UriManager.string_of_uri u1) (UriManager.string_of_uri u2)
276     in
277     let ens1 = List.sort cmp ens1
278     and ens2 = List.sort cmp ens2 in
279     try
280       List.fold_left2
281         (fun res (u1, t1) (u2, t2) ->
282            if not (UriManager.eq u1 u2) then raise NotMetaConvertible
283            else aux res t1 t2)
284         table ens1 ens2
285     with Invalid_argument _ -> raise NotMetaConvertible
286   in
287   aux table t1 t2
288 ;;
289
290
291 let meta_convertibility_eq eq1 eq2 =
292   let _, _, (ty, left, right, _), _, _ = eq1
293   and _, _, (ty', left', right', _), _, _ = eq2 in
294   if ty <> ty' then
295     false
296   else if (left = left') && (right = right') then
297     true
298   else if (left = right') && (right = left') then
299     true
300   else
301     try
302       let table = meta_convertibility_aux ([], []) left left' in
303       let _ = meta_convertibility_aux table right right' in
304       true
305     with NotMetaConvertible ->
306       try
307         let table = meta_convertibility_aux ([], []) left right' in
308         let _ = meta_convertibility_aux table right left' in
309         true
310       with NotMetaConvertible ->
311         false
312 ;;
313
314
315 let meta_convertibility t1 t2 =
316   let f t =
317     String.concat ", "
318       (List.map
319          (fun (k, v) -> Printf.sprintf "(%d, %d)" k v) t)
320   in
321   if t1 = t2 then
322     true
323   else
324     try
325       let l, r = meta_convertibility_aux ([], []) t1 t2 in
326       (*     Printf.printf "meta_convertibility:\n%s\n%s\n\n" (f l) (f r); *)
327       true
328     with NotMetaConvertible ->
329       false
330 ;;
331
332
333 (*
334 let replace_metas (* context *) term =
335   let module C = Cic in
336   let rec aux = function
337     | C.Meta (i, c) ->
338 (*         let irl = *)
339 (*           CicMkImplicit.identity_relocation_list_for_metavariable context *)
340 (*         in *)
341 (*         if c = irl then *)
342 (*           C.Implicit (Some (`MetaIndex i)) *)
343 (*         else ( *)
344 (*           Printf.printf "WARNING: c non e` un identity_relocation_list!\n%s\n" *)
345 (*             (String.concat "\n" *)
346 (*                (List.map *)
347 (*                   (function None -> "" | Some t -> CicPp.ppterm t) c)); *)
348 (*           C.Meta (i, c) *)
349 (*         ) *)
350         C.Implicit (Some (`MetaInfo (i, c)))
351     | C.Var (u, ens) -> C.Var (u, aux_ens ens)
352     | C.Const (u, ens) -> C.Const (u, aux_ens ens)
353     | C.Cast (s, t) -> C.Cast (aux s, aux t)
354     | C.Prod (name, s, t) -> C.Prod (name, aux s, aux t)
355     | C.Lambda (name, s, t) -> C.Lambda (name, aux s, aux t)
356     | C.LetIn (name, s, t) -> C.LetIn (name, aux s, aux t)
357     | C.Appl l -> C.Appl (List.map aux l)
358     | C.MutInd (uri, i, ens) -> C.MutInd (uri, i, aux_ens ens)
359     | C.MutConstruct (uri, i, j, ens) -> C.MutConstruct (uri, i, j, aux_ens ens)
360     | C.MutCase (uri, i, s, t, l) ->
361         C.MutCase (uri, i, aux s, aux t, List.map aux l)
362     | C.Fix (i, il) ->
363         let il' =
364           List.map (fun (s, i, t1, t2) -> (s, i, aux t1, aux t2)) il in
365         C.Fix (i, il')
366     | C.CoFix (i, il) ->
367         let il' =
368           List.map (fun (s, t1, t2) -> (s, aux t1, aux t2)) il in
369         C.CoFix (i, il')
370     | t -> t
371   and aux_ens ens =
372     List.map (fun (u, t) -> (u, aux t)) ens
373   in
374   aux term
375 ;;
376
377
378 let restore_metas (* context *) term =
379   let module C = Cic in
380   let rec aux = function
381     | C.Implicit (Some (`MetaInfo (i, c))) ->
382 (*         let c = *)
383 (*           CicMkImplicit.identity_relocation_list_for_metavariable context *)
384 (*         in *)
385 (*         C.Meta (i, c) *)
386 (*         let local_context:(C.term option) list = *)
387 (*           Marshal.from_string mc 0 *)
388 (*         in *)
389 (*         C.Meta (i, local_context) *)
390         C.Meta (i, c)
391     | C.Var (u, ens) -> C.Var (u, aux_ens ens)
392     | C.Const (u, ens) -> C.Const (u, aux_ens ens)
393     | C.Cast (s, t) -> C.Cast (aux s, aux t)
394     | C.Prod (name, s, t) -> C.Prod (name, aux s, aux t)
395     | C.Lambda (name, s, t) -> C.Lambda (name, aux s, aux t)
396     | C.LetIn (name, s, t) -> C.LetIn (name, aux s, aux t)
397     | C.Appl l -> C.Appl (List.map aux l)
398     | C.MutInd (uri, i, ens) -> C.MutInd (uri, i, aux_ens ens)
399     | C.MutConstruct (uri, i, j, ens) -> C.MutConstruct (uri, i, j, aux_ens ens)
400     | C.MutCase (uri, i, s, t, l) ->
401         C.MutCase (uri, i, aux s, aux t, List.map aux l)
402     | C.Fix (i, il) ->
403         let il' =
404           List.map (fun (s, i, t1, t2) -> (s, i, aux t1, aux t2)) il in
405         C.Fix (i, il')
406     | C.CoFix (i, il) ->
407         let il' =
408           List.map (fun (s, t1, t2) -> (s, aux t1, aux t2)) il in
409         C.CoFix (i, il')
410     | t -> t
411   and aux_ens ens =
412     List.map (fun (u, t) -> (u, aux t)) ens
413   in
414   aux term
415 ;;
416
417
418 let rec restore_subst (* context *) subst =
419   List.map
420     (fun (i, (c, t, ty)) ->
421        i, (c, restore_metas (* context *) t, ty))
422     subst
423 ;;
424 *)
425
426
427 let rec check_irl start = function
428   | [] -> true
429   | None::tl -> check_irl (start+1) tl
430   | (Some (Cic.Rel x))::tl ->
431       if x = start then check_irl (start+1) tl else false
432   | _ -> false
433 ;;
434
435 let rec is_simple_term = function
436   | Cic.Appl ((Cic.Meta _)::_) -> false
437   | Cic.Appl l -> List.for_all is_simple_term l
438   | Cic.Meta (i, l) -> check_irl 1 l
439   | Cic.Rel _ -> true
440   | Cic.Const _ -> true
441   | _ -> false
442 ;;
443
444
445 let lookup_subst meta subst =
446   match meta with
447   | Cic.Meta (i, _) -> (
448       try let _, (_, t, _) = List.find (fun (m, _) -> m = i) subst in t
449       with Not_found -> meta
450     )
451   | _ -> assert false
452 ;;
453
454
455 let unification_simple metasenv context t1 t2 ugraph =
456   let module C = Cic in
457   let module M = CicMetaSubst in
458   let module U = CicUnification in
459   let lookup = lookup_subst in
460   let rec occurs_check subst what where =
461     match where with
462     | t when what = t -> true
463     | C.Appl l -> List.exists (occurs_check subst what) l
464     | C.Meta _ ->
465         let t = lookup where subst in
466         if t <> where then occurs_check subst what t else false
467     | _ -> false
468   in
469   let rec unif subst menv s t =
470     let s = match s with C.Meta _ -> lookup s subst | _ -> s
471     and t = match t with C.Meta _ -> lookup t subst | _ -> t
472     in
473     match s, t with
474     | s, t when s = t -> subst, menv
475     | C.Meta (i, _), C.Meta (j, _) when i > j ->
476         unif subst menv t s
477     | C.Meta _, t when occurs_check subst s t ->
478         raise (U.UnificationFailure "Inference.unification.unif")
479     | C.Meta (i, l), t ->
480         let _, _, ty = CicUtil.lookup_meta i menv in
481         let subst =
482           if not (List.mem_assoc i subst) then (i, (context, t, ty))::subst
483           else subst
484         in
485         let menv = List.filter (fun (m, _, _) -> i <> m) menv in
486         subst, menv
487     | _, C.Meta _ -> unif subst menv t s
488     | C.Appl (hds::_), C.Appl (hdt::_) when hds <> hdt ->
489         raise (U.UnificationFailure "Inference.unification.unif")
490     | C.Appl (hds::tls), C.Appl (hdt::tlt) -> (
491         try
492           List.fold_left2
493             (fun (subst', menv) s t -> unif subst' menv s t)
494             (subst, menv) tls tlt
495         with e ->
496           raise (U.UnificationFailure "Inference.unification.unif")
497       )
498     | _, _ -> raise (U.UnificationFailure "Inference.unification.unif")
499   in
500   let subst, menv = unif [] metasenv t1 t2 in
501   List.rev subst, menv, ugraph
502 ;;
503
504
505 let unification metasenv context t1 t2 ugraph =
506 (*   Printf.printf "| unification %s %s\n" (CicPp.ppterm t1) (CicPp.ppterm t2); *)
507   let subst, menv, ug =
508     if not (is_simple_term t1) || not (is_simple_term t2) then
509       CicUnification.fo_unif metasenv context t1 t2 ugraph
510     else
511       unification_simple metasenv context t1 t2 ugraph
512   in
513   let rec fix_term = function
514     | (Cic.Meta (i, l) as t) ->
515         let t' = lookup_subst t subst in
516         if t <> t' then fix_term t' else t
517     | Cic.Appl l -> Cic.Appl (List.map fix_term l)
518     | t -> t
519   in
520   let rec fix_subst = function
521     | [] -> []
522     | (i, (c, t, ty))::tl -> (i, (c, fix_term t, fix_term ty))::(fix_subst tl)
523   in
524 (*   Printf.printf "| subst: %s\n" (print_subst ~prefix:" ; " subst); *)
525 (*   print_endline "|"; *)
526   fix_subst subst, menv, ug
527 ;;
528
529
530 (* let unification = CicUnification.fo_unif;; *)
531
532 exception MatchingFailure;;
533
534
535 let matching_simple metasenv context t1 t2 ugraph =
536   let module C = Cic in
537   let module M = CicMetaSubst in
538   let module U = CicUnification in
539   let lookup meta subst =
540     match meta with
541     | C.Meta (i, _) -> (
542         try let _, (_, t, _) = List.find (fun (m, _) -> m = i) subst in t
543         with Not_found -> meta
544       )
545     | _ -> assert false
546   in
547   let rec do_match subst menv s t =
548 (*     Printf.printf "do_match %s %s\n%s\n" (CicPp.ppterm s) (CicPp.ppterm t) *)
549 (*       (print_subst subst); *)
550 (*     print_newline (); *)
551 (*     let s = match s with C.Meta _ -> lookup s subst | _ -> s *)
552 (*     let t = match t with C.Meta _ -> lookup t subst | _ -> t in  *)
553     (*       Printf.printf "after apply_subst: %s %s\n%s" *)
554     (*         (CicPp.ppterm s) (CicPp.ppterm t) (print_subst subst); *)
555     (*       print_newline (); *)
556     match s, t with
557     | s, t when s = t -> subst, menv
558 (*     | C.Meta (i, _), C.Meta (j, _) when i > j -> *)
559 (*         do_match subst menv t s *)
560 (*     | C.Meta _, t when occurs_check subst s t -> *)
561 (*         raise MatchingFailure *)
562 (*     | s, C.Meta _ when occurs_check subst t s -> *)
563 (*         raise MatchingFailure *)
564     | s, C.Meta (i, l) ->
565         let filter_menv i menv =
566           List.filter (fun (m, _, _) -> i <> m) menv
567         in
568         let subst, menv =
569           let value = lookup t subst in
570           match value with
571 (*           | C.Meta (i', l') when Hashtbl.mem table i' -> *)
572 (*               (i', (context, s, ty))::subst, menv (\* filter_menv i' menv *\) *)
573           | value when value = t ->
574               let _, _, ty = CicUtil.lookup_meta i menv in
575               (i, (context, s, ty))::subst, filter_menv i menv
576           | value when value <> s ->
577               raise MatchingFailure
578           | value -> do_match subst menv s value
579         in
580         subst, menv
581 (*           else if value <> s then *)
582 (*             raise MatchingFailure *)
583 (*           else subst *)
584 (*           if not (List.mem_assoc i subst) then (i, (context, t, ty))::subst *)
585 (*           else subst *)
586 (*         in *)
587 (*         let menv = List.filter (fun (m, _, _) -> i <> m) menv in *)
588 (*         subst, menv *)
589 (*     | _, C.Meta _ -> do_match subst menv t s *)
590 (*     | C.Appl (hds::_), C.Appl (hdt::_) when hds <> hdt -> *)
591 (*         raise MatchingFailure *)
592     | C.Appl ls, C.Appl lt -> (
593         try
594           List.fold_left2
595             (fun (subst, menv) s t -> do_match subst menv s t)
596             (subst, menv) ls lt
597         with e ->
598 (*           print_endline (Printexc.to_string e); *)
599 (*           Printf.printf "NO MATCH: %s %s\n" (CicPp.ppterm s) (CicPp.ppterm t); *)
600 (*           print_newline ();           *)
601           raise MatchingFailure
602       )
603     | _, _ ->
604 (*         Printf.printf "NO MATCH: %s %s\n" (CicPp.ppterm s) (CicPp.ppterm t); *)
605 (*         print_newline (); *)
606         raise MatchingFailure
607   in
608   let subst, menv = do_match [] metasenv t1 t2 in
609   (*     Printf.printf "DONE!: subst = \n%s\n" (print_subst subst); *)
610   (*     print_newline (); *)
611   subst, menv, ugraph
612 ;;
613
614
615 let matching metasenv context t1 t2 ugraph =
616 (*   if (is_simple_term t1) && (is_simple_term t2) then *)
617 (*     let subst, menv, ug = *)
618 (*       matching_simple metasenv context t1 t2 ugraph in *)
619 (* (\*     Printf.printf "matching %s %s:\n%s\n" *\) *)
620 (* (\*       (CicPp.ppterm t1) (CicPp.ppterm t2) (print_subst subst); *\) *)
621 (* (\*     print_newline (); *\) *)
622 (*     subst, menv, ug *)
623 (*   else *)
624 (*   Printf.printf "matching %s %s" (CicPp.ppterm t1) (CicPp.ppterm t2); *)
625 (*   print_newline (); *)
626     try
627       let subst, metasenv, ugraph =
628         (*       CicUnification.fo_unif metasenv context t1 t2 ugraph *)
629         unification metasenv context t1 t2 ugraph
630       in
631       let t' = CicMetaSubst.apply_subst subst t1 in
632       if not (meta_convertibility t1 t') then
633         raise MatchingFailure
634       else
635         let metas = metas_of_term t1 in
636         let fix_subst = function
637           | (i, (c, Cic.Meta (j, lc), ty)) when List.mem i metas ->
638               (j, (c, Cic.Meta (i, lc), ty))
639           | s -> s
640         in
641         let subst = List.map fix_subst subst in
642
643 (*         Printf.printf "matching %s %s:\n%s\n" *)
644 (*           (CicPp.ppterm t1) (CicPp.ppterm t2) (print_subst subst); *)
645 (*         print_newline (); *)
646
647         subst, metasenv, ugraph
648     with e ->
649 (*       Printf.printf "failed to match %s %s\n" *)
650 (*         (CicPp.ppterm t1) (CicPp.ppterm t2); *)
651 (*       print_endline (Printexc.to_string e); *)
652       raise MatchingFailure
653 ;;
654
655 (* let matching = *)
656 (*   let profile = CicUtil.profile "Inference.matching" in *)
657 (*   (fun metasenv context t1 t2 ugraph -> *)
658 (*      profile (matching metasenv context t1 t2) ugraph) *)
659 (* ;; *)
660
661
662 let beta_expand ?(metas_ok=true) ?(match_only=false)
663     what type_of_what where context metasenv ugraph = 
664   let module S = CicSubstitution in
665   let module C = Cic in
666
667   let print_info = false in
668   
669 (*   let _ = *)
670 (*     let names = names_of_context context in *)
671 (*     Printf.printf "beta_expand:\nwhat: %s, %s\nwhere: %s, %s\n" *)
672 (*       (CicPp.pp what names) (CicPp.ppterm what) *)
673 (*       (CicPp.pp where names) (CicPp.ppterm where); *)
674 (*     print_newline (); *)
675 (*   in *)
676   (*
677     return value:
678     ((list of all possible beta expansions, subst, metasenv, ugraph),
679      lifted term)
680   *)
681   let rec aux lift_amount term context metasenv subst ugraph =
682 (*     Printf.printf "enter aux %s\n" (CicPp.ppterm term); *)
683     let res, lifted_term = 
684       match term with
685       | C.Rel m  ->
686           [], if m <= lift_amount then C.Rel m else C.Rel (m+1)
687             
688       | C.Var (uri, exp_named_subst) ->
689           let ens', lifted_ens =
690             aux_ens lift_amount exp_named_subst context metasenv subst ugraph
691           in
692           let expansions = 
693             List.map
694               (fun (e, s, m, ug) ->
695                  (C.Var (uri, e), s, m, ug)) ens'
696           in
697           expansions, C.Var (uri, lifted_ens)
698             
699       | C.Meta (i, l) ->
700           let l', lifted_l = 
701             List.fold_right
702               (fun arg (res, lifted_tl) ->
703                  match arg with
704                  | Some arg ->
705                      let arg_res, lifted_arg =
706                        aux lift_amount arg context metasenv subst ugraph in
707                      let l1 =
708                        List.map
709                          (fun (a, s, m, ug) -> (Some a)::lifted_tl, s, m, ug)
710                          arg_res
711                      in
712                      (l1 @
713                         (List.map
714                            (fun (r, s, m, ug) -> (Some lifted_arg)::r, s, m, ug)
715                            res),
716                       (Some lifted_arg)::lifted_tl)
717                  | None ->
718                      (List.map
719                         (fun (r, s, m, ug) -> None::r, s, m, ug)
720                         res, 
721                       None::lifted_tl)
722               ) l ([], [])
723           in
724           let e = 
725             List.map
726               (fun (l, s, m, ug) ->
727                  (C.Meta (i, l), s, m, ug)) l'
728           in
729           e, C.Meta (i, lifted_l)
730             
731       | C.Sort _
732       | C.Implicit _ as t -> [], t
733           
734       | C.Cast (s, t) ->
735           let l1, lifted_s =
736             aux lift_amount s context metasenv subst ugraph in
737           let l2, lifted_t =
738             aux lift_amount t context metasenv subst ugraph
739           in
740           let l1' =
741             List.map
742               (fun (t, s, m, ug) ->
743                  C.Cast (t, lifted_t), s, m, ug) l1 in
744           let l2' =
745             List.map
746               (fun (t, s, m, ug) ->
747                  C.Cast (lifted_s, t), s, m, ug) l2 in
748           l1'@l2', C.Cast (lifted_s, lifted_t)
749             
750       | C.Prod (nn, s, t) ->
751           let l1, lifted_s =
752             aux lift_amount s context metasenv subst ugraph in
753           let l2, lifted_t =
754             aux (lift_amount+1) t ((Some (nn, C.Decl s))::context)
755               metasenv subst ugraph
756           in
757           let l1' =
758             List.map
759               (fun (t, s, m, ug) ->
760                  C.Prod (nn, t, lifted_t), s, m, ug) l1 in
761           let l2' =
762             List.map
763               (fun (t, s, m, ug) ->
764                  C.Prod (nn, lifted_s, t), s, m, ug) l2 in
765           l1'@l2', C.Prod (nn, lifted_s, lifted_t)
766
767       | C.Lambda (nn, s, t) ->
768           let l1, lifted_s =
769             aux lift_amount s context metasenv subst ugraph in
770           let l2, lifted_t =
771             aux (lift_amount+1) t ((Some (nn, C.Decl s))::context)
772               metasenv subst ugraph
773           in
774           let l1' =
775             List.map
776               (fun (t, s, m, ug) ->
777                  C.Lambda (nn, t, lifted_t), s, m, ug) l1 in
778           let l2' =
779             List.map
780               (fun (t, s, m, ug) ->
781                  C.Lambda (nn, lifted_s, t), s, m, ug) l2 in
782           l1'@l2', C.Lambda (nn, lifted_s, lifted_t)
783
784       | C.LetIn (nn, s, t) ->
785           let l1, lifted_s =
786             aux lift_amount s context metasenv subst ugraph in
787           let l2, lifted_t =
788             aux (lift_amount+1) t ((Some (nn, C.Def (s, None)))::context)
789               metasenv subst ugraph
790           in
791           let l1' =
792             List.map
793               (fun (t, s, m, ug) ->
794                  C.LetIn (nn, t, lifted_t), s, m, ug) l1 in
795           let l2' =
796             List.map
797               (fun (t, s, m, ug) ->
798                  C.LetIn (nn, lifted_s, t), s, m, ug) l2 in
799           l1'@l2', C.LetIn (nn, lifted_s, lifted_t)
800
801       | C.Appl l ->
802           let l', lifted_l =
803             aux_list lift_amount l context metasenv subst ugraph
804           in
805           (List.map (fun (l, s, m, ug) -> (C.Appl l, s, m, ug)) l',
806            C.Appl lifted_l)
807             
808       | C.Const (uri, exp_named_subst) ->
809           let ens', lifted_ens =
810             aux_ens lift_amount exp_named_subst context metasenv subst ugraph
811           in
812           let expansions = 
813             List.map
814               (fun (e, s, m, ug) ->
815                  (C.Const (uri, e), s, m, ug)) ens'
816           in
817           (expansions, C.Const (uri, lifted_ens))
818
819       | C.MutInd (uri, i ,exp_named_subst) ->
820           let ens', lifted_ens =
821             aux_ens lift_amount exp_named_subst context metasenv subst ugraph
822           in
823           let expansions = 
824             List.map
825               (fun (e, s, m, ug) ->
826                  (C.MutInd (uri, i, e), s, m, ug)) ens'
827           in
828           (expansions, C.MutInd (uri, i, lifted_ens))
829
830       | C.MutConstruct (uri, i, j, exp_named_subst) ->
831           let ens', lifted_ens =
832             aux_ens lift_amount exp_named_subst context metasenv subst ugraph
833           in
834           let expansions = 
835             List.map
836               (fun (e, s, m, ug) ->
837                  (C.MutConstruct (uri, i, j, e), s, m, ug)) ens'
838           in
839           (expansions, C.MutConstruct (uri, i, j, lifted_ens))
840
841       | C.MutCase (sp, i, outt, t, pl) ->
842           let pl_res, lifted_pl =
843             aux_list lift_amount pl context metasenv subst ugraph
844           in
845           let l1, lifted_outt =
846             aux lift_amount outt context metasenv subst ugraph in
847           let l2, lifted_t =
848             aux lift_amount t context metasenv subst ugraph in
849
850           let l1' =
851             List.map
852               (fun (outt, s, m, ug) ->
853                  C.MutCase (sp, i, outt, lifted_t, lifted_pl), s, m, ug) l1 in
854           let l2' =
855             List.map
856               (fun (t, s, m, ug) ->
857                  C.MutCase (sp, i, lifted_outt, t, lifted_pl), s, m, ug) l2 in
858           let l3' =
859             List.map
860               (fun (pl, s, m, ug) ->
861                  C.MutCase (sp, i, lifted_outt, lifted_t, pl), s, m, ug) pl_res
862           in
863           (l1'@l2'@l3', C.MutCase (sp, i, lifted_outt, lifted_t, lifted_pl))
864
865       | C.Fix (i, fl) ->
866           let len = List.length fl in
867           let fl', lifted_fl =
868             List.fold_right
869               (fun (nm, idx, ty, bo) (res, lifted_tl) ->
870                  let lifted_ty = S.lift lift_amount ty in
871                  let bo_res, lifted_bo =
872                    aux (lift_amount+len) bo context metasenv subst ugraph in
873                  let l1 =
874                    List.map
875                      (fun (a, s, m, ug) ->
876                         (nm, idx, lifted_ty, a)::lifted_tl, s, m, ug)
877                      bo_res
878                  in
879                  (l1 @
880                     (List.map
881                        (fun (r, s, m, ug) ->
882                           (nm, idx, lifted_ty, lifted_bo)::r, s, m, ug) res),
883                   (nm, idx, lifted_ty, lifted_bo)::lifted_tl)
884               ) fl ([], [])
885           in
886           (List.map
887              (fun (fl, s, m, ug) -> C.Fix (i, fl), s, m, ug) fl',
888            C.Fix (i, lifted_fl))
889             
890       | C.CoFix (i, fl) ->
891           let len = List.length fl in
892           let fl', lifted_fl =
893             List.fold_right
894               (fun (nm, ty, bo) (res, lifted_tl) ->
895                  let lifted_ty = S.lift lift_amount ty in
896                  let bo_res, lifted_bo =
897                    aux (lift_amount+len) bo context metasenv subst ugraph in
898                  let l1 =
899                    List.map
900                      (fun (a, s, m, ug) ->
901                         (nm, lifted_ty, a)::lifted_tl, s, m, ug)
902                      bo_res
903                  in
904                  (l1 @
905                     (List.map
906                        (fun (r, s, m, ug) ->
907                           (nm, lifted_ty, lifted_bo)::r, s, m, ug) res),
908                   (nm, lifted_ty, lifted_bo)::lifted_tl)
909               ) fl ([], [])
910           in
911           (List.map
912              (fun (fl, s, m, ug) -> C.CoFix (i, fl), s, m, ug) fl',
913            C.CoFix (i, lifted_fl))
914     in
915     let retval = 
916       match term with
917       | C.Meta _ when (not metas_ok) ->
918           res, lifted_term
919       | _ ->
920 (*           let term' = *)
921 (*             if match_only then replace_metas context term *)
922 (*             else term *)
923 (*           in *)
924           try
925             let subst', metasenv', ugraph' =
926 (*               Printf.printf "provo a unificare %s e %s\n" *)
927 (*                 (CicPp.ppterm (S.lift lift_amount what)) (CicPp.ppterm term); *)
928               if match_only then
929                 matching metasenv context term (S.lift lift_amount what) ugraph
930               else
931                 CicUnification.fo_unif metasenv context
932                   (S.lift lift_amount what) term ugraph
933             in
934 (*           Printf.printf "Ok, trovato: %s\n\nwhat: %s" (CicPp.ppterm term) *)
935 (*             (CicPp.ppterm (S.lift lift_amount what)); *)
936 (*           Printf.printf "substitution:\n%s\n\n" (print_subst subst'); *)
937 (*           Printf.printf "metasenv': %s\n" (print_metasenv metasenv'); *)
938             (* Printf.printf "metasenv: %s\n\n" (print_metasenv metasenv); *)
939 (*             if match_only then *)
940 (*               let t' = CicMetaSubst.apply_subst subst' term in *)
941 (*               if not (meta_convertibility term t') then ( *)
942 (*                 res, lifted_term *)
943 (*               ) else ( *)
944 (*                 let metas = metas_of_term term in *)
945 (*                 let fix_subst = function *)
946 (*                   | (i, (c, C.Meta (j, lc), ty)) when List.mem i metas -> *)
947 (*                       (j, (c, C.Meta (i, lc), ty)) *)
948 (*                   | s -> s *)
949 (*                 in *)
950 (*                 let subst' = List.map fix_subst subst' in *)
951 (*                 ((C.Rel (1 + lift_amount), subst', metasenv', ugraph')::res, *)
952 (*                  lifted_term) *)
953 (*               ) *)
954 (*             else *)
955               ((C.Rel (1 + lift_amount), subst', metasenv', ugraph')::res,
956                lifted_term)
957           with e ->
958             if print_info then (
959               print_endline ("beta_expand ERROR!: " ^ (Printexc.to_string e));
960             );
961             res, lifted_term
962     in
963 (*     Printf.printf "exit aux\n"; *)
964     retval
965
966   and aux_list lift_amount l context metasenv subst ugraph =
967     List.fold_right
968       (fun arg (res, lifted_tl) ->
969          let arg_res, lifted_arg =
970            aux lift_amount arg context metasenv subst ugraph in
971          let l1 = List.map
972            (fun (a, s, m, ug) -> a::lifted_tl, s, m, ug) arg_res
973          in
974          (l1 @ (List.map
975                   (fun (r, s, m, ug) -> lifted_arg::r, s, m, ug) res),
976           lifted_arg::lifted_tl)
977       ) l ([], [])
978
979   and aux_ens lift_amount exp_named_subst context metasenv subst ugraph =
980     List.fold_right
981       (fun (u, arg) (res, lifted_tl) ->
982          let arg_res, lifted_arg =
983            aux lift_amount arg context metasenv subst ugraph in
984          let l1 =
985            List.map
986              (fun (a, s, m, ug) -> (u, a)::lifted_tl, s, m, ug) arg_res
987          in
988          (l1 @ (List.map (fun (r, s, m, ug) ->
989                             (u, lifted_arg)::r, s, m, ug) res),
990           (u, lifted_arg)::lifted_tl)
991       ) exp_named_subst ([], [])
992
993   in
994   let expansions, _ =
995 (*     let where = *)
996 (*       if match_only then replace_metas (\* context *\) where *)
997 (*       else where *)
998 (*     in *)
999     if print_info then (
1000       Printf.printf "searching %s inside %s\n"
1001         (CicPp.ppterm what) (CicPp.ppterm where);
1002     );
1003     aux 0 where context metasenv [] ugraph
1004   in
1005   let mapfun =
1006 (*     if match_only then *)
1007 (*       (fun (term, subst, metasenv, ugraph) -> *)
1008 (*          let term' = *)
1009 (*            C.Lambda (C.Anonymous, type_of_what, restore_metas term) *)
1010 (*          and subst = restore_subst subst in *)
1011 (*          (term', subst, metasenv, ugraph)) *)
1012 (*     else *)
1013       (fun (term, subst, metasenv, ugraph) ->
1014          let term' = C.Lambda (C.Anonymous, type_of_what, term) in
1015          (term', subst, metasenv, ugraph))
1016   in
1017   List.map mapfun expansions
1018 ;;
1019
1020
1021 let find_equalities ?(eq_uri=HelmLibraryObjects.Logic.eq_URI) context proof =
1022   let module C = Cic in
1023   let module S = CicSubstitution in
1024   let module T = CicTypeChecker in
1025   let newmeta = ProofEngineHelpers.new_meta_of_proof ~proof in
1026   let ok_types ty menv =
1027     List.for_all (fun (_, _, mt) -> mt = ty) menv
1028   in
1029   let rec aux index newmeta = function
1030     | [] -> [], newmeta
1031     | (Some (_, C.Decl (term)))::tl ->
1032         let do_find context term =
1033           match term with
1034           | C.Prod (name, s, t) ->
1035 (*               let newmeta = ProofEngineHelpers.new_meta_of_proof ~proof in *)
1036               let (head, newmetas, args, newmeta) =
1037                 ProofEngineHelpers.saturate_term newmeta []
1038                   context (S.lift index term)
1039               in
1040               let p =
1041                 if List.length args = 0 then
1042                   C.Rel index
1043                 else
1044                   C.Appl ((C.Rel index)::args)
1045               in (
1046                 match head with
1047                 | C.Appl [C.MutInd (uri, _, _); ty; t1; t2]
1048                     when (UriManager.eq uri eq_uri) && (ok_types ty newmetas) ->
1049                     debug_print (
1050                       Printf.sprintf "OK: %s" (CicPp.ppterm term));
1051 (*                     debug_print ( *)
1052 (*                       Printf.sprintf "args: %s\n" *)
1053 (*                         (String.concat ", " (List.map CicPp.ppterm args))); *)
1054 (*                     debug_print ( *)
1055 (*                       Printf.sprintf "newmetas:\n%s\n" *)
1056 (*                         (print_metasenv newmetas)); *)
1057                     let o = !Utils.compare_terms t1 t2 in
1058                     let w = compute_equality_weight ty t1 t2 in
1059                     let proof = BasicProof p in
1060                     let e = (w, proof, (ty, t1, t2, o), newmetas, args) in
1061                     Some e, (newmeta+1)
1062                 | _ -> None, newmeta
1063               )
1064           | C.Appl [C.MutInd (uri, _, _); ty; t1; t2]
1065               when UriManager.eq uri eq_uri ->
1066               let t1 = S.lift index t1
1067               and t2 = S.lift index t2 in
1068               let o = !Utils.compare_terms t1 t2 in
1069               let w = compute_equality_weight ty t1 t2 in
1070               let e = (w, BasicProof (C.Rel index), (ty, t1, t2, o), [], []) in
1071               Some e, (newmeta+1)
1072           | _ -> None, newmeta
1073         in (
1074           match do_find context term with
1075           | Some p, newmeta ->
1076               let tl, newmeta' = (aux (index+1) newmeta tl) in
1077               p::tl, max newmeta newmeta'
1078           | None, _ ->
1079               aux (index+1) newmeta tl
1080         )
1081     | _::tl ->
1082         aux (index+1) newmeta tl
1083   in
1084   aux 1 newmeta context
1085 ;;
1086
1087
1088 let equations_blacklist =
1089   List.fold_left
1090     (fun s u -> UriManager.UriSet.add (UriManager.uri_of_string u) s)
1091     UriManager.UriSet.empty [
1092       "cic:/Coq/Init/Logic/eq.ind#xpointer(1/1/1)";
1093       "cic:/Coq/Init/Logic/trans_eq.con";
1094       "cic:/Coq/Init/Logic/f_equal.con";
1095       "cic:/Coq/Init/Logic/f_equal2.con";
1096       "cic:/Coq/Init/Logic/f_equal3.con";
1097       "cic:/Coq/Init/Logic/sym_eq.con";
1098 (*       "cic:/Coq/Logic/Eqdep/UIP_refl.con"; *)
1099     ]
1100 ;;
1101
1102 let find_library_equalities ~(dbd:Mysql.dbd) context status maxmeta = 
1103   let module C = Cic in
1104   let module S = CicSubstitution in
1105   let module T = CicTypeChecker in
1106   let candidates =
1107     List.fold_left
1108       (fun l uri ->
1109          if UriManager.UriSet.mem uri equations_blacklist then
1110            l
1111          else
1112            let t = CicUtil.term_of_uri uri in
1113            let ty, _ =
1114              CicTypeChecker.type_of_aux' [] context t CicUniv.empty_ugraph
1115            in
1116            (t, ty)::l)
1117       []
1118       (MetadataQuery.equations_for_goal ~dbd status)
1119   in
1120   let eq_uri1 = UriManager.uri_of_string HelmLibraryObjects.Logic.eq_XURI
1121   and eq_uri2 = HelmLibraryObjects.Logic.eq_URI in
1122   let iseq uri =
1123     (UriManager.eq uri eq_uri1) || (UriManager.eq uri eq_uri2)
1124   in
1125   let ok_types ty menv =
1126     List.for_all (fun (_, _, mt) -> mt = ty) menv
1127   in
1128   let rec aux newmeta = function
1129     | [] -> [], newmeta
1130     | (term, termty)::tl ->
1131         let res, newmeta = 
1132           match termty with
1133           | C.Prod (name, s, t) ->
1134               let head, newmetas, args, newmeta =
1135                 ProofEngineHelpers.saturate_term newmeta [] context termty
1136               in
1137               let p =
1138                 if List.length args = 0 then
1139                   term
1140                 else
1141                   C.Appl (term::args)
1142               in (
1143                 match head with
1144                 | C.Appl [C.MutInd (uri, _, _); ty; t1; t2]
1145                     when (iseq uri) && (ok_types ty newmetas) ->
1146                     debug_print (
1147                       Printf.sprintf "OK: %s" (CicPp.ppterm term));
1148                     let o = !Utils.compare_terms t1 t2 in
1149                     let w = compute_equality_weight ty t1 t2 in
1150                     let proof = BasicProof p in
1151                     let e = (w, proof, (ty, t1, t2, o), newmetas, args) in
1152                     Some e, (newmeta+1)
1153                 | _ -> None, newmeta
1154               )
1155           | C.Appl [C.MutInd (uri, _, _); ty; t1; t2] when iseq uri ->
1156               let o = !Utils.compare_terms t1 t2 in
1157               let w = compute_equality_weight ty t1 t2 in
1158               let e = (w, BasicProof term, (ty, t1, t2, o), [], []) in
1159               Some e, (newmeta+1)
1160           | _ -> None, newmeta
1161         in
1162         match res with
1163         | Some e ->
1164             let tl, newmeta' = aux newmeta tl in
1165             e::tl, max newmeta newmeta'
1166         | None ->
1167             aux newmeta tl
1168   in
1169   aux maxmeta candidates
1170 ;;
1171
1172
1173 let fix_metas newmeta ((w, p, (ty, left, right, o), menv, args) as equality) =
1174 (*   print_endline ("fix_metas " ^ (string_of_int newmeta)); *)
1175   let table = Hashtbl.create (List.length args) in
1176   let is_this_case = ref false in
1177   let newargs, newmeta =
1178     List.fold_right
1179       (fun t (newargs, index) ->
1180          match t with
1181          | Cic.Meta (i, l) ->
1182              Hashtbl.add table i index;
1183 (*              if index = 5469 then ( *)
1184 (*                Printf.printf "?5469 COMES FROM (%d): %s\n" *)
1185 (*                  i (string_of_equality equality); *)
1186 (*                print_newline (); *)
1187 (*                is_this_case := true *)
1188 (*              ); *)
1189              ((Cic.Meta (index, l))::newargs, index+1)
1190          | _ -> assert false)
1191       args ([], newmeta+1)
1192   in
1193   let repl where =
1194     ProofEngineReduction.replace ~equality:(=) ~what:args ~with_what:newargs
1195       ~where
1196   in
1197   let menv' =
1198     List.fold_right
1199       (fun (i, context, term) menv ->
1200          try
1201            let index = Hashtbl.find table i in
1202            (index, context, term)::menv
1203          with Not_found ->
1204            (i, context, term)::menv)
1205       menv []
1206   in
1207   let ty = repl ty
1208   and left = repl left
1209   and right = repl right in
1210   let metas = (metas_of_term left) @ (metas_of_term right) in
1211   let menv' = List.filter (fun (i, _, _) -> List.mem i metas) menv'
1212   and newargs =
1213     List.filter
1214       (function Cic.Meta (i, _) -> List.mem i metas | _ -> assert false) newargs
1215   in
1216   let rec fix_proof = function
1217     | NoProof -> NoProof
1218     | BasicProof term -> BasicProof (repl term)
1219     | ProofBlock (subst, eq_URI, t', (pos, eq), p) ->
1220
1221 (*         Printf.printf "fix_proof of equality %s, subst is:\n%s\n" *)
1222 (*           (string_of_equality equality) (print_subst subst); *)
1223         
1224         let subst' =
1225           List.fold_left
1226             (fun s arg ->
1227                match arg with
1228                | Cic.Meta (i, l) -> (
1229                    try
1230                      let j = Hashtbl.find table i in
1231                      if List.mem_assoc i subst then
1232                        s
1233                      else
1234 (*                        let _, context, ty = CicUtil.lookup_meta j menv' in *)
1235 (*                        (i, (context, Cic.Meta (j, l), ty))::s *)
1236                        let _, context, ty = CicUtil.lookup_meta i menv in
1237                        (i, (context, Cic.Meta (j, l), ty))::s
1238                    with _ -> s
1239                  )
1240                | _ -> assert false)
1241             [] args
1242         in
1243 (*         let subst'' = *)
1244 (*           List.map *)
1245 (*             (fun (i, e) -> *)
1246 (*                try let j = Hashtbl.find table i in (j, e) *)
1247 (*                with _ -> (i, e)) subst *)
1248 (*         in *)
1249
1250 (*         Printf.printf "subst' is:\n%s\n" (print_subst subst'); *)
1251 (*         print_newline (); *)
1252         
1253         ProofBlock (subst' @ subst, eq_URI, t', (pos, eq), p)
1254 (*     | ProofSymBlock (ens, p) -> *)
1255 (*         let ens' = List.map (fun (u, t) -> (u, repl t)) ens in *)
1256 (*         ProofSymBlock (ens', fix_proof p) *)
1257     | p -> assert false
1258   in
1259 (*   (newmeta + (List.length newargs) + 2, *)
1260   let neweq = (w, fix_proof p, (ty, left, right, o), menv', newargs) in
1261 (*   if !is_this_case then ( *)
1262 (*     print_endline "\nTHIS IS THE TROUBLE!!!"; *)
1263 (*     let pt = build_proof_term neweq in *)
1264 (*     Printf.printf "equality: %s\nproof: %s\n" *)
1265 (*       (string_of_equality neweq) (CicPp.ppterm pt); *)
1266 (*     print_endline (String.make 79 '-'); *)
1267 (*   ); *)
1268   (newmeta + 1, neweq)
1269 (*    (w, fix_proof p, (ty, left, right, o), menv', newargs)) *)
1270 ;;
1271
1272
1273 let term_is_equality ?(eq_uri=HelmLibraryObjects.Logic.eq_URI) term =
1274   let iseq uri = UriManager.eq uri eq_uri in
1275   match term with
1276   | Cic.Appl [Cic.MutInd (uri, _, _); _; _; _] when iseq uri -> true
1277   | _ -> false
1278 ;;
1279
1280
1281 exception TermIsNotAnEquality;;
1282
1283 let equality_of_term ?(eq_uri=HelmLibraryObjects.Logic.eq_URI) proof term =
1284   let iseq uri = UriManager.eq uri eq_uri in
1285   match term with
1286   | Cic.Appl [Cic.MutInd (uri, _, _); ty; t1; t2] when iseq uri ->
1287       let o = !Utils.compare_terms t1 t2 in
1288       let w = compute_equality_weight ty t1 t2 in
1289       let e = (w, BasicProof proof, (ty, t1, t2, o), [], []) in
1290       e
1291 (*       (proof, (ty, t1, t2, o), [], []) *)
1292   | _ ->
1293       raise TermIsNotAnEquality
1294 ;;
1295
1296
1297 type environment = Cic.metasenv * Cic.context * CicUniv.universe_graph;;
1298
1299
1300 (*
1301 let superposition_left (metasenv, context, ugraph) target source =
1302   let module C = Cic in
1303   let module S = CicSubstitution in
1304   let module M = CicMetaSubst in
1305   let module HL = HelmLibraryObjects in
1306   let module CR = CicReduction in
1307   (* we assume that target is ground (does not contain metavariables): this
1308    * should always be the case (I hope, at least) *)
1309   let proof, (eq_ty, left, right, t_order), _, _ = target in
1310   let eqproof, (ty, t1, t2, s_order), newmetas, args = source in
1311
1312   let compare_terms = !Utils.compare_terms in
1313
1314   if eq_ty <> ty then
1315     []
1316   else    
1317     let where, is_left =
1318       match t_order (* compare_terms left right *) with
1319       | Lt -> right, false
1320       | Gt -> left, true
1321       | _ -> (
1322           Printf.printf "????????? %s = %s" (CicPp.ppterm left)
1323             (CicPp.ppterm right);
1324           print_newline ();
1325           assert false (* again, for ground terms this shouldn't happen... *)
1326         )
1327     in
1328     let metasenv' = newmetas @ metasenv in
1329     let result = s_order (* compare_terms t1 t2 *) in
1330     let res1, res2 = 
1331       match result with
1332       | Gt -> (beta_expand t1 ty where context metasenv' ugraph), []
1333       | Lt -> [], (beta_expand t2 ty where context metasenv' ugraph)
1334       | _ ->
1335           let res1 =
1336             List.filter
1337               (fun (t, s, m, ug) ->
1338                  compare_terms (M.apply_subst s t1) (M.apply_subst s t2) = Gt)
1339               (beta_expand t1 ty where context metasenv' ugraph)
1340           and res2 =
1341             List.filter
1342               (fun (t, s, m, ug) ->
1343                  compare_terms (M.apply_subst s t2) (M.apply_subst s t1) = Gt)
1344               (beta_expand t2 ty where context metasenv' ugraph)
1345           in
1346           res1, res2
1347     in
1348     (*   let what, other = *)
1349     (*     if is_left then left, right *)
1350     (*     else right, left *)
1351     (*   in *)
1352     let build_new what other eq_URI (t, s, m, ug) =
1353       let newgoal, newgoalproof =
1354         match t with
1355         | C.Lambda (nn, ty, bo) ->
1356             let bo' = S.subst (M.apply_subst s other) bo in
1357             let bo'' =
1358               C.Appl (
1359                 [C.MutInd (HL.Logic.eq_URI, 0, []);
1360                  S.lift 1 eq_ty] @
1361                   if is_left then [bo'; S.lift 1 right]
1362                   else [S.lift 1 left; bo'])
1363             in
1364             let t' = C.Lambda (nn, ty, bo'') in
1365             S.subst (M.apply_subst s other) bo,
1366             M.apply_subst s
1367               (C.Appl [C.Const (eq_URI, []); ty; what; t';
1368                        proof; other; eqproof])
1369         | _ -> assert false
1370       in
1371       let equation =
1372         if is_left then (eq_ty, newgoal, right, compare_terms newgoal right)
1373         else (eq_ty, left, newgoal, compare_terms left newgoal)
1374       in
1375       (newgoalproof (* eqproof *), equation, [], [])
1376     in
1377     let new1 = List.map (build_new t1 t2 HL.Logic.eq_ind_URI) res1
1378     and new2 = List.map (build_new t2 t1 HL.Logic.eq_ind_r_URI) res2 in
1379     new1 @ new2
1380 ;;
1381
1382
1383 let superposition_right newmeta (metasenv, context, ugraph) target source =
1384   let module C = Cic in
1385   let module S = CicSubstitution in
1386   let module M = CicMetaSubst in
1387   let module HL = HelmLibraryObjects in
1388   let module CR = CicReduction in
1389   let eqproof, (eq_ty, left, right, t_order), newmetas, args = target in
1390   let eqp', (ty', t1, t2, s_order), newm', args' = source in
1391   let maxmeta = ref newmeta in
1392
1393   let compare_terms = !Utils.compare_terms in
1394
1395   if eq_ty <> ty' then
1396     newmeta, []
1397   else
1398     (*   let ok term subst other other_eq_side ugraph = *)
1399     (*     match term with *)
1400     (*     | C.Lambda (nn, ty, bo) -> *)
1401     (*         let bo' = S.subst (M.apply_subst subst other) bo in *)
1402     (*         let res, _ = CR.are_convertible context bo' other_eq_side ugraph in *)
1403     (*         not res *)
1404     (*     |  _ -> assert false *)
1405     (*   in *)
1406     let condition left right what other (t, s, m, ug) =
1407       let subst = M.apply_subst s in
1408       let cmp1 = compare_terms (subst what) (subst other) in
1409       let cmp2 = compare_terms (subst left) (subst right) in
1410       (*     cmp1 = Gt && cmp2 = Gt *)
1411       cmp1 <> Lt && cmp1 <> Le && cmp2 <> Lt && cmp2 <> Le
1412         (*     && (ok t s other right ug) *)
1413     in
1414     let metasenv' = metasenv @ newmetas @ newm' in
1415     let beta_expand = beta_expand ~metas_ok:false in
1416     let cmp1 = t_order (* compare_terms left right *)
1417     and cmp2 = s_order (* compare_terms t1 t2 *) in
1418     let res1, res2, res3, res4 =
1419       let res l r s t =
1420         List.filter
1421           (condition l r s t)
1422           (beta_expand s eq_ty l context metasenv' ugraph)
1423       in
1424       match cmp1, cmp2 with
1425       | Gt, Gt ->
1426           (beta_expand t1 eq_ty left context metasenv' ugraph), [], [], []
1427       | Gt, Lt ->
1428           [], (beta_expand t2 eq_ty left context metasenv' ugraph), [], []
1429       | Lt, Gt ->
1430           [], [], (beta_expand t1 eq_ty right context metasenv' ugraph), []
1431       | Lt, Lt ->
1432           [], [], [], (beta_expand t2 eq_ty right context metasenv' ugraph)
1433       | Gt, _ ->
1434           let res1 = res left right t1 t2
1435           and res2 = res left right t2 t1 in
1436           res1, res2, [], []
1437       | Lt, _ ->
1438           let res3 = res right left t1 t2
1439           and res4 = res right left t2 t1 in
1440           [], [], res3, res4
1441       | _, Gt ->
1442           let res1 = res left right t1 t2
1443           and res3 = res right left t1 t2 in
1444           res1, [], res3, []
1445       | _, Lt ->
1446           let res2 = res left right t2 t1
1447           and res4 = res right left t2 t1 in
1448           [], res2, [], res4
1449       | _, _ ->
1450           let res1 = res left right t1 t2
1451           and res2 = res left right t2 t1
1452           and res3 = res right left t1 t2
1453           and res4 = res right left t2 t1 in
1454           res1, res2, res3, res4
1455     in
1456     let newmetas = newmetas @ newm' in
1457     let newargs = args @ args' in
1458     let build_new what other is_left eq_URI (t, s, m, ug) =
1459       (*     let what, other = *)
1460       (*       if is_left then left, right *)
1461       (*       else right, left *)
1462       (*     in *)
1463       let newterm, neweqproof =
1464         match t with
1465         | C.Lambda (nn, ty, bo) ->
1466             let bo' = M.apply_subst s (S.subst other bo) in
1467             let bo'' =
1468               C.Appl (
1469                 [C.MutInd (HL.Logic.eq_URI, 0, []); S.lift 1 eq_ty] @
1470                   if is_left then [bo'; S.lift 1 right]
1471                   else [S.lift 1 left; bo'])
1472             in
1473             let t' = C.Lambda (nn, ty, bo'') in
1474             bo',
1475             M.apply_subst s
1476               (C.Appl [C.Const (eq_URI, []); ty; what; t';
1477                        eqproof; other; eqp'])
1478         | _ -> assert false
1479       in
1480       let newmeta, newequality =
1481         let left, right =
1482           if is_left then (newterm, M.apply_subst s right)
1483           else (M.apply_subst s left, newterm) in
1484         let neworder = compare_terms left right in
1485         fix_metas !maxmeta
1486           (neweqproof, (eq_ty, left, right, neworder), newmetas, newargs)
1487       in
1488       maxmeta := newmeta;
1489       newequality
1490     in
1491     let new1 = List.map (build_new t1 t2 true HL.Logic.eq_ind_URI) res1
1492     and new2 = List.map (build_new t2 t1 true HL.Logic.eq_ind_r_URI) res2
1493     and new3 = List.map (build_new t1 t2 false HL.Logic.eq_ind_URI) res3
1494     and new4 = List.map (build_new t2 t1 false HL.Logic.eq_ind_r_URI) res4 in
1495     let ok = function
1496       | _, (_, left, right, _), _, _ ->
1497           not (fst (CR.are_convertible context left right ugraph))
1498     in
1499     (!maxmeta,
1500      (List.filter ok (new1 @ new2 @ new3 @ new4)))
1501 ;;
1502 *)
1503
1504
1505 let is_identity ((_, context, ugraph) as env) = function
1506   | ((_, _, (ty, left, right, _), _, _) as equality) ->
1507       (left = right ||
1508           (fst (CicReduction.are_convertible context left right ugraph)))
1509 ;;
1510
1511
1512 (*
1513 let demodulation newmeta (metasenv, context, ugraph) target source =
1514   let module C = Cic in
1515   let module S = CicSubstitution in
1516   let module M = CicMetaSubst in
1517   let module HL = HelmLibraryObjects in
1518   let module CR = CicReduction in
1519
1520   let proof, (eq_ty, left, right, t_order), metas, args = target
1521   and proof', (ty, t1, t2, s_order), metas', args' = source in
1522
1523   let compare_terms = !Utils.compare_terms in
1524   
1525   if eq_ty <> ty then
1526     newmeta, target
1527   else
1528     let first_step, get_params = 
1529       match s_order (* compare_terms t1 t2 *) with
1530       | Gt -> 1, (function
1531                     | 1 -> true, t1, t2, HL.Logic.eq_ind_URI
1532                     | 0 -> false, t1, t2, HL.Logic.eq_ind_URI
1533                     | _ -> assert false)
1534       | Lt -> 1, (function
1535                     | 1 -> true, t2, t1, HL.Logic.eq_ind_r_URI
1536                     | 0 -> false, t2, t1, HL.Logic.eq_ind_r_URI
1537                     | _ -> assert false)
1538       | _ ->
1539           let first_step = 3 in
1540           let get_params step =
1541             match step with
1542             | 3 -> true, t1, t2, HL.Logic.eq_ind_URI
1543             | 2 -> false, t1, t2, HL.Logic.eq_ind_URI
1544             | 1 -> true, t2, t1, HL.Logic.eq_ind_r_URI
1545             | 0 -> false, t2, t1, HL.Logic.eq_ind_r_URI
1546             | _ -> assert false
1547           in
1548           first_step, get_params
1549     in
1550     let rec demodulate newmeta step metasenv target =
1551       let proof, (eq_ty, left, right, t_order), metas, args = target in
1552       let is_left, what, other, eq_URI = get_params step in
1553
1554       let env = metasenv, context, ugraph in
1555       let names = names_of_context context in
1556 (*       Printf.printf *)
1557 (*         "demodulate\ntarget: %s\nwhat: %s\nother: %s\nis_left: %s\n" *)
1558 (*         (string_of_equality ~env target) (CicPp.pp what names) *)
1559 (*         (CicPp.pp other names) (string_of_bool is_left); *)
1560 (*       Printf.printf "step: %d" step; *)
1561 (*       print_newline (); *)
1562
1563       let ok (t, s, m, ug) =
1564         compare_terms (M.apply_subst s what) (M.apply_subst s other) = Gt
1565       in
1566       let res =
1567         let r = (beta_expand ~metas_ok:false ~match_only:true
1568                    what ty (if is_left then left else right)
1569                    context (metasenv @ metas) ugraph) 
1570         in
1571 (*         let m' = metas_of_term what *)
1572 (*         and m'' = metas_of_term (if is_left then left else right) in *)
1573 (*         if (List.mem 527 m'') && (List.mem 6 m') then ( *)
1574 (*           Printf.printf *)
1575 (*             "demodulate\ntarget: %s\nwhat: %s\nother: %s\nis_left: %s\n" *)
1576 (*             (string_of_equality ~env target) (CicPp.pp what names) *)
1577 (*             (CicPp.pp other names) (string_of_bool is_left); *)
1578 (*           Printf.printf "step: %d" step; *)
1579 (*           print_newline (); *)
1580 (*           print_endline "res:"; *)
1581 (*           List.iter (fun (t, s, m, ug) -> print_endline (CicPp.pp t names)) r; *)
1582 (*           print_newline (); *)
1583 (*           Printf.printf "metasenv:\n%s\n" (print_metasenv (metasenv @ metas)); *)
1584 (*           print_newline (); *)
1585 (*         ); *)
1586         List.filter ok r
1587       in
1588       match res with
1589       | [] ->
1590           if step = 0 then newmeta, target
1591           else demodulate newmeta (step-1) metasenv target
1592       | (t, s, m, ug)::_ -> 
1593           let newterm, newproof =
1594             match t with
1595             | C.Lambda (nn, ty, bo) ->
1596 (*                 let bo' = M.apply_subst s (S.subst other bo) in *)
1597                 let bo' = S.subst (M.apply_subst s other) bo in
1598                 let bo'' =
1599                   C.Appl (
1600                     [C.MutInd (HL.Logic.eq_URI, 0, []);
1601                      S.lift 1 eq_ty] @
1602                       if is_left then [bo'; S.lift 1 right]
1603                       else [S.lift 1 left; bo'])
1604                 in
1605                 let t' = C.Lambda (nn, ty, bo'') in
1606 (*                 M.apply_subst s (S.subst other bo), *)
1607                 bo', 
1608                 M.apply_subst s
1609                   (C.Appl [C.Const (eq_URI, []); ty; what; t';
1610                            proof; other; proof'])
1611             | _ -> assert false
1612           in
1613           let newmeta, newtarget =
1614             let left, right =
1615 (*               if is_left then (newterm, M.apply_subst s right) *)
1616 (*               else (M.apply_subst s left, newterm) in *)
1617               if is_left then newterm, right
1618               else left, newterm
1619             in
1620             let neworder = compare_terms left right in
1621 (*             let newmetasenv = metasenv @ metas in *)
1622 (*             let newargs = args @ args' in *)
1623 (*             fix_metas newmeta *)
1624 (*               (newproof, (eq_ty, left, right), newmetasenv, newargs) *)
1625             let m = (metas_of_term left) @ (metas_of_term right) in
1626             let newmetasenv = List.filter (fun (i, _, _) -> List.mem i m) metas
1627             and newargs =
1628               List.filter
1629                 (function C.Meta (i, _) -> List.mem i m | _ -> assert false)
1630                 args
1631             in
1632             newmeta,
1633             (newproof, (eq_ty, left, right, neworder), newmetasenv, newargs)
1634           in
1635 (*           Printf.printf *)
1636 (*             "demodulate, newtarget: %s\ntarget was: %s\n" *)
1637 (*             (string_of_equality ~env newtarget) *)
1638 (*             (string_of_equality ~env target); *)
1639 (* (\*           let _, _, newm, newa = newtarget in *\) *)
1640 (* (\*           Printf.printf "newmetasenv:\n%s\nnewargs:\n%s\n" *\) *)
1641 (* (\*             (print_metasenv newm) *\) *)
1642 (* (\*             (String.concat "\n" (List.map CicPp.ppterm newa)); *\) *)
1643 (*           print_newline (); *)
1644           if is_identity env newtarget then
1645             newmeta, newtarget
1646           else
1647             demodulate newmeta first_step metasenv newtarget
1648     in
1649     demodulate newmeta first_step (metasenv @ metas') target
1650 ;;
1651
1652
1653 (*
1654 let demodulation newmeta env target source =
1655   newmeta, target
1656 ;;
1657 *)
1658
1659
1660 let subsumption env target source =
1661   let _, (ty, tl, tr, _), tmetas, _ = target
1662   and _, (ty', sl, sr, _), smetas, _ = source in
1663   if ty <> ty' then
1664     false
1665   else
1666     let metasenv, context, ugraph = env in
1667     let metasenv = metasenv @ tmetas @ smetas in
1668     let names = names_of_context context in
1669     let samesubst subst subst' =
1670 (*       Printf.printf "samesubst:\nsubst: %s\nsubst': %s\n" *)
1671 (*         (print_subst subst) (print_subst subst'); *)
1672 (*       print_newline (); *)
1673       let tbl = Hashtbl.create (List.length subst) in
1674       List.iter (fun (m, (c, t1, t2)) -> Hashtbl.add tbl m (c, t1, t2)) subst;
1675       List.for_all
1676         (fun (m, (c, t1, t2)) ->
1677            try
1678              let c', t1', t2' = Hashtbl.find tbl m in
1679              if (c = c') && (t1 = t1') && (t2 = t2') then true
1680              else false
1681            with Not_found ->
1682              true)
1683         subst'
1684     in
1685     let subsaux left right left' right' =
1686       try
1687         let subst, menv, ug = matching metasenv context left left' ugraph
1688         and subst', menv', ug' = matching metasenv context right right' ugraph
1689         in
1690 (*         Printf.printf "left = right: %s = %s\n" *)
1691 (*           (CicPp.pp left names) (CicPp.pp right names); *)
1692 (*         Printf.printf "left' = right': %s = %s\n" *)
1693 (*           (CicPp.pp left' names) (CicPp.pp right' names);         *)
1694         samesubst subst subst'
1695       with e ->
1696 (*         print_endline (Printexc.to_string e); *)
1697         false
1698     in
1699     let res = 
1700       if subsaux tl tr sl sr then true
1701       else subsaux tl tr sr sl
1702     in
1703     if res then (
1704       Printf.printf "subsumption!:\ntarget: %s\nsource: %s\n"
1705         (string_of_equality ~env target) (string_of_equality ~env source);
1706       print_newline ();
1707     );
1708     res
1709 ;;
1710 *)
1711
1712
1713 let extract_differing_subterms t1 t2 =
1714   let module C = Cic in
1715   let rec aux t1 t2 =
1716     match t1, t2 with
1717     | C.Appl l1, C.Appl l2 when (List.length l1) <> (List.length l2) ->
1718         [(t1, t2)]
1719     | C.Appl (h1::tl1), C.Appl (h2::tl2) ->
1720         let res = List.concat (List.map2 aux tl1 tl2) in
1721         if h1 <> h2 then
1722           if res = [] then [(h1, h2)] else [(t1, t2)]
1723         else
1724           if List.length res > 1 then [(t1, t2)] else res
1725     | t1, t2 ->
1726         if t1 <> t2 then [(t1, t2)] else []
1727   in
1728   let res = aux t1 t2 in
1729   match res with
1730   | hd::[] -> Some hd
1731   | _ -> None
1732 ;;
1733
1734