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