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