]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/paramodulation/saturation.ml
- new given_clause
[helm.git] / components / 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 (* <:profiler<"saturation">> *)
29
30 open Inference;;
31 open Utils;;
32
33 (* set to false to disable paramodulation inside auto_tac *)
34 let connect_to_auto = true;;
35
36
37 (* profiling statistics... *)
38 let infer_time = ref 0.;;
39 let forward_simpl_time = ref 0.;;
40 let forward_simpl_new_time = ref 0.;;
41 let backward_simpl_time = ref 0.;;
42 let passive_maintainance_time = ref 0.;;
43
44 (* limited-resource-strategy related globals *)
45 let processed_clauses = ref 0;; (* number of equalities selected so far... *)
46 let time_limit = ref 0.;; (* in seconds, settable by the user... *)
47 let start_time = ref 0.;; (* time at which the execution started *)
48 let elapsed_time = ref 0.;;
49 (* let maximal_weight = ref None;; *)
50 let maximal_retained_equality = ref None;;
51
52 (* equality-selection related globals *)
53 let use_fullred = ref true;;
54 let weight_age_ratio = ref 6 (* 5 *);; (* settable by the user *)
55 let weight_age_counter = ref !weight_age_ratio ;;
56 let symbols_ratio = ref 0 (* 3 *);;
57 let symbols_counter = ref 0;;
58
59 (* non-recursive Knuth-Bendix term ordering by default *)
60 (* Utils.compare_terms := Utils.rpo;; *)
61 (* Utils.compare_terms := Utils.nonrec_kbo;; *)
62 (* Utils.compare_terms := Utils.ao;; *)
63
64 (* statistics... *)
65 let derived_clauses = ref 0;;
66 let kept_clauses = ref 0;;
67
68 (* index of the greatest Cic.Meta created - TODO: find a better way! *)
69 let maxmeta = ref 0;;
70
71 (* varbiables controlling the search-space *)
72 let maxdepth = ref 3;;
73 let maxwidth = ref 3;;
74
75 type new_proof = 
76   Equality.goal_proof * Equality.proof * Subst.substitution * Cic.metasenv
77 type result =
78   | ParamodulationFailure of string
79   | ParamodulationSuccess of new_proof
80 ;;
81
82 type goal = Equality.goal_proof * Cic.metasenv * Cic.term;;
83
84 type theorem = Cic.term * Cic.term * Cic.metasenv;;
85
86 let symbols_of_equality equality = 
87   let (_, _, (_, left, right, _), _,_) = Equality.open_equality equality in
88   let m1 = symbols_of_term left in
89   let m = 
90     TermMap.fold
91       (fun k v res ->
92          try
93            let c = TermMap.find k res in
94            TermMap.add k (c+v) res
95          with Not_found ->
96            TermMap.add k v res)
97       (symbols_of_term right) m1
98   in
99   m
100 ;;
101
102 (* griggio *)
103 module OrderedEquality = struct 
104   type t = Equality.equality
105
106   let compare eq1 eq2 =
107     match Equality.meta_convertibility_eq eq1 eq2 with
108     | true -> 0
109     | false ->
110         let w1, _, (ty,left, right, _), m1,_ = Equality.open_equality eq1 in
111         let w2, _, (ty',left', right', _), m2,_ = Equality.open_equality eq2 in
112         match Pervasives.compare w1 w2 with
113         | 0 -> 
114             let res = (List.length m1) - (List.length m2) in 
115             if res <> 0 then res else 
116               Equality.compare eq1 eq2
117         | res -> res 
118 end 
119
120 module EqualitySet = Set.Make(OrderedEquality);;
121
122 exception Empty_list;;
123
124 let passive_is_empty = function
125   | ([], _), _ -> true
126   | _ -> false
127 ;;
128
129
130 let size_of_passive ((passive_list, ps), _) = List.length passive_list
131 (* EqualitySet.cardinal ps *)
132 ;;
133
134
135 let size_of_active (active_list, _) = List.length active_list
136 ;;
137
138 let age_factor = 0.01;;
139
140 (**
141    selects one equality from passive. The selection strategy is a combination
142    of weight, age and goal-similarity
143 *)
144
145 let rec select env goals passive =
146   processed_clauses := !processed_clauses + 1;
147   let goal =
148     match (List.rev goals) with (_, goal::_)::_ -> goal | _ -> assert false
149   in
150   let (pos_list, pos_set), passive_table = passive in
151   let remove eq l = List.filter (fun e -> Equality.compare e eq <> 0) l in
152   if !weight_age_ratio > 0 then
153     weight_age_counter := !weight_age_counter - 1;
154   match !weight_age_counter with
155   | 0 -> (
156       weight_age_counter := !weight_age_ratio;
157       let rec skip_giant pos_list pos_set passive_table =
158         match pos_list with
159           | (hd:EqualitySet.elt)::tl ->
160               let w,_,_,_,_ = Equality.open_equality hd in
161               let passive_table =
162                 Indexing.remove_index passive_table hd
163               in 
164               let pos_set = EqualitySet.remove hd pos_set in
165                 if w < 500 then
166                   hd, ((tl, pos_set), passive_table)
167                 else
168                   (prerr_endline ("\n\n\nGIANT SKIPPED: "^string_of_int w^"\n\n\n");
169                   skip_giant tl pos_set passive_table)
170           | _ -> assert false
171       in
172         skip_giant pos_list pos_set passive_table)
173   | _ when (!symbols_counter > 0) -> 
174      (symbols_counter := !symbols_counter - 1;
175       let cardinality map =
176         TermMap.fold (fun k v res -> res + v) map 0
177       in
178       let symbols =
179         let _, _, term = goal in
180         symbols_of_term term
181       in
182       let card = cardinality symbols in
183       let foldfun k v (r1, r2) = 
184         if TermMap.mem k symbols then
185           let c = TermMap.find k symbols in
186           let c1 = abs (c - v) in
187           let c2 = v - c1 in
188           r1 + c2, r2 + c1
189         else
190           r1, r2 + v
191       in
192       let f equality (i, e) =
193         let common, others =
194           TermMap.fold foldfun (symbols_of_equality equality) (0, 0)
195         in
196         let c = others + (abs (common - card)) in
197         if c < i then (c, equality)
198         else (i, e)
199       in
200       let e1 = EqualitySet.min_elt pos_set in
201       let initial =
202         let common, others = 
203           TermMap.fold foldfun (symbols_of_equality e1) (0, 0)
204         in
205         (others + (abs (common - card))), e1
206       in
207       let _, current = EqualitySet.fold f pos_set initial in
208       let passive_table =
209         Indexing.remove_index passive_table current
210       in
211         current,
212       ((remove current pos_list, EqualitySet.remove current pos_set),
213        passive_table))
214   | _ ->
215       symbols_counter := !symbols_ratio;
216       let current = EqualitySet.min_elt pos_set in
217       let passive_table =
218         Indexing.remove_index passive_table current
219       in
220         current, 
221       ((remove current pos_list, EqualitySet.remove current pos_set),
222       passive_table)
223 ;;
224
225 let filter_dependent passive id =
226   prerr_endline ("+++++++++++++++passives "^
227                    ( string_of_int (size_of_passive passive)));
228   let (pos_list, pos_set), passive_table = passive in
229   let passive =
230     List.fold_right
231       (fun eq ((list,set),table) ->
232          if Equality.depend eq id then
233            (let _,_,_,_,id_eq = Equality.open_equality eq in
234               if id_eq = 9228 then 
235                 prerr_endline ("\n\n--------filtering "^(string_of_int id_eq));
236            ((list, 
237              EqualitySet.remove eq set),
238             Indexing.remove_index table eq))
239          else 
240               ((eq::list, set),table))
241       pos_list (([],pos_set),passive_table) in
242   prerr_endline ("+++++++++++++++passives "^
243                    ( string_of_int (size_of_passive passive)));  
244   passive
245 ;;
246
247
248 (* initializes the passive set of equalities *)
249 let make_passive pos =
250   let set_of equalities =
251     List.fold_left (fun s e -> EqualitySet.add e s) EqualitySet.empty equalities
252   in
253   let table =
254       List.fold_left (fun tbl e -> Indexing.index tbl e) Indexing.empty pos
255   in
256   (pos, set_of pos),
257   table
258 ;;
259
260
261 let make_active () =
262   [], Indexing.empty
263 ;;
264
265
266 (* adds to passive a list of equalities new_pos *)
267 let add_to_passive passive new_pos =
268   let (pos_list, pos_set), table = passive in
269   let ok set equality = not (EqualitySet.mem equality set) in
270   let pos = List.filter (ok pos_set) new_pos in
271   let table = 
272      List.fold_left (fun tbl e -> Indexing.index tbl e) table pos 
273   in
274   let add set equalities =
275     List.fold_left (fun s e -> EqualitySet.add e s) set equalities
276   in
277   (pos_list @ pos, add pos_set pos),
278   table
279 ;;
280
281 (* TODO *)
282 (* removes from passive equalities that are estimated impossible to activate
283    within the current time limit *)
284 let prune_passive howmany (active, _) passive =
285   let (pl, ps), tbl = passive in
286   let howmany = float_of_int howmany
287   and ratio = float_of_int !weight_age_ratio in
288   let round v =
289     let t = ceil v in 
290     int_of_float (if t -. v < 0.5 then t else v)
291   in
292   let in_weight = round (howmany *. ratio /. (ratio +. 1.))
293   and in_age = round (howmany /. (ratio +. 1.)) in 
294   debug_print
295     (lazy (Printf.sprintf "in_weight: %d, in_age: %d\n" in_weight in_age));
296   let counter = ref !symbols_ratio in
297   let rec pickw w ps =
298     if w > 0 then
299       if !counter > 0 then
300         let _ =
301           counter := !counter - 1;
302           if !counter = 0 then counter := !symbols_ratio in
303         let e = EqualitySet.min_elt ps in
304         let ps' = pickw (w-1) (EqualitySet.remove e ps) in
305           EqualitySet.add e ps'
306       else
307         let e = EqualitySet.min_elt ps in
308         let ps' = pickw (w-1) (EqualitySet.remove e ps) in
309         EqualitySet.add e ps'        
310     else
311       EqualitySet.empty
312   in
313   let ps = pickw in_weight ps in
314   let rec picka w s l =
315     if w > 0 then
316       match l with
317       | [] -> w, s, []
318       | hd::tl when not (EqualitySet.mem hd s) ->
319           let w, s, l = picka (w-1) s tl in
320           w, EqualitySet.add hd s, hd::l
321       | hd::tl ->
322           let w, s, l = picka w s tl in
323           w, s, hd::l
324     else
325       0, s, l
326   in
327   let _, ps, pl = picka in_age ps pl in
328   if not (EqualitySet.is_empty ps) then
329     maximal_retained_equality := Some (EqualitySet.max_elt ps); 
330   let tbl =
331     EqualitySet.fold
332       (fun e tbl -> Indexing.index tbl e) ps Indexing.empty
333   in
334   (pl, ps), tbl  
335 ;;
336
337
338 (** inference of new equalities between current and some in active *)
339 let infer env current (active_list, active_table) =
340   let (_,c,_) = env in 
341   if Utils.debug_metas then
342     (ignore(Indexing.check_target c current "infer1");
343      ignore(List.map (function current -> Indexing.check_target c current "infer2") active_list)); 
344   let new_pos = 
345     let maxm, res =
346       Indexing.superposition_right !maxmeta env active_table current in
347       if Utils.debug_metas then
348         ignore(List.map 
349                  (function current -> 
350                     Indexing.check_target c current "sup0") res);
351       maxmeta := maxm;
352       let rec infer_positive table = function
353         | [] -> []
354         | equality::tl ->
355             let maxm, res =
356               Indexing.superposition_right !maxmeta env table equality in
357               maxmeta := maxm;
358               if Utils.debug_metas then
359                 ignore
360                   (List.map 
361                      (function current -> 
362                         Indexing.check_target c current "sup2") res);
363               let pos = infer_positive table tl in
364               res @ pos
365       in
366       let maxm, copy_of_current = Equality.fix_metas !maxmeta current in
367         maxmeta := maxm;
368       let curr_table = Indexing.index Indexing.empty current in
369       let pos = infer_positive curr_table (copy_of_current::active_list) 
370       in 
371       if Utils.debug_metas then 
372         ignore(List.map 
373                  (function current -> 
374                     Indexing.check_target c current "sup3") pos);
375         res @ pos
376   in
377   derived_clauses := !derived_clauses + (List.length new_pos);
378   match !maximal_retained_equality with
379     | None -> new_pos
380     | Some eq ->
381       ignore(assert false);
382       (* if we have a maximal_retained_equality, we can discard all equalities
383          "greater" than it, as they will never be reached...  An equality is
384          greater than maximal_retained_equality if it is bigger
385          wrt. OrderedEquality.compare and it is less similar than
386          maximal_retained_equality to the current goal *)
387         List.filter (fun e -> OrderedEquality.compare e eq <= 0) new_pos
388 ;;
389
390 let check_for_deep_subsumption env active_table eq =
391   let _,_,(eq_ty, left, right, order),metas,id = Equality.open_equality eq in
392   if id = 14242 then assert false;
393   
394   let check_subsumed deep l r = 
395     let eqtmp = 
396       Equality.mk_tmp_equality(0,(eq_ty,l,r,Utils.Incomparable),metas)in
397     match Indexing.subsumption env active_table eqtmp with
398     | None -> false
399     | Some (s,eq') -> 
400 (*
401         prerr_endline 
402           ("\n\n " ^ Equality.string_of_equality ~env eq ^ 
403           "\nis"^(if deep then " CONTEXTUALLY " else " ")^"subsumed by \n " ^ 
404           Equality.string_of_equality ~env eq' ^ "\n\n");
405 *)
406         true        
407   in 
408   let rec aux b (ok_so_far, subsumption_used) t1 t2  = 
409     match t1,t2 with
410       | t1, t2 when not ok_so_far -> ok_so_far, subsumption_used
411       | t1, t2 when subsumption_used -> t1 = t2, subsumption_used
412 (* VERSIONE ERRATA 
413       | Cic.Appl (h1::l),Cic.Appl (h2::l') when h1 = h2 ->
414           let rc = check_subsumed b t1 t1 in 
415             if rc then 
416               true, true
417             else if h1 = h2 then
418               (try 
419                  List.fold_left2 
420                    (fun (ok_so_far, subsumption_used) t t' -> 
421                       aux true (ok_so_far, subsumption_used) t t')
422                    (ok_so_far, subsumption_used) l l'
423                with Invalid_argument _ -> false,subsumption_used)
424             else
425               false, subsumption_used
426       | _ -> false, subsumption_used *)
427       | Cic.Appl (h1::l),Cic.Appl (h2::l') ->
428           let rc = check_subsumed b t1 t2 in 
429             if rc then 
430               true, true
431             else if h1 = h2 then
432               (try 
433                  List.fold_left2 
434                    (fun (ok_so_far, subsumption_used) t t' -> 
435                       aux true (ok_so_far, subsumption_used) t t')
436                    (ok_so_far, subsumption_used) l l'
437                with Invalid_argument _ -> false,subsumption_used)
438             else
439               false, subsumption_used
440     | _ -> false, subsumption_used 
441   in
442   fst (aux false (true,false) left right)
443 ;;
444
445 (*
446 let check_for_deep env active_table eq =
447   match Indexing.subsumption env active_table eq with
448   | None -> false
449   | Some _ -> true
450 ;;
451 *)
452
453 let profiler = HExtlib.profile "check_for_deep";;
454
455 let check_for_deep_subsumption env active_table eq = 
456   profiler.HExtlib.profile (check_for_deep_subsumption env active_table) eq
457 ;;
458
459 (* buttare via sign *)
460
461 (** simplifies current using active and passive *)
462 let forward_simplify env (sign,current) ?passive (active_list, active_table) =
463   let _, context, _ = env in
464   let passive_table =
465     match passive with
466     | None -> None
467     | Some ((_, _), pt) -> Some pt
468   in
469   let demodulate table current = 
470     let newmeta, newcurrent =
471       Indexing.demodulation_equality !maxmeta env table sign current in
472     maxmeta := newmeta;
473     if Equality.is_identity env newcurrent then
474 (*         debug_print  *)
475 (*           (lazy *)
476 (*              (Printf.sprintf "\ncurrent was: %s\nnewcurrent is: %s\n" *)
477 (*                 (string_of_equality current) *)
478 (*                 (string_of_equality newcurrent))); *)
479 (*         debug_print *)
480 (*           (lazy *)
481 (*              (Printf.sprintf "active is: %s" *)
482 (*                 (String.concat "\n"  *)
483 (*                    (List.map (fun (_, e) -> (string_of_equality e)) active_list)))); *)
484         None
485     else
486       Some newcurrent
487   in
488   let rec demod current =
489     if Utils.debug_metas then
490       ignore (Indexing.check_target context current "demod0");
491     let res = demodulate active_table current in
492       if Utils.debug_metas then
493         ignore ((function None -> () | Some x -> 
494                    ignore (Indexing.check_target context x "demod1");()) res);
495     match res with
496     | None -> None
497     | Some newcurrent ->
498         match passive_table with
499         | None -> res
500         | Some passive_table -> 
501             match demodulate passive_table newcurrent with
502               | None -> None
503               | Some newnewcurrent -> 
504                   if Equality.compare newcurrent newnewcurrent <> 0 then 
505                     demod newnewcurrent
506                   else Some newnewcurrent
507   in 
508   let res = demod current in
509   match res with
510   | None -> None
511   | Some c ->
512       if Indexing.in_index active_table c then
513         None
514       else
515         match passive_table with
516         | None -> 
517             if check_for_deep_subsumption env active_table c then
518               None
519             else 
520               res
521 (*
522             if Indexing.subsumption env active_table c = None then
523               res
524             else
525               None
526 *)
527         | Some passive_table ->
528             if Indexing.in_index passive_table c then None
529             else 
530               if check_for_deep_subsumption env active_table c then
531                 None
532               else 
533 (*              if Indexing.subsumption env active_table c = None then*)
534                 (match Indexing.subsumption env passive_table c with
535                 | None -> res
536                 | Some (_,c') -> 
537                     None
538                     (*prerr_endline "\n\nPESCO DALLE PASSIVE LA PIU' GENERALE\n\n";
539                     Some c'*))
540 (*
541               else
542                 None
543 *)
544 ;;
545
546 type fs_time_info_t = {
547   mutable build_all: float;
548   mutable demodulate: float;
549   mutable subsumption: float;
550 };;
551
552 let fs_time_info = { build_all = 0.; demodulate = 0.; subsumption = 0. };;
553
554
555 (** simplifies new using active and passive *)
556 let forward_simplify_new env new_pos ?passive active =
557   if Utils.debug_metas then
558     begin
559       let m,c,u = env in
560         ignore(List.map 
561         (fun current -> Indexing.check_target c current "forward new pos") 
562       new_pos;)
563     end;
564   let t1 = Unix.gettimeofday () in
565
566   let active_list, active_table = active in
567   let passive_table =
568     match passive with
569     | None -> None
570     | Some ((_, _), pt) -> Some pt
571   in
572   let t2 = Unix.gettimeofday () in
573   fs_time_info.build_all <- fs_time_info.build_all +. (t2 -. t1);
574   
575   let demodulate sign table target =
576     let newmeta, newtarget =
577       Indexing.demodulation_equality !maxmeta env table sign target in
578     maxmeta := newmeta;
579     newtarget
580   in
581   let t1 = Unix.gettimeofday () in
582   (* we could also demodulate using passive. Currently we don't *)
583   let new_pos =
584     List.map (demodulate Positive active_table) new_pos 
585   in
586   let t2 = Unix.gettimeofday () in
587   fs_time_info.demodulate <- fs_time_info.demodulate +. (t2 -. t1);
588
589   let new_pos_set =
590     List.fold_left
591       (fun s e ->
592          if not (Equality.is_identity env e) then
593            if EqualitySet.mem e s then s
594            else EqualitySet.add e s
595          else s)
596       EqualitySet.empty new_pos
597   in
598   let new_pos = EqualitySet.elements new_pos_set in
599
600   let subs =
601     match passive_table with
602     | None ->
603         (fun e -> (Indexing.subsumption env active_table e = None))
604     | Some passive_table ->
605         (fun e -> ((Indexing.subsumption env active_table e = None) &&
606                          (Indexing.subsumption env passive_table e = None)))
607   in
608 (*   let t1 = Unix.gettimeofday () in *)
609 (*   let t2 = Unix.gettimeofday () in *)
610 (*   fs_time_info.subsumption <- fs_time_info.subsumption +. (t2 -. t1); *)
611   let is_duplicate =
612     match passive_table with
613     | None ->
614         (fun e -> not (Indexing.in_index active_table e))
615     | Some passive_table ->
616         (fun e ->
617            not ((Indexing.in_index active_table e) ||
618                   (Indexing.in_index passive_table e)))
619   in
620   List.filter subs (List.filter is_duplicate new_pos)
621 ;;
622
623
624 (** simplifies a goal with equalities in active and passive *)  
625 let rec simplify_goal env goal ?passive (active_list, active_table) =
626   let passive_table =
627     match passive with
628     | None -> None
629     | Some ((_, _), pt) -> Some pt
630   in
631   let demodulate table goal = 
632     let changed, newmeta, newgoal =
633       Indexing.demodulation_goal !maxmeta env table goal in
634     maxmeta := newmeta;
635     changed, newgoal
636   in
637   let changed, goal =
638     match passive_table with
639     | None -> demodulate active_table goal
640     | Some passive_table ->
641         let changed, goal = demodulate active_table goal in
642 (*        let changed', goal = demodulate passive_table goal in*)
643         (changed (*|| changed'*)), goal
644   in
645   changed,
646   if not changed then 
647     goal 
648   else 
649     snd (simplify_goal env goal ?passive (active_list, active_table)) 
650 ;;
651
652
653 let simplify_goals env goals ?passive active =
654   let a_goals, p_goals = goals in
655   let p_goals = 
656     List.map
657       (fun (d, gl) ->
658          let gl =
659            List.map (fun g -> snd (simplify_goal env g ?passive active)) gl in
660          d, gl)
661       p_goals
662   in
663   let goals =
664     List.fold_left
665       (fun (a, p) (d, gl) ->
666          let changed = ref false in
667          let gl =
668            List.map
669              (fun g ->
670                 let c, g = simplify_goal env g ?passive active in
671                 changed := !changed || c; g) gl in
672          if !changed then (a, (d, gl)::p) else ((d, gl)::a, p))
673       ([], p_goals) a_goals
674   in
675   goals
676 ;;
677
678
679 (** simplifies active usign new *)
680 let backward_simplify_active env new_pos new_table min_weight active =
681   let active_list, active_table = active in
682   let active_list, newa, pruned = 
683     List.fold_right
684       (fun equality (res, newn,pruned) ->
685          let ew, _, _, _,id = Equality.open_equality equality in
686          if ew < min_weight then
687            equality::res, newn,pruned
688          else
689            match forward_simplify env (Utils.Positive, equality) (new_pos, new_table) with
690            | None -> res, newn, id::pruned
691            | Some e ->
692                if Equality.compare equality e = 0 then
693                  e::res, newn, pruned
694                else 
695                  res, e::newn, pruned)
696       active_list ([], [],[])
697   in
698   let find eq1 where =
699     List.exists (Equality.meta_convertibility_eq eq1) where
700   in
701   let id_of_eq eq = 
702     let _, _, _, _,id = Equality.open_equality eq in id
703   in
704   let ((active1,pruned),tbl), newa =
705     List.fold_right
706       (fun eq ((res,pruned), tbl) ->
707          if List.mem eq res then
708            (res, (id_of_eq eq)::pruned),tbl 
709          else if (Equality.is_identity env eq) || (find eq res) then (
710            (res, (id_of_eq eq)::pruned),tbl
711          ) 
712          else
713            (eq::res,pruned), Indexing.index tbl eq)
714       active_list (([],pruned), Indexing.empty),
715     List.fold_right
716       (fun eq p ->
717          if (Equality.is_identity env eq) then p
718          else eq::p)
719       newa []
720   in
721   if List.length active1 <> List.length (fst active) then
722     prerr_endline "\n\n\nMANCAVANO DELLE PRUNED!!!!\n\n\n";
723   match newa with
724   | [] -> (active1,tbl), None, pruned 
725   | _ -> (active1,tbl), Some newa, pruned
726 ;;
727
728
729 (** simplifies passive using new *)
730 let backward_simplify_passive env new_pos new_table min_weight passive =
731   let (pl, ps), passive_table = passive in
732   let f sign equality (resl, ress, newn) =
733     let ew, _, _, _ , _ = Equality.open_equality equality in
734     if ew < min_weight then
735       equality::resl, ress, newn
736     else
737       match forward_simplify env (sign, equality) (new_pos, new_table) with
738       | None -> resl, EqualitySet.remove equality ress, newn
739       | Some e ->
740           if equality = e then
741             equality::resl, ress, newn
742           else
743             let ress = EqualitySet.remove equality ress in
744               resl, ress, e::newn
745   in
746   let pl, ps, newp = List.fold_right (f Positive) pl ([], ps, []) in
747   let passive_table =
748     List.fold_left
749       (fun tbl e -> Indexing.index tbl e) Indexing.empty pl
750   in
751   match newp with
752   | [] -> ((pl, ps), passive_table), None
753   |  _ -> ((pl, ps), passive_table), Some (newp)
754 ;;
755
756 let build_table equations =
757     List.fold_left
758       (fun (l, t, w) e ->
759          let ew, _, _, _ , _ = Equality.open_equality e in
760          e::l, Indexing.index t e, min ew w)
761       ([], Indexing.empty, 1000000) equations
762 ;;
763   
764
765 let backward_simplify env new' ?passive active =
766   let new_pos, new_table, min_weight = build_table new' in
767 (*
768     List.fold_left
769       (fun (l, t, w) e ->
770          let ew, _, _, _ , _ = Equality.open_equality e in
771          e::l, Indexing.index t e, min ew w)
772       ([], Indexing.empty, 1000000) new'
773   in
774 *)
775   let active, newa, pruned =
776     backward_simplify_active env new_pos new_table min_weight active in
777   match passive with
778   | None ->
779       active, (make_passive []), newa, None, pruned
780   | Some passive ->
781      active, passive, newa, None, pruned
782 (* prova
783       let passive, newp =
784         backward_simplify_passive env new_pos new_table min_weight passive in
785       active, passive, newa, newp *)
786 ;;
787
788
789 let close env new' given =
790   let new_pos, new_table, min_weight =
791     List.fold_left
792       (fun (l, t, w) e ->
793          let ew, _, _, _ , _ = Equality.open_equality e in
794          e::l, Indexing.index t e, min ew w)
795       ([], Indexing.empty, 1000000) (snd new')
796   in
797   List.fold_left
798     (fun p c ->
799        let pos = infer env c (new_pos,new_table) in
800          pos@p)
801     [] given 
802 ;;
803
804 let is_commutative_law eq =
805   let w, proof, (eq_ty, left, right, order), metas , _ = 
806     Equality.open_equality eq 
807   in
808     match left,right with
809         Cic.Appl[f1;Cic.Meta _ as a1;Cic.Meta _ as b1], 
810         Cic.Appl[f2;Cic.Meta _ as a2;Cic.Meta _ as b2] ->
811           f1 = f2 && a1 = b2 && a2 = b1
812       | _ -> false
813 ;;
814
815 let prova env new' active = 
816   let given = List.filter is_commutative_law (fst active) in
817   let _ =
818     debug_print
819       (lazy
820          (Printf.sprintf "symmetric:\n%s\n"
821             (String.concat "\n"
822                (List.map
823                   (fun e -> Equality.string_of_equality ~env e)
824                    given)))) in
825     close env new' given
826 ;;
827
828 (* returns an estimation of how many equalities in passive can be activated
829    within the current time limit *)
830 let get_selection_estimate () =
831   elapsed_time := (Unix.gettimeofday ()) -. !start_time;
832   (*   !processed_clauses * (int_of_float (!time_limit /. !elapsed_time)) *)
833   int_of_float (
834     ceil ((float_of_int !processed_clauses) *.
835             ((!time_limit (* *. 2. *)) /. !elapsed_time -. 1.)))
836 ;;
837
838
839 (** initializes the set of goals *)
840 let make_goals goal =
841   let active = []
842   and passive = [0, [goal]] in
843   active, passive
844 ;;
845
846
847 (** initializes the set of theorems *)
848 let make_theorems theorems =
849   theorems, []
850 ;;
851
852
853 let activate_goal (active, passive) =
854   if active = [] then
855     match passive with
856     | goal_conj::tl -> true, (goal_conj::active, tl)
857     | [] -> false, (active, passive)
858   else  
859     true, (active,passive)
860 ;;
861
862
863 let activate_theorem (active, passive) =
864   match passive with
865   | theorem::tl -> true, (theorem::active, tl)
866   | [] -> false, (active, passive)
867 ;;
868
869
870
871 let simplify_theorems env theorems ?passive (active_list, active_table) =
872   let pl, passive_table =
873     match passive with
874     | None -> [], None
875     | Some ((pn, _), (pp, _), pt) ->
876         let pn = List.map (fun e -> (Negative, e)) pn
877         and pp = List.map (fun e -> (Positive, e)) pp in
878         pn @ pp, Some pt
879   in
880   let a_theorems, p_theorems = theorems in
881   let demodulate table theorem =
882     let newmeta, newthm =
883       Indexing.demodulation_theorem !maxmeta env table theorem in
884     maxmeta := newmeta;
885     theorem != newthm, newthm
886   in
887   let foldfun table (a, p) theorem =
888     let changed, theorem = demodulate table theorem in
889     if changed then (a, theorem::p) else (theorem::a, p)
890   in
891   let mapfun table theorem = snd (demodulate table theorem) in
892   match passive_table with
893   | None ->
894       let p_theorems = List.map (mapfun active_table) p_theorems in
895       List.fold_left (foldfun active_table) ([], p_theorems) a_theorems
896   | Some passive_table ->
897       let p_theorems = List.map (mapfun active_table) p_theorems in
898       let p_theorems, a_theorems =
899         List.fold_left (foldfun active_table) ([], p_theorems) a_theorems in
900       let p_theorems = List.map (mapfun passive_table) p_theorems in
901       List.fold_left (foldfun passive_table) ([], p_theorems) a_theorems
902 ;;
903
904
905 let rec simpl env e others others_simpl =
906   let active = others @ others_simpl in
907   let tbl =
908     List.fold_left
909       (fun t e -> Indexing.index t e)
910       Indexing.empty active
911   in
912   let res = forward_simplify env (Positive,e) (active, tbl) in
913     match others with
914       | hd::tl -> (
915           match res with
916             | None -> simpl env hd tl others_simpl
917             | Some e -> simpl env hd tl (e::others_simpl)
918         )
919       | [] -> (
920           match res with
921             | None -> others_simpl
922             | Some e -> e::others_simpl
923         )
924 ;;
925
926 let simplify_equalities env equalities =
927   debug_print
928     (lazy 
929        (Printf.sprintf "equalities:\n%s\n"
930           (String.concat "\n"
931              (List.map Equality.string_of_equality equalities))));
932   debug_print (lazy "SIMPLYFYING EQUALITIES...");
933   match equalities with
934     | [] -> []
935     | hd::tl ->
936         let res =
937           List.rev (simpl env hd tl [])
938         in
939           debug_print
940             (lazy
941                (Printf.sprintf "equalities AFTER:\n%s\n"
942                   (String.concat "\n"
943                      (List.map Equality.string_of_equality res))));
944           res
945 ;;
946
947 let print_goals goals = 
948   (String.concat "\n"
949      (List.map
950         (fun (d, gl) ->
951            let gl' =
952              List.map
953                (fun (p, _, t) ->
954                   (* (string_of_proof p) ^ ", " ^ *) (CicPp.ppterm t)) gl
955            in
956            Printf.sprintf "%d: %s" d (String.concat "; " gl')) goals))
957 ;;
958
959 let check_if_goal_is_subsumed ((_,ctx,_) as env) table (goalproof,menv,ty) =
960   let names = names_of_context ctx in
961   Printf.eprintf "check_goal_subsumed: %s\n" (CicPp.pp ty names);
962   match ty with
963   | Cic.Appl[Cic.MutInd(uri,_,_);eq_ty;left;right] 
964     when UriManager.eq uri (LibraryObjects.eq_URI ()) ->
965       (let goal_equation = 
966          Equality.mk_equality
967            (0,Equality.Exact (Cic.Implicit None),(eq_ty,left,right,Eq),menv) 
968       in
969       match Indexing.subsumption env table goal_equation with
970 (*       match Indexing.unification env table goal_equation with *)
971         | Some (subst, equality ) ->
972             let (_,p,(ty,l,r,_),m,id) = Equality.open_equality equality in
973             let cicmenv = Subst.apply_subst_metasenv subst (m @ menv) in
974             Some (goalproof, p, subst, cicmenv)
975         | None -> None)
976   | _ -> None
977 ;;
978
979 let counter = ref 0
980
981 (** given-clause algorithm with full reduction strategy *)
982 let rec given_clause_fullred dbd env goals theorems ~passive active =
983   let goals = simplify_goals env goals ~passive active in 
984   let _,context,_ = env in
985   let ok, goals = activate_goal goals in
986 (*   let theorems = simplify_theorems env theorems ~passive active in *)
987   if ok then
988     let names = List.map (HExtlib.map_option (fun (name,_) -> name)) context in 
989     let _, _, t = List.hd (snd (List.hd (fst goals))) in
990     let _ = prerr_endline ("goal activated = " ^ (CicPp.pp t names)) in
991 (*     let _ = *)
992 (*       debug_print *)
993 (*         (lazy *)
994 (*            (Printf.sprintf "\ngoals = \nactive\n%s\npassive\n%s\n" *)
995 (*               (print_goals (fst goals)) (print_goals (snd goals)))); *)
996 (*       let current = List.hd (fst goals) in *)
997 (*       let p, _, t = List.hd (snd current) in *)
998 (*       debug_print *)
999 (*         (lazy *)
1000 (*            (Printf.sprintf "goal activated:\n%s\n%s\n" *)
1001 (*               (CicPp.ppterm t) (string_of_proof p))); *)
1002 (*     in *)
1003     let ok, proof =
1004       (* apply_goal_to_theorems dbd env theorems ~passive active goals in *)
1005       let iseq uri = UriManager.eq uri (LibraryObjects.eq_URI ()) in
1006       match (fst goals) with
1007         | (_,[goalproof,m,Cic.Appl[Cic.MutInd(uri,_,ens);eq_ty;left;right]])::_ 
1008             when left = right && iseq uri -> 
1009             let reflproof = Equality.Exact (Equality.refl_proof eq_ty left) in
1010             true, Some (goalproof, reflproof, Subst.empty_subst,m)
1011         | (_, [goal])::_ ->
1012             (match check_if_goal_is_subsumed env (snd active) goal with
1013             | None -> false,None
1014             | Some p ->
1015                 prerr_endline "Proof found by subsumption!";
1016                 true, Some p)
1017         | _ -> false, None
1018     in 
1019     if ok then
1020       ( prerr_endline "esco qui";
1021         (*
1022         let s = Printf.sprintf "actives:\n%s\n"
1023           (String.concat "\n"
1024              ((List.map
1025                  (fun (s, e) -> (string_of_sign s) ^ " " ^
1026                     (string_of_equality ~env e))
1027                  (fst active)))) in
1028         let sp = Printf.sprintf "passives:\n%s\n"
1029           (String.concat "\n"
1030              (List.map
1031                 (string_of_equality ~env)
1032                 (let x,y,_ = passive in (fst x)@(fst y)))) in
1033           prerr_endline s;
1034           prerr_endline sp; *)
1035         match proof with 
1036         | None -> assert false 
1037         | Some p ->  ParamodulationSuccess p)
1038     else
1039       given_clause_fullred_aux dbd env goals theorems passive active
1040   else
1041 (*     let ok', theorems = activate_theorem theorems in *)
1042 (*     if ok' then *)
1043 (*       let ok, goals = apply_theorem_to_goals env theorems active goals in *)
1044 (*       if ok then *)
1045 (*         let proof = *)
1046 (*           match (fst goals) with *)
1047 (*           | (_, [proof, _, _])::_ -> Some proof *)
1048 (*           | _ -> assert false *)
1049 (*         in *)
1050 (*         ParamodulationSuccess (proof, env) *)
1051 (*       else *)
1052 (*         given_clause_fullred_aux env goals theorems passive active *)
1053 (*     else *)
1054       if (passive_is_empty passive) then ParamodulationFailure ""
1055       else given_clause_fullred_aux dbd env goals theorems passive active
1056     
1057 and given_clause_fullred_aux dbd env goals theorems passive active =
1058   prerr_endline (string_of_int !counter ^ 
1059                  " MAXMETA: " ^ string_of_int !maxmeta ^ 
1060                  " #ACTIVES: " ^ string_of_int (size_of_active active) ^
1061                  " #PASSIVES: " ^ string_of_int (size_of_passive passive));
1062   incr counter;
1063 (*
1064     if !counter mod 10 = 0 then
1065     begin
1066       let size = HExtlib.estimate_size (passive,active) in
1067       let sizep = HExtlib.estimate_size (passive) in
1068       let sizea = HExtlib.estimate_size (active) in
1069       let (l1,s1),(l2,s2), t = passive in 
1070       let sizetbl = HExtlib.estimate_size t in
1071       let sizel = HExtlib.estimate_size (l1,l2) in
1072       let sizes = HExtlib.estimate_size (s1,s2) in
1073
1074       prerr_endline ("SIZE: " ^ string_of_int size);        
1075       prerr_endline ("SIZE P: " ^ string_of_int sizep);        
1076       prerr_endline ("SIZE A: " ^ string_of_int sizea);        
1077       prerr_endline ("SIZE TBL: " ^ string_of_int sizetbl ^ 
1078                        " SIZE L: " ^ string_of_int sizel ^ 
1079                        " SIZE S:" ^ string_of_int sizes);
1080     end;*)
1081 (*
1082   if (size_of_active active) mod 50 = 0 then
1083     (let s = Printf.sprintf "actives:\n%s\n"
1084       (String.concat "\n"
1085          ((List.map
1086              (fun (s, e) -> (string_of_sign s) ^ " " ^
1087                 (string_of_equality ~env e))
1088              (fst active)))) in
1089      let sp = Printf.sprintf "passives:\n%s\n"
1090       (String.concat "\n"
1091          (List.map
1092              (string_of_equality ~env)
1093              (let x,y,_ = passive in (fst x)@(fst y)))) in
1094       prerr_endline s;
1095       prerr_endline sp); *)
1096   let time1 = Unix.gettimeofday () in
1097   let (_,context,_) = env in
1098   let selection_estimate = get_selection_estimate () in
1099   let kept = size_of_passive passive in
1100   let passive =
1101     if !time_limit = 0. || !processed_clauses = 0 then
1102       passive
1103     else if !elapsed_time > !time_limit then (
1104       debug_print (lazy (Printf.sprintf "Time limit (%.2f) reached: %.2f\n"
1105                            !time_limit !elapsed_time));
1106       make_passive [] 
1107     ) else if kept > selection_estimate then (
1108       debug_print
1109         (lazy (Printf.sprintf ("Too many passive equalities: pruning..." ^^
1110                                  "(kept: %d, selection_estimate: %d)\n")
1111                  kept selection_estimate));
1112       prune_passive selection_estimate active passive
1113     ) else
1114       passive
1115   in
1116
1117   let time2 = Unix.gettimeofday () in
1118   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
1119   
1120   kept_clauses := (size_of_passive passive) + (size_of_active active);
1121   match passive_is_empty passive with
1122   | true -> ParamodulationFailure ""
1123       (* given_clause_fullred dbd env goals theorems passive active  *)     
1124   | false ->
1125       let current, passive = select env (fst goals) passive in
1126       prerr_endline 
1127         ("Selected = " ^ Equality.string_of_equality ~env current);
1128 (* ^ 
1129            (let w,p,(t,l,r,o),m = current in
1130            " size w: " ^ string_of_int (HExtlib.estimate_size w)^
1131            " size p: " ^ string_of_int (HExtlib.estimate_size p)^
1132            " size t: " ^ string_of_int (HExtlib.estimate_size t)^
1133            " size l: " ^ string_of_int (HExtlib.estimate_size l)^
1134            " size r: " ^ string_of_int (HExtlib.estimate_size r)^
1135            " size o: " ^ string_of_int (HExtlib.estimate_size o)^
1136            " size m: " ^ string_of_int (HExtlib.estimate_size m)^
1137            " size m-c: " ^ string_of_int 
1138              (HExtlib.estimate_size (List.map (fun (x,_,_) -> x) m)))) *)
1139       let time1 = Unix.gettimeofday () in
1140       let res = forward_simplify env (Positive, current) ~passive active in
1141       let time2 = Unix.gettimeofday () in
1142       forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
1143       match res with
1144       | None ->
1145           (* weight_age_counter := !weight_age_counter + 1; *)
1146           given_clause_fullred dbd env goals theorems passive active
1147       | Some current ->
1148 (*          prerr_endline (Printf.sprintf "selected simpl: %s"
1149                                (Equality.string_of_equality ~env current));*)
1150           let t1 = Unix.gettimeofday () in
1151           let new' = infer env current active in
1152           let _ =
1153             debug_print
1154               (lazy
1155                  (Printf.sprintf "new' (senza semplificare):\n%s\n"
1156                     (String.concat "\n"
1157                        (List.map
1158                           (fun e -> "Positive " ^
1159                              (Equality.string_of_equality ~env e)) new'))))
1160           in
1161           let t2 = Unix.gettimeofday () in
1162             infer_time := !infer_time +. (t2 -. t1);
1163             let active =
1164               if Equality.is_identity env current then active
1165               else
1166                 let al, tbl = active in
1167                   al @ [current], Indexing.index tbl current
1168             in
1169             let rec simplify new' active passive =
1170               let t1 = Unix.gettimeofday () in
1171               let new' = forward_simplify_new env new'~passive active in
1172               let t2 = Unix.gettimeofday () in
1173               forward_simpl_new_time :=
1174                 !forward_simpl_new_time +. (t2 -. t1);
1175               let t1 = Unix.gettimeofday () in
1176               let active, passive, newa, retained, pruned =
1177                 backward_simplify env new' ~passive  active in
1178               let passive = 
1179                 List.fold_left filter_dependent passive pruned in
1180               let t2 = Unix.gettimeofday () in
1181                 backward_simpl_time := !backward_simpl_time +. (t2 -. t1);
1182               match newa, retained with
1183               | None, None -> active, passive, new'
1184               | Some p, None
1185               | None, Some p ->
1186                   if Utils.debug_metas then
1187                     begin
1188                       List.iter 
1189                         (fun x->Indexing.check_target context x "simplify1")
1190                         p;
1191                     end;
1192                   simplify (new' @ p) active passive
1193               | Some p, Some rp ->
1194                   simplify (new' @ p @ rp) active passive
1195             in
1196             let active, passive, new' = simplify new' active passive in
1197             let goals = 
1198               let a,b,_ = build_table new' in
1199               simplify_goals env goals ~passive (a,b)
1200             in
1201               
1202 (* pessima prova 
1203             let new1 = prova env new' active in
1204             let new' = (fst new') @ (fst new1), (snd new') @ (snd new1) in
1205             let _ =
1206               match new1 with
1207               | neg, pos ->
1208                   debug_print
1209                     (lazy
1210                        (Printf.sprintf "new1:\n%s\n"
1211                           (String.concat "\n"
1212                              ((List.map
1213                                  (fun e -> "Negative " ^
1214                                     (string_of_equality ~env e)) neg) @
1215                                 (List.map
1216                                    (fun e -> "Positive " ^
1217                                       (string_of_equality ~env e)) pos)))))
1218             in
1219 end prova *)
1220             let k = size_of_passive passive in
1221             if k < (kept - 1) then
1222               processed_clauses := !processed_clauses + (kept - 1 - k);
1223             
1224             let _ =
1225               debug_print
1226                 (lazy
1227                    (Printf.sprintf "active:\n%s\n"
1228                       (String.concat "\n"
1229                          ((List.map
1230                              (fun e -> (Equality.string_of_equality ~env e))
1231                              (fst active))))))
1232             in
1233             let _ =
1234               debug_print
1235                 (lazy
1236                    (Printf.sprintf "new':\n%s\n"
1237                       (String.concat "\n"
1238                          ((List.map
1239                              (fun e -> "Negative " ^
1240                                 (Equality.string_of_equality ~env e)) new')))))
1241             in
1242             let passive = add_to_passive passive new' in
1243               given_clause_fullred dbd env goals theorems passive active
1244 ;;
1245
1246 (*
1247 let profiler0 = HExtlib.profile "P/Saturation.given_clause_fullred"
1248
1249 let given_clause_fullred dbd env goals theorems passive active =
1250   profiler0.HExtlib.profile 
1251     (given_clause_fullred dbd env goals theorems passive) active
1252 *)
1253
1254 let iseq uri = UriManager.eq uri (LibraryObjects.eq_URI ());;
1255
1256 let check_if_goal_is_identity env = function
1257   | (goalproof,m,Cic.Appl[Cic.MutInd(uri,_,ens);eq_ty;left;right]) 
1258     when left = right && iseq uri ->
1259       let reflproof = Equality.Exact (Equality.refl_proof eq_ty left) in
1260       Some (goalproof, reflproof,Subst.empty_subst,m)
1261   | _ -> None
1262 ;;                              
1263     
1264 let rec check goal = function
1265   | [] -> None
1266   | f::tl ->
1267       match f goal with
1268       | None -> check goal tl
1269       | (Some p) as ok  -> ok
1270 ;;
1271   
1272 let simplify_goal_set env goals passive active = 
1273   (*
1274   let supl_goals = 
1275      (List.flatten 
1276        (List.map (Indexing.superposition_left env (snd active)) 
1277          goals))
1278   in
1279   *)
1280   let simplified =
1281     HExtlib.filter_map 
1282       (fun g -> 
1283         match simplify_goal env g ~passive active with 
1284         | true, g -> Some g
1285         | false, g -> Some g)
1286       goals
1287   in
1288   HExtlib.list_uniq ~eq:(fun (_,_,t1) (_,_,t2) -> t1 = t2)
1289     (List.sort (fun (_,_,t1) (_,_,t2) -> compare t1 t1)
1290       ((*goals @*) simplified))
1291 ;;
1292
1293 let check_if_goals_set_is_solved env active goals =
1294   List.fold_left 
1295     (fun proof goal ->
1296       match proof with
1297       | Some p -> proof
1298       | None -> 
1299           check goal [
1300             check_if_goal_is_identity env;
1301             check_if_goal_is_subsumed env (snd active)])
1302     None goals
1303 ;;
1304
1305 let size_of_goal_set = List.length;;
1306
1307 (** given-clause algorithm with full reduction strategy: NEW implementation *)
1308 (* here goals is a set of goals in OR *)
1309 let given_clause
1310   ((_,context,_) as env) goals theorems passive active max_iterations max_time
1311
1312   let initial_time = Unix.gettimeofday () in
1313   let iterations_left iterno = 
1314     let now = Unix.gettimeofday () in
1315     let time_left = max_time -. now in
1316     let time_spent_until_now = now -. initial_time in
1317     let iteration_medium_cost = 
1318       time_spent_until_now /. (float_of_int iterno)
1319     in
1320     let iterations_left = time_left /. iteration_medium_cost in
1321     int_of_float iterations_left 
1322   in
1323   let rec step goals theorems passive active iterno =
1324     if iterno > max_iterations then
1325       (ParamodulationFailure "No more iterations to spend")
1326     else if Unix.gettimeofday () > max_time then
1327       (ParamodulationFailure "No more time to spend")
1328     else
1329       let goals = simplify_goal_set env goals passive active in  
1330       match check_if_goals_set_is_solved env active goals with
1331       | Some p -> 
1332           Printf.eprintf "Found a proof in: %f\n" 
1333             (Unix.gettimeofday() -. initial_time);
1334           ParamodulationSuccess p
1335       | None -> 
1336           prerr_endline 
1337             (Printf.sprintf "%d #ACTIVES: %d #PASSIVES: %d #GOALSET: %d\n"
1338             iterno (size_of_active active) (size_of_passive passive)
1339             (size_of_goal_set goals));
1340           (* PRUNING OF PASSIVE THAT WILL NEVER BE PROCESSED *)  
1341           let passive =
1342             let selection_estimate = iterations_left iterno in
1343             let kept = size_of_passive passive in
1344             if kept > selection_estimate then 
1345               begin
1346                 (*Printf.eprintf "Too many passive equalities: pruning...";
1347                 prune_passive selection_estimate active*) passive
1348               end
1349             else
1350               passive
1351           in
1352           kept_clauses := (size_of_passive passive) + (size_of_active active);
1353           (* SELECTION *)
1354           if passive_is_empty passive then
1355             ParamodulationFailure "No more passive" (* maybe this is a success! *)
1356           else
1357             begin
1358               let current, passive = select env [1,goals] passive in
1359               Printf.eprintf  "Selected = %s\n"
1360                 (Equality.string_of_equality ~env current);
1361               (* SIMPLIFICATION OF CURRENT *)
1362               let res = 
1363                 forward_simplify env (Positive, current) ~passive active 
1364               in
1365               match res with
1366               | None -> step goals theorems passive active (iterno+1)
1367               | Some current ->
1368                   (* GENERATION OF NEW EQUATIONS *)
1369                   let new' = infer env current active in
1370                   let active = 
1371                     if Equality.is_identity env current then 
1372                       assert false 
1373                       (* nonsense code, check to se if it can be removed *)
1374                     else
1375                       let al, tbl = active in
1376                       al @ [current], Indexing.index tbl current
1377                   in
1378                   (* FORWARD AND BACKWARD SIMPLIFICATION *)
1379                   let rec simplify new' active passive =
1380                     let new' = forward_simplify_new env new' ~passive active in
1381                     let active, passive, newa, retained, pruned =
1382                       backward_simplify env new' ~passive  active 
1383                     in
1384                     let passive = List.fold_left filter_dependent passive pruned in
1385                     match newa, retained with
1386                     | None, None -> active, passive, new'
1387                     | Some p, None 
1388                     | None, Some p -> simplify (new' @ p) active passive
1389                     | Some p, Some rp -> simplify (new' @ p @ rp) active passive
1390                   in
1391                   let active, passive, new' = simplify new' active passive in
1392                   let goals = 
1393                     let a,b,_ = build_table new' in
1394                     simplify_goal_set env goals passive (a,b)
1395                   in
1396                   let passive = add_to_passive passive new' in
1397                   step goals theorems passive active (iterno+1)
1398             end
1399   in
1400     step goals theorems passive active 1
1401 ;;
1402
1403 let rec saturate_equations env goal accept_fun passive active =
1404   elapsed_time := Unix.gettimeofday () -. !start_time;
1405   if !elapsed_time > !time_limit then
1406     (active, passive)
1407   else
1408     let current, passive = select env [1, [goal]] passive in
1409     let res = forward_simplify env (Positive, current) ~passive active in
1410     match res with
1411     | None ->
1412         saturate_equations env goal accept_fun passive active
1413     | Some current ->
1414         debug_print (lazy (Printf.sprintf "selected: %s"
1415                              (Equality.string_of_equality ~env current)));
1416         let new' = infer env current active in
1417         let active =
1418           if Equality.is_identity env current then active
1419           else
1420             let al, tbl = active in
1421             al @ [current], Indexing.index tbl current
1422         in
1423         let rec simplify new' active passive =
1424           let new' = forward_simplify_new env new' ~passive active in
1425           let active, passive, newa, retained, pruned =
1426             backward_simplify env new' ~passive active in
1427           let passive = 
1428             List.fold_left filter_dependent passive pruned in
1429           match newa, retained with
1430           | None, None -> active, passive, new'
1431           | Some p, None
1432           | None, Some p -> simplify (new' @ p) active passive
1433           | Some p, Some rp -> simplify (new' @ p @ rp) active passive
1434         in
1435         let active, passive, new' = simplify new' active passive in
1436         let _ =
1437           debug_print
1438             (lazy
1439                (Printf.sprintf "active:\n%s\n"
1440                   (String.concat "\n"
1441                      (List.map
1442                          (fun e -> Equality.string_of_equality ~env e)
1443                          (fst active)))))
1444         in
1445         let _ =
1446           debug_print
1447             (lazy
1448                (Printf.sprintf "new':\n%s\n"
1449                   (String.concat "\n"
1450                      (List.map
1451                          (fun e -> "Negative " ^
1452                             (Equality.string_of_equality ~env e)) new'))))
1453         in
1454         let new' = List.filter accept_fun new' in
1455         let passive = add_to_passive passive new' in
1456         saturate_equations env goal accept_fun passive active
1457 ;;
1458   
1459 let main dbd full term metasenv ugraph = ()
1460 (*
1461 let main dbd full term metasenv ugraph =
1462   let module C = Cic in
1463   let module T = CicTypeChecker in
1464   let module PET = ProofEngineTypes in
1465   let module PP = CicPp in
1466   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1467   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1468   let proof, goals = status in
1469   let goal' = List.nth goals 0 in
1470   let _, metasenv, meta_proof, _ = proof in
1471   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1472   let eq_indexes, equalities, maxm = find_equalities context proof in
1473   let lib_eq_uris, library_equalities, maxm =
1474
1475     find_library_equalities dbd context (proof, goal') (maxm+2)
1476   in
1477   let library_equalities = List.map snd library_equalities in
1478   maxmeta := maxm+2; (* TODO ugly!! *)
1479   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
1480   let new_meta_goal, metasenv, type_of_goal =
1481     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1482     debug_print
1483       (lazy
1484          (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n\n" (CicPp.ppterm ty)));
1485     Cic.Meta (maxm+1, irl),
1486     (maxm+1, context, ty)::metasenv,
1487     ty
1488   in
1489   let env = (metasenv, context, ugraph) in
1490   let t1 = Unix.gettimeofday () in
1491   let theorems =
1492     if full then
1493       let theorems = find_library_theorems dbd env (proof, goal') lib_eq_uris in
1494       let context_hyp = find_context_hypotheses env eq_indexes in
1495       context_hyp @ theorems, []
1496     else
1497       let refl_equal =
1498         let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
1499         UriManager.uri_of_string (us ^ "#xpointer(1/1/1)")
1500       in
1501       let t = CicUtil.term_of_uri refl_equal in
1502       let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
1503       [(t, ty, [])], []
1504   in
1505   let t2 = Unix.gettimeofday () in
1506   debug_print
1507     (lazy
1508        (Printf.sprintf "Time to retrieve theorems: %.9f\n" (t2 -. t1)));
1509   let _ =
1510     debug_print
1511       (lazy
1512          (Printf.sprintf
1513             "Theorems:\n-------------------------------------\n%s\n"
1514             (String.concat "\n"
1515                (List.map
1516                   (fun (t, ty, _) ->
1517                      Printf.sprintf
1518                        "Term: %s, type: %s" (CicPp.ppterm t) (CicPp.ppterm ty))
1519                   (fst theorems)))))
1520   in
1521   (*try*)
1522     let goal = 
1523       ([],Equality.BasicProof (Equality.empty_subst ,new_meta_goal)), [], goal 
1524     in
1525     let equalities = simplify_equalities env 
1526       (equalities@library_equalities) in 
1527     let active = make_active () in
1528     let passive = make_passive equalities in
1529     Printf.printf "\ncurrent goal: %s\n"
1530       (let _, _, g = goal in CicPp.ppterm g);
1531     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
1532     Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
1533     Printf.printf "\nequalities:\n%s\n"
1534       (String.concat "\n"
1535          (List.map
1536             (Equality.string_of_equality ~env) equalities));
1537 (*             (equalities @ library_equalities))); *)
1538       print_endline "--------------------------------------------------";
1539       let start = Unix.gettimeofday () in
1540       print_endline "GO!";
1541       start_time := Unix.gettimeofday ();
1542       let res =
1543         let goals = make_goals goal in
1544         (if !use_fullred then given_clause_fullred else given_clause_fullred)
1545           dbd env goals theorems passive active
1546       in
1547       let finish = Unix.gettimeofday () in
1548       let _ =
1549         match res with
1550         | ParamodulationFailure ->
1551             Printf.printf "NO proof found! :-(\n\n"
1552         | ParamodulationSuccess (Some ((cicproof,cicmenv),(proof, env))) ->
1553             Printf.printf "OK, found a proof!\n";
1554             let oldproof = Equation.build_proof_term proof in
1555             let newproof,_,newenv,_ = 
1556                 CicRefine.type_of_aux' 
1557                   cicmenv context cicproof CicUniv.empty_ugraph
1558             in
1559             (* REMEMBER: we have to instantiate meta_proof, we should use
1560                apply  the "apply" tactic to proof and status 
1561             *)
1562             let names = names_of_context context in
1563             prerr_endline "OLD PROOF";
1564             print_endline (PP.pp proof names);
1565             prerr_endline "NEW PROOF";
1566             print_endline (PP.pp newproof names);
1567             let newmetasenv =
1568               List.fold_left
1569                 (fun m eq -> 
1570                   let (_, _, _, menv,_) = Equality.open_equality eq in 
1571                   m @ menv) 
1572               metasenv equalities
1573             in
1574             let _ =
1575               (*try*)
1576                 let ty, ug =
1577                   CicTypeChecker.type_of_aux' newmetasenv context proof ugraph
1578                 in
1579                 print_endline (string_of_float (finish -. start));
1580                 Printf.printf
1581                   "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n\n"
1582                   (CicPp.pp type_of_goal names) (CicPp.pp ty names)
1583                   (string_of_bool
1584                      (fst (CicReduction.are_convertible
1585                              context type_of_goal ty ug)));
1586               (*with e ->
1587                 Printf.printf "\nEXCEPTION!!! %s\n" (Printexc.to_string e);
1588                 Printf.printf "MAXMETA USED: %d\n" !maxmeta;
1589                 print_endline (string_of_float (finish -. start));*)
1590             in
1591             ()
1592               
1593         | ParamodulationSuccess None ->
1594             Printf.printf "Success, but no proof?!?\n\n"
1595       in
1596         if Utils.time then
1597           begin
1598             prerr_endline 
1599               ((Printf.sprintf ("infer_time: %.9f\nforward_simpl_time: %.9f\n" ^^
1600                        "forward_simpl_new_time: %.9f\n" ^^
1601                        "backward_simpl_time: %.9f\n")
1602               !infer_time !forward_simpl_time !forward_simpl_new_time
1603               !backward_simpl_time) ^
1604               (Printf.sprintf "passive_maintainance_time: %.9f\n"
1605                  !passive_maintainance_time) ^
1606               (Printf.sprintf "    successful unification/matching time: %.9f\n"
1607                  !Indexing.match_unif_time_ok) ^
1608               (Printf.sprintf "    failed unification/matching time: %.9f\n"
1609                  !Indexing.match_unif_time_no) ^
1610               (Printf.sprintf "    indexing retrieval time: %.9f\n"
1611                  !Indexing.indexing_retrieval_time) ^
1612               (Printf.sprintf "    demodulate_term.build_newtarget_time: %.9f\n"
1613                  !Indexing.build_newtarget_time) ^
1614               (Printf.sprintf "derived %d clauses, kept %d clauses.\n"
1615                  !derived_clauses !kept_clauses)) 
1616             end
1617 (*
1618   with exc ->
1619     print_endline ("EXCEPTION: " ^ (Printexc.to_string exc));
1620     raise exc
1621 *)
1622 ;;
1623 *)
1624
1625 let default_depth = !maxdepth
1626 and default_width = !maxwidth;;
1627
1628 let reset_refs () =
1629   maxmeta := 0;
1630   symbols_counter := 0;
1631   weight_age_counter := !weight_age_ratio;
1632   processed_clauses := 0;
1633   start_time := 0.;
1634   elapsed_time := 0.;
1635   maximal_retained_equality := None;
1636   infer_time := 0.;
1637   forward_simpl_time := 0.;
1638   forward_simpl_new_time := 0.;
1639   backward_simpl_time := 0.;
1640   passive_maintainance_time := 0.;
1641   derived_clauses := 0;
1642   kept_clauses := 0;
1643   Equality.reset ();
1644 ;;
1645
1646 let saturate 
1647     dbd ?(full=false) ?(depth=default_depth) ?(width=default_width) status = 
1648   let module C = Cic in
1649   reset_refs ();
1650   Indexing.init_index ();
1651   counter := 0;
1652   maxdepth := depth;
1653   maxwidth := width;
1654 (*  CicUnification.unif_ty := false;*)
1655   let proof, goal = status in
1656   let goal' = goal in
1657   let uri, metasenv, meta_proof, term_to_prove = proof in
1658   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1659   let names = names_of_context context in
1660   let eq_indexes, equalities, maxm = find_equalities context proof in
1661   let new_meta_goal, metasenv, type_of_goal =
1662     let irl =
1663       CicMkImplicit.identity_relocation_list_for_metavariable context in
1664     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1665     debug_print
1666       (lazy (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n" (CicPp.ppterm ty)));
1667     Cic.Meta (maxm+1, irl),
1668     (maxm+1, context, ty)::metasenv,
1669     ty
1670   in
1671   let ugraph = CicUniv.empty_ugraph in
1672   let env = (metasenv, context, ugraph) in 
1673   prerr_endline 
1674     ("METASENV DEL GOAL: " ^ CicMetaSubst.ppmetasenv [] metasenv );
1675   let goal = [], metasenv, goal in
1676   let res, time =
1677     let t1 = Unix.gettimeofday () in
1678     let lib_eq_uris, library_equalities, maxm =
1679       find_library_equalities dbd context (proof, goal') (maxm+2)
1680     in
1681     let library_equalities = List.map snd library_equalities in
1682     let t2 = Unix.gettimeofday () in
1683     maxmeta := maxm+2;
1684     let equalities = simplify_equalities env (equalities@library_equalities) in 
1685     debug_print
1686       (lazy
1687          (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)));
1688     let t1 = Unix.gettimeofday () in
1689     let theorems =
1690       if full then
1691         let thms = find_library_theorems dbd env (proof, goal') lib_eq_uris in
1692         let context_hyp = find_context_hypotheses env eq_indexes in
1693         context_hyp @ thms, []
1694       else
1695         let refl_equal =
1696           let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
1697           UriManager.uri_of_string (us ^ "#xpointer(1/1/1)")
1698         in
1699         let t = CicUtil.term_of_uri refl_equal in
1700         let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
1701         [(t, ty, [])], []
1702     in
1703     let t2 = Unix.gettimeofday () in
1704     let _ =
1705       debug_print
1706         (lazy
1707            (Printf.sprintf
1708               "Theorems:\n-------------------------------------\n%s\n"
1709               (String.concat "\n"
1710                  (List.map
1711                     (fun (t, ty, _) ->
1712                        Printf.sprintf
1713                          "Term: %s, type: %s"
1714                          (CicPp.ppterm t) (CicPp.ppterm ty))
1715                     (fst theorems)))));
1716       debug_print
1717         (lazy
1718            (Printf.sprintf "Time to retrieve theorems: %.9f\n" (t2 -. t1)));
1719     in
1720     let active = make_active () in
1721     let passive = make_passive equalities in
1722     let start = Unix.gettimeofday () in
1723     let res =
1724 (*
1725       let goals = make_goals goal in
1726       given_clause_fullred dbd env goals theorems passive active
1727 *)
1728       let goals = [goal] in
1729       let max_iterations = 1000 in
1730       let max_time = 
1731         Unix.gettimeofday () +. 
1732         600. (* minutes *)
1733       in
1734       given_clause env goals theorems passive active max_iterations max_time 
1735     in
1736     let finish = Unix.gettimeofday () in
1737     (res, finish -. start)
1738   in
1739   match res with
1740   | ParamodulationFailure s ->
1741       raise (ProofEngineTypes.Fail (lazy ("NO proof found: " ^ s)))
1742   | ParamodulationSuccess 
1743     (goalproof,newproof,subsumption_subst, proof_menv) ->
1744       prerr_endline "OK, found a proof!";
1745
1746       prerr_endline "NEWPROOF";
1747      (* prerr_endline (Equality.string_of_proof_new ~names newproof
1748       * goalproof);*)
1749       prerr_endline (Equality.pp_proof names goalproof newproof);
1750
1751 (*       assert false; *)
1752       
1753       (* generation of the proof *)
1754       let cic_proof_new = 
1755         Equality.build_goal_proof 
1756           goalproof (Equality.build_proof_term newproof) type_of_goal
1757       in
1758       let cic_proof_new = 
1759         Subst.apply_subst subsumption_subst cic_proof_new 
1760       in
1761       
1762       (* replacing fake mets with real ones *)
1763       let equality_for_replace i t1 =
1764         match t1 with
1765         | C.Meta (n, _) -> n = i
1766         | _ -> false
1767       in
1768       let mkirl = CicMkImplicit.identity_relocation_list_for_metavariable in
1769       prerr_endline "replacing metas (new)";
1770       let newproof_menv, what, with_what,_ = 
1771         let irl = mkirl context in
1772         List.fold_left 
1773           (fun (acc1,acc2,acc3,uniq) (i,_,ty) -> 
1774              match uniq with
1775                | Some m -> 
1776                    acc1, 
1777                    (Cic.Meta(i,[]))::acc2, 
1778                    m::acc3, uniq
1779                | None ->
1780                    [i,context,ty], 
1781                    (Cic.Meta(i,[]))::acc2, 
1782                    (Cic.Meta(i,irl)) ::acc3,Some (Cic.Meta(i,irl))) 
1783           ([],[],[],None) proof_menv 
1784       in
1785       let cic_proof_new = ProofEngineReduction.replace_lifting
1786               ~equality:(=)
1787               ~what ~with_what
1788               ~where:cic_proof_new
1789       in
1790
1791       (* pp new/old proof *)
1792 (*      prerr_endline "NEWPROOFCIC";*)
1793 (*      prerr_endline (CicPp.pp cic_proof_new names); *)
1794
1795       (* generation of proof metasenv *)
1796       let newmetasenv_new = metasenv@newproof_menv in
1797       let newmetasenv_new =
1798         let i1 =
1799           match new_meta_goal with
1800           | C.Meta (i, _) -> i | _ -> assert false
1801         in
1802         List.filter (fun (i, _, _) -> i <> i1 && i <> goal') newmetasenv_new
1803       in
1804       (* check/refine/... build the new proof *)
1805       let newstatus =
1806         let cic_proof,newmetasenv,proof_menv,ty, ug =
1807           let cic_proof_new,new_ty,newmetasenv_new,newug = 
1808             try
1809               (*
1810                prerr_endline "refining ... (new) ";
1811                CicRefine.type_of_aux' 
1812                 newmetasenv_new context cic_proof_new ugraph
1813               *)
1814               let ty,ug = 
1815                 prerr_endline "typechecking ... (new) ";
1816                 CicTypeChecker.type_of_aux' 
1817                   newmetasenv_new context cic_proof_new ugraph
1818               in
1819               cic_proof_new, ty, newmetasenv_new, ug
1820             with
1821             | CicTypeChecker.TypeCheckerFailure s ->
1822                 prerr_endline "THE PROOF DOESN'T TYPECHECK!!!";
1823                 prerr_endline (Lazy.force s);
1824                 assert false
1825             | CicRefine.RefineFailure s 
1826             | CicRefine.Uncertain s 
1827             | CicRefine.AssertFailure s -> 
1828                 prerr_endline "FAILURE IN REFINE";
1829                 prerr_endline (Lazy.force s);
1830                 assert false
1831           in
1832           if List.length newmetasenv_new <> 0 then
1833             prerr_endline 
1834               ("Some METAS are still open: "(* ^ CicMetaSubst.ppmetasenv
1835                [] newmetasenv_new*));
1836           cic_proof_new, newmetasenv_new, newmetasenv_new,new_ty, newug
1837           (* THE OLD PROOF: cic_proof,newmetasenv,proof_menv,oldty,oldug *)
1838         in
1839         prerr_endline "FINAL PROOF";
1840         prerr_endline (CicPp.pp cic_proof names);
1841         prerr_endline "ENDOFPROOFS";
1842         (*  
1843         debug_print
1844           (lazy
1845              (Printf.sprintf
1846                 "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n"
1847                 (CicPp.pp type_of_goal names) (CicPp.pp ty names)
1848                 (string_of_bool
1849                    (fst (CicReduction.are_convertible
1850                            context type_of_goal ty ug)))));
1851         *)
1852         let real_proof =
1853           ProofEngineReduction.replace
1854             ~equality:equality_for_replace
1855             ~what:[goal'] ~with_what:[cic_proof]
1856             ~where:meta_proof
1857         in
1858         (*
1859         debug_print
1860           (lazy
1861              (Printf.sprintf "status:\n%s\n%s\n%s\n%s\n"
1862                 (match uri with Some uri -> UriManager.string_of_uri uri
1863                  | None -> "")
1864                 (print_metasenv newmetasenv)
1865                 (CicPp.pp real_proof [](* names *))
1866                 (CicPp.pp term_to_prove names)));
1867         *)
1868         let open_goals = List.map (fun (i,_,_) -> i) proof_menv in
1869         (uri, newmetasenv, real_proof, term_to_prove), open_goals
1870       in
1871       if Utils.time then
1872         begin
1873           let tall = fs_time_info.build_all in
1874           let tdemodulate = fs_time_info.demodulate in
1875           let tsubsumption = fs_time_info.subsumption in
1876           prerr_endline (
1877             (Printf.sprintf "\nTIME NEEDED: %.9f" time) ^
1878               (Printf.sprintf "\ntall: %.9f" tall) ^
1879               (Printf.sprintf "\ntdemod: %.9f" tdemodulate) ^
1880               (Printf.sprintf "\ntsubsumption: %.9f" tsubsumption) ^
1881               (Printf.sprintf "\ninfer_time: %.9f" !infer_time) ^
1882               (Printf.sprintf "\nforward_simpl_times: %.9f" 
1883                 !forward_simpl_time) ^
1884               (Printf.sprintf "\nforward_simpl_new_times: %.9f" 
1885                 !forward_simpl_new_time) ^
1886               (Printf.sprintf "\nbackward_simpl_times: %.9f" 
1887                 !backward_simpl_time) ^
1888               (Printf.sprintf "\npassive_maintainance_time: %.9f" 
1889                  !passive_maintainance_time))
1890         end;
1891       newstatus 
1892 ;;
1893
1894 let retrieve_and_print dbd term metasenv ugraph = 
1895   let module C = Cic in
1896   let module T = CicTypeChecker in
1897   let module PET = ProofEngineTypes in
1898   let module PP = CicPp in
1899   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1900   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1901   let proof, goals = status in
1902   let goal' = List.nth goals 0 in
1903   let uri, metasenv, meta_proof, term_to_prove = proof in
1904   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1905   let eq_indexes, equalities, maxm = find_equalities context proof in
1906   let new_meta_goal, metasenv, type_of_goal =
1907     let irl =
1908       CicMkImplicit.identity_relocation_list_for_metavariable context in
1909     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1910     debug_print
1911       (lazy (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n" (CicPp.ppterm ty)));
1912     Cic.Meta (maxm+1, irl),
1913     (maxm+1, context, ty)::metasenv,
1914     ty
1915   in
1916   let ugraph = CicUniv.empty_ugraph in
1917   let env = (metasenv, context, ugraph) in
1918   let t1 = Unix.gettimeofday () in
1919   let lib_eq_uris, library_equalities, maxm =
1920     find_library_equalities dbd context (proof, goal') (maxm+2) in
1921   let t2 = Unix.gettimeofday () in
1922   maxmeta := maxm+2;
1923   let equalities = (* equalities @ *) library_equalities in
1924   debug_print
1925      (lazy
1926         (Printf.sprintf "\n\nequalities:\n%s\n"
1927            (String.concat "\n"
1928               (List.map 
1929           (fun (u, e) ->
1930 (*                  Printf.sprintf "%s: %s" *)
1931                    (UriManager.string_of_uri u)
1932 (*                    (string_of_equality e) *)
1933                      )
1934           equalities))));
1935   debug_print (lazy "RETR: SIMPLYFYING EQUALITIES...");
1936   let rec simpl e others others_simpl =
1937     let (u, e) = e in
1938     let active = List.map (fun (u, e) -> (Positive, e))
1939       (others @ others_simpl) in
1940     let tbl =
1941       List.fold_left
1942         (fun t (_, e) -> Indexing.index t e)
1943         Indexing.empty active
1944     in
1945     let res = forward_simplify env (Positive, e) (active, tbl) in
1946     match others with
1947         | hd::tl -> (
1948             match res with
1949               | None -> simpl hd tl others_simpl
1950               | Some e -> simpl hd tl ((u, e)::others_simpl)
1951           )
1952         | [] -> (
1953             match res with
1954               | None -> others_simpl
1955               | Some e -> (u, e)::others_simpl
1956           ) 
1957   in
1958   let _equalities =
1959     match equalities with
1960       | [] -> []
1961       | hd::tl ->
1962           let others = tl in (* List.map (fun e -> (Positive, e)) tl in *)
1963           let res =
1964             List.rev (simpl (*(Positive,*) hd others [])
1965           in
1966             debug_print
1967               (lazy
1968                  (Printf.sprintf "\nequalities AFTER:\n%s\n"
1969                     (String.concat "\n"
1970                        (List.map
1971                           (fun (u, e) ->
1972                              Printf.sprintf "%s: %s"
1973                                (UriManager.string_of_uri u)
1974                                (Equality.string_of_equality e)
1975                           )
1976                           res))));
1977             res in
1978     debug_print
1979       (lazy
1980          (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)))
1981 ;;
1982
1983
1984 let main_demod_equalities dbd term metasenv ugraph =
1985   let module C = Cic in
1986   let module T = CicTypeChecker in
1987   let module PET = ProofEngineTypes in
1988   let module PP = CicPp in
1989   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1990   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1991   let proof, goals = status in
1992   let goal' = List.nth goals 0 in
1993   let _, metasenv, meta_proof, _ = proof in
1994   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1995   let eq_indexes, equalities, maxm = find_equalities context proof in
1996   let lib_eq_uris, library_equalities, maxm =
1997     find_library_equalities dbd context (proof, goal') (maxm+2)
1998   in
1999   let library_equalities = List.map snd library_equalities in
2000   maxmeta := maxm+2; (* TODO ugly!! *)
2001   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
2002   let new_meta_goal, metasenv, type_of_goal =
2003     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
2004     debug_print
2005       (lazy
2006          (Printf.sprintf "\n\nTRYING TO INFER EQUALITIES MATCHING: %s\n\n"
2007             (CicPp.ppterm ty)));
2008     Cic.Meta (maxm+1, irl),
2009     (maxm+1, context, ty)::metasenv,
2010     ty
2011   in
2012   let env = (metasenv, context, ugraph) in
2013   (*try*)
2014     let goal = [], [], goal 
2015     in
2016     let equalities = simplify_equalities env (equalities@library_equalities) in
2017     let active = make_active () in
2018     let passive = make_passive equalities in
2019     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
2020     Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
2021     Printf.printf "\nequalities:\n%s\n"
2022       (String.concat "\n"
2023          (List.map
2024             (Equality.string_of_equality ~env) equalities));
2025     print_endline "--------------------------------------------------";
2026     print_endline "GO!";
2027     start_time := Unix.gettimeofday ();
2028     if !time_limit < 1. then time_limit := 60.;    
2029     let ra, rp =
2030       saturate_equations env goal (fun e -> true) passive active
2031     in
2032
2033     let initial =
2034       List.fold_left (fun s e -> EqualitySet.add e s)
2035         EqualitySet.empty equalities
2036     in
2037     let addfun s e = 
2038       if not (EqualitySet.mem e initial) then EqualitySet.add e s else s
2039     in
2040
2041     let passive =
2042       match rp with
2043       | (p, _), _ ->
2044           EqualitySet.elements (List.fold_left addfun EqualitySet.empty p)
2045     in
2046     let active =
2047       let l = fst ra in
2048       EqualitySet.elements (List.fold_left addfun EqualitySet.empty l)
2049     in
2050     Printf.printf "\n\nRESULTS:\nActive:\n%s\n\nPassive:\n%s\n"
2051        (String.concat "\n" (List.map (Equality.string_of_equality ~env) active)) 
2052      (*  (String.concat "\n"
2053          (List.map (fun e -> CicPp.ppterm (term_of_equality e)) active)) *)
2054 (*       (String.concat "\n" (List.map (string_of_equality ~env) passive)); *)
2055       (String.concat "\n"
2056          (List.map (fun e -> CicPp.ppterm (Equality.term_of_equality e)) passive));
2057     print_newline ();
2058 (*
2059   with e ->
2060     debug_print (lazy ("EXCEPTION: " ^ (Printexc.to_string e)))
2061 *)
2062 ;;
2063
2064 let demodulate_tac ~dbd ~pattern ((proof,goal) as initialstatus) = 
2065   let module I = Inference in
2066   let curi,metasenv,pbo,pty = proof in
2067   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
2068   let eq_indexes, equalities, maxm = I.find_equalities context proof in
2069   let lib_eq_uris, library_equalities, maxm =
2070     I.find_library_equalities dbd context (proof, goal) (maxm+2) in
2071   if library_equalities = [] then prerr_endline "VUOTA!!!";
2072   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
2073   let library_equalities = List.map snd library_equalities in
2074   let initgoal = [], [], ty in
2075   let env = (metasenv, context, CicUniv.empty_ugraph) in
2076   let equalities = simplify_equalities env (equalities@library_equalities) in   
2077   let table = 
2078     List.fold_left 
2079       (fun tbl eq -> Indexing.index tbl eq) 
2080       Indexing.empty equalities 
2081   in
2082   let _, newmeta,(newproof,newmetasenv, newty) = 
2083     Indexing.demodulation_goal 
2084       maxm (metasenv,context,CicUniv.empty_ugraph) table initgoal 
2085   in
2086   if newmeta != maxm then
2087     begin
2088       let opengoal = Cic.Meta(maxm,irl) in
2089       let proofterm = 
2090         Equality.build_goal_proof newproof opengoal ty in
2091         let extended_metasenv = (maxm,context,newty)::metasenv in
2092         let extended_status = 
2093           (curi,extended_metasenv,pbo,pty),goal in
2094         let (status,newgoals) = 
2095           ProofEngineTypes.apply_tactic 
2096             (PrimitiveTactics.apply_tac ~term:proofterm)
2097             extended_status in
2098         (status,maxm::newgoals)
2099     end
2100   else if newty = ty then
2101     raise (ProofEngineTypes.Fail (lazy "no progress"))
2102   else ProofEngineTypes.apply_tactic 
2103     (ReductionTactics.simpl_tac ~pattern) 
2104     initialstatus
2105 ;;
2106
2107 let demodulate_tac ~dbd ~pattern = 
2108   ProofEngineTypes.mk_tactic (demodulate_tac ~dbd ~pattern)
2109 ;;