]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/paramodulation/saturation.ml
added function saturate_equations that tries to infer as many equations as possible...
[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 (
490 (*      debug_print  *)
491 (*        (lazy *)
492 (*           (Printf.sprintf "\ncurrent was: %s\nnewcurrent is: %s\n" *)
493 (*              (string_of_equality current) *)
494 (*              (string_of_equality newcurrent))); *)
495 (*      debug_print *)
496 (*        (lazy *)
497 (*           (Printf.sprintf "active is: %s" *)
498 (*              (String.concat "\n"  *)
499 (*                 (List.map (fun (_, e) -> (string_of_equality e)) active_list)))); *)
500         None
501       )
502     else
503       Some (sign, newcurrent)
504   in
505   let res =
506     let res = demodulate active_table current in
507     match res with
508     | None -> None
509     | Some (sign, newcurrent) ->
510         match passive_table with
511         | None -> res
512         | Some passive_table -> demodulate passive_table newcurrent
513   in
514   match res with
515   | None -> None
516   | Some (Negative, c) ->
517       let ok = not (
518         List.exists
519           (fun (s, eq) -> s = Negative && meta_convertibility_eq eq c)
520           all)
521       in
522       if ok then res else None
523   | Some (Positive, c) ->
524       if Indexing.in_index active_table c then
525         None
526       else
527         match passive_table with
528         | None -> 
529             if fst (Indexing.subsumption env active_table c) then
530               None
531             else
532               res
533         | Some passive_table ->
534             if Indexing.in_index passive_table c then None
535             else 
536               let r1, _ = Indexing.subsumption env active_table c in
537               if r1 then None else
538                 let r2, _ = Indexing.subsumption env passive_table c in 
539                 if r2 then None else res
540 ;;
541
542 type fs_time_info_t = {
543   mutable build_all: float;
544   mutable demodulate: float;
545   mutable subsumption: float;
546 };;
547
548 let fs_time_info = { build_all = 0.; demodulate = 0.; subsumption = 0. };;
549
550
551 (** simplifies new using active and passive *)
552 let forward_simplify_new env (new_neg, new_pos) ?passive active =
553   let t1 = Unix.gettimeofday () in
554
555   let active_list, active_table = active in
556   let pl, passive_table =
557     match passive with
558     | None -> [], None
559     | Some ((pn, _), (pp, _), pt) ->
560         let pn = List.map (fun e -> (Negative, e)) pn
561         and pp = List.map (fun e -> (Positive, e)) pp in
562         pn @ pp, Some pt
563   in
564   let all = active_list @ pl in
565   
566   let t2 = Unix.gettimeofday () in
567   fs_time_info.build_all <- fs_time_info.build_all +. (t2 -. t1);
568   
569   let demodulate sign table target =
570     let newmeta, newtarget =
571       Indexing.demodulation_equality !maxmeta env table sign target in
572     maxmeta := newmeta;
573     newtarget
574   in
575   let t1 = Unix.gettimeofday () in
576
577   let new_neg, new_pos =
578     let new_neg = List.map (demodulate Negative active_table) new_neg
579     and new_pos = List.map (demodulate Positive active_table) new_pos in
580     match passive_table with
581     | None -> new_neg, new_pos
582     | Some passive_table ->
583         List.map (demodulate Negative passive_table) new_neg,
584         List.map (demodulate Positive passive_table) new_pos
585   in
586
587   let t2 = Unix.gettimeofday () in
588   fs_time_info.demodulate <- fs_time_info.demodulate +. (t2 -. t1);
589
590   let new_pos_set =
591     List.fold_left
592       (fun s e ->
593          if not (Inference.is_identity env e) then
594            if EqualitySet.mem e s then s
595            else EqualitySet.add e s
596          else s)
597       EqualitySet.empty new_pos
598   in
599   let new_pos = EqualitySet.elements new_pos_set in
600
601   let subs =
602     match passive_table with
603     | None ->
604         (fun e -> not (fst (Indexing.subsumption env active_table e)))
605     | Some passive_table ->
606         (fun e -> not ((fst (Indexing.subsumption env active_table e)) ||
607                          (fst (Indexing.subsumption env passive_table e))))
608   in
609 (*   let t1 = Unix.gettimeofday () in *)
610 (*   let t2 = Unix.gettimeofday () in *)
611 (*   fs_time_info.subsumption <- fs_time_info.subsumption +. (t2 -. t1); *)
612   let is_duplicate =
613     match passive_table with
614     | None ->
615         (fun e -> not (Indexing.in_index active_table e))
616     | Some passive_table ->
617         (fun e ->
618            not ((Indexing.in_index active_table e) ||
619                   (Indexing.in_index passive_table e)))
620   in
621   new_neg, List.filter subs (List.filter is_duplicate new_pos)
622 ;;
623
624
625 (** simplifies active usign new *)
626 let backward_simplify_active env new_pos new_table min_weight active =
627   let active_list, active_table = active in
628   let active_list, newa = 
629     List.fold_right
630       (fun (s, equality) (res, newn) ->
631          let ew, _, _, _, _ = equality in
632          if ew < min_weight then
633            (s, equality)::res, newn
634          else
635            match forward_simplify env (s, equality) (new_pos, new_table) with
636            | None -> res, newn
637            | Some (s, e) ->
638                if equality = e then
639                  (s, e)::res, newn
640                else 
641                  res, (s, e)::newn)
642       active_list ([], [])
643   in
644   let find eq1 where =
645     List.exists (fun (s, e) -> meta_convertibility_eq eq1 e) where
646   in
647   let active, newa =
648     List.fold_right
649       (fun (s, eq) (res, tbl) ->
650          if List.mem (s, eq) res then
651            res, tbl
652          else if (is_identity env eq) || (find eq res) then (
653            res, tbl
654          ) 
655          else
656            (s, eq)::res, if s = Negative then tbl else Indexing.index tbl eq)
657       active_list ([], Indexing.empty_table ()),
658     List.fold_right
659       (fun (s, eq) (n, p) ->
660          if (s <> Negative) && (is_identity env eq) then (
661            (n, p)
662          ) else
663            if s = Negative then eq::n, p
664            else n, eq::p)
665       newa ([], [])
666   in
667   match newa with
668   | [], [] -> active, None
669   | _ -> active, Some newa
670 ;;
671
672
673 (** simplifies passive using new *)
674 let backward_simplify_passive env new_pos new_table min_weight passive =
675   let (nl, ns), (pl, ps), passive_table = passive in
676   let f sign equality (resl, ress, newn) =
677     let ew, _, _, _, _ = equality in
678     if ew < min_weight then
679       equality::resl, ress, newn
680     else
681       match forward_simplify env (sign, equality) (new_pos, new_table) with
682       | None -> resl, EqualitySet.remove equality ress, newn
683       | Some (s, e) ->
684           if equality = e then
685             equality::resl, ress, newn
686           else
687             let ress = EqualitySet.remove equality ress in
688             resl, ress, e::newn
689   in
690   let nl, ns, newn = List.fold_right (f Negative) nl ([], ns, [])
691   and pl, ps, newp = List.fold_right (f Positive) pl ([], ps, []) in
692   let passive_table =
693     List.fold_left
694       (fun tbl e -> Indexing.index tbl e) (Indexing.empty_table ()) pl
695   in
696   match newn, newp with
697   | [], [] -> ((nl, ns), (pl, ps), passive_table), None
698   | _, _ -> ((nl, ns), (pl, ps), passive_table), Some (newn, newp)
699 ;;
700
701
702 let backward_simplify env new' ?passive active =
703   let new_pos, new_table, min_weight =
704     List.fold_left
705       (fun (l, t, w) e ->
706          let ew, _, _, _, _ = e in
707          (Positive, e)::l, Indexing.index t e, min ew w)
708       ([], Indexing.empty_table (), 1000000) (snd new')
709   in
710   let active, newa =
711     backward_simplify_active env new_pos new_table min_weight active in
712   match passive with
713   | None ->
714       active, (make_passive [] []), newa, None
715   | Some passive ->
716       let passive, newp =
717         backward_simplify_passive env new_pos new_table min_weight passive in
718       active, passive, newa, newp
719 ;;
720
721
722 (* returns an estimation of how many equalities in passive can be activated
723    within the current time limit *)
724 let get_selection_estimate () =
725   elapsed_time := (Unix.gettimeofday ()) -. !start_time;
726   (*   !processed_clauses * (int_of_float (!time_limit /. !elapsed_time)) *)
727   int_of_float (
728     ceil ((float_of_int !processed_clauses) *.
729             ((!time_limit (* *. 2. *)) /. !elapsed_time -. 1.)))
730 ;;
731
732
733 (** initializes the set of goals *)
734 let make_goals goal =
735   let active = []
736   and passive = [0, [goal]] in
737   active, passive
738 ;;
739
740
741 (** initializes the set of theorems *)
742 let make_theorems theorems =
743   theorems, []
744 ;;
745
746
747 let activate_goal (active, passive) =
748   match passive with
749   | goal_conj::tl -> true, (goal_conj::active, tl)
750   | [] -> false, (active, passive)
751 ;;
752
753
754 let activate_theorem (active, passive) =
755   match passive with
756   | theorem::tl -> true, (theorem::active, tl)
757   | [] -> false, (active, passive)
758 ;;
759
760
761 (** simplifies a goal with equalities in active and passive *)  
762 let simplify_goal env goal ?passive (active_list, active_table) =
763   let pl, passive_table =
764     match passive with
765     | None -> [], None
766     | Some ((pn, _), (pp, _), pt) ->
767         let pn = List.map (fun e -> (Negative, e)) pn
768         and pp = List.map (fun e -> (Positive, e)) pp in
769         pn @ pp, Some pt
770   in
771   let all = if pl = [] then active_list else active_list @ pl in
772
773   let demodulate table goal = 
774     let newmeta, newgoal =
775       Indexing.demodulation_goal !maxmeta env table goal in
776     maxmeta := newmeta;
777     goal != newgoal, newgoal
778   in
779   let changed, goal =
780     match passive_table with
781     | None -> demodulate active_table goal
782     | Some passive_table ->
783         let changed, goal = demodulate active_table goal in
784         let changed', goal = demodulate passive_table goal in
785         (changed || changed'), goal
786   in
787   changed, goal
788 ;;
789
790
791 let simplify_goals env goals ?passive active =
792   let a_goals, p_goals = goals in
793   let p_goals = 
794     List.map
795       (fun (d, gl) ->
796          let gl =
797            List.map (fun g -> snd (simplify_goal env g ?passive active)) gl in
798          d, gl)
799       p_goals
800   in
801   let goals =
802     List.fold_left
803       (fun (a, p) (d, gl) ->
804          let changed = ref false in
805          let gl =
806            List.map
807              (fun g ->
808                 let c, g = simplify_goal env g ?passive active in
809                 changed := !changed || c; g) gl in
810          if !changed then (a, (d, gl)::p) else ((d, gl)::a, p))
811       ([], p_goals) a_goals
812   in
813   goals
814 ;;
815
816
817 let simplify_theorems env theorems ?passive (active_list, active_table) =
818   let pl, passive_table =
819     match passive with
820     | None -> [], None
821     | Some ((pn, _), (pp, _), pt) ->
822         let pn = List.map (fun e -> (Negative, e)) pn
823         and pp = List.map (fun e -> (Positive, e)) pp in
824         pn @ pp, Some pt
825   in
826   let all = if pl = [] then active_list else active_list @ pl in
827   let a_theorems, p_theorems = theorems in
828   let demodulate table theorem =
829     let newmeta, newthm =
830       Indexing.demodulation_theorem !maxmeta env table theorem in
831     maxmeta := newmeta;
832     theorem != newthm, newthm
833   in
834   let foldfun table (a, p) theorem =
835     let changed, theorem = demodulate table theorem in
836     if changed then (a, theorem::p) else (theorem::a, p)
837   in
838   let mapfun table theorem = snd (demodulate table theorem) in
839   match passive_table with
840   | None ->
841       let p_theorems = List.map (mapfun active_table) p_theorems in
842       List.fold_left (foldfun active_table) ([], p_theorems) a_theorems
843   | Some passive_table ->
844       let p_theorems = List.map (mapfun active_table) p_theorems in
845       let p_theorems, a_theorems =
846         List.fold_left (foldfun active_table) ([], p_theorems) a_theorems in
847       let p_theorems = List.map (mapfun passive_table) p_theorems in
848       List.fold_left (foldfun passive_table) ([], p_theorems) a_theorems
849 ;;
850
851
852 (* applies equality to goal to see if the goal can be closed *)
853 let apply_equality_to_goal env equality goal =
854   let module C = Cic in
855   let module HL = HelmLibraryObjects in
856   let module I = Inference in
857   let metasenv, context, ugraph = env in
858   let _, proof, (ty, left, right, _), metas, args = equality in
859   let eqterm =
860     C.Appl [C.MutInd (LibraryObjects.eq_URI (), 0, []); ty; left; right] in
861   let gproof, gmetas, gterm = goal in
862 (*   debug_print *)
863 (*     (lazy *)
864 (*        (Printf.sprintf "APPLY EQUALITY TO GOAL: %s, %s" *)
865 (*           (string_of_equality equality) (CicPp.ppterm gterm))); *)
866   try
867     let subst, metasenv', _ =
868       let menv = metasenv @ metas @ gmetas in
869       Inference.unification menv context eqterm gterm ugraph
870     in
871     let newproof =
872       match proof with
873       | I.BasicProof t -> I.BasicProof (CicMetaSubst.apply_subst subst t)
874       | I.ProofBlock (s, uri, nt, t, pe, p) ->
875           I.ProofBlock (subst @ s, uri, nt, t, pe, p)
876       | _ -> assert false
877     in
878     let newgproof =
879       let rec repl = function
880         | I.ProofGoalBlock (_, gp) -> I.ProofGoalBlock (newproof, gp)
881         | I.NoProof -> newproof
882         | I.BasicProof p -> newproof
883         | I.SubProof (t, i, p) -> I.SubProof (t, i, repl p)
884         | _ -> assert false
885       in
886       repl gproof
887     in
888     true, subst, newgproof
889   with CicUnification.UnificationFailure _ ->
890     false, [], I.NoProof
891 ;;
892
893
894
895 let new_meta metasenv =
896   let m = CicMkImplicit.new_meta metasenv [] in
897   incr maxmeta;
898   while !maxmeta <= m do incr maxmeta done;
899   !maxmeta
900 ;;
901
902
903 (* applies a theorem or an equality to goal, returning a list of subgoals or
904    an indication of failure *)
905 let apply_to_goal env theorems ?passive active goal =
906   let metasenv, context, ugraph = env in
907   let proof, metas, term = goal in
908   (*   debug_print *)
909   (*     (lazy *)
910   (*        (Printf.sprintf "apply_to_goal with goal: %s" *)
911   (*           (\* (string_of_proof proof)  *\)(CicPp.ppterm term))); *)
912   let status =
913     let irl =
914       CicMkImplicit.identity_relocation_list_for_metavariable context in
915     let proof', newmeta =
916       let rec get_meta = function
917         | SubProof (t, i, p) ->
918             let t', i' = get_meta p in
919             if i' = -1 then t, i else t', i'
920         | ProofGoalBlock (_, p) -> get_meta p
921         | _ -> Cic.Implicit None, -1
922       in
923       let p, m = get_meta proof in
924       if m = -1 then
925         let n = new_meta (metasenv @ metas) in
926         Cic.Meta (n, irl), n
927       else
928         p, m
929     in
930     let metasenv = (newmeta, context, term)::metasenv @ metas in
931     let bit = new_meta metasenv, context, term in 
932     let metasenv' = bit::metasenv in
933     ((None, metasenv', Cic.Meta (newmeta, irl), term), newmeta)
934   in
935   let rec aux = function
936     | [] -> `No
937     | (theorem, thmty, _)::tl ->
938         try
939           let subst, (newproof, newgoals) =
940             PrimitiveTactics.apply_tac_verbose_with_subst ~term:theorem status
941           in
942           if newgoals = [] then
943             let _, _, p, _ = newproof in
944             let newp =
945               let rec repl = function
946                 | Inference.ProofGoalBlock (_, gp) ->
947                     Inference.ProofGoalBlock (Inference.BasicProof p, gp)
948                 | Inference.NoProof -> Inference.BasicProof p
949                 | Inference.BasicProof _ -> Inference.BasicProof p
950                 | Inference.SubProof (t, i, p2) ->
951                     Inference.SubProof (t, i, repl p2)
952                 | _ -> assert false
953               in
954               repl proof
955             in
956             let _, m = status in
957             let subst = List.filter (fun (i, _) -> i = m) subst in
958             `Ok (subst, [newp, metas, term])
959           else
960             let _, menv, p, _ = newproof in
961             let irl =
962               CicMkImplicit.identity_relocation_list_for_metavariable context
963             in
964             let goals =
965               List.map
966                 (fun i ->
967                    let _, _, ty = CicUtil.lookup_meta i menv in
968                    let p' =
969                      let rec gp = function
970                        | SubProof (t, i, p) ->
971                            SubProof (t, i, gp p)
972                        | ProofGoalBlock (sp1, sp2) ->
973                            ProofGoalBlock (sp1, gp sp2)
974                        | BasicProof _
975                        | NoProof ->
976                            SubProof (p, i, BasicProof (Cic.Meta (i, irl)))
977                        | ProofSymBlock (s, sp) ->
978                            ProofSymBlock (s, gp sp)
979                        | ProofBlock (s, u, nt, t, pe, sp) ->
980                            ProofBlock (s, u, nt, t, pe, gp sp)
981                      in gp proof
982                    in
983                    (p', menv, ty))
984                 newgoals
985             in
986             let goals =
987               let weight t =
988                 let w, m = weight_of_term t in
989                 w + 2 * (List.length m)
990               in
991               List.sort
992                 (fun (_, _, t1) (_, _, t2) ->
993                    Pervasives.compare (weight t1) (weight t2))
994                 goals
995             in
996             let best = aux tl in
997             match best with
998             | `Ok (_, _) -> best
999             | `No -> `GoOn ([subst, goals])
1000             | `GoOn sl -> `GoOn ((subst, goals)::sl)
1001         with ProofEngineTypes.Fail msg ->
1002           aux tl
1003   in
1004   let r, s, l =
1005     if Inference.term_is_equality term then
1006       let rec appleq_a = function
1007         | [] -> false, [], []
1008         | (Positive, equality)::tl ->
1009             let ok, s, newproof = apply_equality_to_goal env equality goal in
1010             if ok then true, s, [newproof, metas, term] else appleq_a tl
1011         | _::tl -> appleq_a tl
1012       in
1013       let rec appleq_p = function
1014         | [] -> false, [], []
1015         | equality::tl ->
1016             let ok, s, newproof = apply_equality_to_goal env equality goal in
1017             if ok then true, s, [newproof, metas, term] else appleq_p tl
1018       in
1019       let al, _ = active in
1020       match passive with
1021       | None -> appleq_a al
1022       | Some (_, (pl, _), _) ->
1023           let r, s, l = appleq_a al in if r then r, s, l else appleq_p pl
1024     else
1025       false, [], []
1026   in
1027   if r = true then `Ok (s, l) else aux theorems
1028 ;;
1029
1030
1031 (* sorts a conjunction of goals in order to detect earlier if it is
1032    unsatisfiable. Non-predicate goals are placed at the end of the list *)
1033 let sort_goal_conj (metasenv, context, ugraph) (depth, gl) =
1034   let gl = 
1035     List.stable_sort
1036       (fun (_, e1, g1) (_, e2, g2) ->
1037          let ty1, _ =
1038            CicTypeChecker.type_of_aux' (e1 @ metasenv) context g1 ugraph 
1039          and ty2, _ =
1040            CicTypeChecker.type_of_aux' (e2 @ metasenv) context g2 ugraph
1041          in
1042          let prop1 =
1043            let b, _ =
1044              CicReduction.are_convertible context (Cic.Sort Cic.Prop) ty1 ugraph
1045            in
1046            if b then 0 else 1
1047          and prop2 =
1048            let b, _ =
1049              CicReduction.are_convertible context (Cic.Sort Cic.Prop) ty2 ugraph
1050            in
1051            if b then 0 else 1
1052          in
1053          if prop1 = 0 && prop2 = 0 then
1054            let e1 = if Inference.term_is_equality g1 then 0 else 1
1055            and e2 = if Inference.term_is_equality g2 then 0 else 1 in
1056            e1 - e2
1057          else
1058            prop1 - prop2)
1059       gl
1060   in
1061   (depth, gl)
1062 ;;
1063
1064
1065 let is_meta_closed goals =
1066   List.for_all (fun (_, _, g) -> CicUtil.is_meta_closed g) goals
1067 ;;
1068
1069
1070 (* applies a series of theorems/equalities to a conjunction of goals *)
1071 let rec apply_to_goal_conj env theorems ?passive active (depth, goals) =
1072   let aux (goal, r) tl =
1073     let propagate_subst subst (proof, metas, term) =
1074       let rec repl = function
1075         | NoProof -> NoProof
1076         | BasicProof t ->
1077             BasicProof (CicMetaSubst.apply_subst subst t)
1078         | ProofGoalBlock (p, pb) ->
1079             let pb' = repl pb in
1080             ProofGoalBlock (p, pb')
1081         | SubProof (t, i, p) ->
1082             let t' = CicMetaSubst.apply_subst subst t in
1083             let p = repl p in
1084             SubProof (t', i, p)
1085         | ProofSymBlock (ens, p) -> ProofSymBlock (ens, repl p)
1086         | ProofBlock (s, u, nty, t, pe, p) ->
1087             ProofBlock (subst @ s, u, nty, t, pe, p)
1088       in (repl proof, metas, term)
1089     in
1090     (* let r = apply_to_goal env theorems ?passive active goal in *) (
1091       match r with
1092       | `No -> `No (depth, goals)
1093       | `GoOn sl ->
1094           let l =
1095             List.map
1096               (fun (s, gl) ->
1097                  let tl = List.map (propagate_subst s) tl in
1098                  sort_goal_conj env (depth+1, gl @ tl)) sl
1099           in
1100           `GoOn l
1101       | `Ok (subst, gl) ->
1102           if tl = [] then
1103             `Ok (depth, gl)
1104           else
1105             let p, _, _ = List.hd gl in
1106             let subproof =
1107               let rec repl = function
1108                 | SubProof (_, _, p) -> repl p
1109                 | ProofGoalBlock (p1, p2) ->
1110                     ProofGoalBlock (repl p1, repl p2)
1111                 | p -> p
1112               in
1113               build_proof_term (repl p)
1114             in
1115             let i = 
1116               let rec get_meta = function
1117                 | SubProof (_, i, p) ->
1118                     let i' = get_meta p in
1119                     if i' = -1 then i else i'
1120 (*                         max i (get_meta p) *)
1121                 | ProofGoalBlock (_, p) -> get_meta p
1122                 | _ -> -1
1123               in
1124               get_meta p
1125             in
1126             let subst =
1127               let _, (context, _, _) = List.hd subst in
1128               [i, (context, subproof, Cic.Implicit None)]
1129             in
1130             let tl = List.map (propagate_subst subst) tl in
1131             let conj = sort_goal_conj env (depth(* +1 *), tl) in
1132             `GoOn ([conj])
1133     )
1134   in
1135   if depth > !maxdepth || (List.length goals) > !maxwidth then 
1136     `No (depth, goals)
1137   else
1138     let rec search_best res = function
1139       | [] -> res
1140       | goal::tl ->
1141           let r = apply_to_goal env theorems ?passive active goal in
1142           match r with
1143           | `Ok _ -> (goal, r)
1144           | `No -> search_best res tl
1145           | `GoOn l ->
1146               let newres = 
1147                 match res with
1148                 | _, `Ok _ -> assert false
1149                 | _, `No -> goal, r
1150                 | _, `GoOn l2 ->
1151                     if (List.length l) < (List.length l2) then goal, r else res
1152               in
1153               search_best newres tl
1154     in
1155     let hd = List.hd goals in
1156     let res = hd, (apply_to_goal env theorems ?passive active hd) in
1157     let best =
1158       match res with
1159       | _, `Ok _ -> res
1160       | _, _ -> search_best res (List.tl goals)
1161     in
1162     let res = aux best (List.filter (fun g -> g != (fst best)) goals) in
1163     match res with
1164     | `GoOn ([conj]) when is_meta_closed (snd conj) &&
1165         (List.length (snd conj)) < (List.length goals)->
1166         apply_to_goal_conj env theorems ?passive active conj
1167     | _ -> res
1168 ;;
1169
1170
1171 (*
1172 module OrderedGoals = struct
1173   type t = int * (Inference.proof * Cic.metasenv * Cic.term) list
1174
1175   let compare g1 g2 =
1176     let d1, l1 = g1
1177     and d2, l2 = g2 in
1178     let r = d2 - d1 in
1179     if r <> 0 then r
1180     else let r = (List.length l1) - (List.length l2) in
1181     if r <> 0 then r
1182     else
1183       let res = ref 0 in
1184       let _ = 
1185         List.exists2
1186           (fun (_, _, t1) (_, _, t2) ->
1187              let r = Pervasives.compare t1 t2 in
1188              if r <> 0 then (
1189                res := r;
1190                true
1191              ) else
1192                false) l1 l2
1193       in !res
1194 end
1195
1196 module GoalsSet = Set.Make(OrderedGoals);;
1197
1198
1199 exception SearchSpaceOver;;
1200 *)
1201
1202
1203 (*
1204 let apply_to_goals env is_passive_empty theorems active goals =
1205   debug_print (lazy "\n\n\tapply_to_goals\n\n");
1206   let add_to set goals =
1207     List.fold_left (fun s g -> GoalsSet.add g s) set goals 
1208   in
1209   let rec aux set = function
1210     | [] ->
1211         debug_print (lazy "HERE!!!");
1212         if is_passive_empty then raise SearchSpaceOver else false, set
1213     | goals::tl ->
1214         let res = apply_to_goal_conj env theorems active goals in
1215         match res with
1216         | `Ok newgoals ->
1217             let _ =
1218               let d, p, t =
1219                 match newgoals with
1220                 | (d, (p, _, t)::_) -> d, p, t
1221                 | _ -> assert false
1222               in
1223               debug_print
1224                 (lazy
1225                    (Printf.sprintf "\nOK!!!!\ndepth: %d\nProof: %s\ngoal: %s\n"
1226                       d (string_of_proof p) (CicPp.ppterm t)))
1227             in
1228             true, GoalsSet.singleton newgoals
1229         | `GoOn newgoals ->
1230             let set' = add_to set (goals::tl) in
1231             let set' = add_to set' newgoals in
1232             false, set'
1233         | `No newgoals ->
1234             aux set tl
1235   in
1236   let n = List.length goals in
1237   let res, goals = aux (add_to GoalsSet.empty goals) goals in
1238   let goals = GoalsSet.elements goals in
1239   debug_print (lazy "\n\tapply_to_goals end\n");
1240   let m = List.length goals in
1241   if m = n && is_passive_empty then
1242     raise SearchSpaceOver
1243   else
1244     res, goals
1245 ;;
1246 *)
1247
1248
1249 (* sorts the list of passive goals to minimize the search for a proof (doesn't
1250    work that well yet...) *)
1251 let sort_passive_goals goals =
1252   List.stable_sort
1253     (fun (d1, l1) (d2, l2) ->
1254        let r1 = d2 - d1 
1255        and r2 = (List.length l1) - (List.length l2) in
1256        let foldfun ht (_, _, t) = 
1257          let _ = List.map (fun i -> Hashtbl.replace ht i 1) (metas_of_term t)
1258          in ht
1259        in
1260        let m1 = Hashtbl.length (List.fold_left foldfun (Hashtbl.create 3) l1)
1261        and m2 = Hashtbl.length (List.fold_left foldfun (Hashtbl.create 3) l2)
1262        in let r3 = m1 - m2 in
1263        if r3 <> 0 then r3
1264        else if r2 <> 0 then r2 
1265        else r1)
1266     (*          let _, _, g1 = List.hd l1 *)
1267 (*          and _, _, g2 = List.hd l2 in *)
1268 (*          let e1 = if Inference.term_is_equality g1 then 0 else 1 *)
1269 (*          and e2 = if Inference.term_is_equality g2 then 0 else 1 *)
1270 (*          in let r4 = e1 - e2 in *)
1271 (*          if r4 <> 0 then r3 else r1) *)
1272     goals
1273 ;;
1274
1275
1276 let print_goals goals = 
1277   (String.concat "\n"
1278      (List.map
1279         (fun (d, gl) ->
1280            let gl' =
1281              List.map
1282                (fun (p, _, t) ->
1283                   (* (string_of_proof p) ^ ", " ^ *) (CicPp.ppterm t)) gl
1284            in
1285            Printf.sprintf "%d: %s" d (String.concat "; " gl')) goals))
1286 ;;
1287
1288
1289 (* tries to prove the first conjunction in goals with applications of
1290    theorems/equalities, returning new sub-goals or an indication of success *)
1291 let apply_goal_to_theorems dbd env theorems ?passive active goals =
1292   let theorems, _ = theorems in
1293   let a_goals, p_goals = goals in
1294   let goal = List.hd a_goals in
1295   let not_in_active gl =
1296     not
1297       (List.exists
1298          (fun (_, gl') ->
1299             if (List.length gl) = (List.length gl') then
1300               List.for_all2 (fun (_, _, g1) (_, _, g2) -> g1 = g2) gl gl'
1301             else
1302               false)
1303          a_goals)
1304   in
1305   let aux theorems =
1306     let res = apply_to_goal_conj env theorems ?passive active goal in
1307     match res with
1308     | `Ok newgoals ->
1309         true, ([newgoals], [])
1310     | `No _ ->
1311         false, (a_goals, p_goals)
1312     | `GoOn newgoals ->
1313         let newgoals =
1314           List.filter
1315             (fun (d, gl) ->
1316                (d <= !maxdepth) && (List.length gl) <= !maxwidth &&
1317                  not_in_active gl)
1318             newgoals in
1319         let p_goals = newgoals @ p_goals in
1320         let p_goals = sort_passive_goals p_goals in
1321         false, (a_goals, p_goals)
1322   in
1323   aux theorems
1324 ;;
1325
1326
1327 let apply_theorem_to_goals env theorems active goals =
1328   let a_goals, p_goals = goals in
1329   let theorem = List.hd (fst theorems) in
1330   let theorems = [theorem] in
1331   let rec aux p = function
1332     | [] -> false, ([], p)
1333     | goal::tl ->
1334         let res = apply_to_goal_conj env theorems active goal in
1335         match res with
1336         | `Ok newgoals -> true, ([newgoals], [])
1337         | `No _ -> aux p tl
1338         | `GoOn newgoals -> aux (newgoals @ p) tl
1339   in
1340   let ok, (a, p) = aux p_goals a_goals in
1341   if ok then
1342     ok, (a, p)
1343   else
1344     let p_goals =
1345       List.stable_sort
1346         (fun (d1, l1) (d2, l2) ->
1347            let r = d2 - d1 in
1348            if r <> 0 then r
1349            else let r = (List.length l1) - (List.length l2) in
1350            if r <> 0 then r
1351            else
1352              let res = ref 0 in
1353              let _ = 
1354                List.exists2
1355                  (fun (_, _, t1) (_, _, t2) ->
1356                     let r = Pervasives.compare t1 t2 in
1357                     if r <> 0 then (res := r; true) else false) l1 l2
1358              in !res)
1359         p
1360     in
1361     ok, (a_goals, p_goals)
1362 ;;
1363
1364
1365 (* given-clause algorithm with lazy reduction strategy *)
1366 let rec given_clause dbd env goals theorems passive active =
1367   let goals = simplify_goals env goals active in
1368   let ok, goals = activate_goal goals in
1369   (*   let theorems = simplify_theorems env theorems active in *)
1370   if ok then
1371     let ok, goals = apply_goal_to_theorems dbd env theorems active goals in
1372     if ok then
1373       let proof =
1374         match (fst goals) with
1375         | (_, [proof, _, _])::_ -> Some proof
1376         | _ -> assert false
1377       in
1378       ParamodulationSuccess (proof, env)
1379     else
1380       given_clause_aux dbd env goals theorems passive active
1381   else
1382 (*     let ok', theorems = activate_theorem theorems in *)
1383     let ok', theorems = false, theorems in
1384     if ok' then
1385       let ok, goals = apply_theorem_to_goals env theorems active goals in
1386       if ok then
1387         let proof =
1388           match (fst goals) with
1389           | (_, [proof, _, _])::_ -> Some proof
1390           | _ -> assert false
1391         in
1392         ParamodulationSuccess (proof, env)
1393       else
1394         given_clause_aux dbd env goals theorems passive active
1395     else
1396       if (passive_is_empty passive) then ParamodulationFailure
1397       else given_clause_aux dbd env goals theorems passive active
1398
1399 and given_clause_aux dbd env goals theorems passive active = 
1400   let time1 = Unix.gettimeofday () in
1401
1402   let selection_estimate = get_selection_estimate () in
1403   let kept = size_of_passive passive in
1404   let passive =
1405     if !time_limit = 0. || !processed_clauses = 0 then
1406       passive
1407     else if !elapsed_time > !time_limit then (
1408       debug_print (lazy (Printf.sprintf "Time limit (%.2f) reached: %.2f\n"
1409                            !time_limit !elapsed_time));
1410       make_passive [] []
1411     ) else if kept > selection_estimate then (
1412       debug_print
1413         (lazy (Printf.sprintf ("Too many passive equalities: pruning..." ^^
1414                                  "(kept: %d, selection_estimate: %d)\n")
1415                  kept selection_estimate));
1416       prune_passive selection_estimate active passive
1417     ) else
1418       passive
1419   in
1420
1421   let time2 = Unix.gettimeofday () in
1422   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
1423
1424   kept_clauses := (size_of_passive passive) + (size_of_active active);
1425   match passive_is_empty passive with
1426   | true -> (* ParamodulationFailure *)
1427       given_clause dbd env goals theorems passive active
1428   | false ->
1429       let (sign, current), passive = select env (fst goals) passive active in
1430       let time1 = Unix.gettimeofday () in
1431       let res = forward_simplify env (sign, current) ~passive active in
1432       let time2 = Unix.gettimeofday () in
1433       forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
1434       match res with
1435       | None ->
1436           given_clause dbd env goals theorems passive active
1437       | Some (sign, current) ->
1438           if (sign = Negative) && (is_identity env current) then (
1439             debug_print
1440               (lazy (Printf.sprintf "OK!!! %s %s" (string_of_sign sign)
1441                        (string_of_equality ~env current)));
1442             let _, proof, _, _, _  = current in
1443             ParamodulationSuccess (Some proof, env)
1444           ) else (            
1445             debug_print
1446               (lazy "\n================================================");
1447             debug_print (lazy (Printf.sprintf "selected: %s %s"
1448                                  (string_of_sign sign)
1449                                  (string_of_equality ~env current)));
1450
1451             let t1 = Unix.gettimeofday () in
1452             let new' = infer env sign current active in
1453             let t2 = Unix.gettimeofday () in
1454             infer_time := !infer_time +. (t2 -. t1);
1455             
1456             let res, goal' = contains_empty env new' in
1457             if res then
1458               let proof =
1459                 match goal' with
1460                 | Some goal -> let _, proof, _, _, _ = goal in Some proof
1461                 | None -> None
1462               in
1463               ParamodulationSuccess (proof, env)
1464             else 
1465               let t1 = Unix.gettimeofday () in
1466               let new' = forward_simplify_new env new' active in
1467               let t2 = Unix.gettimeofday () in
1468               let _ =
1469                 forward_simpl_new_time :=
1470                   !forward_simpl_new_time +. (t2 -. t1)
1471               in
1472               let active =
1473                 match sign with
1474                 | Negative -> active
1475                 | Positive ->
1476                     let t1 = Unix.gettimeofday () in
1477                     let active, _, newa, _ =
1478                       backward_simplify env ([], [current]) active
1479                     in
1480                     let t2 = Unix.gettimeofday () in
1481                     backward_simpl_time :=
1482                       !backward_simpl_time +. (t2 -. t1);
1483                     match newa with
1484                     | None -> active
1485                     | Some (n, p) ->
1486                         let al, tbl = active in
1487                         let nn = List.map (fun e -> Negative, e) n in
1488                         let pp, tbl =
1489                           List.fold_right
1490                             (fun e (l, t) ->
1491                                (Positive, e)::l,
1492                                Indexing.index tbl e)
1493                             p ([], tbl)
1494                         in
1495                         nn @ al @ pp, tbl
1496               in
1497               match contains_empty env new' with
1498               | false, _ -> 
1499                   let active =
1500                     let al, tbl = active in
1501                     match sign with
1502                     | Negative -> (sign, current)::al, tbl
1503                     | Positive ->
1504                         al @ [(sign, current)], Indexing.index tbl current
1505                   in
1506                   let passive = add_to_passive passive new' in
1507                   let (_, ns), (_, ps), _ = passive in
1508                   given_clause dbd env goals theorems passive active
1509               | true, goal ->
1510                   let proof =
1511                     match goal with
1512                     | Some goal ->
1513                         let _, proof, _, _, _ = goal in Some proof
1514                     | None -> None
1515                   in
1516                   ParamodulationSuccess (proof, env)
1517           )
1518 ;;
1519
1520
1521 (** given-clause algorithm with full reduction strategy *)
1522 let rec given_clause_fullred dbd env goals theorems passive active =
1523   let goals = simplify_goals env goals ~passive active in
1524   let ok, goals = activate_goal goals in
1525 (*   let theorems = simplify_theorems env theorems ~passive active in *)
1526   if ok then
1527 (*     let _ = *)
1528 (*       debug_print *)
1529 (*         (lazy *)
1530 (*            (Printf.sprintf "\ngoals = \nactive\n%s\npassive\n%s\n" *)
1531 (*               (print_goals (fst goals)) (print_goals (snd goals)))); *)
1532 (*       let current = List.hd (fst goals) in *)
1533 (*       let p, _, t = List.hd (snd current) in *)
1534 (*       debug_print *)
1535 (*         (lazy *)
1536 (*            (Printf.sprintf "goal activated:\n%s\n%s\n" *)
1537 (*               (CicPp.ppterm t) (string_of_proof p))); *)
1538 (*     in *)
1539     let ok, goals =
1540       apply_goal_to_theorems dbd env theorems ~passive active goals
1541     in
1542     if ok then
1543       let proof =
1544         match (fst goals) with
1545         | (_, [proof, _, _])::_ -> Some proof
1546         | _ -> assert false
1547       in
1548       ParamodulationSuccess (proof, env)
1549     else
1550       given_clause_fullred_aux dbd env goals theorems passive active
1551   else
1552 (*     let ok', theorems = activate_theorem theorems in *)
1553 (*     if ok' then *)
1554 (*       let ok, goals = apply_theorem_to_goals env theorems active goals in *)
1555 (*       if ok then *)
1556 (*         let proof = *)
1557 (*           match (fst goals) with *)
1558 (*           | (_, [proof, _, _])::_ -> Some proof *)
1559 (*           | _ -> assert false *)
1560 (*         in *)
1561 (*         ParamodulationSuccess (proof, env) *)
1562 (*       else *)
1563 (*         given_clause_fullred_aux env goals theorems passive active *)
1564 (*     else *)
1565       if (passive_is_empty passive) then ParamodulationFailure
1566       else given_clause_fullred_aux dbd env goals theorems passive active
1567     
1568 and given_clause_fullred_aux dbd env goals theorems passive active =
1569   let time1 = Unix.gettimeofday () in
1570   
1571   let selection_estimate = get_selection_estimate () in
1572   let kept = size_of_passive passive in
1573   let passive =
1574     if !time_limit = 0. || !processed_clauses = 0 then
1575       passive
1576     else if !elapsed_time > !time_limit then (
1577       debug_print (lazy (Printf.sprintf "Time limit (%.2f) reached: %.2f\n"
1578                            !time_limit !elapsed_time));
1579       make_passive [] []
1580     ) else if kept > selection_estimate then (
1581       debug_print
1582         (lazy (Printf.sprintf ("Too many passive equalities: pruning..." ^^
1583                                  "(kept: %d, selection_estimate: %d)\n")
1584                  kept selection_estimate));
1585       prune_passive selection_estimate active passive
1586     ) else
1587       passive
1588   in
1589
1590   let time2 = Unix.gettimeofday () in
1591   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
1592   
1593   kept_clauses := (size_of_passive passive) + (size_of_active active);
1594   match passive_is_empty passive with
1595   | true -> (* ParamodulationFailure *)
1596       given_clause_fullred dbd env goals theorems passive active        
1597   | false ->
1598       let (sign, current), passive = select env (fst goals) passive active in
1599       let time1 = Unix.gettimeofday () in
1600       let res = forward_simplify env (sign, current) ~passive active in
1601       let time2 = Unix.gettimeofday () in
1602       forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
1603       match res with
1604       | None ->
1605           given_clause_fullred dbd env goals theorems passive active
1606       | Some (sign, current) ->
1607           if (sign = Negative) && (is_identity env current) then (
1608             debug_print
1609               (lazy (Printf.sprintf "OK!!! %s %s" (string_of_sign sign)
1610                        (string_of_equality ~env current)));
1611             let _, proof, _, _, _ = current in 
1612             ParamodulationSuccess (Some proof, env)
1613           ) else (
1614             debug_print
1615               (lazy "\n================================================");
1616             debug_print (lazy (Printf.sprintf "selected: %s %s"
1617                                  (string_of_sign sign)
1618                                  (string_of_equality ~env current)));
1619
1620             let t1 = Unix.gettimeofday () in
1621             let new' = infer env sign current active in
1622             let t2 = Unix.gettimeofday () in
1623             infer_time := !infer_time +. (t2 -. t1);
1624
1625             let active =
1626               if is_identity env current then active
1627               else
1628                 let al, tbl = active in
1629                 match sign with
1630                 | Negative -> (sign, current)::al, tbl
1631                 | Positive ->
1632                     al @ [(sign, current)], Indexing.index tbl current
1633             in
1634             let rec simplify new' active passive =
1635               let t1 = Unix.gettimeofday () in
1636               let new' = forward_simplify_new env new' ~passive active in
1637               let t2 = Unix.gettimeofday () in
1638               forward_simpl_new_time :=
1639                 !forward_simpl_new_time +. (t2 -. t1);
1640               let t1 = Unix.gettimeofday () in
1641               let active, passive, newa, retained =
1642                 backward_simplify env new' ~passive active in
1643               let t2 = Unix.gettimeofday () in
1644               backward_simpl_time := !backward_simpl_time +. (t2 -. t1);
1645               match newa, retained with
1646               | None, None -> active, passive, new'
1647               | Some (n, p), None
1648               | None, Some (n, p) ->
1649                   let nn, np = new' in
1650                   simplify (nn @ n, np @ p) active passive
1651               | Some (n, p), Some (rn, rp) ->
1652                   let nn, np = new' in
1653                   simplify (nn @ n @ rn, np @ p @ rp) active passive
1654             in
1655             let active, passive, new' = simplify new' active passive in
1656
1657             let k = size_of_passive passive in
1658             if k < (kept - 1) then
1659               processed_clauses := !processed_clauses + (kept - 1 - k);
1660             
1661             let _ =
1662               debug_print
1663                 (lazy
1664                    (Printf.sprintf "active:\n%s\n"
1665                       (String.concat "\n"
1666                          ((List.map
1667                              (fun (s, e) -> (string_of_sign s) ^ " " ^
1668                                 (string_of_equality ~env e))
1669                              (fst active))))))
1670             in
1671             let _ =
1672               match new' with
1673               | neg, pos ->
1674                   debug_print
1675                     (lazy
1676                        (Printf.sprintf "new':\n%s\n"
1677                           (String.concat "\n"
1678                              ((List.map
1679                                  (fun e -> "Negative " ^
1680                                     (string_of_equality ~env e)) neg) @
1681                                 (List.map
1682                                    (fun e -> "Positive " ^
1683                                       (string_of_equality ~env e)) pos)))))
1684             in
1685             match contains_empty env new' with
1686             | false, _ -> 
1687                 let passive = add_to_passive passive new' in
1688                 given_clause_fullred dbd env goals theorems passive active
1689             | true, goal ->
1690                 let proof =
1691                   match goal with
1692                   | Some goal -> let _, proof, _, _, _ = goal in Some proof
1693                   | None -> None
1694                 in
1695                 ParamodulationSuccess (proof, env)
1696           )
1697 ;;
1698
1699
1700 let rec saturate_equations env goal accept_fun passive active =
1701   elapsed_time := Unix.gettimeofday () -. !start_time;
1702   if !elapsed_time > !time_limit then
1703     (active, passive)
1704   else
1705     let (sign, current), passive = select env [1, [goal]] passive active in
1706     let res = forward_simplify env (sign, current) ~passive active in
1707     match res with
1708     | None ->
1709         saturate_equations env goal accept_fun passive active
1710     | Some (sign, current) ->
1711         assert (sign = Positive);
1712         debug_print
1713           (lazy "\n================================================");
1714         debug_print (lazy (Printf.sprintf "selected: %s %s"
1715                              (string_of_sign sign)
1716                              (string_of_equality ~env current)));
1717         let new' = infer env sign current active in
1718         let active =
1719           if is_identity env current then active
1720           else
1721             let al, tbl = active in
1722             al @ [(sign, current)], Indexing.index tbl current
1723         in
1724         let rec simplify new' active passive =
1725           let new' = forward_simplify_new env new' ~passive active in
1726           let active, passive, newa, retained =
1727             backward_simplify env new' ~passive active in
1728           match newa, retained with
1729           | None, None -> active, passive, new'
1730           | Some (n, p), None
1731           | None, Some (n, p) ->
1732               let nn, np = new' in
1733               simplify (nn @ n, np @ p) active passive
1734           | Some (n, p), Some (rn, rp) ->
1735               let nn, np = new' in
1736               simplify (nn @ n @ rn, np @ p @ rp) active passive
1737         in
1738         let active, passive, new' = simplify new' active passive in
1739         let _ =
1740           debug_print
1741             (lazy
1742                (Printf.sprintf "active:\n%s\n"
1743                   (String.concat "\n"
1744                      ((List.map
1745                          (fun (s, e) -> (string_of_sign s) ^ " " ^
1746                             (string_of_equality ~env e))
1747                          (fst active))))))
1748         in
1749         let _ =
1750           match new' with
1751           | neg, pos ->
1752               debug_print
1753                 (lazy
1754                    (Printf.sprintf "new':\n%s\n"
1755                       (String.concat "\n"
1756                          ((List.map
1757                              (fun e -> "Negative " ^
1758                                 (string_of_equality ~env e)) neg) @
1759                             (List.map
1760                                (fun e -> "Positive " ^
1761                                   (string_of_equality ~env e)) pos)))))
1762         in
1763         let new' = match new' with _, pos -> [], List.filter accept_fun pos in
1764         let passive = add_to_passive passive new' in
1765         saturate_equations env goal accept_fun passive active
1766 ;;
1767   
1768
1769
1770
1771 let main dbd full term metasenv ugraph =
1772   let module C = Cic in
1773   let module T = CicTypeChecker in
1774   let module PET = ProofEngineTypes in
1775   let module PP = CicPp in
1776   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1777   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1778   let proof, goals = status in
1779   let goal' = List.nth goals 0 in
1780   let _, metasenv, meta_proof, _ = proof in
1781   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1782   let eq_indexes, equalities, maxm = find_equalities context proof in
1783   let lib_eq_uris, library_equalities, maxm =
1784     find_library_equalities dbd context (proof, goal') (maxm+2)
1785   in
1786   let library_equalities = List.map snd library_equalities in
1787   maxmeta := maxm+2; (* TODO ugly!! *)
1788   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
1789   let new_meta_goal, metasenv, type_of_goal =
1790     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1791     debug_print
1792       (lazy
1793          (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n\n" (CicPp.ppterm ty)));
1794     Cic.Meta (maxm+1, irl),
1795     (maxm+1, context, ty)::metasenv,
1796     ty
1797   in
1798   let env = (metasenv, context, ugraph) in
1799   let t1 = Unix.gettimeofday () in
1800   let theorems =
1801     if full then
1802       let theorems = find_library_theorems dbd env (proof, goal') lib_eq_uris in
1803       let context_hyp = find_context_hypotheses env eq_indexes in
1804       context_hyp @ theorems, []
1805     else
1806       let refl_equal =
1807         let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
1808         UriManager.uri_of_string (us ^ "#xpointer(1/1/1)")
1809       in
1810       let t = CicUtil.term_of_uri refl_equal in
1811       let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
1812       [(t, ty, [])], []
1813   in
1814   let t2 = Unix.gettimeofday () in
1815   debug_print
1816     (lazy
1817        (Printf.sprintf "Time to retrieve theorems: %.9f\n" (t2 -. t1)));
1818   let _ =
1819     debug_print
1820       (lazy
1821          (Printf.sprintf
1822             "Theorems:\n-------------------------------------\n%s\n"
1823             (String.concat "\n"
1824                (List.map
1825                   (fun (t, ty, _) ->
1826                      Printf.sprintf
1827                        "Term: %s, type: %s" (CicPp.ppterm t) (CicPp.ppterm ty))
1828                   (fst theorems)))))
1829   in
1830   try
1831     let goal = Inference.BasicProof new_meta_goal, [], goal in
1832     let equalities =
1833       let equalities = equalities @ library_equalities in
1834       debug_print
1835         (lazy 
1836            (Printf.sprintf "equalities:\n%s\n"
1837               (String.concat "\n"
1838                  (List.map string_of_equality equalities))));
1839       debug_print (lazy "SIMPLYFYING EQUALITIES...");
1840       let rec simpl e others others_simpl =
1841         let active = others @ others_simpl in
1842         let tbl =
1843           List.fold_left
1844             (fun t (_, e) -> Indexing.index t e)
1845             (Indexing.empty_table ()) active
1846         in
1847         let res = forward_simplify env e (active, tbl) in
1848         match others with
1849         | hd::tl -> (
1850             match res with
1851             | None -> simpl hd tl others_simpl
1852             | Some e -> simpl hd tl (e::others_simpl)
1853           )
1854         | [] -> (
1855             match res with
1856             | None -> others_simpl
1857             | Some e -> e::others_simpl
1858           )
1859       in
1860       match equalities with
1861       | [] -> []
1862       | hd::tl ->
1863           let others = List.map (fun e -> (Positive, e)) tl in
1864           let res =
1865             List.rev (List.map snd (simpl (Positive, hd) others []))
1866           in
1867           debug_print
1868             (lazy
1869                (Printf.sprintf "equalities AFTER:\n%s\n"
1870                   (String.concat "\n"
1871                      (List.map string_of_equality res))));
1872           res
1873     in
1874     let active = make_active () in
1875     let passive = make_passive [] equalities in
1876     Printf.printf "\ncurrent goal: %s\n"
1877       (let _, _, g = goal in CicPp.ppterm g);
1878     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
1879     Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
1880     Printf.printf "\nequalities:\n%s\n"
1881       (String.concat "\n"
1882          (List.map
1883             (string_of_equality ~env) equalities));
1884 (*             (equalities @ library_equalities))); *)
1885       print_endline "--------------------------------------------------";
1886       let start = Unix.gettimeofday () in
1887       print_endline "GO!";
1888       start_time := Unix.gettimeofday ();
1889       let res =
1890         let goals = make_goals goal in
1891         (if !use_fullred then given_clause_fullred else given_clause)
1892           dbd env goals theorems passive active
1893       in
1894       let finish = Unix.gettimeofday () in
1895       let _ =
1896         match res with
1897         | ParamodulationFailure ->
1898             Printf.printf "NO proof found! :-(\n\n"
1899         | ParamodulationSuccess (Some proof, env) ->
1900             let proof = Inference.build_proof_term proof in
1901             Printf.printf "OK, found a proof!\n";
1902             (* REMEMBER: we have to instantiate meta_proof, we should use
1903                apply  the "apply" tactic to proof and status 
1904             *)
1905             let names = names_of_context context in
1906             print_endline (PP.pp proof names);
1907             let newmetasenv =
1908               List.fold_left
1909                 (fun m (_, _, _, menv, _) -> m @ menv) metasenv equalities
1910             in
1911             let _ =
1912               try
1913                 let ty, ug =
1914                   CicTypeChecker.type_of_aux' newmetasenv context proof ugraph
1915                 in
1916                 print_endline (string_of_float (finish -. start));
1917                 Printf.printf
1918                   "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n\n"
1919                   (CicPp.pp type_of_goal names) (CicPp.pp ty names)
1920                   (string_of_bool
1921                      (fst (CicReduction.are_convertible
1922                              context type_of_goal ty ug)));
1923               with e ->
1924                 Printf.printf "\nEXCEPTION!!! %s\n" (Printexc.to_string e);
1925                 Printf.printf "MAXMETA USED: %d\n" !maxmeta;
1926                 print_endline (string_of_float (finish -. start));
1927             in
1928             ()
1929               
1930         | ParamodulationSuccess (None, env) ->
1931             Printf.printf "Success, but no proof?!?\n\n"
1932       in
1933       Printf.printf ("infer_time: %.9f\nforward_simpl_time: %.9f\n" ^^
1934                        "forward_simpl_new_time: %.9f\n" ^^
1935                        "backward_simpl_time: %.9f\n")
1936         !infer_time !forward_simpl_time !forward_simpl_new_time
1937         !backward_simpl_time;
1938       Printf.printf "passive_maintainance_time: %.9f\n"
1939         !passive_maintainance_time;
1940       Printf.printf "    successful unification/matching time: %.9f\n"
1941         !Indexing.match_unif_time_ok;
1942       Printf.printf "    failed unification/matching time: %.9f\n"
1943         !Indexing.match_unif_time_no;
1944       Printf.printf "    indexing retrieval time: %.9f\n"
1945         !Indexing.indexing_retrieval_time;
1946       Printf.printf "    demodulate_term.build_newtarget_time: %.9f\n"
1947         !Indexing.build_newtarget_time;
1948       Printf.printf "derived %d clauses, kept %d clauses.\n"
1949         !derived_clauses !kept_clauses;
1950   with exc ->
1951     print_endline ("EXCEPTION: " ^ (Printexc.to_string exc));
1952     raise exc
1953 ;;
1954
1955
1956 let default_depth = !maxdepth
1957 and default_width = !maxwidth;;
1958
1959 let reset_refs () =
1960   maxmeta := 0;
1961   symbols_counter := 0;
1962   weight_age_counter := !weight_age_ratio;
1963   processed_clauses := 0;
1964   start_time := 0.;
1965   elapsed_time := 0.;
1966   maximal_retained_equality := None;
1967   infer_time := 0.;
1968   forward_simpl_time := 0.;
1969   forward_simpl_new_time := 0.;
1970   backward_simpl_time := 0.;
1971   passive_maintainance_time := 0.;
1972   derived_clauses := 0;
1973   kept_clauses := 0;
1974 ;;
1975
1976 let saturate
1977     dbd ?(full=false) ?(depth=default_depth) ?(width=default_width) status = 
1978   let module C = Cic in
1979   reset_refs ();
1980   Indexing.init_index ();
1981   maxdepth := depth;
1982   maxwidth := width;
1983   let proof, goal = status in
1984   let goal' = goal in
1985   let uri, metasenv, meta_proof, term_to_prove = proof in
1986   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1987   let eq_indexes, equalities, maxm = find_equalities context proof in
1988   let new_meta_goal, metasenv, type_of_goal =
1989     let irl =
1990       CicMkImplicit.identity_relocation_list_for_metavariable context in
1991     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1992     debug_print
1993       (lazy (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n" (CicPp.ppterm ty)));
1994     Cic.Meta (maxm+1, irl),
1995     (maxm+1, context, ty)::metasenv,
1996     ty
1997   in
1998   let ugraph = CicUniv.empty_ugraph in
1999   let env = (metasenv, context, ugraph) in
2000   let goal = Inference.BasicProof new_meta_goal, [], goal in
2001   let res, time =
2002     let t1 = Unix.gettimeofday () in
2003     let lib_eq_uris, library_equalities, maxm =
2004       find_library_equalities dbd context (proof, goal') (maxm+2)
2005     in
2006     let library_equalities = List.map snd library_equalities in
2007     let t2 = Unix.gettimeofday () in
2008     maxmeta := maxm+2;
2009     let equalities =
2010       let equalities = equalities @ library_equalities in
2011       debug_print
2012         (lazy
2013            (Printf.sprintf "equalities:\n%s\n"
2014               (String.concat "\n"
2015                  (List.map string_of_equality equalities))));
2016       debug_print (lazy "SIMPLYFYING EQUALITIES...");
2017       let rec simpl e others others_simpl =
2018         let active = others @ others_simpl in
2019         let tbl =
2020           List.fold_left
2021             (fun t (_, e) -> Indexing.index t e)
2022             (Indexing.empty_table ()) active
2023         in
2024         let res = forward_simplify env e (active, tbl) in
2025         match others with
2026         | hd::tl -> (
2027             match res with
2028             | None -> simpl hd tl others_simpl
2029             | Some e -> simpl hd tl (e::others_simpl)
2030           )
2031         | [] -> (
2032             match res with
2033             | None -> others_simpl
2034             | Some e -> e::others_simpl
2035           )
2036       in
2037       match equalities with
2038       | [] -> []
2039       | hd::tl ->
2040           let others = List.map (fun e -> (Positive, e)) tl in
2041           let res =
2042             List.rev (List.map snd (simpl (Positive, hd) others []))
2043           in
2044           debug_print
2045             (lazy
2046                (Printf.sprintf "equalities AFTER:\n%s\n"
2047                   (String.concat "\n"
2048                      (List.map string_of_equality res))));
2049           res
2050     in
2051     debug_print
2052       (lazy
2053          (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)));
2054     let t1 = Unix.gettimeofday () in
2055     let theorems =
2056       if full then
2057         let thms = find_library_theorems dbd env (proof, goal') lib_eq_uris in
2058         let context_hyp = find_context_hypotheses env eq_indexes in
2059         context_hyp @ thms, []
2060       else
2061         let refl_equal =
2062           let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
2063           UriManager.uri_of_string (us ^ "#xpointer(1/1/1)")
2064         in
2065         let t = CicUtil.term_of_uri refl_equal in
2066         let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
2067         [(t, ty, [])], []
2068     in
2069     let t2 = Unix.gettimeofday () in
2070     let _ =
2071       debug_print
2072         (lazy
2073            (Printf.sprintf
2074               "Theorems:\n-------------------------------------\n%s\n"
2075               (String.concat "\n"
2076                  (List.map
2077                     (fun (t, ty, _) ->
2078                        Printf.sprintf
2079                          "Term: %s, type: %s"
2080                          (CicPp.ppterm t) (CicPp.ppterm ty))
2081                     (fst theorems)))));
2082       debug_print
2083         (lazy
2084            (Printf.sprintf "Time to retrieve theorems: %.9f\n" (t2 -. t1)));
2085     in
2086     let active = make_active () in
2087     let passive = make_passive [] equalities in
2088     let start = Unix.gettimeofday () in
2089     let res =
2090       let goals = make_goals goal in
2091       given_clause_fullred dbd env goals theorems passive active
2092     in
2093     let finish = Unix.gettimeofday () in
2094     (res, finish -. start)
2095   in
2096   match res with
2097   | ParamodulationSuccess (Some proof, env) ->
2098       debug_print (lazy "OK, found a proof!");
2099       let proof = Inference.build_proof_term proof in
2100       let names = names_of_context context in
2101       let newmetasenv =
2102         let i1 =
2103           match new_meta_goal with
2104           | C.Meta (i, _) -> i | _ -> assert false
2105         in
2106         List.filter (fun (i, _, _) -> i <> i1 && i <> goal') metasenv
2107       in
2108       let newstatus =
2109         try
2110           let ty, ug =
2111             CicTypeChecker.type_of_aux' newmetasenv context proof ugraph
2112           in
2113           debug_print (lazy (CicPp.pp proof [](* names *)));
2114           debug_print
2115             (lazy
2116                (Printf.sprintf
2117                   "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n"
2118                   (CicPp.pp type_of_goal names) (CicPp.pp ty names)
2119                   (string_of_bool
2120                      (fst (CicReduction.are_convertible
2121                              context type_of_goal ty ug)))));
2122           let equality_for_replace i t1 =
2123             match t1 with
2124             | C.Meta (n, _) -> n = i
2125             | _ -> false
2126           in
2127           let real_proof =
2128             ProofEngineReduction.replace
2129               ~equality:equality_for_replace
2130               ~what:[goal'] ~with_what:[proof]
2131               ~where:meta_proof
2132           in
2133           debug_print
2134             (lazy
2135                (Printf.sprintf "status:\n%s\n%s\n%s\n%s\n"
2136                   (match uri with Some uri -> UriManager.string_of_uri uri
2137                    | None -> "")
2138                   (print_metasenv newmetasenv)
2139                   (CicPp.pp real_proof [](* names *))
2140                   (CicPp.pp term_to_prove names)));
2141           ((uri, newmetasenv, real_proof, term_to_prove), [])
2142         with CicTypeChecker.TypeCheckerFailure _ ->
2143           debug_print (lazy "THE PROOF DOESN'T TYPECHECK!!!");
2144           debug_print (lazy (CicPp.pp proof names));
2145           raise (ProofEngineTypes.Fail
2146                   (lazy "Found a proof, but it doesn't typecheck"))
2147       in
2148       debug_print (lazy (Printf.sprintf "\nTIME NEEDED: %.9f" time));
2149       newstatus          
2150   | _ ->
2151       raise (ProofEngineTypes.Fail (lazy "NO proof found"))
2152 ;;
2153
2154 (* dummy function called within matita to trigger linkage *)
2155 let init () = ();;
2156
2157
2158 (* UGLY SIDE EFFECT... *)
2159 if connect_to_auto then ( 
2160   AutoTactic.paramodulation_tactic := saturate;
2161   AutoTactic.term_is_equality := Inference.term_is_equality;
2162 );;
2163
2164
2165 let retrieve_and_print dbd term metasenv ugraph = 
2166   let module C = Cic in
2167   let module T = CicTypeChecker in
2168   let module PET = ProofEngineTypes in
2169   let module PP = CicPp in
2170   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
2171   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
2172   let proof, goals = status in
2173   let goal' = List.nth goals 0 in
2174   let uri, metasenv, meta_proof, term_to_prove = proof in
2175   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
2176   let eq_indexes, equalities, maxm = find_equalities context proof in
2177   let new_meta_goal, metasenv, type_of_goal =
2178     let irl =
2179       CicMkImplicit.identity_relocation_list_for_metavariable context in
2180     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
2181     debug_print
2182       (lazy (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n" (CicPp.ppterm ty)));
2183     Cic.Meta (maxm+1, irl),
2184     (maxm+1, context, ty)::metasenv,
2185     ty
2186   in
2187   let ugraph = CicUniv.empty_ugraph in
2188   let env = (metasenv, context, ugraph) in
2189   let goal = Inference.BasicProof new_meta_goal, [], goal in
2190   let t1 = Unix.gettimeofday () in
2191   let lib_eq_uris, library_equalities, maxm =
2192     find_library_equalities dbd context (proof, goal') (maxm+2)
2193   in
2194   let t2 = Unix.gettimeofday () in
2195     maxmeta := maxm+2;
2196     let equalities =
2197       let equalities = (* equalities @ *) library_equalities in
2198         debug_print
2199           (lazy
2200              (Printf.sprintf "\n\nequalities:\n%s\n"
2201                 (String.concat "\n"
2202                    (List.map 
2203                       (fun (u, e) ->
2204 (*                       Printf.sprintf "%s: %s" *)
2205                            (UriManager.string_of_uri u)
2206 (*                         (string_of_equality e) *)
2207                       )
2208                       equalities))));
2209         debug_print (lazy "SIMPLYFYING EQUALITIES...");
2210         let rec simpl e others others_simpl =
2211           let (u, e) = e in
2212           let active = List.map (fun (u, e) -> (Positive, e))
2213             (others @ others_simpl) in
2214           let tbl =
2215             List.fold_left
2216               (fun t (_, e) -> Indexing.index t e)
2217               (Indexing.empty_table ()) active
2218           in
2219           let res = forward_simplify env (Positive, e) (active, tbl) in
2220             match others with
2221               | hd::tl -> (
2222                   match res with
2223                     | None -> simpl hd tl others_simpl
2224                     | Some e -> simpl hd tl ((u, (snd e))::others_simpl)
2225                 )
2226               | [] -> (
2227                   match res with
2228                     | None -> others_simpl
2229                     | Some e -> (u, (snd e))::others_simpl
2230                 )
2231         in
2232           match equalities with
2233             | [] -> []
2234             | hd::tl ->
2235                 let others = tl in (* List.map (fun e -> (Positive, e)) tl in *)
2236                 let res =
2237                   List.rev (simpl (*(Positive,*) hd others [])
2238                 in
2239                   debug_print
2240                     (lazy
2241                        (Printf.sprintf "\nequalities AFTER:\n%s\n"
2242                           (String.concat "\n"
2243                              (List.map
2244                                 (fun (u, e) ->
2245                                    Printf.sprintf "%s: %s"
2246                                      (UriManager.string_of_uri u)
2247                                      (string_of_equality e)
2248                                 )
2249                                 res))));
2250                   res
2251     in
2252       debug_print
2253         (lazy
2254            (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)))
2255 ;;
2256
2257
2258 let main_demod_equalities dbd term metasenv ugraph =
2259   let module C = Cic in
2260   let module T = CicTypeChecker in
2261   let module PET = ProofEngineTypes in
2262   let module PP = CicPp in
2263   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
2264   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
2265   let proof, goals = status in
2266   let goal' = List.nth goals 0 in
2267   let _, metasenv, meta_proof, _ = proof in
2268   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
2269   let eq_indexes, equalities, maxm = find_equalities context proof in
2270   let lib_eq_uris, library_equalities, maxm =
2271     find_library_equalities dbd context (proof, goal') (maxm+2)
2272   in
2273   let library_equalities = List.map snd library_equalities in
2274   maxmeta := maxm+2; (* TODO ugly!! *)
2275   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
2276   let new_meta_goal, metasenv, type_of_goal =
2277     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
2278     debug_print
2279       (lazy
2280          (Printf.sprintf "\n\nTRYING TO INFER EQUALITIES MATCHING: %s\n\n"
2281             (CicPp.ppterm ty)));
2282     Cic.Meta (maxm+1, irl),
2283     (maxm+1, context, ty)::metasenv,
2284     ty
2285   in
2286   let env = (metasenv, context, ugraph) in
2287   let t1 = Unix.gettimeofday () in
2288   try
2289     let goal = Inference.BasicProof new_meta_goal, [], goal in
2290     let equalities =
2291       let equalities = equalities @ library_equalities in
2292       debug_print
2293         (lazy 
2294            (Printf.sprintf "equalities:\n%s\n"
2295               (String.concat "\n"
2296                  (List.map string_of_equality equalities))));
2297       debug_print (lazy "SIMPLYFYING EQUALITIES...");
2298       let rec simpl e others others_simpl =
2299         let active = others @ others_simpl in
2300         let tbl =
2301           List.fold_left
2302             (fun t (_, e) -> Indexing.index t e)
2303             (Indexing.empty_table ()) active
2304         in
2305         let res = forward_simplify env e (active, tbl) in
2306         match others with
2307         | hd::tl -> (
2308             match res with
2309             | None -> simpl hd tl others_simpl
2310             | Some e -> simpl hd tl (e::others_simpl)
2311           )
2312         | [] -> (
2313             match res with
2314             | None -> others_simpl
2315             | Some e -> e::others_simpl
2316           )
2317       in
2318       match equalities with
2319       | [] -> []
2320       | hd::tl ->
2321           let others = List.map (fun e -> (Positive, e)) tl in
2322           let res =
2323             List.rev (List.map snd (simpl (Positive, hd) others []))
2324           in
2325           debug_print
2326             (lazy
2327                (Printf.sprintf "equalities AFTER:\n%s\n"
2328                   (String.concat "\n"
2329                      (List.map string_of_equality res))));
2330           res
2331     in
2332     let active = make_active () in
2333     let passive = make_passive [] equalities in
2334     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
2335     Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
2336     Printf.printf "\nequalities:\n%s\n"
2337       (String.concat "\n"
2338          (List.map
2339             (string_of_equality ~env) equalities));
2340     print_endline "--------------------------------------------------";
2341     let start = Unix.gettimeofday () in
2342     print_endline "GO!";
2343     start_time := Unix.gettimeofday ();
2344     if !time_limit < 1. then time_limit := 60.;    
2345     let ra, rp =
2346       saturate_equations env goal (fun e -> true) passive active
2347     in
2348     let finish = Unix.gettimeofday () in
2349     Printf.printf "\n\nRESULTS:\nActive:\n%s\n\nPassive:\n%s\n"
2350       (String.concat "\n"
2351          (List.map (fun (s, e) -> (string_of_equality ~env e)) (fst ra)))
2352       (String.concat "\n"
2353          (List.map (string_of_equality ~env)
2354             (match rp with (n, _), (p, _), _ -> p)));
2355     print_newline ();
2356   with e ->
2357     debug_print (lazy ("EXCEPTION: " ^ (Printexc.to_string e)))
2358 ;;