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