]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/paramodulation/saturation.ml
new paramodulation
[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 = C.Appl [C.MutInd (HL.Logic.eq_URI, 0, []); ty; left; right] in
879   let gproof, gmetas, gterm = goal in
880   try
881     let subst, metasenv', _ =
882       let menv = metasenv @ metas @ gmetas in
883       Inference.unification menv context eqterm gterm ugraph
884     in
885     let newproof =
886       match proof with
887       | I.BasicProof t -> I.BasicProof (CicMetaSubst.apply_subst subst t)
888       | I.ProofBlock (s, uri, nt, t, pe, p) ->
889           I.ProofBlock (subst @ s, uri, nt, t, pe, p)
890       | _ -> assert false
891     in
892     let newgproof =
893       let rec repl = function
894         | I.ProofGoalBlock (_, gp) -> I.ProofGoalBlock (newproof, gp)
895         | I.NoProof -> newproof
896         | I.BasicProof p -> newproof
897         | I.SubProof (t, i, p) -> I.SubProof (t, i, repl p)
898         | _ -> assert false
899       in
900       repl gproof
901     in
902     true, subst, newgproof
903   with CicUnification.UnificationFailure _ ->
904     false, [], I.NoProof
905 ;;
906
907
908 (*
909 let apply_to_goal env theorems active (depth, goals) =
910   let _ =
911     debug_print ("apply_to_goal: " ^ (string_of_int (List.length goals)))
912   in
913   let metasenv, context, ugraph = env in
914   let goal = List.hd goals in
915   let proof, metas, term = goal in
916 (*   debug_print *)
917 (*     (Printf.sprintf "apply_to_goal with goal: %s" (CicPp.ppterm term)); *)
918   let newmeta = CicMkImplicit.new_meta metasenv [] in
919   let metasenv = (newmeta, context, term)::metasenv @ metas in
920   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
921   let status =
922     ((None, metasenv, Cic.Meta (newmeta, irl), term), newmeta)
923   in
924   let rec aux = function
925     | [] -> false, [] (* goals *) (* None *)
926     | (theorem, thmty, _)::tl ->
927         try
928           let subst_in, (newproof, newgoals) =
929             PrimitiveTactics.apply_tac_verbose ~term:theorem status
930           in
931           if newgoals = [] then
932             let _, _, p, _ = newproof in
933             let newp =
934               let rec repl = function
935                 | Inference.ProofGoalBlock (_, gp) ->
936                     Inference.ProofGoalBlock (Inference.BasicProof p, gp)
937                 | Inference.NoProof -> Inference.BasicProof p
938                 | Inference.BasicProof _ -> Inference.BasicProof p
939                 | Inference.SubProof (t, i, p2) ->
940                     Inference.SubProof (t, i, repl p2)
941                 | _ -> assert false
942               in
943               repl proof
944             in
945             true, [[newp, metas, term]] (* Some newp *)
946           else if List.length newgoals = 1 then
947             let _, menv, p, _ = newproof in
948             let irl =
949               CicMkImplicit.identity_relocation_list_for_metavariable context
950             in
951             let goals =
952               List.map
953                 (fun i ->
954                    let _, _, ty = CicUtil.lookup_meta i menv in
955                    let proof =
956                      Inference.SubProof
957                        (p, i, Inference.BasicProof (Cic.Meta (i, irl)))
958                    in (proof, menv, ty))
959                 newgoals
960             in
961             let res, others = aux tl in
962             if res then (true, others) else (false, goals::others)
963           else
964             aux tl
965         with ProofEngineTypes.Fail msg ->
966           (*     debug_print ("FAIL!!:" ^ msg); *)
967           aux tl
968   in
969   let r, l =
970     if Inference.term_is_equality term then
971       let rec appleq = function
972         | [] -> false, []
973         | (Positive, equality)::tl ->
974             let ok, _, newproof = apply_equality_to_goal env equality goal in
975             if ok then true, [(depth, [newproof, metas, term])] else appleq tl
976         | _::tl -> appleq tl
977       in
978       let al, _ = active in
979       appleq al
980     else
981       false, []
982   in
983   if r = true then r, l else
984     let r, l = aux theorems in
985     if r = true then
986       r, List.map (fun l -> (depth+1, l)) l
987     else
988       r, (depth, goals)::(List.map (fun l -> (depth+1, l)) l)
989 ;;
990 *)
991
992
993 let new_meta () =
994   incr maxmeta; !maxmeta
995 ;;
996
997
998 let apply_to_goal env theorems active goal =
999   let metasenv, context, ugraph = env in
1000   let proof, metas, term = goal in
1001   debug_print
1002     (lazy
1003        (Printf.sprintf "apply_to_goal with goal: %s, %s"
1004           (string_of_proof proof) (CicPp.ppterm term)));
1005   let status =
1006     let irl =
1007       CicMkImplicit.identity_relocation_list_for_metavariable context in
1008     let proof', newmeta =
1009       let rec get_meta = function
1010         | SubProof (t, i, _) -> t, i
1011         | ProofGoalBlock (_, p) -> get_meta p
1012         | _ ->
1013             let n = new_meta () in (* CicMkImplicit.new_meta metasenv [] in *)
1014             Cic.Meta (n, irl), n
1015       in
1016       get_meta proof
1017     in
1018 (*     let newmeta = CicMkImplicit.new_meta metasenv [] in *)
1019     let metasenv = (newmeta, context, term)::metasenv @ metas in
1020     ((None, metasenv, Cic.Meta (newmeta, irl), term), newmeta)
1021 (*     ((None, metasenv, proof', term), newmeta) *)
1022   in
1023   let rec aux = function
1024     | [] -> `No (* , [], [] *)
1025     | (theorem, thmty, _)::tl ->
1026         try
1027           let subst, (newproof, newgoals) =
1028             PrimitiveTactics.apply_tac_verbose_with_subst ~term:theorem status
1029           in
1030           if newgoals = [] then
1031             let _, _, p, _ = newproof in
1032             let newp =
1033               let rec repl = function
1034                 | Inference.ProofGoalBlock (_, gp) ->
1035                     Inference.ProofGoalBlock (Inference.BasicProof p, gp)
1036                 | Inference.NoProof -> Inference.BasicProof p
1037                 | Inference.BasicProof _ -> Inference.BasicProof p
1038                 | Inference.SubProof (t, i, p2) ->
1039                     Inference.SubProof (t, i, repl p2)
1040                 | _ -> assert false
1041               in
1042               repl proof
1043             in
1044             let _, m = status in
1045             let subst = List.filter (fun (i, _) -> i = m) subst in
1046 (*             debug_print *)
1047 (*               (lazy *)
1048 (*                  (Printf.sprintf "m = %d\nsubst = %s\n" *)
1049 (*                     m (print_subst subst))); *)
1050             `Ok (subst, [newp, metas, term])
1051           else
1052             let _, menv, p, _ = newproof in
1053             let irl =
1054               CicMkImplicit.identity_relocation_list_for_metavariable context
1055             in
1056             let goals =
1057               List.map
1058                 (fun i ->
1059                    let _, _, ty = CicUtil.lookup_meta i menv in
1060                    let p' =
1061                      let rec gp = function
1062                        | SubProof (t, i, p) ->
1063                            SubProof (t, i, gp p)
1064                        | ProofGoalBlock (sp1, sp2) ->
1065 (*                            SubProof (p, i, sp) *)
1066                            ProofGoalBlock (sp1, gp sp2)
1067 (*                            gp sp *)
1068                        | BasicProof _
1069                        | NoProof ->
1070                            SubProof (p, i, BasicProof (Cic.Meta (i, irl)))
1071                        | ProofSymBlock (s, sp) ->
1072                            ProofSymBlock (s, gp sp)
1073                        | ProofBlock (s, u, nt, t, pe, sp) ->
1074                            ProofBlock (s, u, nt, t, pe, gp sp)
1075 (*                        | _ -> assert false *)
1076                      in gp proof
1077                    in
1078                    debug_print
1079                      (lazy
1080                         (Printf.sprintf "new sub goal: %s, %s"
1081                            (string_of_proof p') (CicPp.ppterm ty)));
1082                    (p', menv, ty))
1083                 newgoals
1084             in
1085 (*             debug_print *)
1086 (*               (lazy *)
1087 (*                  (Printf.sprintf "\nGoOn with subst: %s" (print_subst subst))); *)
1088             let best = aux tl in
1089             match best with
1090             | `Ok (_, _) -> best
1091             | `No -> `GoOn ([subst, goals])
1092             | `GoOn sl(* , subst', goals' *) ->
1093 (*                 if (List.length goals') < (List.length goals) then best *)
1094 (*                 else `GoOn, subst, goals *)
1095                 `GoOn ((subst, goals)::sl)
1096         with ProofEngineTypes.Fail msg ->
1097           aux tl
1098   in
1099   let r, s, l =
1100     if Inference.term_is_equality term then
1101       let rec appleq = function
1102         | [] -> false, [], []
1103         | (Positive, equality)::tl ->
1104             let ok, s, newproof = apply_equality_to_goal env equality goal in
1105             if ok then true, s, [newproof, metas, term] else appleq tl
1106         | _::tl -> appleq tl
1107       in
1108       let al, _ = active in
1109       appleq al
1110     else
1111       false, [], []
1112   in
1113   if r = true then `Ok (s, l) else aux theorems
1114 ;;
1115
1116
1117 let apply_to_goal_conj env theorems active (depth, goals) =
1118   let rec aux = function
1119     | goal::tl ->
1120         let propagate_subst subst (proof, metas, term) =
1121           debug_print
1122             (lazy
1123                (Printf.sprintf "\npropagate_subst:\n%s\n%s, %s\n"
1124                   (print_subst subst) (string_of_proof proof)
1125                   (CicPp.ppterm term)));
1126           let rec repl = function
1127             | NoProof -> NoProof
1128             | BasicProof t ->
1129                 BasicProof (CicMetaSubst.apply_subst subst t)
1130             | ProofGoalBlock (p, pb) ->
1131                 debug_print (lazy "HERE");
1132                 let pb' = repl pb in
1133                 ProofGoalBlock (p, pb')
1134             | SubProof (t, i, p) ->
1135                 let t' = CicMetaSubst.apply_subst subst t in
1136                 debug_print
1137                   (lazy
1138                      (Printf.sprintf
1139                         "SubProof %d\nt = %s\nsubst = %s\nt' = %s\n"
1140                         i (CicPp.ppterm t) (print_subst subst)
1141                         (CicPp.ppterm t')));
1142                 let p = repl p in
1143                 SubProof (t', i, p)
1144             | ProofSymBlock (ens, p) -> ProofSymBlock (ens, repl p)
1145             | ProofBlock (s, u, nty, t, pe, p) ->
1146                 ProofBlock (subst @ s, u, nty, t, pe, p)
1147           in (repl proof, metas, term)
1148         in
1149         let r = apply_to_goal env theorems active goal in (
1150           match r with
1151           | `No -> `No (depth, goals)
1152           | `GoOn sl (* (subst, gl) *) ->
1153 (*               let tl = List.map (propagate_subst subst) tl in *)
1154               debug_print (lazy "GO ON!!!");
1155               let l =
1156                 List.map
1157                   (fun (s, gl) ->
1158                      (depth+1, gl @ (List.map (propagate_subst s) tl))) sl
1159               in
1160               debug_print
1161                 (lazy
1162                    (Printf.sprintf "%s\n"
1163                       (String.concat "; "
1164                          (List.map
1165                             (fun (s, gl) ->
1166                                (Printf.sprintf "[%s]"
1167                                   (String.concat "; "
1168                                      (List.map
1169                                         (fun (p, _, g) ->
1170                                            (Printf.sprintf "<%s, %s>"
1171                                               (string_of_proof p)
1172                                               (CicPp.ppterm g))) gl)))) l))));
1173               `GoOn l (* (depth+1, gl @ tl) *)
1174           | `Ok (subst, gl) ->
1175               if tl = [] then
1176 (*                 let _ = *)
1177 (*                   let p, _, t = List.hd gl in *)
1178 (*                   debug_print *)
1179 (*                     (lazy *)
1180 (*                        (Printf.sprintf "OK: %s, %s\n" *)
1181 (*                           (string_of_proof p) (CicPp.ppterm t))) *)
1182 (*                 in *)
1183                 `Ok (depth, gl)
1184               else
1185                 let p, _, _ = List.hd gl in
1186                 let subproof =
1187                   let rec repl = function
1188                     | SubProof (_, _, p) -> repl p
1189                     | ProofGoalBlock (p1, p2) ->
1190                         ProofGoalBlock (repl p1, repl p2)
1191                     | p -> p
1192                   in
1193                   build_proof_term (repl p)
1194                 in
1195                 let i = 
1196                   let rec get_meta = function
1197                     | SubProof (_, i, p) -> max i (get_meta p)
1198                     | ProofGoalBlock (_, p) -> get_meta p
1199                     | _ -> -1 (* assert false *)
1200                   in
1201                   get_meta p
1202                 in
1203                 let subst =
1204                   let _, (context, _, _) = List.hd subst in
1205                   [i, (context, subproof, Cic.Implicit None)]
1206                 in
1207                 let tl = List.map (propagate_subst subst) tl in
1208                 `GoOn ([depth+1, tl])
1209         )
1210     | _ -> assert false
1211   in
1212   debug_print
1213     (lazy
1214        (Printf.sprintf "apply_to_goal_conj (%d, [%s])"
1215           depth
1216           (String.concat "; "
1217              (List.map (fun (_, _, t) -> CicPp.ppterm t) goals))));
1218   if depth > !maxdepth || (List.length goals) > !maxwidth then (
1219     debug_print
1220       (lazy (Printf.sprintf "Pruning because depth = %d, width = %d"
1221                depth (List.length goals)));
1222     `No (depth, goals)
1223   ) else
1224     aux goals
1225 ;;
1226
1227
1228 module OrderedGoals = struct
1229   type t = int * (Inference.proof * Cic.metasenv * Cic.term) list
1230
1231   let compare g1 g2 =
1232     let d1, l1 = g1
1233     and d2, l2 = g2 in
1234     let r = d2 - d1 in
1235     if r <> 0 then r
1236     else let r = (List.length l1) - (List.length l2) in
1237     if r <> 0 then r
1238     else
1239       let res = ref 0 in
1240       let _ = 
1241         List.exists2
1242           (fun (_, _, t1) (_, _, t2) ->
1243              let r = Pervasives.compare t1 t2 in
1244              if r <> 0 then (
1245                res := r;
1246                true
1247              ) else
1248                false) l1 l2
1249       in !res
1250 (*       let res = Pervasives.compare g1 g2 in *)
1251 (*       let _ = *)
1252 (*         let print_goals (d, gl) =  *)
1253 (*           let gl' = List.map (fun (_, _, t) -> CicPp.ppterm t) gl in *)
1254 (*           Printf.sprintf "%d, [%s]" d (String.concat "; " gl') *)
1255 (*         in *)
1256 (*         debug_print *)
1257 (*           (lazy *)
1258 (*              (Printf.sprintf "comparing g1:%s and g2:%s, res: %d\n" *)
1259 (*                 (print_goals g1) (print_goals g2) res)) *)
1260 (*       in *)
1261 (*       res *)
1262 end
1263
1264 module GoalsSet = Set.Make(OrderedGoals);;
1265
1266
1267 exception SearchSpaceOver;;
1268
1269
1270 let apply_to_goals env is_passive_empty theorems active goals =
1271   debug_print (lazy "\n\n\tapply_to_goals\n\n");
1272   let add_to set goals =
1273     List.fold_left (fun s g -> GoalsSet.add g s) set goals 
1274   in
1275   let rec aux set = function
1276     | [] ->
1277         debug_print (lazy "HERE!!!");
1278         if is_passive_empty then raise SearchSpaceOver else false, set
1279     | goals::tl ->
1280         let res = apply_to_goal_conj env theorems active goals in
1281         match res with
1282         | `Ok newgoals ->
1283             let _ =
1284               let d, p, t =
1285                 match newgoals with
1286                 | (d, (p, _, t)::_) -> d, p, t
1287                 | _ -> assert false
1288               in
1289               debug_print
1290                 (lazy
1291                    (Printf.sprintf "\nOK!!!!\ndepth: %d\nProof: %s\ngoal: %s\n"
1292                       d (string_of_proof p) (CicPp.ppterm t)))
1293             in
1294             true, GoalsSet.singleton newgoals
1295         | `GoOn newgoals ->
1296             let print_set set msg = 
1297               debug_print
1298                 (lazy
1299                    (Printf.sprintf "%s:\n%s" msg
1300                       (String.concat "\n"
1301                          (GoalsSet.fold
1302                             (fun (d, gl) l ->
1303                                let gl' =
1304                                  List.map (fun (_, _, t) -> CicPp.ppterm t) gl
1305                                in
1306                                let s =
1307                                  Printf.sprintf "%d, [%s]" d
1308                                    (String.concat "; " gl')
1309                                in
1310                                s::l) set []))))
1311             in
1312             let set = add_to set (goals::tl) in
1313 (*             print_set set "SET BEFORE"; *)
1314             let n = GoalsSet.cardinal set in
1315             let set = add_to set newgoals in
1316 (*             print_set set "SET AFTER"; *)
1317             let m = GoalsSet.cardinal set in
1318 (*             if n < m then *)
1319             false, set
1320 (*             else *)
1321 (*               let _ = print_set set "SET didn't change" in *)
1322 (*               aux set tl *)
1323         | `No newgoals ->
1324             aux set tl
1325 (*             let set = add_to set (newgoals::goals::tl) in *)
1326 (*             let res, set = aux set tl in *)
1327 (*             res, set *)
1328   in
1329   let n = List.length goals in
1330   let res, goals = aux (add_to GoalsSet.empty goals) goals in
1331   let goals = GoalsSet.elements goals in
1332   debug_print (lazy "\n\tapply_to_goals end\n");
1333   let m = List.length goals in
1334   if m = n && is_passive_empty then
1335     raise SearchSpaceOver
1336   else
1337     res, goals
1338 ;;
1339
1340
1341 let rec given_clause env goals theorems passive active =
1342   let time1 = Unix.gettimeofday () in
1343
1344   let selection_estimate = get_selection_estimate () in
1345   let kept = size_of_passive passive in
1346   let passive =
1347     if !time_limit = 0. || !processed_clauses = 0 then
1348       passive
1349     else if !elapsed_time > !time_limit then (
1350       debug_print (lazy (Printf.sprintf "Time limit (%.2f) reached: %.2f\n"
1351                            !time_limit !elapsed_time));
1352       make_passive [] []
1353     ) else if kept > selection_estimate then (
1354       debug_print
1355         (lazy (Printf.sprintf ("Too many passive equalities: pruning..." ^^
1356                                  "(kept: %d, selection_estimate: %d)\n")
1357                  kept selection_estimate));
1358       prune_passive selection_estimate active passive
1359     ) else
1360       passive
1361   in
1362
1363   let time2 = Unix.gettimeofday () in
1364   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
1365
1366   kept_clauses := (size_of_passive passive) + (size_of_active active);
1367     
1368 (*   let refl_equal = *)
1369 (*     CicUtil.term_of_uri *)
1370 (*       (UriManager.uri_of_string "cic:/Coq/Init/Logic/eq.ind#xpointer(1/1/1)") *)
1371 (*   in *)
1372   let goals = simplify_goals env goals active in
1373   let theorems = simplify_theorems env theorems active in 
1374   let is_passive_empty = passive_is_empty passive in
1375   try
1376     let ok, goals = apply_to_goals env is_passive_empty theorems active goals in
1377     if ok then
1378       let proof =
1379         match goals with
1380         | (_, [proof, _, _])::_ -> Some proof
1381         | _ -> assert false
1382       in
1383       ParamodulationSuccess (proof, env)
1384     else
1385       match is_passive_empty (* passive_is_empty passive *) with
1386       | true -> (* ParamodulationFailure *)
1387           given_clause env goals theorems passive active
1388       | false ->
1389           let (sign, current), passive = select env goals passive active in
1390           let time1 = Unix.gettimeofday () in
1391           let res = forward_simplify env (sign, current) ~passive active in
1392           let time2 = Unix.gettimeofday () in
1393           forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
1394           match res with
1395           | None ->
1396               given_clause env goals theorems passive active
1397           | Some (sign, current) ->
1398               if (sign = Negative) && (is_identity env current) then (
1399                 debug_print
1400                   (lazy (Printf.sprintf "OK!!! %s %s" (string_of_sign sign)
1401                            (string_of_equality ~env current)));
1402                 let _, proof, _, _, _  = current in
1403                 ParamodulationSuccess (Some proof (* current *), env)
1404               ) else (            
1405                 debug_print
1406                   (lazy "\n================================================");
1407                 debug_print (lazy (Printf.sprintf "selected: %s %s"
1408                                      (string_of_sign sign)
1409                                      (string_of_equality ~env current)));
1410
1411                 let t1 = Unix.gettimeofday () in
1412                 let new' = infer env sign current active in
1413                 let t2 = Unix.gettimeofday () in
1414                 infer_time := !infer_time +. (t2 -. t1);
1415                 
1416                 let res, goal' = contains_empty env new' in
1417                 if res then
1418                   let proof =
1419                     match goal' with
1420                     | Some goal -> let _, proof, _, _, _ = goal in Some proof
1421                     | None -> None
1422                   in
1423                   ParamodulationSuccess (proof (* goal *), env)
1424                 else 
1425                   let t1 = Unix.gettimeofday () in
1426                   let new' = forward_simplify_new env new' active in
1427                   let t2 = Unix.gettimeofday () in
1428                   let _ =
1429                     forward_simpl_new_time :=
1430                       !forward_simpl_new_time +. (t2 -. t1)
1431                   in
1432                   let active =
1433                     match sign with
1434                     | Negative -> active
1435                     | Positive ->
1436                         let t1 = Unix.gettimeofday () in
1437                         let active, _, newa, _ =
1438                           backward_simplify env ([], [current]) active
1439                         in
1440                         let t2 = Unix.gettimeofday () in
1441                         backward_simpl_time :=
1442                           !backward_simpl_time +. (t2 -. t1);
1443                         match newa with
1444                         | None -> active
1445                         | Some (n, p) ->
1446                             let al, tbl = active in
1447                             let nn = List.map (fun e -> Negative, e) n in
1448                             let pp, tbl =
1449                               List.fold_right
1450                                 (fun e (l, t) ->
1451                                    (Positive, e)::l,
1452                                    Indexing.index tbl e)
1453                                 p ([], tbl)
1454                             in
1455                             nn @ al @ pp, tbl
1456                   in
1457 (*               let _ = *)
1458 (*                 Printf.printf "active:\n%s\n" *)
1459 (*                   (String.concat "\n" *)
1460 (*                      ((List.map *)
1461 (*                          (fun (s, e) -> (string_of_sign s) ^ " " ^ *)
1462 (*                             (string_of_equality ~env e)) (fst active)))); *)
1463 (*                 print_newline (); *)
1464 (*               in *)
1465 (*               let _ = *)
1466 (*                 match new' with *)
1467 (*                 | neg, pos -> *)
1468 (*                     Printf.printf "new':\n%s\n" *)
1469 (*                       (String.concat "\n" *)
1470 (*                          ((List.map *)
1471 (*                              (fun e -> "Negative " ^ *)
1472 (*                                 (string_of_equality ~env e)) neg) @ *)
1473 (*                             (List.map *)
1474 (*                                (fun e -> "Positive " ^ *)
1475 (*                                   (string_of_equality ~env e)) pos))); *)
1476 (*                     print_newline (); *)
1477 (*               in *)
1478                   match contains_empty env new' with
1479                   | false, _ -> 
1480                       let active =
1481                         let al, tbl = active in
1482                         match sign with
1483                         | Negative -> (sign, current)::al, tbl
1484                         | Positive ->
1485                             al @ [(sign, current)], Indexing.index tbl current
1486                       in
1487                       let passive = add_to_passive passive new' in
1488                       let (_, ns), (_, ps), _ = passive in
1489 (*                   Printf.printf "passive:\n%s\n" *)
1490 (*                     (String.concat "\n" *)
1491 (*                        ((List.map (fun e -> "Negative " ^ *)
1492 (*                                      (string_of_equality ~env e)) *)
1493 (*                            (EqualitySet.elements ns)) @ *)
1494 (*                           (List.map (fun e -> "Positive " ^ *)
1495 (*                                        (string_of_equality ~env e)) *)
1496 (*                              (EqualitySet.elements ps)))); *)
1497 (*                   print_newline (); *)
1498                       given_clause env goals theorems passive active
1499                   | true, goal ->
1500                       let proof =
1501                         match goal with
1502                         | Some goal ->
1503                             let _, proof, _, _, _ = goal in Some proof
1504                         | None -> None
1505                       in
1506                       ParamodulationSuccess (proof (* goal *), env)
1507               )
1508   with SearchSpaceOver ->
1509     ParamodulationFailure
1510 ;;
1511
1512
1513 let rec given_clause_fullred env goals theorems passive active =
1514   let time1 = Unix.gettimeofday () in
1515   
1516   let selection_estimate = get_selection_estimate () in
1517   let kept = size_of_passive passive in
1518   let passive =
1519     if !time_limit = 0. || !processed_clauses = 0 then
1520       passive
1521     else if !elapsed_time > !time_limit then (
1522       debug_print (lazy (Printf.sprintf "Time limit (%.2f) reached: %.2f\n"
1523                            !time_limit !elapsed_time));
1524       make_passive [] []
1525     ) else if kept > selection_estimate then (
1526       debug_print
1527         (lazy (Printf.sprintf ("Too many passive equalities: pruning..." ^^
1528                                  "(kept: %d, selection_estimate: %d)\n")
1529                  kept selection_estimate));
1530       prune_passive selection_estimate active passive
1531     ) else
1532       passive
1533   in
1534
1535   let time2 = Unix.gettimeofday () in
1536   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
1537     
1538   kept_clauses := (size_of_passive passive) + (size_of_active active);
1539
1540 (*   let refl_equal = *)
1541 (*     CicUtil.term_of_uri *)
1542 (*       (UriManager.uri_of_string "cic:/Coq/Init/Logic/eq.ind#xpointer(1/1/1)") *)
1543 (*   in *)
1544   let goals = simplify_goals env goals ~passive active in
1545   let theorems = simplify_theorems env theorems ~passive active in
1546   let is_passive_empty = passive_is_empty passive in
1547   try
1548     let ok, goals = apply_to_goals env is_passive_empty theorems active goals in
1549     if ok then
1550       let proof =
1551         match goals with
1552         | (_, [proof, _, _])::_ -> Some proof
1553         | _ -> assert false
1554       in
1555       ParamodulationSuccess (proof, env)
1556     else
1557       let _ =
1558         debug_print
1559           (lazy ("new_goals: " ^ (string_of_int (List.length goals))));
1560         debug_print
1561           (lazy
1562              (String.concat "\n"
1563                 (List.map
1564                    (fun (d, gl) ->
1565                       let gl' =
1566                         List.map
1567                           (fun (p, _, t) ->
1568                              (string_of_proof p) ^ ", " ^ (CicPp.ppterm t)) gl
1569                       in
1570                       Printf.sprintf "%d: %s" d (String.concat "; " gl'))
1571                    goals)));
1572       in
1573       match is_passive_empty (* passive_is_empty passive *) with
1574       | true -> (* ParamodulationFailure *)
1575           given_clause_fullred env goals theorems passive active        
1576       | false ->
1577           let (sign, current), passive = select env goals passive active in
1578           let time1 = Unix.gettimeofday () in
1579           let res = forward_simplify env (sign, current) ~passive active in
1580           let time2 = Unix.gettimeofday () in
1581           forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
1582           match res with
1583           | None ->
1584               given_clause_fullred env goals theorems passive active
1585           | Some (sign, current) ->
1586               if (sign = Negative) && (is_identity env current) then (
1587                 debug_print
1588                   (lazy (Printf.sprintf "OK!!! %s %s" (string_of_sign sign)
1589                            (string_of_equality ~env current)));
1590                 let _, proof, _, _, _ = current in 
1591                 ParamodulationSuccess (Some proof (* current *), env)
1592               ) else (
1593                 debug_print
1594                   (lazy "\n================================================");
1595                 debug_print (lazy (Printf.sprintf "selected: %s %s"
1596                                      (string_of_sign sign)
1597                                      (string_of_equality ~env current)));
1598
1599                 let t1 = Unix.gettimeofday () in
1600                 let new' = infer env sign current active in
1601                 let t2 = Unix.gettimeofday () in
1602                 infer_time := !infer_time +. (t2 -. t1);
1603
1604                 let active =
1605                   if is_identity env current then active
1606                   else
1607                     let al, tbl = active in
1608                     match sign with
1609                     | Negative -> (sign, current)::al, tbl
1610                     | Positive ->
1611                         al @ [(sign, current)], Indexing.index tbl current
1612                 in
1613                 let rec simplify new' active passive =
1614                   let t1 = Unix.gettimeofday () in
1615                   let new' = forward_simplify_new env new' ~passive active in
1616                   let t2 = Unix.gettimeofday () in
1617                   forward_simpl_new_time :=
1618                     !forward_simpl_new_time +. (t2 -. t1);
1619                   let t1 = Unix.gettimeofday () in
1620                   let active, passive, newa, retained =
1621                     backward_simplify env new' ~passive active in
1622                   let t2 = Unix.gettimeofday () in
1623                   backward_simpl_time := !backward_simpl_time +. (t2 -. t1);
1624                   match newa, retained with
1625                   | None, None -> active, passive, new'
1626                   | Some (n, p), None
1627                   | None, Some (n, p) ->
1628                       let nn, np = new' in
1629                       simplify (nn @ n, np @ p) active passive
1630                   | Some (n, p), Some (rn, rp) ->
1631                       let nn, np = new' in
1632                       simplify (nn @ n @ rn, np @ p @ rp) active passive
1633                 in
1634                 let active, passive, new' = simplify new' active passive in
1635
1636                 let k = size_of_passive passive in
1637                 if k < (kept - 1) then
1638                   processed_clauses := !processed_clauses + (kept - 1 - k);
1639                 
1640                 let _ =
1641                   debug_print
1642                     (lazy
1643                        (Printf.sprintf "active:\n%s\n"
1644                           (String.concat "\n"
1645                              ((List.map
1646                                  (fun (s, e) -> (string_of_sign s) ^ " " ^
1647                                     (string_of_equality ~env e))
1648                                  (fst active))))))
1649                 in
1650                 let _ =
1651                   match new' with
1652                   | neg, pos ->
1653                       debug_print
1654                         (lazy
1655                            (Printf.sprintf "new':\n%s\n"
1656                               (String.concat "\n"
1657                                  ((List.map
1658                                      (fun e -> "Negative " ^
1659                                         (string_of_equality ~env e)) neg) @
1660                                     (List.map
1661                                        (fun e -> "Positive " ^
1662                                           (string_of_equality ~env e)) pos)))))
1663                 in
1664                 match contains_empty env new' with
1665                 | false, _ -> 
1666                     let passive = add_to_passive passive new' in
1667 (*                 let (_, ns), (_, ps), _ = passive in *)
1668 (*                 Printf.printf "passive:\n%s\n" *)
1669 (*                   (String.concat "\n" *)
1670 (*                      ((List.map (fun e -> "Negative " ^ *)
1671 (*                                    (string_of_equality ~env e)) *)
1672 (*                          (EqualitySet.elements ns)) @ *)
1673 (*                         (List.map (fun e -> "Positive " ^ *)
1674 (*                                      (string_of_equality ~env e)) *)
1675 (*                            (EqualitySet.elements ps)))); *)
1676 (*                 print_newline (); *)
1677                     given_clause_fullred env goals theorems passive active
1678                 | true, goal ->
1679                     let proof =
1680                       match goal with
1681                       | Some goal -> let _, proof, _, _, _ = goal in Some proof
1682                       | None -> None
1683                     in
1684                     ParamodulationSuccess (proof (* goal *), env)
1685               )
1686   with SearchSpaceOver ->
1687     ParamodulationFailure
1688 ;;
1689
1690
1691 (* let given_clause_ref = ref given_clause;; *)
1692
1693 let main dbd term metasenv ugraph =
1694   let module C = Cic in
1695   let module T = CicTypeChecker in
1696   let module PET = ProofEngineTypes in
1697   let module PP = CicPp in
1698   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1699   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1700   let proof, goals = status in
1701   let goal' = List.nth goals 0 in
1702   let _, metasenv, meta_proof, _ = proof in
1703   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1704   let eq_indexes, equalities, maxm = find_equalities context proof in
1705   let lib_eq_uris, library_equalities, maxm =
1706     find_library_equalities dbd context (proof, goal') (maxm+2)
1707   in
1708   maxmeta := maxm+2; (* TODO ugly!! *)
1709   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
1710   let new_meta_goal, metasenv, type_of_goal =
1711     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1712     Printf.printf "\n\nTIPO DEL GOAL: %s\n" (CicPp.ppterm ty);
1713     print_newline ();
1714     Cic.Meta (maxm+1, irl),
1715     (maxm+1, context, ty)::metasenv,
1716     ty
1717   in
1718 (*   let new_meta_goal = Cic.Meta (goal', irl) in *)
1719   let env = (metasenv, context, ugraph) in
1720   let theorems = find_library_theorems dbd env (proof, goal') lib_eq_uris in
1721   let context_hyp = find_context_hypotheses env eq_indexes in
1722   let theorems = context_hyp @ theorems in
1723   let _ =
1724     debug_print
1725       (lazy
1726          (Printf.sprintf
1727             "Theorems:\n-------------------------------------\n%s\n"
1728             (String.concat "\n"
1729                (List.map
1730                   (fun (t, ty, _) ->
1731                      Printf.sprintf
1732                        "Term: %s, type: %s" (CicPp.ppterm t) (CicPp.ppterm ty))
1733                   theorems))))
1734   in
1735   try
1736     let goal = Inference.BasicProof new_meta_goal, [], goal in
1737 (*     let term_equality = equality_of_term new_meta_goal goal in *)
1738 (*     let _, meta_proof, (eq_ty, left, right, ordering), _, _ = term_equality in *)
1739 (*     if is_identity env term_equality then *)
1740 (*       let proof = *)
1741 (*         Cic.Appl [Cic.MutConstruct (\* reflexivity *\) *)
1742 (*                     (HelmLibraryObjects.Logic.eq_URI, 0, 1, []); *)
1743 (*                   eq_ty; left] *)
1744 (*       in *)
1745 (*       let _ =  *)
1746 (*         Printf.printf "OK, found a proof!\n"; *)
1747 (*         let names = names_of_context context in *)
1748 (*         print_endline (PP.pp proof names) *)
1749 (*       in *)
1750 (*       () *)
1751 (*     else *)
1752       let equalities =
1753         let equalities = equalities @ library_equalities in
1754         debug_print
1755           (lazy 
1756              (Printf.sprintf "equalities:\n%s\n"
1757                 (String.concat "\n"
1758                    (List.map string_of_equality equalities))));
1759         debug_print (lazy "SIMPLYFYING EQUALITIES...");
1760         let rec simpl e others others_simpl =
1761           let active = others @ others_simpl in
1762           let tbl =
1763             List.fold_left
1764               (fun t (_, e) -> Indexing.index t e)
1765               (Indexing.empty_table ()) active
1766           in
1767           let res = forward_simplify env e (active, tbl) in
1768           match others with
1769           | hd::tl -> (
1770               match res with
1771               | None -> simpl hd tl others_simpl
1772               | Some e -> simpl hd tl (e::others_simpl)
1773             )
1774           | [] -> (
1775               match res with
1776               | None -> others_simpl
1777               | Some e -> e::others_simpl
1778             )
1779         in
1780         match equalities with
1781         | [] -> []
1782         | hd::tl ->
1783             let others = List.map (fun e -> (Positive, e)) tl in
1784             let res =
1785               List.rev (List.map snd (simpl (Positive, hd) others []))
1786             in
1787             debug_print
1788               (lazy
1789                  (Printf.sprintf "equalities AFTER:\n%s\n"
1790                     (String.concat "\n"
1791                        (List.map string_of_equality res))));
1792             res
1793       in
1794       let active = make_active () in
1795       let passive = make_passive [] (* [term_equality] *) equalities in
1796       Printf.printf "\ncurrent goal: %s\n"
1797         (let _, _, g = goal in CicPp.ppterm g);
1798 (*         (string_of_equality ~env term_equality); *)
1799       Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
1800       Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
1801       Printf.printf "\nequalities:\n%s\n"
1802         (String.concat "\n"
1803            (List.map
1804               (string_of_equality ~env)
1805               (equalities @ library_equalities)));
1806       print_endline "--------------------------------------------------";
1807       let start = Unix.gettimeofday () in
1808       print_endline "GO!";
1809       start_time := Unix.gettimeofday ();
1810       let res =
1811         (if !use_fullred then given_clause_fullred else given_clause)
1812           env [0, [goal]] theorems passive active
1813       in
1814       let finish = Unix.gettimeofday () in
1815       let _ =
1816         match res with
1817         | ParamodulationFailure ->
1818             Printf.printf "NO proof found! :-(\n\n"
1819         | ParamodulationSuccess (Some proof (* goal *), env) ->
1820 (*             let proof = Inference.build_proof_term goal in          *)
1821             let proof = Inference.build_proof_term proof in
1822             Printf.printf "OK, found a proof!\n";
1823             (* REMEMBER: we have to instantiate meta_proof, we should use
1824                apply  the "apply" tactic to proof and status 
1825             *)
1826             let names = names_of_context context in
1827             print_endline (PP.pp proof names);
1828             let newmetasenv =
1829               List.fold_left
1830                 (fun m (_, _, _, menv, _) -> m @ menv) metasenv equalities
1831             in
1832             let _ =
1833               Printf.printf "OK, found a proof!\n";
1834               (* REMEMBER: we have to instantiate meta_proof, we should use
1835                  apply  the "apply" tactic to proof and status 
1836               *)
1837               let names = names_of_context context in
1838               print_endline (PP.pp proof names);
1839               try
1840                 let ty, ug =
1841                   CicTypeChecker.type_of_aux' newmetasenv context proof ugraph
1842                 in
1843 (*                 Printf.printf "OK, found a proof!\n"; *)
1844 (*                 (\* REMEMBER: we have to instantiate meta_proof, we should use *)
1845 (*                    apply  the "apply" tactic to proof and status  *)
1846 (*                 *\) *)
1847 (*                 let names = names_of_context context in *)
1848 (*                 print_endline (PP.pp proof names); *)
1849                 (*           print_endline (PP.ppterm proof); *)
1850                 
1851                 print_endline (string_of_float (finish -. start));
1852                 Printf.printf
1853                   "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n\n"
1854                   (CicPp.pp type_of_goal names) (CicPp.pp ty names)
1855                   (string_of_bool
1856                      (fst (CicReduction.are_convertible
1857                              context type_of_goal ty ug)));
1858               with e ->
1859                 Printf.printf "\nEXCEPTION!!! %s\n" (Printexc.to_string e);
1860                 Printf.printf "MAXMETA USED: %d\n" !maxmeta;
1861                 print_endline (string_of_float (finish -. start));
1862             in
1863             ()
1864               
1865         | ParamodulationSuccess (None, env) ->
1866             Printf.printf "Success, but no proof?!?\n\n"
1867       in
1868       Printf.printf ("infer_time: %.9f\nforward_simpl_time: %.9f\n" ^^
1869                        "forward_simpl_new_time: %.9f\n" ^^
1870                        "backward_simpl_time: %.9f\n")
1871         !infer_time !forward_simpl_time !forward_simpl_new_time
1872         !backward_simpl_time;
1873       Printf.printf "passive_maintainance_time: %.9f\n"
1874         !passive_maintainance_time;
1875       Printf.printf "    successful unification/matching time: %.9f\n"
1876         !Indexing.match_unif_time_ok;
1877       Printf.printf "    failed unification/matching time: %.9f\n"
1878         !Indexing.match_unif_time_no;
1879       Printf.printf "    indexing retrieval time: %.9f\n"
1880         !Indexing.indexing_retrieval_time;
1881       Printf.printf "    demodulate_term.build_newtarget_time: %.9f\n"
1882         !Indexing.build_newtarget_time;
1883       Printf.printf "derived %d clauses, kept %d clauses.\n"
1884         !derived_clauses !kept_clauses;
1885   with exc ->
1886     print_endline ("EXCEPTION: " ^ (Printexc.to_string exc));
1887     raise exc
1888 ;;
1889
1890
1891 let default_depth = !maxdepth
1892 and default_width = !maxwidth;;
1893
1894 let saturate
1895     dbd ?(full=false) ?(depth=default_depth) ?(width=default_width) status = 
1896   let module C = Cic in
1897   maxmeta := 0;
1898   maxdepth := depth;
1899   maxwidth := width;
1900   let proof, goal = status in
1901   let goal' = goal in
1902   let uri, metasenv, meta_proof, term_to_prove = proof in
1903   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1904   let eq_indexes, equalities, maxm = find_equalities context proof in
1905   let new_meta_goal, metasenv, type_of_goal =
1906     let irl =
1907       CicMkImplicit.identity_relocation_list_for_metavariable context in
1908     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1909     debug_print
1910       (lazy (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n" (CicPp.ppterm ty)));
1911     Cic.Meta (maxm+1, irl),
1912     (maxm+1, context, ty)::metasenv,
1913     ty
1914   in
1915   let ugraph = CicUniv.empty_ugraph in
1916   let env = (metasenv, context, ugraph) in
1917   let goal = Inference.BasicProof new_meta_goal, [], goal in
1918   let res, time = 
1919     let lib_eq_uris, library_equalities, maxm =
1920       find_library_equalities dbd context (proof, goal') (maxm+2)
1921     in
1922     maxmeta := maxm+2;
1923     let equalities =
1924       let equalities = equalities @ library_equalities in
1925       debug_print
1926         (lazy
1927            (Printf.sprintf "equalities:\n%s\n"
1928               (String.concat "\n"
1929                  (List.map string_of_equality equalities))));
1930       debug_print (lazy "SIMPLYFYING EQUALITIES...");
1931       let rec simpl e others others_simpl =
1932         let active = others @ others_simpl in
1933         let tbl =
1934           List.fold_left
1935             (fun t (_, e) -> Indexing.index t e)
1936             (Indexing.empty_table ()) active
1937         in
1938         let res = forward_simplify env e (active, tbl) in
1939         match others with
1940         | hd::tl -> (
1941             match res with
1942             | None -> simpl hd tl others_simpl
1943             | Some e -> simpl hd tl (e::others_simpl)
1944           )
1945         | [] -> (
1946             match res with
1947             | None -> others_simpl
1948             | Some e -> e::others_simpl
1949           )
1950       in
1951       match equalities with
1952       | [] -> []
1953       | hd::tl ->
1954           let others = List.map (fun e -> (Positive, e)) tl in
1955           let res =
1956             List.rev (List.map snd (simpl (Positive, hd) others []))
1957           in
1958           debug_print
1959             (lazy
1960                (Printf.sprintf "equalities AFTER:\n%s\n"
1961                   (String.concat "\n"
1962                      (List.map string_of_equality res))));
1963           res
1964     in
1965     let theorems =
1966       if full then
1967         let thms = find_library_theorems dbd env (proof, goal') lib_eq_uris in
1968         let context_hyp = find_context_hypotheses env eq_indexes in
1969         context_hyp @ thms
1970       else
1971         let refl_equal =
1972           UriManager.uri_of_string "cic:/Coq/Init/Logic/eq.ind#xpointer(1/1/1)"
1973         in
1974         let t = CicUtil.term_of_uri refl_equal in
1975         let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
1976         [(t, ty, [])]
1977     in
1978     let _ =
1979       debug_print
1980         (lazy
1981            (Printf.sprintf
1982               "Theorems:\n-------------------------------------\n%s\n"
1983               (String.concat "\n"
1984                  (List.map
1985                     (fun (t, ty, _) ->
1986                        Printf.sprintf
1987                          "Term: %s, type: %s"
1988                          (CicPp.ppterm t) (CicPp.ppterm ty))
1989                     theorems))))
1990     in
1991     let active = make_active () in
1992     let passive = make_passive [(* term_equality *)] equalities in
1993     let start = Unix.gettimeofday () in
1994     let res = given_clause_fullred env [0, [goal]] theorems passive active in
1995     let finish = Unix.gettimeofday () in
1996     (res, finish -. start)
1997   in
1998   match res with
1999   | ParamodulationSuccess (Some proof (* goal *), env) ->
2000       debug_print (lazy "OK, found a proof!");
2001 (*       let proof = Inference.build_proof_term goal in          *)
2002       let proof = Inference.build_proof_term proof in
2003       let names = names_of_context context in
2004       let newmetasenv =
2005         let i1 =
2006           match new_meta_goal with
2007           | C.Meta (i, _) -> i | _ -> assert false
2008         in
2009         List.filter (fun (i, _, _) -> i <> i1 && i <> goal') metasenv
2010       in
2011       let newstatus =
2012         try
2013           let ty, ug =
2014             CicTypeChecker.type_of_aux' newmetasenv context proof ugraph
2015           in
2016           debug_print (lazy (CicPp.pp proof [](* names *)));
2017           debug_print
2018             (lazy
2019                (Printf.sprintf
2020                   "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n"
2021                   (CicPp.pp type_of_goal names) (CicPp.pp ty names)
2022                   (string_of_bool
2023                      (fst (CicReduction.are_convertible
2024                              context type_of_goal ty ug)))));
2025           let equality_for_replace i t1 =
2026             match t1 with
2027             | C.Meta (n, _) -> n = i
2028             | _ -> false
2029           in
2030           let real_proof =
2031             ProofEngineReduction.replace
2032               ~equality:equality_for_replace
2033               ~what:[goal'] ~with_what:[proof]
2034               ~where:meta_proof
2035           in
2036           debug_print
2037             (lazy
2038                (Printf.sprintf "status:\n%s\n%s\n%s\n%s\n"
2039                   (match uri with Some uri -> UriManager.string_of_uri uri
2040                    | None -> "")
2041                   (print_metasenv newmetasenv)
2042                   (CicPp.pp real_proof [](* names *))
2043                   (CicPp.pp term_to_prove names)));
2044           ((uri, newmetasenv, real_proof, term_to_prove), [])
2045         with CicTypeChecker.TypeCheckerFailure _ ->
2046           debug_print (lazy "THE PROOF DOESN'T TYPECHECK!!!");
2047           debug_print (lazy (CicPp.pp proof names));
2048           raise (ProofEngineTypes.Fail
2049                    "Found a proof, but it doesn't typecheck")
2050       in
2051       debug_print (lazy (Printf.sprintf "\nTIME NEEDED: %.9f" time));
2052       newstatus          
2053   | _ ->
2054       raise (ProofEngineTypes.Fail "NO proof found")
2055 ;;
2056
2057 (* dummy function called within matita to trigger linkage *)
2058 let init () = ();;
2059
2060
2061 (* UGLY SIDE EFFECT... *)
2062 if connect_to_auto then ( 
2063   AutoTactic.paramodulation_tactic := saturate;
2064   AutoTactic.term_is_equality := Inference.term_is_equality;
2065 );;
2066