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