]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/paramodulation/saturation.ml
upgraded code to work with non-default equalities
[helm.git] / helm / ocaml / paramodulation / saturation.ml
1 open Inference;;
2 open Utils;;
3
4
5 (* set to false to disable paramodulation inside auto_tac *)
6 let connect_to_auto = true;;
7
8
9 (* profiling statistics... *)
10 let infer_time = ref 0.;;
11 let forward_simpl_time = ref 0.;;
12 let forward_simpl_new_time = ref 0.;;
13 let backward_simpl_time = ref 0.;;
14 let passive_maintainance_time = ref 0.;;
15
16 (* limited-resource-strategy related globals *)
17 let processed_clauses = ref 0;; (* number of equalities selected so far... *)
18 let time_limit = ref 0.;; (* in seconds, settable by the user... *)
19 let start_time = ref 0.;; (* time at which the execution started *)
20 let elapsed_time = ref 0.;;
21 (* let maximal_weight = ref None;; *)
22 let maximal_retained_equality = ref None;;
23
24 (* equality-selection related globals *)
25 let use_fullred = ref true;;
26 let weight_age_ratio = ref (* 5 *) 4;; (* settable by the user *)
27 let weight_age_counter = ref !weight_age_ratio;;
28 let symbols_ratio = ref (* 0 *) 3;;
29 let symbols_counter = ref 0;;
30
31 (* non-recursive Knuth-Bendix term ordering by default *)
32 Utils.compare_terms := Utils.nonrec_kbo;; 
33
34 (* statistics... *)
35 let derived_clauses = ref 0;;
36 let kept_clauses = ref 0;;
37
38 (* index of the greatest Cic.Meta created - TODO: find a better way! *)
39 let maxmeta = ref 0;;
40
41 (* varbiables controlling the search-space *)
42 let maxdepth = ref 3;;
43 let maxwidth = ref 3;;
44
45
46 type result =
47   | ParamodulationFailure
48   | ParamodulationSuccess of Inference.proof option * environment
49 ;;
50
51
52 (*
53 let symbols_of_equality (_, (_, left, right), _, _) =
54   TermSet.union (symbols_of_term left) (symbols_of_term right)
55 ;;
56 *)
57
58 let symbols_of_equality ((_, _, (_, left, right, _), _, _) as equality) =
59   let m1 = symbols_of_term left in
60   let m = 
61     TermMap.fold
62       (fun k v res ->
63          try
64            let c = TermMap.find k res in
65            TermMap.add k (c+v) res
66          with Not_found ->
67            TermMap.add k v res)
68       (symbols_of_term right) m1
69   in
70 (*   Printf.printf "symbols_of_equality %s:\n" *)
71 (*     (string_of_equality equality); *)
72 (*   TermMap.iter (fun k v -> Printf.printf "%s: %d\n" (CicPp.ppterm k) v) m; *)
73 (*   print_newline (); *)
74   m
75 ;;
76
77
78 module OrderedEquality = struct
79   type t = Inference.equality
80
81   let compare eq1 eq2 =
82     match meta_convertibility_eq eq1 eq2 with
83     | true -> 0
84     | false ->
85         let w1, _, (ty, left, right, _), _, a = eq1
86         and w2, _, (ty', left', right', _), _, a' = eq2 in
87 (*         let weight_of t = fst (weight_of_term ~consider_metas:false t) in *)
88 (*         let w1 = (weight_of ty) + (weight_of left) + (weight_of right) *)
89 (*         and w2 = (weight_of ty') + (weight_of left') + (weight_of right') in *)
90         match Pervasives.compare w1 w2 with
91         | 0 ->
92             let res = (List.length a) - (List.length a') in
93             if res <> 0 then res else (
94               try
95                 let res = Pervasives.compare (List.hd a) (List.hd a') in
96                 if res <> 0 then res else Pervasives.compare eq1 eq2
97               with Failure "hd" -> Pervasives.compare eq1 eq2
98 (*               match a, a' with *)
99 (*               | (Cic.Meta (i, _)::_), (Cic.Meta (j, _)::_) -> *)
100 (*                   let res = Pervasives.compare i j in *)
101 (*                   if res <> 0 then res else Pervasives.compare eq1 eq2 *)
102 (*               | _, _ -> Pervasives.compare eq1 eq2 *)
103             )
104         | res -> res
105 end
106
107 module EqualitySet = Set.Make(OrderedEquality);;
108
109
110 let select env goals passive (active, _) =
111   processed_clauses := !processed_clauses + 1;
112
113   let goal =
114     match (List.rev goals) with (_, goal::_)::_ -> goal | _ -> assert false
115   in
116   
117   let (neg_list, neg_set), (pos_list, pos_set), passive_table = passive in
118   let remove eq l =
119     List.filter (fun e -> e <> eq) l
120   in
121   if !weight_age_ratio > 0 then
122     weight_age_counter := !weight_age_counter - 1;
123   match !weight_age_counter with
124   | 0 -> (
125       weight_age_counter := !weight_age_ratio;
126       match neg_list, pos_list with
127       | hd::tl, pos ->
128           (* Negatives aren't indexed, no need to remove them... *)
129           (Negative, hd),
130           ((tl, EqualitySet.remove hd neg_set), (pos, pos_set), passive_table)
131       | [], hd::tl ->
132           let passive_table =
133             Indexing.remove_index passive_table hd
134 (*             if !use_fullred then Indexing.remove_index passive_table hd *)
135 (*             else passive_table *)
136           in
137           (Positive, hd),
138           (([], neg_set), (tl, EqualitySet.remove hd pos_set), passive_table)
139       | _, _ -> assert false
140     )
141   | _ when (!symbols_counter > 0) && (EqualitySet.is_empty neg_set) -> (
142       symbols_counter := !symbols_counter - 1;
143       let cardinality map =
144         TermMap.fold (fun k v res -> res + v) map 0
145       in
146 (*       match active with *)
147 (*       | (Negative, e)::_ -> *)
148 (*           let symbols = symbols_of_equality e in *)
149       let symbols =
150         let _, _, term = goal in
151         symbols_of_term term
152       in
153           let card = cardinality symbols in
154           let foldfun k v (r1, r2) = 
155             if TermMap.mem k symbols then
156               let c = TermMap.find k symbols in
157               let c1 = abs (c - v) in
158               let c2 = v - c1 in
159               r1 + c2, r2 + c1
160             else
161               r1, r2 + v
162           in
163           let f equality (i, e) =
164             let common, others =
165               TermMap.fold foldfun (symbols_of_equality equality) (0, 0)
166             in
167             let c = others + (abs (common - card)) in
168             if c < i then (c, equality)
169 (*             else if c = i then *)
170 (*               match OrderedEquality.compare equality e with *)
171 (*               | -1 -> (c, equality) *)
172 (*               | res -> (i, e) *)
173             else (i, e)
174           in
175           let e1 = EqualitySet.min_elt pos_set in
176           let initial =
177             let common, others = 
178               TermMap.fold foldfun (symbols_of_equality e1) (0, 0)
179             in
180             (others + (abs (common - card))), e1
181           in
182           let _, current = EqualitySet.fold f pos_set initial in
183 (*           Printf.printf "\nsymbols-based selection: %s\n\n" *)
184 (*             (string_of_equality ~env current); *)
185           let passive_table =
186             Indexing.remove_index passive_table current
187 (*             if !use_fullred then Indexing.remove_index passive_table current *)
188 (*             else passive_table *)
189           in
190           (Positive, current),
191           (([], neg_set),
192            (remove current pos_list, EqualitySet.remove current pos_set),
193            passive_table)
194 (*       | _ -> *)
195 (*           let current = EqualitySet.min_elt pos_set in *)
196 (*           let passive_table = *)
197 (*             Indexing.remove_index passive_table current *)
198 (* (\*             if !use_fullred then Indexing.remove_index passive_table current *\) *)
199 (* (\*             else passive_table *\) *)
200 (*           in *)
201 (*           let passive = *)
202 (*             (neg_list, neg_set), *)
203 (*             (remove current pos_list, EqualitySet.remove current pos_set), *)
204 (*             passive_table *)
205 (*           in *)
206 (*           (Positive, current), passive *)
207     )
208   | _ ->
209       symbols_counter := !symbols_ratio;
210       let set_selection set = EqualitySet.min_elt set in
211       if EqualitySet.is_empty neg_set then
212         let current = set_selection pos_set in
213         let passive =
214           (neg_list, neg_set),
215           (remove current pos_list, EqualitySet.remove current pos_set),
216           Indexing.remove_index passive_table current
217 (*           if !use_fullred then Indexing.remove_index passive_table current *)
218 (*           else passive_table *)
219         in
220         (Positive, current), passive
221       else
222         let current = set_selection neg_set in
223         let passive =
224           (remove current neg_list, EqualitySet.remove current neg_set),
225           (pos_list, pos_set),
226           passive_table
227         in
228         (Negative, current), passive
229 ;;
230
231
232 let make_passive neg pos =
233   let set_of equalities =
234     List.fold_left (fun s e -> EqualitySet.add e s) EqualitySet.empty equalities
235   in
236   let table =
237       List.fold_left (fun tbl e -> Indexing.index tbl e)
238         (Indexing.empty_table ()) pos
239 (*     if !use_fullred then *)
240 (*       List.fold_left (fun tbl e -> Indexing.index tbl e) *)
241 (*         (Indexing.empty_table ()) pos *)
242 (*     else *)
243 (*       Indexing.empty_table () *)
244   in
245   (neg, set_of neg),
246   (pos, set_of pos),
247   table
248 ;;
249
250
251 let make_active () =
252   [], Indexing.empty_table () 
253 ;;
254
255
256 let add_to_passive passive (new_neg, new_pos) =
257   let (neg_list, neg_set), (pos_list, pos_set), table = passive in
258   let ok set equality = not (EqualitySet.mem equality set) in
259   let neg = List.filter (ok neg_set) new_neg
260   and pos = List.filter (ok pos_set) new_pos in
261   let table =
262       List.fold_left (fun tbl e -> Indexing.index tbl e) table pos
263 (*     if !use_fullred then *)
264 (*       List.fold_left (fun tbl e -> Indexing.index tbl e) table pos *)
265 (*     else *)
266 (*       table *)
267   in
268   let add set equalities =
269     List.fold_left (fun s e -> EqualitySet.add e s) set equalities
270   in
271   (neg @ neg_list, add neg_set neg),
272   (pos_list @ pos, add pos_set pos),
273   table
274 ;;
275
276
277 let passive_is_empty = function
278   | ([], _), ([], _), _ -> true
279   | _ -> false
280 ;;
281
282
283 let size_of_passive ((_, ns), (_, ps), _) =
284   (EqualitySet.cardinal ns) + (EqualitySet.cardinal ps)
285 ;;
286
287
288 let size_of_active (active_list, _) =
289   List.length active_list
290 ;;
291
292
293 let prune_passive howmany (active, _) passive =
294   let (nl, ns), (pl, ps), tbl = passive in
295   let howmany = float_of_int howmany
296   and ratio = float_of_int !weight_age_ratio in
297   let round v =
298     let t = ceil v in 
299     int_of_float (if t -. v < 0.5 then t else v)
300   in
301   let in_weight = round (howmany *. ratio /. (ratio +. 1.))
302   and in_age = round (howmany /. (ratio +. 1.)) in 
303   debug_print
304     (lazy (Printf.sprintf "in_weight: %d, in_age: %d\n" in_weight in_age));
305   let symbols, card =
306     match active with
307     | (Negative, e)::_ ->
308         let symbols = symbols_of_equality e in
309         let card = TermMap.fold (fun k v res -> res + v) symbols 0 in
310         Some symbols, card
311     | _ -> None, 0
312   in
313   let counter = ref !symbols_ratio in
314   let rec pickw w ns ps =
315     if w > 0 then
316       if not (EqualitySet.is_empty ns) then
317         let e = EqualitySet.min_elt ns in
318         let ns', ps = pickw (w-1) (EqualitySet.remove e ns) ps in
319         EqualitySet.add e ns', ps
320       else if !counter > 0 then
321         let _ =
322           counter := !counter - 1;
323           if !counter = 0 then counter := !symbols_ratio
324         in
325         match symbols with
326         | None ->
327             let e = EqualitySet.min_elt ps in
328             let ns, ps' = pickw (w-1) ns (EqualitySet.remove e ps) in
329             ns, EqualitySet.add e ps'
330         | Some symbols ->
331             let foldfun k v (r1, r2) =
332               if TermMap.mem k symbols then
333                 let c = TermMap.find k symbols in
334                 let c1 = abs (c - v) in
335                 let c2 = v - c1 in
336                 r1 + c2, r2 + c1
337               else
338                 r1, r2 + v
339             in
340             let f equality (i, e) =
341               let common, others =
342                 TermMap.fold foldfun (symbols_of_equality equality) (0, 0)
343               in
344               let c = others + (abs (common - card)) in
345               if c < i then (c, equality)
346               else (i, e)
347             in
348             let e1 = EqualitySet.min_elt ps in
349             let initial =
350               let common, others = 
351                 TermMap.fold foldfun (symbols_of_equality e1) (0, 0)
352               in
353               (others + (abs (common - card))), e1
354             in
355             let _, e = EqualitySet.fold f ps initial in
356             let ns, ps' = pickw (w-1) ns (EqualitySet.remove e ps) in
357             ns, EqualitySet.add e ps'
358       else
359         let e = EqualitySet.min_elt ps in
360         let ns, ps' = pickw (w-1) ns (EqualitySet.remove e ps) in
361         ns, EqualitySet.add e ps'        
362     else
363       EqualitySet.empty, EqualitySet.empty
364   in
365 (*   let in_weight, ns = pickw in_weight ns in *)
366 (*   let _, ps = pickw in_weight ps in *)
367   let ns, ps = pickw in_weight ns ps in
368   let rec picka w s l =
369     if w > 0 then
370       match l with
371       | [] -> w, s, []
372       | hd::tl when not (EqualitySet.mem hd s) ->
373           let w, s, l = picka (w-1) s tl in
374           w, EqualitySet.add hd s, hd::l
375       | hd::tl ->
376           let w, s, l = picka w s tl in
377           w, s, hd::l
378     else
379       0, s, l
380   in
381   let in_age, ns, nl = picka in_age ns nl in
382   let _, ps, pl = picka in_age ps pl in
383   if not (EqualitySet.is_empty ps) then
384 (*     maximal_weight := Some (weight_of_equality (EqualitySet.max_elt ps)); *)
385     maximal_retained_equality := Some (EqualitySet.max_elt ps); 
386   let tbl =
387     EqualitySet.fold
388       (fun e tbl -> Indexing.index tbl e) ps (Indexing.empty_table ())
389 (*     if !use_fullred then *)
390 (*       EqualitySet.fold *)
391 (*         (fun e tbl -> Indexing.index tbl e) ps (Indexing.empty_table ()) *)
392 (*     else *)
393 (*       tbl *)
394   in
395   (nl, ns), (pl, ps), tbl  
396 ;;
397
398
399 let infer env sign current (active_list, active_table) =
400   let new_neg, new_pos = 
401     match sign with
402     | Negative ->
403         let maxm, res = 
404           Indexing.superposition_left !maxmeta env active_table current in
405         maxmeta := maxm;
406         res, [] 
407     | Positive ->
408         let maxm, res =
409           Indexing.superposition_right !maxmeta env active_table current in
410         maxmeta := maxm;
411         let rec infer_positive table = function
412           | [] -> [], []
413           | (Negative, equality)::tl ->
414               let maxm, res =
415                 Indexing.superposition_left !maxmeta env table equality in
416               maxmeta := maxm;
417               let neg, pos = infer_positive table tl in
418               res @ neg, pos
419           | (Positive, equality)::tl ->
420               let maxm, res =
421                 Indexing.superposition_right !maxmeta env table equality in
422               maxmeta := maxm;
423               let neg, pos = infer_positive table tl in
424               neg, res @ pos
425         in
426         let curr_table = Indexing.index (Indexing.empty_table ()) current in
427         let neg, pos = infer_positive curr_table active_list in
428         neg, res @ pos
429   in
430   derived_clauses := !derived_clauses + (List.length new_neg) +
431     (List.length new_pos);
432   match !maximal_retained_equality with
433   | None -> new_neg, new_pos
434   | Some eq ->
435       (* if we have a maximal_retained_equality, we can discard all equalities
436          "greater" than it, as they will never be reached...  An equality is
437          greater than maximal_retained_equality if it is bigger
438          wrt. OrderedEquality.compare and it is less similar than
439          maximal_retained_equality to the current goal *)
440       let symbols, card =
441         match active_list with
442         | (Negative, e)::_ ->
443             let symbols = symbols_of_equality e in
444             let card = TermMap.fold (fun k v res -> res + v) symbols 0 in
445             Some symbols, card
446         | _ -> None, 0
447       in
448       let new_pos = 
449         match symbols with
450         | None ->
451             List.filter (fun e -> OrderedEquality.compare e eq <= 0) new_pos
452         | Some symbols ->
453             let filterfun e =
454               if OrderedEquality.compare e eq <= 0 then
455                 true
456               else
457                 let foldfun k v (r1, r2) =
458                   if TermMap.mem k symbols then
459                     let c = TermMap.find k symbols in
460                     let c1 = abs (c - v) in
461                     let c2 = v - c1 in
462                     r1 + c2, r2 + c1
463                   else
464                     r1, r2 + v
465                 in
466                 let initial =
467                   let common, others =
468                     TermMap.fold foldfun (symbols_of_equality eq) (0, 0) in
469                   others + (abs (common - card))
470                 in
471                 let common, others =
472                   TermMap.fold foldfun (symbols_of_equality e) (0, 0) in
473                 let c = others + (abs (common - card)) in
474                 if c < initial then true else false 
475             in
476             List.filter filterfun new_pos
477       in
478       new_neg, new_pos
479 ;;
480
481
482 let contains_empty env (negative, positive) =
483   let metasenv, context, ugraph = env in
484   try
485     let found =
486       List.find
487         (fun (w, proof, (ty, left, right, ordering), m, a) ->
488            fst (CicReduction.are_convertible context left right ugraph))
489         negative
490     in
491     true, Some found
492   with Not_found ->
493     false, None
494 ;;
495
496
497 let forward_simplify env (sign, current) ?passive (active_list, active_table) =
498   let pl, passive_table =
499     match passive with
500     | None -> [], None
501     | Some ((pn, _), (pp, _), pt) ->
502         let pn = List.map (fun e -> (Negative, e)) pn
503         and pp = List.map (fun e -> (Positive, e)) pp in
504         pn @ pp, Some pt
505   in
506   let all = if pl = [] then active_list else active_list @ pl in
507
508   (*   let rec find_duplicate sign current = function *)
509 (*     | [] -> false *)
510 (*     | (s, eq)::tl when s = sign -> *)
511 (*         if meta_convertibility_eq current eq then true *)
512 (*         else find_duplicate sign current tl *)
513 (*     | _::tl -> find_duplicate sign current tl *)
514 (*   in *)
515
516 (*   let res =  *)
517 (*     if sign = Positive then *)
518 (*       Indexing.subsumption env active_table current *)
519 (*     else *)
520 (*       false *)
521 (*   in *)
522 (*   if res then *)
523 (*     None *)
524 (*   else *)
525   
526   let demodulate table current = 
527     let newmeta, newcurrent =
528       Indexing.demodulation_equality !maxmeta env table sign current in
529     maxmeta := newmeta;
530     if is_identity env newcurrent then
531       if sign = Negative then Some (sign, newcurrent)
532       else None
533     else
534       Some (sign, newcurrent)
535   in
536   let res =
537     let res = demodulate active_table current in
538     match res with
539     | None -> None
540     | Some (sign, newcurrent) ->
541         match passive_table with
542         | None -> res
543         | Some passive_table -> demodulate passive_table newcurrent
544   in
545   match res with
546   | None -> None
547   | Some (Negative, c) ->
548       let ok = not (
549         List.exists
550           (fun (s, eq) -> s = Negative && meta_convertibility_eq eq c)
551           all)
552       in
553       if ok then res else None
554   | Some (Positive, c) ->
555       if Indexing.in_index active_table c then
556         None
557       else
558         match passive_table with
559         | None -> res
560         | Some passive_table ->
561             if Indexing.in_index passive_table c then None
562             else res
563
564 (*   | Some (s, c) -> if find_duplicate s c all then None else res *)
565
566 (*         if s = Utils.Negative then *)
567 (*           res *)
568 (*         else *)
569 (*           if Indexing.subsumption env active_table c then *)
570 (*             None *)
571 (*           else ( *)
572 (*             match passive_table with *)
573 (*             | None -> res *)
574 (*             | Some passive_table -> *)
575 (*                 if Indexing.subsumption env passive_table c then *)
576 (*                   None *)
577 (*                 else *)
578 (*                   res *)
579 (*           ) *)
580
581 (*         let pred (sign, eq) = *)
582 (*           if sign <> s then false *)
583 (*           else subsumption env c eq *)
584 (*         in *)
585 (*         if List.exists pred all then None *)
586 (*         else res *)
587 ;;
588
589 type fs_time_info_t = {
590   mutable build_all: float;
591   mutable demodulate: float;
592   mutable subsumption: float;
593 };;
594
595 let fs_time_info = { build_all = 0.; demodulate = 0.; subsumption = 0. };;
596
597
598 let forward_simplify_new env (new_neg, new_pos) ?passive active =
599   let t1 = Unix.gettimeofday () in
600
601   let active_list, active_table = active in
602   let pl, passive_table =
603     match passive with
604     | None -> [], None
605     | Some ((pn, _), (pp, _), pt) ->
606         let pn = List.map (fun e -> (Negative, e)) pn
607         and pp = List.map (fun e -> (Positive, e)) pp in
608         pn @ pp, Some pt
609   in
610   let all = active_list @ pl in
611   
612   let t2 = Unix.gettimeofday () in
613   fs_time_info.build_all <- fs_time_info.build_all +. (t2 -. t1);
614   
615   let demodulate sign table target =
616     let newmeta, newtarget =
617       Indexing.demodulation_equality !maxmeta env table sign target in
618     maxmeta := newmeta;
619     newtarget
620   in
621 (*   let f sign' target (sign, eq) = *)
622 (*     if sign <> sign' then false *)
623 (*     else subsumption env target eq  *)
624 (*   in *)
625
626   let t1 = Unix.gettimeofday () in
627
628   let new_neg, new_pos =
629     let new_neg = List.map (demodulate Negative active_table) new_neg
630     and new_pos = List.map (demodulate Positive active_table) new_pos in
631     match passive_table with
632     | None -> new_neg, new_pos
633     | Some passive_table ->
634         List.map (demodulate Negative passive_table) new_neg,
635         List.map (demodulate Positive passive_table) new_pos
636   in
637
638   let t2 = Unix.gettimeofday () in
639   fs_time_info.demodulate <- fs_time_info.demodulate +. (t2 -. t1);
640
641   let new_pos_set =
642     List.fold_left
643       (fun s e ->
644          if not (Inference.is_identity env e) then
645            if EqualitySet.mem e s then s
646            else EqualitySet.add e s
647          else s)
648       EqualitySet.empty new_pos
649   in
650   let new_pos = EqualitySet.elements new_pos_set in
651
652   let subs =
653     match passive_table with
654     | None ->
655         (fun e -> not (fst (Indexing.subsumption env active_table e)))
656     | Some passive_table ->
657         (fun e -> not ((fst (Indexing.subsumption env active_table e)) ||
658                          (fst (Indexing.subsumption env passive_table e))))
659   in
660
661   let t1 = Unix.gettimeofday () in
662
663 (*   let new_neg, new_pos = *)
664 (*     List.filter subs new_neg, *)
665 (*     List.filter subs new_pos *)
666 (*   in *)
667
668 (*   let new_neg, new_pos =  *)
669 (*     (List.filter (fun e -> not (List.exists (f Negative e) all)) new_neg, *)
670 (*      List.filter (fun e -> not (List.exists (f Positive e) all)) new_pos) *)
671 (*   in *)
672
673   let t2 = Unix.gettimeofday () in
674   fs_time_info.subsumption <- fs_time_info.subsumption +. (t2 -. t1);
675
676   let is_duplicate =
677     match passive_table with
678     | None ->
679         (fun e -> not (Indexing.in_index active_table e))
680     | Some passive_table ->
681         (fun e ->
682            not ((Indexing.in_index active_table e) ||
683                   (Indexing.in_index passive_table e)))
684   in
685   new_neg, List.filter is_duplicate new_pos
686
687 (*   new_neg, new_pos *)
688
689 (*   let res = *)
690 (*     (List.filter (fun e -> not (List.exists (f Negative e) all)) new_neg, *)
691 (*      List.filter (fun e -> not (List.exists (f Positive e) all)) new_pos) *)
692 (*   in *)
693 (*   res *)
694 ;;
695
696
697 let backward_simplify_active env new_pos new_table min_weight active =
698   let active_list, active_table = active in
699   let active_list, newa = 
700     List.fold_right
701       (fun (s, equality) (res, newn) ->
702          let ew, _, _, _, _ = equality in
703          if ew < min_weight then
704            (s, equality)::res, newn
705          else
706            match forward_simplify env (s, equality) (new_pos, new_table) with
707            | None -> res, newn
708            | Some (s, e) ->
709                if equality = e then
710                  (s, e)::res, newn
711                else 
712                  res, (s, e)::newn)
713       active_list ([], [])
714   in
715   let find eq1 where =
716     List.exists (fun (s, e) -> meta_convertibility_eq eq1 e) where
717   in
718   let active, newa =
719     List.fold_right
720       (fun (s, eq) (res, tbl) ->
721          if List.mem (s, eq) res then
722            res, tbl
723          else if (is_identity env eq) || (find eq res) then (
724            res, tbl
725          ) (* else if (find eq res) then *)
726 (*            res, tbl *)
727          else
728            (s, eq)::res, if s = Negative then tbl else Indexing.index tbl eq)
729       active_list ([], Indexing.empty_table ()),
730     List.fold_right
731       (fun (s, eq) (n, p) ->
732          if (s <> Negative) && (is_identity env eq) then (
733            (n, p)
734          ) else
735            if s = Negative then eq::n, p
736            else n, eq::p)
737       newa ([], [])
738   in
739   match newa with
740   | [], [] -> active, None
741   | _ -> active, Some newa
742 ;;
743
744
745 let backward_simplify_passive env new_pos new_table min_weight passive =
746   let (nl, ns), (pl, ps), passive_table = passive in
747   let f sign equality (resl, ress, newn) =
748     let ew, _, _, _, _ = equality in
749     if ew < min_weight then
750 (*       let _ = debug_print (lazy (Printf.sprintf "OK: %d %d" ew min_weight)) in *)
751       equality::resl, ress, newn
752     else
753       match forward_simplify env (sign, equality) (new_pos, new_table) with
754       | None -> resl, EqualitySet.remove equality ress, newn
755       | Some (s, e) ->
756           if equality = e then
757             equality::resl, ress, newn
758           else
759             let ress = EqualitySet.remove equality ress in
760             resl, ress, e::newn
761   in
762   let nl, ns, newn = List.fold_right (f Negative) nl ([], ns, [])
763   and pl, ps, newp = List.fold_right (f Positive) pl ([], ps, []) in
764   let passive_table =
765     List.fold_left
766       (fun tbl e -> Indexing.index tbl e) (Indexing.empty_table ()) pl
767   in
768   match newn, newp with
769   | [], [] -> ((nl, ns), (pl, ps), passive_table), None
770   | _, _ -> ((nl, ns), (pl, ps), passive_table), Some (newn, newp)
771 ;;
772
773
774 let backward_simplify env new' ?passive active =
775   let new_pos, new_table, min_weight =
776     List.fold_left
777       (fun (l, t, w) e ->
778          let ew, _, _, _, _ = e in
779          (Positive, e)::l, Indexing.index t e, min ew w)
780       ([], Indexing.empty_table (), 1000000) (snd new')
781   in
782   let active, newa =
783     backward_simplify_active env new_pos new_table min_weight active in
784   match passive with
785   | None ->
786       active, (make_passive [] []), newa, None
787   | Some passive ->
788       let passive, newp =
789         backward_simplify_passive env new_pos new_table min_weight passive in
790       active, passive, newa, newp
791 ;;
792
793
794 let get_selection_estimate () =
795   elapsed_time := (Unix.gettimeofday ()) -. !start_time;
796 (*   !processed_clauses * (int_of_float (!time_limit /. !elapsed_time)) *)
797   int_of_float (
798     ceil ((float_of_int !processed_clauses) *.
799             ((!time_limit (* *. 2. *)) /. !elapsed_time -. 1.)))
800 ;;
801
802   
803 let simplify_goal env goal ?passive (active_list, active_table) =
804   let pl, passive_table =
805     match passive with
806     | None -> [], None
807     | Some ((pn, _), (pp, _), pt) ->
808         let pn = List.map (fun e -> (Negative, e)) pn
809         and pp = List.map (fun e -> (Positive, e)) pp in
810         pn @ pp, Some pt
811   in
812   let all = if pl = [] then active_list else active_list @ pl in
813
814   let demodulate table goal = 
815     let newmeta, newgoal =
816       Indexing.demodulation_goal !maxmeta env table goal in
817     maxmeta := newmeta;
818     newgoal
819   in
820   let goal =
821     match passive_table with
822     | None -> demodulate active_table goal
823     | Some passive_table ->
824         let goal = demodulate active_table goal in
825         demodulate passive_table goal
826   in
827   let _ =
828     let p, _, t = goal in
829     debug_print
830       (lazy
831          (Printf.sprintf "Goal after demodulation: %s, %s"
832             (string_of_proof p) (CicPp.ppterm t)))
833   in
834   goal
835 ;;
836
837
838 let simplify_goals env goals ?passive active =
839   List.map
840     (fun (d, gl) ->
841        let gl = List.map (fun g -> simplify_goal env g ?passive active) gl in
842        d, gl)
843     goals
844 ;;
845
846
847 let simplify_theorems env theorems ?passive (active_list, active_table) =
848   let pl, passive_table =
849     match passive with
850     | None -> [], None
851     | Some ((pn, _), (pp, _), pt) ->
852         let pn = List.map (fun e -> (Negative, e)) pn
853         and pp = List.map (fun e -> (Positive, e)) pp in
854         pn @ pp, Some pt
855   in
856   let all = if pl = [] then active_list else active_list @ pl in
857
858   let demodulate table theorem =
859     let newmeta, newthm =
860       Indexing.demodulation_theorem !maxmeta env table theorem in
861     maxmeta := newmeta;
862     newthm
863   in
864   match passive_table with
865   | None -> List.map (demodulate active_table) theorems
866   | Some passive_table ->
867       let theorems = List.map (demodulate active_table) theorems in
868       List.map (demodulate passive_table) theorems
869 ;;
870
871
872 let apply_equality_to_goal env equality goal =
873   let module C = Cic in
874   let module HL = HelmLibraryObjects in
875   let module I = Inference in
876   let metasenv, context, ugraph = env in
877   let _, proof, (ty, left, right, _), metas, args = equality in
878   let eqterm =
879     C.Appl [C.MutInd (LibraryObjects.eq_URI (), 0, []); ty; left; right] in
880   let gproof, gmetas, gterm = goal in
881   try
882     let subst, metasenv', _ =
883       let menv = metasenv @ metas @ gmetas in
884       Inference.unification menv context eqterm gterm ugraph
885     in
886     let newproof =
887       match proof with
888       | I.BasicProof t -> I.BasicProof (CicMetaSubst.apply_subst subst t)
889       | I.ProofBlock (s, uri, nt, t, pe, p) ->
890           I.ProofBlock (subst @ s, uri, nt, t, pe, p)
891       | _ -> assert false
892     in
893     let newgproof =
894       let rec repl = function
895         | I.ProofGoalBlock (_, gp) -> I.ProofGoalBlock (newproof, gp)
896         | I.NoProof -> newproof
897         | I.BasicProof p -> newproof
898         | I.SubProof (t, i, p) -> I.SubProof (t, i, repl p)
899         | _ -> assert false
900       in
901       repl gproof
902     in
903     true, subst, newgproof
904   with CicUnification.UnificationFailure _ ->
905     false, [], I.NoProof
906 ;;
907
908
909 (*
910 let apply_to_goal env theorems active (depth, goals) =
911   let _ =
912     debug_print ("apply_to_goal: " ^ (string_of_int (List.length goals)))
913   in
914   let metasenv, context, ugraph = env in
915   let goal = List.hd goals in
916   let proof, metas, term = goal in
917 (*   debug_print *)
918 (*     (Printf.sprintf "apply_to_goal with goal: %s" (CicPp.ppterm term)); *)
919   let newmeta = CicMkImplicit.new_meta metasenv [] in
920   let metasenv = (newmeta, context, term)::metasenv @ metas in
921   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
922   let status =
923     ((None, metasenv, Cic.Meta (newmeta, irl), term), newmeta)
924   in
925   let rec aux = function
926     | [] -> false, [] (* goals *) (* None *)
927     | (theorem, thmty, _)::tl ->
928         try
929           let subst_in, (newproof, newgoals) =
930             PrimitiveTactics.apply_tac_verbose ~term:theorem status
931           in
932           if newgoals = [] then
933             let _, _, p, _ = newproof in
934             let newp =
935               let rec repl = function
936                 | Inference.ProofGoalBlock (_, gp) ->
937                     Inference.ProofGoalBlock (Inference.BasicProof p, gp)
938                 | Inference.NoProof -> Inference.BasicProof p
939                 | Inference.BasicProof _ -> Inference.BasicProof p
940                 | Inference.SubProof (t, i, p2) ->
941                     Inference.SubProof (t, i, repl p2)
942                 | _ -> assert false
943               in
944               repl proof
945             in
946             true, [[newp, metas, term]] (* Some newp *)
947           else if List.length newgoals = 1 then
948             let _, menv, p, _ = newproof in
949             let irl =
950               CicMkImplicit.identity_relocation_list_for_metavariable context
951             in
952             let goals =
953               List.map
954                 (fun i ->
955                    let _, _, ty = CicUtil.lookup_meta i menv in
956                    let proof =
957                      Inference.SubProof
958                        (p, i, Inference.BasicProof (Cic.Meta (i, irl)))
959                    in (proof, menv, ty))
960                 newgoals
961             in
962             let res, others = aux tl in
963             if res then (true, others) else (false, goals::others)
964           else
965             aux tl
966         with ProofEngineTypes.Fail msg ->
967           (*     debug_print ("FAIL!!:" ^ msg); *)
968           aux tl
969   in
970   let r, l =
971     if Inference.term_is_equality term then
972       let rec appleq = function
973         | [] -> false, []
974         | (Positive, equality)::tl ->
975             let ok, _, newproof = apply_equality_to_goal env equality goal in
976             if ok then true, [(depth, [newproof, metas, term])] else appleq tl
977         | _::tl -> appleq tl
978       in
979       let al, _ = active in
980       appleq al
981     else
982       false, []
983   in
984   if r = true then r, l else
985     let r, l = aux theorems in
986     if r = true then
987       r, List.map (fun l -> (depth+1, l)) l
988     else
989       r, (depth, goals)::(List.map (fun l -> (depth+1, l)) l)
990 ;;
991 *)
992
993
994 let new_meta () =
995   incr maxmeta; !maxmeta
996 ;;
997
998
999 let apply_to_goal env theorems active goal =
1000   let metasenv, context, ugraph = env in
1001   let proof, metas, term = goal in
1002   debug_print
1003     (lazy
1004        (Printf.sprintf "apply_to_goal with goal: %s, %s"
1005           (string_of_proof proof) (CicPp.ppterm term)));
1006   let status =
1007     let irl =
1008       CicMkImplicit.identity_relocation_list_for_metavariable context in
1009     let proof', newmeta =
1010       let rec get_meta = function
1011         | SubProof (t, i, _) -> t, i
1012         | ProofGoalBlock (_, p) -> get_meta p
1013         | _ ->
1014             let n = new_meta () in (* CicMkImplicit.new_meta metasenv [] in *)
1015             Cic.Meta (n, irl), n
1016       in
1017       get_meta proof
1018     in
1019 (*     let newmeta = CicMkImplicit.new_meta metasenv [] in *)
1020     let metasenv = (newmeta, context, term)::metasenv @ metas in
1021     ((None, metasenv, Cic.Meta (newmeta, irl), term), newmeta)
1022 (*     ((None, metasenv, proof', term), newmeta) *)
1023   in
1024   let rec aux = function
1025     | [] -> `No (* , [], [] *)
1026     | (theorem, thmty, _)::tl ->
1027         try
1028           let subst, (newproof, newgoals) =
1029             PrimitiveTactics.apply_tac_verbose_with_subst ~term:theorem status
1030           in
1031           if newgoals = [] then
1032             let _, _, p, _ = newproof in
1033             let newp =
1034               let rec repl = function
1035                 | Inference.ProofGoalBlock (_, gp) ->
1036                     Inference.ProofGoalBlock (Inference.BasicProof p, gp)
1037                 | Inference.NoProof -> Inference.BasicProof p
1038                 | Inference.BasicProof _ -> Inference.BasicProof p
1039                 | Inference.SubProof (t, i, p2) ->
1040                     Inference.SubProof (t, i, repl p2)
1041                 | _ -> assert false
1042               in
1043               repl proof
1044             in
1045             let _, m = status in
1046             let subst = List.filter (fun (i, _) -> i = m) subst in
1047 (*             debug_print *)
1048 (*               (lazy *)
1049 (*                  (Printf.sprintf "m = %d\nsubst = %s\n" *)
1050 (*                     m (print_subst subst))); *)
1051             `Ok (subst, [newp, metas, term])
1052           else
1053             let _, menv, p, _ = newproof in
1054             let irl =
1055               CicMkImplicit.identity_relocation_list_for_metavariable context
1056             in
1057             let goals =
1058               List.map
1059                 (fun i ->
1060                    let _, _, ty = CicUtil.lookup_meta i menv in
1061                    let p' =
1062                      let rec gp = function
1063                        | SubProof (t, i, p) ->
1064                            SubProof (t, i, gp p)
1065                        | ProofGoalBlock (sp1, sp2) ->
1066 (*                            SubProof (p, i, sp) *)
1067                            ProofGoalBlock (sp1, gp sp2)
1068 (*                            gp sp *)
1069                        | BasicProof _
1070                        | NoProof ->
1071                            SubProof (p, i, BasicProof (Cic.Meta (i, irl)))
1072                        | ProofSymBlock (s, sp) ->
1073                            ProofSymBlock (s, gp sp)
1074                        | ProofBlock (s, u, nt, t, pe, sp) ->
1075                            ProofBlock (s, u, nt, t, pe, gp sp)
1076 (*                        | _ -> assert false *)
1077                      in gp proof
1078                    in
1079                    debug_print
1080                      (lazy
1081                         (Printf.sprintf "new sub goal: %s, %s"
1082                            (string_of_proof p') (CicPp.ppterm ty)));
1083                    (p', menv, ty))
1084                 newgoals
1085             in
1086 (*             debug_print *)
1087 (*               (lazy *)
1088 (*                  (Printf.sprintf "\nGoOn with subst: %s" (print_subst subst))); *)
1089             let best = aux tl in
1090             match best with
1091             | `Ok (_, _) -> best
1092             | `No -> `GoOn ([subst, goals])
1093             | `GoOn sl(* , subst', goals' *) ->
1094 (*                 if (List.length goals') < (List.length goals) then best *)
1095 (*                 else `GoOn, subst, goals *)
1096                 `GoOn ((subst, goals)::sl)
1097         with ProofEngineTypes.Fail msg ->
1098           aux tl
1099   in
1100   let r, s, l =
1101     if Inference.term_is_equality term then
1102       let rec appleq = function
1103         | [] -> false, [], []
1104         | (Positive, equality)::tl ->
1105             let ok, s, newproof = apply_equality_to_goal env equality goal in
1106             if ok then true, s, [newproof, metas, term] else appleq tl
1107         | _::tl -> appleq tl
1108       in
1109       let al, _ = active in
1110       appleq al
1111     else
1112       false, [], []
1113   in
1114   if r = true then `Ok (s, l) else aux theorems
1115 ;;
1116
1117
1118 let apply_to_goal_conj env theorems active (depth, goals) =
1119   let rec aux = function
1120     | goal::tl ->
1121         let propagate_subst subst (proof, metas, term) =
1122           debug_print
1123             (lazy
1124                (Printf.sprintf "\npropagate_subst:\n%s\n%s, %s\n"
1125                   (print_subst subst) (string_of_proof proof)
1126                   (CicPp.ppterm term)));
1127           let rec repl = function
1128             | NoProof -> NoProof
1129             | BasicProof t ->
1130                 BasicProof (CicMetaSubst.apply_subst subst t)
1131             | ProofGoalBlock (p, pb) ->
1132                 debug_print (lazy "HERE");
1133                 let pb' = repl pb in
1134                 ProofGoalBlock (p, pb')
1135             | SubProof (t, i, p) ->
1136                 let t' = CicMetaSubst.apply_subst subst t in
1137                 debug_print
1138                   (lazy
1139                      (Printf.sprintf
1140                         "SubProof %d\nt = %s\nsubst = %s\nt' = %s\n"
1141                         i (CicPp.ppterm t) (print_subst subst)
1142                         (CicPp.ppterm t')));
1143                 let p = repl p in
1144                 SubProof (t', i, p)
1145             | ProofSymBlock (ens, p) -> ProofSymBlock (ens, repl p)
1146             | ProofBlock (s, u, nty, t, pe, p) ->
1147                 ProofBlock (subst @ s, u, nty, t, pe, p)
1148           in (repl proof, metas, term)
1149         in
1150         let r = apply_to_goal env theorems active goal in (
1151           match r with
1152           | `No -> `No (depth, goals)
1153           | `GoOn sl (* (subst, gl) *) ->
1154 (*               let tl = List.map (propagate_subst subst) tl in *)
1155               debug_print (lazy "GO ON!!!");
1156               let l =
1157                 List.map
1158                   (fun (s, gl) ->
1159                      (depth+1, gl @ (List.map (propagate_subst s) tl))) sl
1160               in
1161               debug_print
1162                 (lazy
1163                    (Printf.sprintf "%s\n"
1164                       (String.concat "; "
1165                          (List.map
1166                             (fun (s, gl) ->
1167                                (Printf.sprintf "[%s]"
1168                                   (String.concat "; "
1169                                      (List.map
1170                                         (fun (p, _, g) ->
1171                                            (Printf.sprintf "<%s, %s>"
1172                                               (string_of_proof p)
1173                                               (CicPp.ppterm g))) gl)))) l))));
1174               `GoOn l (* (depth+1, gl @ tl) *)
1175           | `Ok (subst, gl) ->
1176               if tl = [] then
1177 (*                 let _ = *)
1178 (*                   let p, _, t = List.hd gl in *)
1179 (*                   debug_print *)
1180 (*                     (lazy *)
1181 (*                        (Printf.sprintf "OK: %s, %s\n" *)
1182 (*                           (string_of_proof p) (CicPp.ppterm t))) *)
1183 (*                 in *)
1184                 `Ok (depth, gl)
1185               else
1186                 let p, _, _ = List.hd gl in
1187                 let subproof =
1188                   let rec repl = function
1189                     | SubProof (_, _, p) -> repl p
1190                     | ProofGoalBlock (p1, p2) ->
1191                         ProofGoalBlock (repl p1, repl p2)
1192                     | p -> p
1193                   in
1194                   build_proof_term (repl p)
1195                 in
1196                 let i = 
1197                   let rec get_meta = function
1198                     | SubProof (_, i, p) -> max i (get_meta p)
1199                     | ProofGoalBlock (_, p) -> get_meta p
1200                     | _ -> -1 (* assert false *)
1201                   in
1202                   get_meta p
1203                 in
1204                 let subst =
1205                   let _, (context, _, _) = List.hd subst in
1206                   [i, (context, subproof, Cic.Implicit None)]
1207                 in
1208                 let tl = List.map (propagate_subst subst) tl in
1209                 `GoOn ([depth+1, tl])
1210         )
1211     | _ -> assert false
1212   in
1213   debug_print
1214     (lazy
1215        (Printf.sprintf "apply_to_goal_conj (%d, [%s])"
1216           depth
1217           (String.concat "; "
1218              (List.map (fun (_, _, t) -> CicPp.ppterm t) goals))));
1219   if depth > !maxdepth || (List.length goals) > !maxwidth then (
1220     debug_print
1221       (lazy (Printf.sprintf "Pruning because depth = %d, width = %d"
1222                depth (List.length goals)));
1223     `No (depth, goals)
1224   ) else
1225     aux goals
1226 ;;
1227
1228
1229 module OrderedGoals = struct
1230   type t = int * (Inference.proof * Cic.metasenv * Cic.term) list
1231
1232   let compare g1 g2 =
1233     let d1, l1 = g1
1234     and d2, l2 = g2 in
1235     let r = d2 - d1 in
1236     if r <> 0 then r
1237     else let r = (List.length l1) - (List.length l2) in
1238     if r <> 0 then r
1239     else
1240       let res = ref 0 in
1241       let _ = 
1242         List.exists2
1243           (fun (_, _, t1) (_, _, t2) ->
1244              let r = Pervasives.compare t1 t2 in
1245              if r <> 0 then (
1246                res := r;
1247                true
1248              ) else
1249                false) l1 l2
1250       in !res
1251 (*       let res = Pervasives.compare g1 g2 in *)
1252 (*       let _ = *)
1253 (*         let print_goals (d, gl) =  *)
1254 (*           let gl' = List.map (fun (_, _, t) -> CicPp.ppterm t) gl in *)
1255 (*           Printf.sprintf "%d, [%s]" d (String.concat "; " gl') *)
1256 (*         in *)
1257 (*         debug_print *)
1258 (*           (lazy *)
1259 (*              (Printf.sprintf "comparing g1:%s and g2:%s, res: %d\n" *)
1260 (*                 (print_goals g1) (print_goals g2) res)) *)
1261 (*       in *)
1262 (*       res *)
1263 end
1264
1265 module GoalsSet = Set.Make(OrderedGoals);;
1266
1267
1268 exception SearchSpaceOver;;
1269
1270
1271 let apply_to_goals env is_passive_empty theorems active goals =
1272   debug_print (lazy "\n\n\tapply_to_goals\n\n");
1273   let add_to set goals =
1274     List.fold_left (fun s g -> GoalsSet.add g s) set goals 
1275   in
1276   let rec aux set = function
1277     | [] ->
1278         debug_print (lazy "HERE!!!");
1279         if is_passive_empty then raise SearchSpaceOver else false, set
1280     | goals::tl ->
1281         let res = apply_to_goal_conj env theorems active goals in
1282         match res with
1283         | `Ok newgoals ->
1284             let _ =
1285               let d, p, t =
1286                 match newgoals with
1287                 | (d, (p, _, t)::_) -> d, p, t
1288                 | _ -> assert false
1289               in
1290               debug_print
1291                 (lazy
1292                    (Printf.sprintf "\nOK!!!!\ndepth: %d\nProof: %s\ngoal: %s\n"
1293                       d (string_of_proof p) (CicPp.ppterm t)))
1294             in
1295             true, GoalsSet.singleton newgoals
1296         | `GoOn newgoals ->
1297             let print_set set msg = 
1298               debug_print
1299                 (lazy
1300                    (Printf.sprintf "%s:\n%s" msg
1301                       (String.concat "\n"
1302                          (GoalsSet.fold
1303                             (fun (d, gl) l ->
1304                                let gl' =
1305                                  List.map (fun (_, _, t) -> CicPp.ppterm t) gl
1306                                in
1307                                let s =
1308                                  Printf.sprintf "%d, [%s]" d
1309                                    (String.concat "; " gl')
1310                                in
1311                                s::l) set []))))
1312             in
1313             let set = add_to set (goals::tl) in
1314 (*             print_set set "SET BEFORE"; *)
1315             let n = GoalsSet.cardinal set in
1316             let set = add_to set newgoals in
1317 (*             print_set set "SET AFTER"; *)
1318             let m = GoalsSet.cardinal set in
1319 (*             if n < m then *)
1320             false, set
1321 (*             else *)
1322 (*               let _ = print_set set "SET didn't change" in *)
1323 (*               aux set tl *)
1324         | `No newgoals ->
1325             aux set tl
1326 (*             let set = add_to set (newgoals::goals::tl) in *)
1327 (*             let res, set = aux set tl in *)
1328 (*             res, set *)
1329   in
1330   let n = List.length goals in
1331   let res, goals = aux (add_to GoalsSet.empty goals) goals in
1332   let goals = GoalsSet.elements goals in
1333   debug_print (lazy "\n\tapply_to_goals end\n");
1334   let m = List.length goals in
1335   if m = n && is_passive_empty then
1336     raise SearchSpaceOver
1337   else
1338     res, goals
1339 ;;
1340
1341
1342 let rec given_clause env goals theorems passive active =
1343   let time1 = Unix.gettimeofday () in
1344
1345   let selection_estimate = get_selection_estimate () in
1346   let kept = size_of_passive passive in
1347   let passive =
1348     if !time_limit = 0. || !processed_clauses = 0 then
1349       passive
1350     else if !elapsed_time > !time_limit then (
1351       debug_print (lazy (Printf.sprintf "Time limit (%.2f) reached: %.2f\n"
1352                            !time_limit !elapsed_time));
1353       make_passive [] []
1354     ) else if kept > selection_estimate then (
1355       debug_print
1356         (lazy (Printf.sprintf ("Too many passive equalities: pruning..." ^^
1357                                  "(kept: %d, selection_estimate: %d)\n")
1358                  kept selection_estimate));
1359       prune_passive selection_estimate active passive
1360     ) else
1361       passive
1362   in
1363
1364   let time2 = Unix.gettimeofday () in
1365   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
1366
1367   kept_clauses := (size_of_passive passive) + (size_of_active active);
1368     
1369 (*   let refl_equal = *)
1370 (*     CicUtil.term_of_uri *)
1371 (*       (UriManager.uri_of_string "cic:/Coq/Init/Logic/eq.ind#xpointer(1/1/1)") *)
1372 (*   in *)
1373   let goals = simplify_goals env goals active in
1374   let theorems = simplify_theorems env theorems active in 
1375   let is_passive_empty = passive_is_empty passive in
1376   try
1377     let ok, goals = apply_to_goals env is_passive_empty theorems active goals in
1378     if ok then
1379       let proof =
1380         match goals with
1381         | (_, [proof, _, _])::_ -> Some proof
1382         | _ -> assert false
1383       in
1384       ParamodulationSuccess (proof, env)
1385     else
1386       match is_passive_empty (* passive_is_empty passive *) with
1387       | true -> (* ParamodulationFailure *)
1388           given_clause env goals theorems passive active
1389       | false ->
1390           let (sign, current), passive = select env goals passive active in
1391           let time1 = Unix.gettimeofday () in
1392           let res = forward_simplify env (sign, current) ~passive active in
1393           let time2 = Unix.gettimeofday () in
1394           forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
1395           match res with
1396           | None ->
1397               given_clause env goals theorems passive active
1398           | Some (sign, current) ->
1399               if (sign = Negative) && (is_identity env current) then (
1400                 debug_print
1401                   (lazy (Printf.sprintf "OK!!! %s %s" (string_of_sign sign)
1402                            (string_of_equality ~env current)));
1403                 let _, proof, _, _, _  = current in
1404                 ParamodulationSuccess (Some proof (* current *), env)
1405               ) else (            
1406                 debug_print
1407                   (lazy "\n================================================");
1408                 debug_print (lazy (Printf.sprintf "selected: %s %s"
1409                                      (string_of_sign sign)
1410                                      (string_of_equality ~env current)));
1411
1412                 let t1 = Unix.gettimeofday () in
1413                 let new' = infer env sign current active in
1414                 let t2 = Unix.gettimeofday () in
1415                 infer_time := !infer_time +. (t2 -. t1);
1416                 
1417                 let res, goal' = contains_empty env new' in
1418                 if res then
1419                   let proof =
1420                     match goal' with
1421                     | Some goal -> let _, proof, _, _, _ = goal in Some proof
1422                     | None -> None
1423                   in
1424                   ParamodulationSuccess (proof (* goal *), env)
1425                 else 
1426                   let t1 = Unix.gettimeofday () in
1427                   let new' = forward_simplify_new env new' active in
1428                   let t2 = Unix.gettimeofday () in
1429                   let _ =
1430                     forward_simpl_new_time :=
1431                       !forward_simpl_new_time +. (t2 -. t1)
1432                   in
1433                   let active =
1434                     match sign with
1435                     | Negative -> active
1436                     | Positive ->
1437                         let t1 = Unix.gettimeofday () in
1438                         let active, _, newa, _ =
1439                           backward_simplify env ([], [current]) active
1440                         in
1441                         let t2 = Unix.gettimeofday () in
1442                         backward_simpl_time :=
1443                           !backward_simpl_time +. (t2 -. t1);
1444                         match newa with
1445                         | None -> active
1446                         | Some (n, p) ->
1447                             let al, tbl = active in
1448                             let nn = List.map (fun e -> Negative, e) n in
1449                             let pp, tbl =
1450                               List.fold_right
1451                                 (fun e (l, t) ->
1452                                    (Positive, e)::l,
1453                                    Indexing.index tbl e)
1454                                 p ([], tbl)
1455                             in
1456                             nn @ al @ pp, tbl
1457                   in
1458 (*               let _ = *)
1459 (*                 Printf.printf "active:\n%s\n" *)
1460 (*                   (String.concat "\n" *)
1461 (*                      ((List.map *)
1462 (*                          (fun (s, e) -> (string_of_sign s) ^ " " ^ *)
1463 (*                             (string_of_equality ~env e)) (fst active)))); *)
1464 (*                 print_newline (); *)
1465 (*               in *)
1466 (*               let _ = *)
1467 (*                 match new' with *)
1468 (*                 | neg, pos -> *)
1469 (*                     Printf.printf "new':\n%s\n" *)
1470 (*                       (String.concat "\n" *)
1471 (*                          ((List.map *)
1472 (*                              (fun e -> "Negative " ^ *)
1473 (*                                 (string_of_equality ~env e)) neg) @ *)
1474 (*                             (List.map *)
1475 (*                                (fun e -> "Positive " ^ *)
1476 (*                                   (string_of_equality ~env e)) pos))); *)
1477 (*                     print_newline (); *)
1478 (*               in *)
1479                   match contains_empty env new' with
1480                   | false, _ -> 
1481                       let active =
1482                         let al, tbl = active in
1483                         match sign with
1484                         | Negative -> (sign, current)::al, tbl
1485                         | Positive ->
1486                             al @ [(sign, current)], Indexing.index tbl current
1487                       in
1488                       let passive = add_to_passive passive new' in
1489                       let (_, ns), (_, ps), _ = passive in
1490 (*                   Printf.printf "passive:\n%s\n" *)
1491 (*                     (String.concat "\n" *)
1492 (*                        ((List.map (fun e -> "Negative " ^ *)
1493 (*                                      (string_of_equality ~env e)) *)
1494 (*                            (EqualitySet.elements ns)) @ *)
1495 (*                           (List.map (fun e -> "Positive " ^ *)
1496 (*                                        (string_of_equality ~env e)) *)
1497 (*                              (EqualitySet.elements ps)))); *)
1498 (*                   print_newline (); *)
1499                       given_clause env goals theorems passive active
1500                   | true, goal ->
1501                       let proof =
1502                         match goal with
1503                         | Some goal ->
1504                             let _, proof, _, _, _ = goal in Some proof
1505                         | None -> None
1506                       in
1507                       ParamodulationSuccess (proof (* goal *), env)
1508               )
1509   with SearchSpaceOver ->
1510     ParamodulationFailure
1511 ;;
1512
1513
1514 let rec given_clause_fullred env goals theorems passive active =
1515   let time1 = Unix.gettimeofday () in
1516   
1517   let selection_estimate = get_selection_estimate () in
1518   let kept = size_of_passive passive in
1519   let passive =
1520     if !time_limit = 0. || !processed_clauses = 0 then
1521       passive
1522     else if !elapsed_time > !time_limit then (
1523       debug_print (lazy (Printf.sprintf "Time limit (%.2f) reached: %.2f\n"
1524                            !time_limit !elapsed_time));
1525       make_passive [] []
1526     ) else if kept > selection_estimate then (
1527       debug_print
1528         (lazy (Printf.sprintf ("Too many passive equalities: pruning..." ^^
1529                                  "(kept: %d, selection_estimate: %d)\n")
1530                  kept selection_estimate));
1531       prune_passive selection_estimate active passive
1532     ) else
1533       passive
1534   in
1535
1536   let time2 = Unix.gettimeofday () in
1537   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
1538     
1539   kept_clauses := (size_of_passive passive) + (size_of_active active);
1540
1541 (*   let refl_equal = *)
1542 (*     CicUtil.term_of_uri *)
1543 (*       (UriManager.uri_of_string "cic:/Coq/Init/Logic/eq.ind#xpointer(1/1/1)") *)
1544 (*   in *)
1545   let goals = simplify_goals env goals ~passive active in
1546   let theorems = simplify_theorems env theorems ~passive active in
1547   let is_passive_empty = passive_is_empty passive in
1548   try
1549     let ok, goals = apply_to_goals env is_passive_empty theorems active goals in
1550     if ok then
1551       let proof =
1552         match goals with
1553         | (_, [proof, _, _])::_ -> Some proof
1554         | _ -> assert false
1555       in
1556       ParamodulationSuccess (proof, env)
1557     else
1558       let _ =
1559         debug_print
1560           (lazy ("new_goals: " ^ (string_of_int (List.length goals))));
1561         debug_print
1562           (lazy
1563              (String.concat "\n"
1564                 (List.map
1565                    (fun (d, gl) ->
1566                       let gl' =
1567                         List.map
1568                           (fun (p, _, t) ->
1569                              (string_of_proof p) ^ ", " ^ (CicPp.ppterm t)) gl
1570                       in
1571                       Printf.sprintf "%d: %s" d (String.concat "; " gl'))
1572                    goals)));
1573       in
1574       match is_passive_empty (* passive_is_empty passive *) with
1575       | true -> (* ParamodulationFailure *)
1576           given_clause_fullred env goals theorems passive active        
1577       | false ->
1578           let (sign, current), passive = select env goals passive active in
1579           let time1 = Unix.gettimeofday () in
1580           let res = forward_simplify env (sign, current) ~passive active in
1581           let time2 = Unix.gettimeofday () in
1582           forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
1583           match res with
1584           | None ->
1585               given_clause_fullred env goals theorems passive active
1586           | Some (sign, current) ->
1587               if (sign = Negative) && (is_identity env current) then (
1588                 debug_print
1589                   (lazy (Printf.sprintf "OK!!! %s %s" (string_of_sign sign)
1590                            (string_of_equality ~env current)));
1591                 let _, proof, _, _, _ = current in 
1592                 ParamodulationSuccess (Some proof (* current *), env)
1593               ) else (
1594                 debug_print
1595                   (lazy "\n================================================");
1596                 debug_print (lazy (Printf.sprintf "selected: %s %s"
1597                                      (string_of_sign sign)
1598                                      (string_of_equality ~env current)));
1599
1600                 let t1 = Unix.gettimeofday () in
1601                 let new' = infer env sign current active in
1602                 let t2 = Unix.gettimeofday () in
1603                 infer_time := !infer_time +. (t2 -. t1);
1604
1605                 let active =
1606                   if is_identity env current then active
1607                   else
1608                     let al, tbl = active in
1609                     match sign with
1610                     | Negative -> (sign, current)::al, tbl
1611                     | Positive ->
1612                         al @ [(sign, current)], Indexing.index tbl current
1613                 in
1614                 let rec simplify new' active passive =
1615                   let t1 = Unix.gettimeofday () in
1616                   let new' = forward_simplify_new env new' ~passive active in
1617                   let t2 = Unix.gettimeofday () in
1618                   forward_simpl_new_time :=
1619                     !forward_simpl_new_time +. (t2 -. t1);
1620                   let t1 = Unix.gettimeofday () in
1621                   let active, passive, newa, retained =
1622                     backward_simplify env new' ~passive active in
1623                   let t2 = Unix.gettimeofday () in
1624                   backward_simpl_time := !backward_simpl_time +. (t2 -. t1);
1625                   match newa, retained with
1626                   | None, None -> active, passive, new'
1627                   | Some (n, p), None
1628                   | None, Some (n, p) ->
1629                       let nn, np = new' in
1630                       simplify (nn @ n, np @ p) active passive
1631                   | Some (n, p), Some (rn, rp) ->
1632                       let nn, np = new' in
1633                       simplify (nn @ n @ rn, np @ p @ rp) active passive
1634                 in
1635                 let active, passive, new' = simplify new' active passive in
1636
1637                 let k = size_of_passive passive in
1638                 if k < (kept - 1) then
1639                   processed_clauses := !processed_clauses + (kept - 1 - k);
1640                 
1641                 let _ =
1642                   debug_print
1643                     (lazy
1644                        (Printf.sprintf "active:\n%s\n"
1645                           (String.concat "\n"
1646                              ((List.map
1647                                  (fun (s, e) -> (string_of_sign s) ^ " " ^
1648                                     (string_of_equality ~env e))
1649                                  (fst active))))))
1650                 in
1651                 let _ =
1652                   match new' with
1653                   | neg, pos ->
1654                       debug_print
1655                         (lazy
1656                            (Printf.sprintf "new':\n%s\n"
1657                               (String.concat "\n"
1658                                  ((List.map
1659                                      (fun e -> "Negative " ^
1660                                         (string_of_equality ~env e)) neg) @
1661                                     (List.map
1662                                        (fun e -> "Positive " ^
1663                                           (string_of_equality ~env e)) pos)))))
1664                 in
1665                 match contains_empty env new' with
1666                 | false, _ -> 
1667                     let passive = add_to_passive passive new' in
1668 (*                 let (_, ns), (_, ps), _ = passive in *)
1669 (*                 Printf.printf "passive:\n%s\n" *)
1670 (*                   (String.concat "\n" *)
1671 (*                      ((List.map (fun e -> "Negative " ^ *)
1672 (*                                    (string_of_equality ~env e)) *)
1673 (*                          (EqualitySet.elements ns)) @ *)
1674 (*                         (List.map (fun e -> "Positive " ^ *)
1675 (*                                      (string_of_equality ~env e)) *)
1676 (*                            (EqualitySet.elements ps)))); *)
1677 (*                 print_newline (); *)
1678                     given_clause_fullred env goals theorems passive active
1679                 | true, goal ->
1680                     let proof =
1681                       match goal with
1682                       | Some goal -> let _, proof, _, _, _ = goal in Some proof
1683                       | None -> None
1684                     in
1685                     ParamodulationSuccess (proof (* goal *), env)
1686               )
1687   with SearchSpaceOver ->
1688     ParamodulationFailure
1689 ;;
1690
1691
1692 (* let given_clause_ref = ref given_clause;; *)
1693
1694 let main dbd term metasenv ugraph =
1695   let module C = Cic in
1696   let module T = CicTypeChecker in
1697   let module PET = ProofEngineTypes in
1698   let module PP = CicPp in
1699   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1700   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1701   let proof, goals = status in
1702   let goal' = List.nth goals 0 in
1703   let _, metasenv, meta_proof, _ = proof in
1704   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1705   let eq_indexes, equalities, maxm = find_equalities context proof in
1706   let lib_eq_uris, library_equalities, maxm =
1707     find_library_equalities dbd context (proof, goal') (maxm+2)
1708   in
1709   maxmeta := maxm+2; (* TODO ugly!! *)
1710   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
1711   let new_meta_goal, metasenv, type_of_goal =
1712     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1713     Printf.printf "\n\nTIPO DEL GOAL: %s\n" (CicPp.ppterm ty);
1714     print_newline ();
1715     Cic.Meta (maxm+1, irl),
1716     (maxm+1, context, ty)::metasenv,
1717     ty
1718   in
1719 (*   let new_meta_goal = Cic.Meta (goal', irl) in *)
1720   let env = (metasenv, context, ugraph) in
1721   let theorems = find_library_theorems dbd env (proof, goal') lib_eq_uris in
1722   let context_hyp = find_context_hypotheses env eq_indexes in
1723   let theorems = context_hyp @ theorems in
1724   let _ =
1725     debug_print
1726       (lazy
1727          (Printf.sprintf
1728             "Theorems:\n-------------------------------------\n%s\n"
1729             (String.concat "\n"
1730                (List.map
1731                   (fun (t, ty, _) ->
1732                      Printf.sprintf
1733                        "Term: %s, type: %s" (CicPp.ppterm t) (CicPp.ppterm ty))
1734                   theorems))))
1735   in
1736   try
1737     let goal = Inference.BasicProof new_meta_goal, [], goal in
1738 (*     let term_equality = equality_of_term new_meta_goal goal in *)
1739 (*     let _, meta_proof, (eq_ty, left, right, ordering), _, _ = term_equality in *)
1740 (*     if is_identity env term_equality then *)
1741 (*       let proof = *)
1742 (*         Cic.Appl [Cic.MutConstruct (\* reflexivity *\) *)
1743 (*                     (HelmLibraryObjects.Logic.eq_URI, 0, 1, []); *)
1744 (*                   eq_ty; left] *)
1745 (*       in *)
1746 (*       let _ =  *)
1747 (*         Printf.printf "OK, found a proof!\n"; *)
1748 (*         let names = names_of_context context in *)
1749 (*         print_endline (PP.pp proof names) *)
1750 (*       in *)
1751 (*       () *)
1752 (*     else *)
1753       let equalities =
1754         let equalities = equalities @ library_equalities in
1755         debug_print
1756           (lazy 
1757              (Printf.sprintf "equalities:\n%s\n"
1758                 (String.concat "\n"
1759                    (List.map string_of_equality equalities))));
1760         debug_print (lazy "SIMPLYFYING EQUALITIES...");
1761         let rec simpl e others others_simpl =
1762           let active = others @ others_simpl in
1763           let tbl =
1764             List.fold_left
1765               (fun t (_, e) -> Indexing.index t e)
1766               (Indexing.empty_table ()) active
1767           in
1768           let res = forward_simplify env e (active, tbl) in
1769           match others with
1770           | hd::tl -> (
1771               match res with
1772               | None -> simpl hd tl others_simpl
1773               | Some e -> simpl hd tl (e::others_simpl)
1774             )
1775           | [] -> (
1776               match res with
1777               | None -> others_simpl
1778               | Some e -> e::others_simpl
1779             )
1780         in
1781         match equalities with
1782         | [] -> []
1783         | hd::tl ->
1784             let others = List.map (fun e -> (Positive, e)) tl in
1785             let res =
1786               List.rev (List.map snd (simpl (Positive, hd) others []))
1787             in
1788             debug_print
1789               (lazy
1790                  (Printf.sprintf "equalities AFTER:\n%s\n"
1791                     (String.concat "\n"
1792                        (List.map string_of_equality res))));
1793             res
1794       in
1795       let active = make_active () in
1796       let passive = make_passive [] (* [term_equality] *) equalities in
1797       Printf.printf "\ncurrent goal: %s\n"
1798         (let _, _, g = goal in CicPp.ppterm g);
1799 (*         (string_of_equality ~env term_equality); *)
1800       Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
1801       Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
1802       Printf.printf "\nequalities:\n%s\n"
1803         (String.concat "\n"
1804            (List.map
1805               (string_of_equality ~env)
1806               (equalities @ library_equalities)));
1807       print_endline "--------------------------------------------------";
1808       let start = Unix.gettimeofday () in
1809       print_endline "GO!";
1810       start_time := Unix.gettimeofday ();
1811       let res =
1812         (if !use_fullred then given_clause_fullred else given_clause)
1813           env [0, [goal]] theorems passive active
1814       in
1815       let finish = Unix.gettimeofday () in
1816       let _ =
1817         match res with
1818         | ParamodulationFailure ->
1819             Printf.printf "NO proof found! :-(\n\n"
1820         | ParamodulationSuccess (Some proof (* goal *), env) ->
1821 (*             let proof = Inference.build_proof_term goal in          *)
1822             let proof = Inference.build_proof_term proof in
1823             Printf.printf "OK, found a proof!\n";
1824             (* REMEMBER: we have to instantiate meta_proof, we should use
1825                apply  the "apply" tactic to proof and status 
1826             *)
1827             let names = names_of_context context in
1828             print_endline (PP.pp proof names);
1829             let newmetasenv =
1830               List.fold_left
1831                 (fun m (_, _, _, menv, _) -> m @ menv) metasenv equalities
1832             in
1833             let _ =
1834               Printf.printf "OK, found a proof!\n";
1835               (* REMEMBER: we have to instantiate meta_proof, we should use
1836                  apply  the "apply" tactic to proof and status 
1837               *)
1838               let names = names_of_context context in
1839               print_endline (PP.pp proof names);
1840               try
1841                 let ty, ug =
1842                   CicTypeChecker.type_of_aux' newmetasenv context proof ugraph
1843                 in
1844 (*                 Printf.printf "OK, found a proof!\n"; *)
1845 (*                 (\* REMEMBER: we have to instantiate meta_proof, we should use *)
1846 (*                    apply  the "apply" tactic to proof and status  *)
1847 (*                 *\) *)
1848 (*                 let names = names_of_context context in *)
1849 (*                 print_endline (PP.pp proof names); *)
1850                 (*           print_endline (PP.ppterm proof); *)
1851                 
1852                 print_endline (string_of_float (finish -. start));
1853                 Printf.printf
1854                   "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n\n"
1855                   (CicPp.pp type_of_goal names) (CicPp.pp ty names)
1856                   (string_of_bool
1857                      (fst (CicReduction.are_convertible
1858                              context type_of_goal ty ug)));
1859               with e ->
1860                 Printf.printf "\nEXCEPTION!!! %s\n" (Printexc.to_string e);
1861                 Printf.printf "MAXMETA USED: %d\n" !maxmeta;
1862                 print_endline (string_of_float (finish -. start));
1863             in
1864             ()
1865               
1866         | ParamodulationSuccess (None, env) ->
1867             Printf.printf "Success, but no proof?!?\n\n"
1868       in
1869       Printf.printf ("infer_time: %.9f\nforward_simpl_time: %.9f\n" ^^
1870                        "forward_simpl_new_time: %.9f\n" ^^
1871                        "backward_simpl_time: %.9f\n")
1872         !infer_time !forward_simpl_time !forward_simpl_new_time
1873         !backward_simpl_time;
1874       Printf.printf "passive_maintainance_time: %.9f\n"
1875         !passive_maintainance_time;
1876       Printf.printf "    successful unification/matching time: %.9f\n"
1877         !Indexing.match_unif_time_ok;
1878       Printf.printf "    failed unification/matching time: %.9f\n"
1879         !Indexing.match_unif_time_no;
1880       Printf.printf "    indexing retrieval time: %.9f\n"
1881         !Indexing.indexing_retrieval_time;
1882       Printf.printf "    demodulate_term.build_newtarget_time: %.9f\n"
1883         !Indexing.build_newtarget_time;
1884       Printf.printf "derived %d clauses, kept %d clauses.\n"
1885         !derived_clauses !kept_clauses;
1886   with exc ->
1887     print_endline ("EXCEPTION: " ^ (Printexc.to_string exc));
1888     raise exc
1889 ;;
1890
1891
1892 let default_depth = !maxdepth
1893 and default_width = !maxwidth;;
1894
1895 let saturate
1896     dbd ?(full=false) ?(depth=default_depth) ?(width=default_width) status = 
1897   let module C = Cic in
1898   maxmeta := 0;
1899   maxdepth := depth;
1900   maxwidth := width;
1901   let proof, goal = status in
1902   let goal' = goal in
1903   let uri, metasenv, meta_proof, term_to_prove = proof in
1904   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1905   let eq_indexes, equalities, maxm = find_equalities context proof in
1906   let new_meta_goal, metasenv, type_of_goal =
1907     let irl =
1908       CicMkImplicit.identity_relocation_list_for_metavariable context in
1909     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1910     debug_print
1911       (lazy (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n" (CicPp.ppterm ty)));
1912     Cic.Meta (maxm+1, irl),
1913     (maxm+1, context, ty)::metasenv,
1914     ty
1915   in
1916   let ugraph = CicUniv.empty_ugraph in
1917   let env = (metasenv, context, ugraph) in
1918   let goal = Inference.BasicProof new_meta_goal, [], goal in
1919   let res, time = 
1920     let lib_eq_uris, library_equalities, maxm =
1921       find_library_equalities dbd context (proof, goal') (maxm+2)
1922     in
1923     maxmeta := maxm+2;
1924     let equalities =
1925       let equalities = equalities @ library_equalities in
1926       debug_print
1927         (lazy
1928            (Printf.sprintf "equalities:\n%s\n"
1929               (String.concat "\n"
1930                  (List.map string_of_equality equalities))));
1931       debug_print (lazy "SIMPLYFYING EQUALITIES...");
1932       let rec simpl e others others_simpl =
1933         let active = others @ others_simpl in
1934         let tbl =
1935           List.fold_left
1936             (fun t (_, e) -> Indexing.index t e)
1937             (Indexing.empty_table ()) active
1938         in
1939         let res = forward_simplify env e (active, tbl) in
1940         match others with
1941         | hd::tl -> (
1942             match res with
1943             | None -> simpl hd tl others_simpl
1944             | Some e -> simpl hd tl (e::others_simpl)
1945           )
1946         | [] -> (
1947             match res with
1948             | None -> others_simpl
1949             | Some e -> e::others_simpl
1950           )
1951       in
1952       match equalities with
1953       | [] -> []
1954       | hd::tl ->
1955           let others = List.map (fun e -> (Positive, e)) tl in
1956           let res =
1957             List.rev (List.map snd (simpl (Positive, hd) others []))
1958           in
1959           debug_print
1960             (lazy
1961                (Printf.sprintf "equalities AFTER:\n%s\n"
1962                   (String.concat "\n"
1963                      (List.map string_of_equality res))));
1964           res
1965     in
1966     let theorems =
1967       if full then
1968         let thms = find_library_theorems dbd env (proof, goal') lib_eq_uris in
1969         let context_hyp = find_context_hypotheses env eq_indexes in
1970         context_hyp @ thms
1971       else
1972         let refl_equal =
1973           let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
1974           UriManager.uri_of_string (us ^ "#xpointer(1/1/1)")
1975         in
1976         let t = CicUtil.term_of_uri refl_equal in
1977         let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
1978         [(t, ty, [])]
1979     in
1980     let _ =
1981       debug_print
1982         (lazy
1983            (Printf.sprintf
1984               "Theorems:\n-------------------------------------\n%s\n"
1985               (String.concat "\n"
1986                  (List.map
1987                     (fun (t, ty, _) ->
1988                        Printf.sprintf
1989                          "Term: %s, type: %s"
1990                          (CicPp.ppterm t) (CicPp.ppterm ty))
1991                     theorems))))
1992     in
1993     let active = make_active () in
1994     let passive = make_passive [(* term_equality *)] equalities in
1995     let start = Unix.gettimeofday () in
1996     let res = given_clause_fullred env [0, [goal]] theorems passive active in
1997     let finish = Unix.gettimeofday () in
1998     (res, finish -. start)
1999   in
2000   match res with
2001   | ParamodulationSuccess (Some proof (* goal *), env) ->
2002       debug_print (lazy "OK, found a proof!");
2003 (*       let proof = Inference.build_proof_term goal in          *)
2004       let proof = Inference.build_proof_term proof in
2005       let names = names_of_context context in
2006       let newmetasenv =
2007         let i1 =
2008           match new_meta_goal with
2009           | C.Meta (i, _) -> i | _ -> assert false
2010         in
2011         List.filter (fun (i, _, _) -> i <> i1 && i <> goal') metasenv
2012       in
2013       let newstatus =
2014         try
2015           let ty, ug =
2016             CicTypeChecker.type_of_aux' newmetasenv context proof ugraph
2017           in
2018           debug_print (lazy (CicPp.pp proof [](* names *)));
2019           debug_print
2020             (lazy
2021                (Printf.sprintf
2022                   "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n"
2023                   (CicPp.pp type_of_goal names) (CicPp.pp ty names)
2024                   (string_of_bool
2025                      (fst (CicReduction.are_convertible
2026                              context type_of_goal ty ug)))));
2027           let equality_for_replace i t1 =
2028             match t1 with
2029             | C.Meta (n, _) -> n = i
2030             | _ -> false
2031           in
2032           let real_proof =
2033             ProofEngineReduction.replace
2034               ~equality:equality_for_replace
2035               ~what:[goal'] ~with_what:[proof]
2036               ~where:meta_proof
2037           in
2038           debug_print
2039             (lazy
2040                (Printf.sprintf "status:\n%s\n%s\n%s\n%s\n"
2041                   (match uri with Some uri -> UriManager.string_of_uri uri
2042                    | None -> "")
2043                   (print_metasenv newmetasenv)
2044                   (CicPp.pp real_proof [](* names *))
2045                   (CicPp.pp term_to_prove names)));
2046           ((uri, newmetasenv, real_proof, term_to_prove), [])
2047         with CicTypeChecker.TypeCheckerFailure _ ->
2048           debug_print (lazy "THE PROOF DOESN'T TYPECHECK!!!");
2049           debug_print (lazy (CicPp.pp proof names));
2050           raise (ProofEngineTypes.Fail
2051                    "Found a proof, but it doesn't typecheck")
2052       in
2053       debug_print (lazy (Printf.sprintf "\nTIME NEEDED: %.9f" time));
2054       newstatus          
2055   | _ ->
2056       raise (ProofEngineTypes.Fail "NO proof found")
2057 ;;
2058
2059 (* dummy function called within matita to trigger linkage *)
2060 let init () = ();;
2061
2062
2063 (* UGLY SIDE EFFECT... *)
2064 if connect_to_auto then ( 
2065   AutoTactic.paramodulation_tactic := saturate;
2066   AutoTactic.term_is_equality := Inference.term_is_equality;
2067 );;
2068