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