]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/tactics/paramodulation/saturation.ml
5eb62666f2d88ed5422a897f72d1e148fa01fc1b
[helm.git] / helm / software / 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 = Indexing.demodulation_goal env table goal in
632   let changed, goal =
633     match passive_table with
634     | None -> demodulate active_table goal
635     | Some passive_table ->
636         let changed, goal = demodulate active_table goal in
637 (*        let changed', goal = demodulate passive_table goal in*)
638         (changed (*|| changed'*)), goal
639   in
640   changed,
641   if not changed then 
642     goal 
643   else 
644     snd (simplify_goal env goal ?passive (active_list, active_table)) 
645 ;;
646
647
648 let simplify_goals env goals ?passive active =
649   let a_goals, p_goals = goals in
650   let p_goals = 
651     List.map
652       (fun g -> snd (simplify_goal env g ?passive active))
653       p_goals
654   in
655   let a_goals = 
656     List.map
657       (fun g -> snd (simplify_goal env g ?passive active))
658       a_goals
659   in
660   a_goals, p_goals
661 ;;
662
663
664 (** simplifies active usign new *)
665 let backward_simplify_active env new_pos new_table min_weight active =
666   let active_list, active_table = active in
667   let active_list, newa, pruned = 
668     List.fold_right
669       (fun equality (res, newn,pruned) ->
670          let ew, _, _, _,id = Equality.open_equality equality in
671          if ew < min_weight then
672            equality::res, newn,pruned
673          else
674            match forward_simplify env (Utils.Positive, equality) (new_pos, new_table) with
675            | None -> res, newn, id::pruned
676            | Some e ->
677                if Equality.compare equality e = 0 then
678                  e::res, newn, pruned
679                else 
680                  res, e::newn, pruned)
681       active_list ([], [],[])
682   in
683   let find eq1 where =
684     List.exists (Equality.meta_convertibility_eq eq1) where
685   in
686   let id_of_eq eq = 
687     let _, _, _, _,id = Equality.open_equality eq in id
688   in
689   let ((active1,pruned),tbl), newa =
690     List.fold_right
691       (fun eq ((res,pruned), tbl) ->
692          if List.mem eq res then
693            (res, (id_of_eq eq)::pruned),tbl 
694          else if (Equality.is_identity env eq) || (find eq res) then (
695            (res, (id_of_eq eq)::pruned),tbl
696          ) 
697          else
698            (eq::res,pruned), Indexing.index tbl eq)
699       active_list (([],pruned), Indexing.empty),
700     List.fold_right
701       (fun eq p ->
702          if (Equality.is_identity env eq) then p
703          else eq::p)
704       newa []
705   in
706   match newa with
707   | [] -> (active1,tbl), None, pruned 
708   | _ -> (active1,tbl), Some newa, pruned
709 ;;
710
711
712 (** simplifies passive using new *)
713 let backward_simplify_passive env new_pos new_table min_weight passive =
714   let (pl, ps), passive_table = passive in
715   let f sign equality (resl, ress, newn) =
716     let ew, _, _, _ , _ = Equality.open_equality equality in
717     if ew < min_weight then
718       equality::resl, ress, newn
719     else
720       match forward_simplify env (sign, equality) (new_pos, new_table) with
721       | None -> resl, EqualitySet.remove equality ress, newn
722       | Some e ->
723           if equality = e then
724             equality::resl, ress, newn
725           else
726             let ress = EqualitySet.remove equality ress in
727               resl, ress, e::newn
728   in
729   let pl, ps, newp = List.fold_right (f Positive) pl ([], ps, []) in
730   let passive_table =
731     List.fold_left
732       (fun tbl e -> Indexing.index tbl e) Indexing.empty pl
733   in
734   match newp with
735   | [] -> ((pl, ps), passive_table), None
736   |  _ -> ((pl, ps), passive_table), Some (newp)
737 ;;
738
739 let build_table equations =
740     List.fold_left
741       (fun (l, t, w) e ->
742          let ew, _, _, _ , _ = Equality.open_equality e in
743          e::l, Indexing.index t e, min ew w)
744       ([], Indexing.empty, 1000000) equations
745 ;;
746   
747
748 let backward_simplify env new' ?passive active =
749   let new_pos, new_table, min_weight = build_table new' in
750 (*
751     List.fold_left
752       (fun (l, t, w) e ->
753          let ew, _, _, _ , _ = Equality.open_equality e in
754          e::l, Indexing.index t e, min ew w)
755       ([], Indexing.empty, 1000000) new'
756   in
757 *)
758   let active, newa, pruned =
759     backward_simplify_active env new_pos new_table min_weight active in
760   match passive with
761   | None ->
762       active, (make_passive []), newa, None, pruned
763   | Some passive ->
764      active, passive, newa, None, pruned
765 (* prova
766       let passive, newp =
767         backward_simplify_passive env new_pos new_table min_weight passive in
768       active, passive, newa, newp *)
769 ;;
770
771
772 let close env new' given =
773   let new_pos, new_table, min_weight =
774     List.fold_left
775       (fun (l, t, w) e ->
776          let ew, _, _, _ , _ = Equality.open_equality e in
777          e::l, Indexing.index t e, min ew w)
778       ([], Indexing.empty, 1000000) (snd new')
779   in
780   List.fold_left
781     (fun p c ->
782        let pos = infer env c (new_pos,new_table) in
783          pos@p)
784     [] given 
785 ;;
786
787 let is_commutative_law eq =
788   let w, proof, (eq_ty, left, right, order), metas , _ = 
789     Equality.open_equality eq 
790   in
791     match left,right with
792         Cic.Appl[f1;Cic.Meta _ as a1;Cic.Meta _ as b1], 
793         Cic.Appl[f2;Cic.Meta _ as a2;Cic.Meta _ as b2] ->
794           f1 = f2 && a1 = b2 && a2 = b1
795       | _ -> false
796 ;;
797
798 let prova env new' active = 
799   let given = List.filter is_commutative_law (fst active) in
800   let _ =
801     debug_print
802       (lazy
803          (Printf.sprintf "symmetric:\n%s\n"
804             (String.concat "\n"
805                (List.map
806                   (fun e -> Equality.string_of_equality ~env e)
807                    given)))) in
808     close env new' given
809 ;;
810
811 (* returns an estimation of how many equalities in passive can be activated
812    within the current time limit *)
813 let get_selection_estimate () =
814   elapsed_time := (Unix.gettimeofday ()) -. !start_time;
815   (*   !processed_clauses * (int_of_float (!time_limit /. !elapsed_time)) *)
816   int_of_float (
817     ceil ((float_of_int !processed_clauses) *.
818             ((!time_limit (* *. 2. *)) /. !elapsed_time -. 1.)))
819 ;;
820
821
822 (** initializes the set of goals *)
823 let make_goals goal =
824   let active = []
825   and passive = [0, [goal]] in
826   active, passive
827 ;;
828
829 let make_goal_set goal = 
830   ([],[goal]) 
831 ;;
832
833 (** initializes the set of theorems *)
834 let make_theorems theorems =
835   theorems, []
836 ;;
837
838
839 let activate_goal (active, passive) =
840   if active = [] then
841     match passive with
842     | goal_conj::tl -> true, (goal_conj::active, tl)
843     | [] -> false, (active, passive)
844   else  
845     true, (active,passive)
846 ;;
847
848
849 let activate_theorem (active, passive) =
850   match passive with
851   | theorem::tl -> true, (theorem::active, tl)
852   | [] -> false, (active, passive)
853 ;;
854
855
856
857 let simplify_theorems env theorems ?passive (active_list, active_table) =
858   let pl, passive_table =
859     match passive with
860     | None -> [], None
861     | Some ((pn, _), (pp, _), pt) ->
862         let pn = List.map (fun e -> (Negative, e)) pn
863         and pp = List.map (fun e -> (Positive, e)) pp in
864         pn @ pp, Some pt
865   in
866   let a_theorems, p_theorems = theorems in
867   let demodulate table theorem =
868     let newmeta, newthm =
869       Indexing.demodulation_theorem !maxmeta env table theorem in
870     maxmeta := newmeta;
871     theorem != newthm, newthm
872   in
873   let foldfun table (a, p) theorem =
874     let changed, theorem = demodulate table theorem in
875     if changed then (a, theorem::p) else (theorem::a, p)
876   in
877   let mapfun table theorem = snd (demodulate table theorem) in
878   match passive_table with
879   | None ->
880       let p_theorems = List.map (mapfun active_table) p_theorems in
881       List.fold_left (foldfun active_table) ([], p_theorems) a_theorems
882   | Some passive_table ->
883       let p_theorems = List.map (mapfun active_table) p_theorems in
884       let p_theorems, a_theorems =
885         List.fold_left (foldfun active_table) ([], p_theorems) a_theorems in
886       let p_theorems = List.map (mapfun passive_table) p_theorems in
887       List.fold_left (foldfun passive_table) ([], p_theorems) a_theorems
888 ;;
889
890
891 let rec simpl env e others others_simpl =
892   let active = others @ others_simpl in
893   let tbl =
894     List.fold_left
895       (fun t e -> Indexing.index t e)
896       Indexing.empty active
897   in
898   let res = forward_simplify env (Positive,e) (active, tbl) in
899     match others with
900       | hd::tl -> (
901           match res with
902             | None -> simpl env hd tl others_simpl
903             | Some e -> simpl env hd tl (e::others_simpl)
904         )
905       | [] -> (
906           match res with
907             | None -> others_simpl
908             | Some e -> e::others_simpl
909         )
910 ;;
911
912 let simplify_equalities env equalities =
913   debug_print
914     (lazy 
915        (Printf.sprintf "equalities:\n%s\n"
916           (String.concat "\n"
917              (List.map Equality.string_of_equality equalities))));
918   debug_print (lazy "SIMPLYFYING EQUALITIES...");
919   match equalities with
920     | [] -> []
921     | hd::tl ->
922         let res =
923           List.rev (simpl env hd tl [])
924         in
925           debug_print
926             (lazy
927                (Printf.sprintf "equalities AFTER:\n%s\n"
928                   (String.concat "\n"
929                      (List.map Equality.string_of_equality res))));
930           res
931 ;;
932
933 let print_goals goals = 
934   (String.concat "\n"
935      (List.map
936         (fun (d, gl) ->
937            let gl' =
938              List.map
939                (fun (p, _, t) ->
940                   (* (string_of_proof p) ^ ", " ^ *) (CicPp.ppterm t)) gl
941            in
942            Printf.sprintf "%d: %s" d (String.concat "; " gl')) goals))
943 ;;
944
945 let check_if_goal_is_subsumed ((_,ctx,_) as env) table (goalproof,menv,ty) =
946 (*  let names = names_of_context ctx in*)
947 (*  Printf.eprintf "check_goal_subsumed: %s\n" (CicPp.pp ty names);*)
948   match ty with
949   | Cic.Appl[Cic.MutInd(uri,_,_);eq_ty;left;right] 
950     when UriManager.eq uri (LibraryObjects.eq_URI ()) ->
951       (let goal_equation = 
952          Equality.mk_equality
953            (0,Equality.Exact (Cic.Implicit None),(eq_ty,left,right,Eq),menv) 
954       in
955 (*      match Indexing.subsumption env table goal_equation with*)
956        match Indexing.unification env table goal_equation with 
957         | Some (subst, equality ) ->
958             let (_,p,(ty,l,r,_),m,id) = Equality.open_equality equality in
959             let cicmenv = Subst.apply_subst_metasenv subst (m @ menv) in
960             Some (goalproof, p, subst, cicmenv)
961         | None -> None)
962   | _ -> None
963 ;;
964
965 let counter = ref 0
966
967 (** given-clause algorithm with full reduction strategy *)
968 let rec given_clause_fullred dbd env goals theorems ~passive active =
969   let goals = simplify_goals env goals ~passive active in 
970   let _,context,_ = env in
971   let ok, (goals:
972     (Equality.goal_proof * Cic.metasenv * Cic.term) list * 
973     (Equality.goal_proof * Cic.metasenv * Cic.term) list) = activate_goal 
974     
975     (goals: 
976   (Equality.goal_proof * Cic.metasenv * Cic.term) list * 
977     (Equality.goal_proof * Cic.metasenv * Cic.term) list)
978   in
979 (*   let theorems = simplify_theorems env theorems ~passive active in *)
980   if ok then
981     let names = List.map (HExtlib.map_option (fun (name,_) -> name)) context in 
982     let _, _, t = List.hd (fst goals) in
983     let _ = prerr_endline ("goal activated = " ^ (CicPp.pp t names)) in
984 (*     let _ = *)
985 (*       debug_print *)
986 (*         (lazy *)
987 (*            (Printf.sprintf "\ngoals = \nactive\n%s\npassive\n%s\n" *)
988 (*               (print_goals (fst goals)) (print_goals (snd goals)))); *)
989 (*       let current = List.hd (fst goals) in *)
990 (*       let p, _, t = List.hd (snd current) in *)
991 (*       debug_print *)
992 (*         (lazy *)
993 (*            (Printf.sprintf "goal activated:\n%s\n%s\n" *)
994 (*               (CicPp.ppterm t) (string_of_proof p))); *)
995 (*     in *)
996     let ok, proof =
997       (* apply_goal_to_theorems dbd env theorems ~passive active goals in *)
998       let iseq uri = UriManager.eq uri (LibraryObjects.eq_URI ()) in
999       match fst goals with
1000         | (goalproof,m,Cic.Appl[Cic.MutInd(uri,_,ens);eq_ty;left;right])::_ 
1001             when left = right && iseq uri -> 
1002             let reflproof = Equality.Exact (Equality.refl_proof eq_ty left) in
1003             true, Some (goalproof, reflproof, Subst.empty_subst,m)
1004         | goal::_ ->
1005             (match check_if_goal_is_subsumed env (snd active) goal with
1006             | None -> false,None
1007             | Some p ->
1008                 prerr_endline "Proof found by subsumption!";
1009                 true, Some p)
1010         | _ -> false, None
1011     in 
1012     if ok then
1013       ( prerr_endline "esco qui";
1014         (*
1015         let s = Printf.sprintf "actives:\n%s\n"
1016           (String.concat "\n"
1017              ((List.map
1018                  (fun (s, e) -> (string_of_sign s) ^ " " ^
1019                     (string_of_equality ~env e))
1020                  (fst active)))) in
1021         let sp = Printf.sprintf "passives:\n%s\n"
1022           (String.concat "\n"
1023              (List.map
1024                 (string_of_equality ~env)
1025                 (let x,y,_ = passive in (fst x)@(fst y)))) in
1026           prerr_endline s;
1027           prerr_endline sp; *)
1028         match proof with 
1029         | None -> assert false 
1030         | Some p ->  ParamodulationSuccess p)
1031     else
1032       given_clause_fullred_aux dbd env goals theorems passive active
1033   else
1034 (*     let ok', theorems = activate_theorem theorems in *)
1035 (*     if ok' then *)
1036 (*       let ok, goals = apply_theorem_to_goals env theorems active goals in *)
1037 (*       if ok then *)
1038 (*         let proof = *)
1039 (*           match (fst goals) with *)
1040 (*           | (_, [proof, _, _])::_ -> Some proof *)
1041 (*           | _ -> assert false *)
1042 (*         in *)
1043 (*         ParamodulationSuccess (proof, env) *)
1044 (*       else *)
1045 (*         given_clause_fullred_aux env goals theorems passive active *)
1046 (*     else *)
1047       if (passive_is_empty passive) then ParamodulationFailure ""
1048       else given_clause_fullred_aux dbd env goals theorems passive active
1049     
1050 and given_clause_fullred_aux dbd env goals theorems passive active =
1051   prerr_endline (string_of_int !counter ^ 
1052                  " MAXMETA: " ^ string_of_int !maxmeta ^ 
1053                  " #ACTIVES: " ^ string_of_int (size_of_active active) ^
1054                  " #PASSIVES: " ^ string_of_int (size_of_passive passive));
1055   incr counter;
1056 (*
1057     if !counter mod 10 = 0 then
1058     begin
1059       let size = HExtlib.estimate_size (passive,active) in
1060       let sizep = HExtlib.estimate_size (passive) in
1061       let sizea = HExtlib.estimate_size (active) in
1062       let (l1,s1),(l2,s2), t = passive in 
1063       let sizetbl = HExtlib.estimate_size t in
1064       let sizel = HExtlib.estimate_size (l1,l2) in
1065       let sizes = HExtlib.estimate_size (s1,s2) in
1066
1067       prerr_endline ("SIZE: " ^ string_of_int size);        
1068       prerr_endline ("SIZE P: " ^ string_of_int sizep);        
1069       prerr_endline ("SIZE A: " ^ string_of_int sizea);        
1070       prerr_endline ("SIZE TBL: " ^ string_of_int sizetbl ^ 
1071                        " SIZE L: " ^ string_of_int sizel ^ 
1072                        " SIZE S:" ^ string_of_int sizes);
1073     end;*)
1074 (*
1075   if (size_of_active active) mod 50 = 0 then
1076     (let s = Printf.sprintf "actives:\n%s\n"
1077       (String.concat "\n"
1078          ((List.map
1079              (fun (s, e) -> (string_of_sign s) ^ " " ^
1080                 (string_of_equality ~env e))
1081              (fst active)))) in
1082      let sp = Printf.sprintf "passives:\n%s\n"
1083       (String.concat "\n"
1084          (List.map
1085              (string_of_equality ~env)
1086              (let x,y,_ = passive in (fst x)@(fst y)))) in
1087       prerr_endline s;
1088       prerr_endline sp); *)
1089   let time1 = Unix.gettimeofday () in
1090   let (_,context,_) = env in
1091   let selection_estimate = get_selection_estimate () in
1092   let kept = size_of_passive passive in
1093   let passive =
1094     if !time_limit = 0. || !processed_clauses = 0 then
1095       passive
1096     else if !elapsed_time > !time_limit then (
1097       debug_print (lazy (Printf.sprintf "Time limit (%.2f) reached: %.2f\n"
1098                            !time_limit !elapsed_time));
1099       make_passive [] 
1100     ) else if kept > selection_estimate then (
1101       debug_print
1102         (lazy (Printf.sprintf ("Too many passive equalities: pruning..." ^^
1103                                  "(kept: %d, selection_estimate: %d)\n")
1104                  kept selection_estimate));
1105       prune_passive selection_estimate active passive
1106     ) else
1107       passive
1108   in
1109
1110   let time2 = Unix.gettimeofday () in
1111   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
1112   
1113   kept_clauses := (size_of_passive passive) + (size_of_active active);
1114   match passive_is_empty passive with
1115   | true -> ParamodulationFailure ""
1116       (* given_clause_fullred dbd env goals theorems passive active  *)     
1117   | false ->
1118       let current, passive = select env goals passive in
1119       prerr_endline 
1120         ("Selected = " ^ Equality.string_of_equality ~env current);
1121 (* ^ 
1122            (let w,p,(t,l,r,o),m = current in
1123            " size w: " ^ string_of_int (HExtlib.estimate_size w)^
1124            " size p: " ^ string_of_int (HExtlib.estimate_size p)^
1125            " size t: " ^ string_of_int (HExtlib.estimate_size t)^
1126            " size l: " ^ string_of_int (HExtlib.estimate_size l)^
1127            " size r: " ^ string_of_int (HExtlib.estimate_size r)^
1128            " size o: " ^ string_of_int (HExtlib.estimate_size o)^
1129            " size m: " ^ string_of_int (HExtlib.estimate_size m)^
1130            " size m-c: " ^ string_of_int 
1131              (HExtlib.estimate_size (List.map (fun (x,_,_) -> x) m)))) *)
1132       let time1 = Unix.gettimeofday () in
1133       let res = forward_simplify env (Positive, current) ~passive active in
1134       let time2 = Unix.gettimeofday () in
1135       forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
1136       match res with
1137       | None ->
1138           (* weight_age_counter := !weight_age_counter + 1; *)
1139           given_clause_fullred dbd env goals theorems passive active
1140       | Some current ->
1141 (*          prerr_endline (Printf.sprintf "selected simpl: %s"
1142                                (Equality.string_of_equality ~env current));*)
1143           let t1 = Unix.gettimeofday () in
1144           let new' = infer env current active in
1145           let _ =
1146             debug_print
1147               (lazy
1148                  (Printf.sprintf "new' (senza semplificare):\n%s\n"
1149                     (String.concat "\n"
1150                        (List.map
1151                           (fun e -> "Positive " ^
1152                              (Equality.string_of_equality ~env e)) new'))))
1153           in
1154           let t2 = Unix.gettimeofday () in
1155             infer_time := !infer_time +. (t2 -. t1);
1156             let active =
1157               if Equality.is_identity env current then active
1158               else
1159                 let al, tbl = active in
1160                   al @ [current], Indexing.index tbl current
1161             in
1162             let rec simplify new' active passive =
1163               let t1 = Unix.gettimeofday () in
1164               let new' = forward_simplify_new env new'~passive active in
1165               let t2 = Unix.gettimeofday () in
1166               forward_simpl_new_time :=
1167                 !forward_simpl_new_time +. (t2 -. t1);
1168               let t1 = Unix.gettimeofday () in
1169               let active, passive, newa, retained, pruned =
1170                 backward_simplify env new' ~passive  active in
1171               let passive = 
1172                 List.fold_left filter_dependent passive pruned in
1173               let t2 = Unix.gettimeofday () in
1174                 backward_simpl_time := !backward_simpl_time +. (t2 -. t1);
1175               match newa, retained with
1176               | None, None -> active, passive, new'
1177               | Some p, None
1178               | None, Some p ->
1179                   if Utils.debug_metas then
1180                     begin
1181                       List.iter 
1182                         (fun x->Indexing.check_target context x "simplify1")
1183                         p;
1184                     end;
1185                   simplify (new' @ p) active passive
1186               | Some p, Some rp ->
1187                   simplify (new' @ p @ rp) active passive
1188             in
1189             let active, passive, new' = simplify new' active passive in
1190             let goals = 
1191               let a,b,_ = build_table new' in
1192               simplify_goals env goals ~passive (a,b)
1193             in
1194               
1195 (* pessima prova 
1196             let new1 = prova env new' active in
1197             let new' = (fst new') @ (fst new1), (snd new') @ (snd new1) in
1198             let _ =
1199               match new1 with
1200               | neg, pos ->
1201                   debug_print
1202                     (lazy
1203                        (Printf.sprintf "new1:\n%s\n"
1204                           (String.concat "\n"
1205                              ((List.map
1206                                  (fun e -> "Negative " ^
1207                                     (string_of_equality ~env e)) neg) @
1208                                 (List.map
1209                                    (fun e -> "Positive " ^
1210                                       (string_of_equality ~env e)) pos)))))
1211             in
1212 end prova *)
1213             let k = size_of_passive passive in
1214             if k < (kept - 1) then
1215               processed_clauses := !processed_clauses + (kept - 1 - k);
1216             
1217             let _ =
1218               debug_print
1219                 (lazy
1220                    (Printf.sprintf "active:\n%s\n"
1221                       (String.concat "\n"
1222                          ((List.map
1223                              (fun e -> (Equality.string_of_equality ~env e))
1224                              (fst active))))))
1225             in
1226             let _ =
1227               debug_print
1228                 (lazy
1229                    (Printf.sprintf "new':\n%s\n"
1230                       (String.concat "\n"
1231                          ((List.map
1232                              (fun e -> "Negative " ^
1233                                 (Equality.string_of_equality ~env e)) new')))))
1234             in
1235             let passive = add_to_passive passive new' in
1236               given_clause_fullred dbd env goals theorems passive active
1237 ;;
1238
1239 (*
1240 let profiler0 = HExtlib.profile "P/Saturation.given_clause_fullred"
1241
1242 let given_clause_fullred dbd env goals theorems passive active =
1243   profiler0.HExtlib.profile 
1244     (given_clause_fullred dbd env goals theorems passive) active
1245 *)
1246
1247 let iseq uri = UriManager.eq uri (LibraryObjects.eq_URI ());;
1248
1249 let check_if_goal_is_identity env = function
1250   | (goalproof,m,Cic.Appl[Cic.MutInd(uri,_,ens);eq_ty;left;right]) 
1251     when left = right && iseq uri ->
1252       let reflproof = Equality.Exact (Equality.refl_proof eq_ty left) in
1253       Some (goalproof, reflproof,Subst.empty_subst,m)
1254   | _ -> None
1255 ;;                              
1256     
1257 let rec check goal = function
1258   | [] -> None
1259   | f::tl ->
1260       match f goal with
1261       | None -> check goal tl
1262       | (Some p) as ok  -> ok
1263 ;;
1264   
1265 let simplify_goal_set env goals passive active = 
1266   let active_goals, passive_goals = goals in 
1267   let find (_,_,g) where =
1268     List.exists (fun (_,_,g1) -> Equality.meta_convertibility g g1) where
1269   in
1270   let simplified =
1271     List.fold_left
1272       (fun acc goal -> 
1273         match simplify_goal env goal ~passive active with 
1274         | _, g -> if find g acc then acc else g::acc)
1275       [] active_goals
1276   in
1277   if List.length active_goals <>  List.length simplified then
1278     prerr_endline "SEMPLIFICANDO HO SCARTATO...";
1279   (simplified,passive_goals)
1280         (*
1281   HExtlib.list_uniq ~eq:(fun (_,_,t1) (_,_,t2) -> t1 = t2)
1282     (List.sort (fun (_,_,t1) (_,_,t2) -> compare t1 t1)
1283       ((*goals @*) simplified))
1284       *)
1285 ;;
1286
1287 let check_if_goals_set_is_solved env active goals =
1288   let active_goals, passive_goals = goals in 
1289   List.fold_left 
1290     (fun proof goal ->
1291       match proof with
1292       | Some p -> proof
1293       | None -> 
1294           check goal [
1295             check_if_goal_is_identity env;
1296             check_if_goal_is_subsumed env (snd active)])
1297     None active_goals
1298 ;;
1299
1300 let infer_goal_set env active goals = 
1301   let active_goals, passive_goals = goals in
1302   let rec aux = function
1303     | [] -> goals
1304     | ((_,_,t1) as hd)::tl when 
1305        not (List.exists 
1306              (fun (_,_,t) -> Equality.meta_convertibility t t1) 
1307              active_goals)
1308        -> 
1309         let selected = hd in
1310         let passive_goals = tl in
1311         let new' = Indexing.superposition_left env (snd active) selected in
1312         let metasenv, context, ugraph = env in
1313         let names = names_of_context context in
1314         selected::active_goals, passive_goals @ new'
1315     | _::tl -> aux tl
1316   in 
1317   aux passive_goals
1318 ;;
1319
1320 let infer_goal_set_with_current env current goals = 
1321   let active_goals, passive_goals = goals in
1322   let _,table,_ = build_table [current] in
1323   active_goals,
1324   List.fold_left 
1325     (fun acc g ->
1326       let new' = Indexing.superposition_left env table g in
1327       acc @ new')
1328     passive_goals active_goals
1329 ;;
1330
1331
1332
1333 let size_of_goal_set_a (l,_) = List.length l;;
1334 let size_of_goal_set_p (_,l) = List.length l;;
1335
1336 (** given-clause algorithm with full reduction strategy: NEW implementation *)
1337 (* here goals is a set of goals in OR *)
1338 let given_clause 
1339   ((_,context,_) as env) goals theorems passive active max_iterations max_time
1340
1341   let initial_time = Unix.gettimeofday () in
1342   let iterations_left iterno = 
1343     let now = Unix.gettimeofday () in
1344     let time_left = max_time -. now in
1345     let time_spent_until_now = now -. initial_time in
1346     let iteration_medium_cost = 
1347       time_spent_until_now /. (float_of_int iterno)
1348     in
1349     let iterations_left = time_left /. iteration_medium_cost in
1350     int_of_float iterations_left 
1351   in
1352   let rec step goals theorems passive active iterno =
1353     if iterno > max_iterations then
1354       (ParamodulationFailure "No more iterations to spend")
1355     else if Unix.gettimeofday () > max_time then
1356       (ParamodulationFailure "No more time to spend")
1357     else
1358       let goals = simplify_goal_set env goals passive active in  
1359       match check_if_goals_set_is_solved env active goals with
1360       | Some p -> 
1361           Printf.eprintf "Found a proof in: %f\n" 
1362             (Unix.gettimeofday() -. initial_time);
1363           ParamodulationSuccess p
1364       | None -> 
1365           prerr_endline 
1366             (Printf.sprintf "%d #ACTIVES: %d #PASSIVES: %d #GOALSET: %d(%d)\n"
1367             iterno (size_of_active active) (size_of_passive passive)
1368             (size_of_goal_set_a goals) (size_of_goal_set_p goals));
1369           (* PRUNING OF PASSIVE THAT WILL NEVER BE PROCESSED *)  
1370           let passive =
1371             let selection_estimate = iterations_left iterno in
1372             let kept = size_of_passive passive in
1373             if kept > selection_estimate then 
1374               begin
1375                 (*Printf.eprintf "Too many passive equalities: pruning...";
1376                 prune_passive selection_estimate active*) passive
1377               end
1378             else
1379               passive
1380           in
1381           kept_clauses := (size_of_passive passive) + (size_of_active active);
1382           (* SELECTION *)
1383           if passive_is_empty passive then
1384             ParamodulationFailure "No more passive" (* maybe this is a success! *)
1385           else
1386             begin
1387               let goals = infer_goal_set env active goals in
1388               let current, passive = select env goals passive in
1389               Printf.eprintf  "Selected = %s\n"
1390                 (Equality.string_of_equality ~env current);
1391               (* SIMPLIFICATION OF CURRENT *)
1392               let res = 
1393                 forward_simplify env (Positive, current) ~passive active 
1394               in
1395               match res with
1396               | None -> step goals theorems passive active (iterno+1)
1397               | Some current ->
1398                   (* GENERATION OF NEW EQUATIONS *)
1399                   let new' = infer env current active in
1400                   let goals = infer_goal_set_with_current env current goals in
1401                   let active = 
1402                     if Equality.is_identity env current then 
1403                       assert false 
1404                       (* nonsense code, check to se if it can be removed *)
1405                     else
1406                       let al, tbl = active in
1407                       al @ [current], Indexing.index tbl current
1408                   in
1409                   (* FORWARD AND BACKWARD SIMPLIFICATION *)
1410                   let rec simplify new' active passive =
1411                     let new' = forward_simplify_new env new' ~passive active in
1412                     let active, passive, newa, retained, pruned =
1413                       backward_simplify env new' ~passive  active 
1414                     in
1415                     let passive = List.fold_left filter_dependent passive pruned in
1416                     match newa, retained with
1417                     | None, None -> active, passive, new'
1418                     | Some p, None 
1419                     | None, Some p -> simplify (new' @ p) active passive
1420                     | Some p, Some rp -> simplify (new' @ p @ rp) active passive
1421                   in
1422                   let active, passive, new' = simplify new' active passive in
1423                   let goals = 
1424                     let a,b,_ = build_table new' in
1425                     simplify_goal_set env goals passive (a,b)
1426                   in
1427                   let passive = add_to_passive passive new' in
1428                   step goals theorems passive active (iterno+1)
1429             end
1430   in
1431     step goals theorems passive active 1
1432 ;;
1433
1434 let rec saturate_equations env goal accept_fun passive active =
1435   elapsed_time := Unix.gettimeofday () -. !start_time;
1436   if !elapsed_time > !time_limit then
1437     (active, passive)
1438   else
1439     let current, passive = select env ([goal],[]) passive in
1440     let res = forward_simplify env (Positive, current) ~passive active in
1441     match res with
1442     | None ->
1443         saturate_equations env goal accept_fun passive active
1444     | Some current ->
1445         debug_print (lazy (Printf.sprintf "selected: %s"
1446                              (Equality.string_of_equality ~env current)));
1447         let new' = infer env current active in
1448         let active =
1449           if Equality.is_identity env current then active
1450           else
1451             let al, tbl = active in
1452             al @ [current], Indexing.index tbl current
1453         in
1454         let rec simplify new' active passive =
1455           let new' = forward_simplify_new env new' ~passive active in
1456           let active, passive, newa, retained, pruned =
1457             backward_simplify env new' ~passive active in
1458           let passive = 
1459             List.fold_left filter_dependent passive pruned in
1460           match newa, retained with
1461           | None, None -> active, passive, new'
1462           | Some p, None
1463           | None, Some p -> simplify (new' @ p) active passive
1464           | Some p, Some rp -> simplify (new' @ p @ rp) active passive
1465         in
1466         let active, passive, new' = simplify new' active passive in
1467         let _ =
1468           debug_print
1469             (lazy
1470                (Printf.sprintf "active:\n%s\n"
1471                   (String.concat "\n"
1472                      (List.map
1473                          (fun e -> Equality.string_of_equality ~env e)
1474                          (fst active)))))
1475         in
1476         let _ =
1477           debug_print
1478             (lazy
1479                (Printf.sprintf "new':\n%s\n"
1480                   (String.concat "\n"
1481                      (List.map
1482                          (fun e -> "Negative " ^
1483                             (Equality.string_of_equality ~env e)) new'))))
1484         in
1485         let new' = List.filter accept_fun new' in
1486         let passive = add_to_passive passive new' in
1487         saturate_equations env goal accept_fun passive active
1488 ;;
1489   
1490 let main dbd full term metasenv ugraph = ()
1491 (*
1492 let main dbd full term metasenv ugraph =
1493   let module C = Cic in
1494   let module T = CicTypeChecker in
1495   let module PET = ProofEngineTypes in
1496   let module PP = CicPp in
1497   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1498   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1499   let proof, goals = status in
1500   let goal' = List.nth goals 0 in
1501   let _, metasenv, meta_proof, _ = proof in
1502   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1503   let eq_indexes, equalities, maxm = find_equalities context proof in
1504   let lib_eq_uris, library_equalities, maxm =
1505
1506     find_library_equalities dbd context (proof, goal') (maxm+2)
1507   in
1508   let library_equalities = List.map snd library_equalities in
1509   maxmeta := maxm+2; (* TODO ugly!! *)
1510   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
1511   let new_meta_goal, metasenv, type_of_goal =
1512     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1513     debug_print
1514       (lazy
1515          (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n\n" (CicPp.ppterm ty)));
1516     Cic.Meta (maxm+1, irl),
1517     (maxm+1, context, ty)::metasenv,
1518     ty
1519   in
1520   let env = (metasenv, context, ugraph) in
1521   let t1 = Unix.gettimeofday () in
1522   let theorems =
1523     if full then
1524       let theorems = find_library_theorems dbd env (proof, goal') lib_eq_uris in
1525       let context_hyp = find_context_hypotheses env eq_indexes in
1526       context_hyp @ theorems, []
1527     else
1528       let refl_equal =
1529         let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
1530         UriManager.uri_of_string (us ^ "#xpointer(1/1/1)")
1531       in
1532       let t = CicUtil.term_of_uri refl_equal in
1533       let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
1534       [(t, ty, [])], []
1535   in
1536   let t2 = Unix.gettimeofday () in
1537   debug_print
1538     (lazy
1539        (Printf.sprintf "Time to retrieve theorems: %.9f\n" (t2 -. t1)));
1540   let _ =
1541     debug_print
1542       (lazy
1543          (Printf.sprintf
1544             "Theorems:\n-------------------------------------\n%s\n"
1545             (String.concat "\n"
1546                (List.map
1547                   (fun (t, ty, _) ->
1548                      Printf.sprintf
1549                        "Term: %s, type: %s" (CicPp.ppterm t) (CicPp.ppterm ty))
1550                   (fst theorems)))))
1551   in
1552   (*try*)
1553     let goal = 
1554       ([],Equality.BasicProof (Equality.empty_subst ,new_meta_goal)), [], goal 
1555     in
1556     let equalities = simplify_equalities env 
1557       (equalities@library_equalities) in 
1558     let active = make_active () in
1559     let passive = make_passive equalities in
1560     Printf.printf "\ncurrent goal: %s\n"
1561       (let _, _, g = goal in CicPp.ppterm g);
1562     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
1563     Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
1564     Printf.printf "\nequalities:\n%s\n"
1565       (String.concat "\n"
1566          (List.map
1567             (Equality.string_of_equality ~env) equalities));
1568 (*             (equalities @ library_equalities))); *)
1569       print_endline "--------------------------------------------------";
1570       let start = Unix.gettimeofday () in
1571       print_endline "GO!";
1572       start_time := Unix.gettimeofday ();
1573       let res =
1574         let goals = make_goals goal in
1575         (if !use_fullred then given_clause_fullred else given_clause_fullred)
1576           dbd env goals theorems passive active
1577       in
1578       let finish = Unix.gettimeofday () in
1579       let _ =
1580         match res with
1581         | ParamodulationFailure ->
1582             Printf.printf "NO proof found! :-(\n\n"
1583         | ParamodulationSuccess (Some ((cicproof,cicmenv),(proof, env))) ->
1584             Printf.printf "OK, found a proof!\n";
1585             let oldproof = Equation.build_proof_term proof in
1586             let newproof,_,newenv,_ = 
1587                 CicRefine.type_of_aux' 
1588                   cicmenv context cicproof CicUniv.empty_ugraph
1589             in
1590             (* REMEMBER: we have to instantiate meta_proof, we should use
1591                apply  the "apply" tactic to proof and status 
1592             *)
1593             let names = names_of_context context in
1594             prerr_endline "OLD PROOF";
1595             print_endline (PP.pp proof names);
1596             prerr_endline "NEW PROOF";
1597             print_endline (PP.pp newproof names);
1598             let newmetasenv =
1599               List.fold_left
1600                 (fun m eq -> 
1601                   let (_, _, _, menv,_) = Equality.open_equality eq in 
1602                   m @ menv) 
1603               metasenv equalities
1604             in
1605             let _ =
1606               (*try*)
1607                 let ty, ug =
1608                   CicTypeChecker.type_of_aux' newmetasenv context proof ugraph
1609                 in
1610                 print_endline (string_of_float (finish -. start));
1611                 Printf.printf
1612                   "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n\n"
1613                   (CicPp.pp type_of_goal names) (CicPp.pp ty names)
1614                   (string_of_bool
1615                      (fst (CicReduction.are_convertible
1616                              context type_of_goal ty ug)));
1617               (*with e ->
1618                 Printf.printf "\nEXCEPTION!!! %s\n" (Printexc.to_string e);
1619                 Printf.printf "MAXMETA USED: %d\n" !maxmeta;
1620                 print_endline (string_of_float (finish -. start));*)
1621             in
1622             ()
1623               
1624         | ParamodulationSuccess None ->
1625             Printf.printf "Success, but no proof?!?\n\n"
1626       in
1627         if Utils.time then
1628           begin
1629             prerr_endline 
1630               ((Printf.sprintf ("infer_time: %.9f\nforward_simpl_time: %.9f\n" ^^
1631                        "forward_simpl_new_time: %.9f\n" ^^
1632                        "backward_simpl_time: %.9f\n")
1633               !infer_time !forward_simpl_time !forward_simpl_new_time
1634               !backward_simpl_time) ^
1635               (Printf.sprintf "passive_maintainance_time: %.9f\n"
1636                  !passive_maintainance_time) ^
1637               (Printf.sprintf "    successful unification/matching time: %.9f\n"
1638                  !Indexing.match_unif_time_ok) ^
1639               (Printf.sprintf "    failed unification/matching time: %.9f\n"
1640                  !Indexing.match_unif_time_no) ^
1641               (Printf.sprintf "    indexing retrieval time: %.9f\n"
1642                  !Indexing.indexing_retrieval_time) ^
1643               (Printf.sprintf "    demodulate_term.build_newtarget_time: %.9f\n"
1644                  !Indexing.build_newtarget_time) ^
1645               (Printf.sprintf "derived %d clauses, kept %d clauses.\n"
1646                  !derived_clauses !kept_clauses)) 
1647             end
1648 (*
1649   with exc ->
1650     print_endline ("EXCEPTION: " ^ (Printexc.to_string exc));
1651     raise exc
1652 *)
1653 ;;
1654 *)
1655
1656 let default_depth = !maxdepth
1657 and default_width = !maxwidth;;
1658
1659 let reset_refs () =
1660   maxmeta := 0;
1661   symbols_counter := 0;
1662   weight_age_counter := !weight_age_ratio;
1663   processed_clauses := 0;
1664   start_time := 0.;
1665   elapsed_time := 0.;
1666   maximal_retained_equality := None;
1667   infer_time := 0.;
1668   forward_simpl_time := 0.;
1669   forward_simpl_new_time := 0.;
1670   backward_simpl_time := 0.;
1671   passive_maintainance_time := 0.;
1672   derived_clauses := 0;
1673   kept_clauses := 0;
1674   Equality.reset ();
1675 ;;
1676
1677 let saturate 
1678     dbd ?(full=false) ?(depth=default_depth) ?(width=default_width) status = 
1679   let module C = Cic in
1680   reset_refs ();
1681   Indexing.init_index ();
1682   counter := 0;
1683   maxdepth := depth;
1684   maxwidth := width;
1685 (*  CicUnification.unif_ty := false;*)
1686   let proof, goalno = status in
1687   let uri, metasenv, meta_proof, term_to_prove = proof in
1688   let _, context, type_of_goal = CicUtil.lookup_meta goalno metasenv in
1689   let names = names_of_context context in
1690   let eq_indexes, equalities, maxm = find_equalities context proof in
1691   let ugraph = CicUniv.empty_ugraph in
1692   let env = (metasenv, context, ugraph) in 
1693   let goal = [], metasenv, type_of_goal in
1694   let res, time =
1695     let t1 = Unix.gettimeofday () in
1696     let lib_eq_uris, library_equalities, maxm =
1697       find_library_equalities dbd context (proof, goalno) (maxm+2)
1698     in
1699     let library_equalities = List.map snd library_equalities in
1700     let t2 = Unix.gettimeofday () in
1701     maxmeta := maxm+2;
1702     let equalities = simplify_equalities env (equalities@library_equalities) in 
1703     debug_print
1704       (lazy
1705          (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)));
1706     let t1 = Unix.gettimeofday () in
1707     let theorems =
1708       if full then
1709         let thms = find_library_theorems dbd env (proof, goalno) lib_eq_uris in
1710         let context_hyp = find_context_hypotheses env eq_indexes in
1711         context_hyp @ thms, []
1712       else
1713         let refl_equal =
1714           let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
1715           UriManager.uri_of_string (us ^ "#xpointer(1/1/1)")
1716         in
1717         let t = CicUtil.term_of_uri refl_equal in
1718         let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
1719         [(t, ty, [])], []
1720     in
1721     let t2 = Unix.gettimeofday () in
1722     let _ =
1723       debug_print
1724         (lazy
1725            (Printf.sprintf
1726               "Theorems:\n-------------------------------------\n%s\n"
1727               (String.concat "\n"
1728                  (List.map
1729                     (fun (t, ty, _) ->
1730                        Printf.sprintf
1731                          "Term: %s, type: %s"
1732                          (CicPp.ppterm t) (CicPp.ppterm ty))
1733                     (fst theorems)))));
1734       debug_print
1735         (lazy
1736            (Printf.sprintf "Time to retrieve theorems: %.9f\n" (t2 -. t1)));
1737     in
1738     let active = make_active () in
1739     let passive = make_passive equalities in
1740     let start = Unix.gettimeofday () in
1741     let res =
1742 (*
1743       let goals = make_goals goal in
1744       given_clause_fullred dbd env goals theorems passive active
1745 *)
1746       let goals = make_goal_set goal in
1747       let max_iterations = 1000 in
1748       let max_time = Unix.gettimeofday () +.  600. (* minutes *) in
1749       given_clause env goals theorems passive active max_iterations max_time 
1750     in
1751     let finish = Unix.gettimeofday () in
1752     (res, finish -. start)
1753   in
1754   match res with
1755   | ParamodulationFailure s ->
1756       raise (ProofEngineTypes.Fail (lazy ("NO proof found: " ^ s)))
1757   | ParamodulationSuccess 
1758     (goalproof,newproof,subsumption_subst, proof_menv) ->
1759       prerr_endline "OK, found a proof!";
1760       prerr_endline (Equality.pp_proof names goalproof newproof);
1761       prerr_endline "ENDOFPROOFS";
1762       (* generation of the CIC proof *)
1763       let side_effects = 
1764         List.filter (fun i -> i <> goalno)
1765           (ProofEngineHelpers.compare_metasenvs 
1766             ~newmetasenv:metasenv ~oldmetasenv:proof_menv)
1767       in
1768       let goal_proof, side_effects_t = 
1769         let initial = Equality.build_proof_term newproof in
1770         Equality.build_goal_proof goalproof initial type_of_goal side_effects
1771       in
1772       let goal_proof = Subst.apply_subst subsumption_subst goal_proof in
1773       let side_effects_t = 
1774         List.map (Subst.apply_subst subsumption_subst) side_effects_t
1775       in
1776       (* replacing fake mets with real ones *)
1777       prerr_endline "replacing metas...";
1778       let irl=CicMkImplicit.identity_relocation_list_for_metavariable context in
1779       let goal_proof_menv, what, with_what,free_meta = 
1780         List.fold_left 
1781           (fun (acc1,acc2,acc3,uniq) (i,_,ty) -> 
1782              match uniq with
1783                | Some m -> 
1784                    acc1, (Cic.Meta(i,[]))::acc2, m::acc3, uniq
1785                | None ->
1786                    [i,context,ty], (Cic.Meta(i,[]))::acc2, 
1787                    (Cic.Meta(i,irl)) ::acc3,Some (Cic.Meta(i,irl))) 
1788           ([],[],[],None) proof_menv 
1789       in
1790       let replace where = 
1791         ProofEngineReduction.replace_lifting 
1792           ~equality:(=) ~what ~with_what ~where
1793       in
1794       let goal_proof = replace goal_proof in
1795         (* ok per le meta libere... ma per quelle che c'erano e sono rimaste? 
1796          * what mi pare buono, sostituisce solo le meta farlocche *)
1797       let side_effects_t = List.map replace side_effects_t in
1798       let free_metas = 
1799         List.filter (fun i -> i <> goalno)
1800           (ProofEngineHelpers.compare_metasenvs 
1801             ~oldmetasenv:metasenv ~newmetasenv:goal_proof_menv)
1802       in
1803       (* check/refine/... build the new proof *)
1804       let replaced_goal = 
1805         ProofEngineReduction.replace
1806           ~what:side_effects ~with_what:side_effects_t
1807           ~equality:(fun i t -> match t with Cic.Meta(j,_)->j=i|_->false)
1808           ~where:type_of_goal
1809       in
1810       let subst_side_effects,real_menv,_ = 
1811         let fail t s = raise (ProofEngineTypes.Fail (lazy (t^Lazy.force s))) in
1812         let free_metas_menv = 
1813           List.map (fun i -> CicUtil.lookup_meta i goal_proof_menv) free_metas
1814         in
1815         try
1816           CicUnification.fo_unif_subst [] context (metasenv @ free_metas_menv)
1817            replaced_goal type_of_goal CicUniv.empty_ugraph
1818         with
1819         | CicUnification.UnificationFailure s
1820         | CicUnification.Uncertain s 
1821         | CicUnification.AssertFailure s -> 
1822             fail "Maybe the local context of metas in the goal was not an IRL" s
1823       in
1824       let final_subst = 
1825         (goalno,(context,goal_proof,type_of_goal))::subst_side_effects
1826       in
1827       let _ = 
1828         try
1829           CicTypeChecker.type_of_aux' real_menv context goal_proof
1830             CicUniv.empty_ugraph
1831         with 
1832         | CicUtil.Meta_not_found _ 
1833         | CicTypeChecker.TypeCheckerFailure _ 
1834         | CicTypeChecker.AssertFailure _ 
1835         | Invalid_argument "list_fold_left2" as exn ->
1836             prerr_endline "THE PROOF DOES NOT TYPECHECK!";
1837             prerr_endline (CicPp.pp goal_proof names);
1838             raise exn
1839       in
1840       let proof, real_metasenv = 
1841         ProofEngineHelpers.subst_meta_and_metasenv_in_proof
1842           proof goalno (CicMetaSubst.apply_subst final_subst) real_menv
1843       in
1844       let open_goals = 
1845         match free_meta with Some(Cic.Meta(m,_)) when m<>goalno ->[m] | _ ->[] 
1846       in
1847       Printf.eprintf 
1848         "GOALS APERTI: %s\nMETASENV PRIMA:\n%s\nMETASENV DOPO:\n%s\n" 
1849           (String.concat ", " (List.map string_of_int open_goals))
1850           (CicMetaSubst.ppmetasenv [] metasenv)
1851           (CicMetaSubst.ppmetasenv [] real_metasenv);
1852       prerr_endline (Printf.sprintf "\nTIME NEEDED: %8.2f" time);
1853       proof, open_goals
1854 ;;
1855
1856 let retrieve_and_print dbd term metasenv ugraph = 
1857   let module C = Cic in
1858   let module T = CicTypeChecker in
1859   let module PET = ProofEngineTypes in
1860   let module PP = CicPp in
1861   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1862   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1863   let proof, goals = status in
1864   let goal' = List.nth goals 0 in
1865   let uri, metasenv, meta_proof, term_to_prove = proof in
1866   let _, context, type_of_goal = CicUtil.lookup_meta goal' metasenv in
1867   let eq_indexes, equalities, maxm = find_equalities context proof in
1868   let ugraph = CicUniv.empty_ugraph in
1869   let env = (metasenv, context, ugraph) in
1870   let t1 = Unix.gettimeofday () in
1871   let lib_eq_uris, library_equalities, maxm =
1872     find_library_equalities dbd context (proof, goal') (maxm+2) in
1873   let t2 = Unix.gettimeofday () in
1874   maxmeta := maxm+2;
1875   let equalities = (* equalities @ *) library_equalities in
1876   debug_print
1877      (lazy
1878         (Printf.sprintf "\n\nequalities:\n%s\n"
1879            (String.concat "\n"
1880               (List.map 
1881           (fun (u, e) ->
1882 (*                  Printf.sprintf "%s: %s" *)
1883                    (UriManager.string_of_uri u)
1884 (*                    (string_of_equality e) *)
1885                      )
1886           equalities))));
1887   debug_print (lazy "RETR: SIMPLYFYING EQUALITIES...");
1888   let rec simpl e others others_simpl =
1889     let (u, e) = e in
1890     let active = List.map (fun (u, e) -> (Positive, e))
1891       (others @ others_simpl) in
1892     let tbl =
1893       List.fold_left
1894         (fun t (_, e) -> Indexing.index t e)
1895         Indexing.empty active
1896     in
1897     let res = forward_simplify env (Positive, e) (active, tbl) in
1898     match others with
1899         | hd::tl -> (
1900             match res with
1901               | None -> simpl hd tl others_simpl
1902               | Some e -> simpl hd tl ((u, e)::others_simpl)
1903           )
1904         | [] -> (
1905             match res with
1906               | None -> others_simpl
1907               | Some e -> (u, e)::others_simpl
1908           ) 
1909   in
1910   let _equalities =
1911     match equalities with
1912       | [] -> []
1913       | hd::tl ->
1914           let others = tl in (* List.map (fun e -> (Positive, e)) tl in *)
1915           let res =
1916             List.rev (simpl (*(Positive,*) hd others [])
1917           in
1918             debug_print
1919               (lazy
1920                  (Printf.sprintf "\nequalities AFTER:\n%s\n"
1921                     (String.concat "\n"
1922                        (List.map
1923                           (fun (u, e) ->
1924                              Printf.sprintf "%s: %s"
1925                                (UriManager.string_of_uri u)
1926                                (Equality.string_of_equality e)
1927                           )
1928                           res))));
1929             res in
1930     debug_print
1931       (lazy
1932          (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)))
1933 ;;
1934
1935
1936 let main_demod_equalities dbd term metasenv ugraph =
1937   let module C = Cic in
1938   let module T = CicTypeChecker in
1939   let module PET = ProofEngineTypes in
1940   let module PP = CicPp in
1941   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1942   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1943   let proof, goals = status in
1944   let goal' = List.nth goals 0 in
1945   let _, metasenv, meta_proof, _ = proof in
1946   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1947   let eq_indexes, equalities, maxm = find_equalities context proof in
1948   let lib_eq_uris, library_equalities, maxm =
1949     find_library_equalities dbd context (proof, goal') (maxm+2)
1950   in
1951   let library_equalities = List.map snd library_equalities in
1952   maxmeta := maxm+2; (* TODO ugly!! *)
1953   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
1954   let new_meta_goal, metasenv, type_of_goal =
1955     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1956     debug_print
1957       (lazy
1958          (Printf.sprintf "\n\nTRYING TO INFER EQUALITIES MATCHING: %s\n\n"
1959             (CicPp.ppterm ty)));
1960     Cic.Meta (maxm+1, irl),
1961     (maxm+1, context, ty)::metasenv,
1962     ty
1963   in
1964   let env = (metasenv, context, ugraph) in
1965   (*try*)
1966     let goal = [], [], goal 
1967     in
1968     let equalities = simplify_equalities env (equalities@library_equalities) in
1969     let active = make_active () in
1970     let passive = make_passive equalities in
1971     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
1972     Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
1973     Printf.printf "\nequalities:\n%s\n"
1974       (String.concat "\n"
1975          (List.map
1976             (Equality.string_of_equality ~env) equalities));
1977     print_endline "--------------------------------------------------";
1978     print_endline "GO!";
1979     start_time := Unix.gettimeofday ();
1980     if !time_limit < 1. then time_limit := 60.;    
1981     let ra, rp =
1982       saturate_equations env goal (fun e -> true) passive active
1983     in
1984
1985     let initial =
1986       List.fold_left (fun s e -> EqualitySet.add e s)
1987         EqualitySet.empty equalities
1988     in
1989     let addfun s e = 
1990       if not (EqualitySet.mem e initial) then EqualitySet.add e s else s
1991     in
1992
1993     let passive =
1994       match rp with
1995       | (p, _), _ ->
1996           EqualitySet.elements (List.fold_left addfun EqualitySet.empty p)
1997     in
1998     let active =
1999       let l = fst ra in
2000       EqualitySet.elements (List.fold_left addfun EqualitySet.empty l)
2001     in
2002     Printf.printf "\n\nRESULTS:\nActive:\n%s\n\nPassive:\n%s\n"
2003        (String.concat "\n" (List.map (Equality.string_of_equality ~env) active)) 
2004      (*  (String.concat "\n"
2005          (List.map (fun e -> CicPp.ppterm (term_of_equality e)) active)) *)
2006 (*       (String.concat "\n" (List.map (string_of_equality ~env) passive)); *)
2007       (String.concat "\n"
2008          (List.map (fun e -> CicPp.ppterm (Equality.term_of_equality e)) passive));
2009     print_newline ();
2010 (*
2011   with e ->
2012     debug_print (lazy ("EXCEPTION: " ^ (Printexc.to_string e)))
2013 *)
2014 ;;
2015
2016 let demodulate_tac ~dbd ~pattern ((proof,goal)(*s initialstatus*)) = 
2017   let module I = Inference in
2018   let curi,metasenv,pbo,pty = proof in
2019   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
2020   let eq_indexes, equalities, maxm = I.find_equalities context proof in
2021   let lib_eq_uris, library_equalities, maxm =
2022     I.find_library_equalities dbd context (proof, goal) (maxm+2) in
2023   if library_equalities = [] then prerr_endline "VUOTA!!!";
2024   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
2025   let library_equalities = List.map snd library_equalities in
2026   let initgoal = [], [], ty in
2027   let env = (metasenv, context, CicUniv.empty_ugraph) in
2028   let equalities = simplify_equalities env (equalities@library_equalities) in   
2029   let table = 
2030     List.fold_left 
2031       (fun tbl eq -> Indexing.index tbl eq) 
2032       Indexing.empty equalities 
2033   in
2034   let changed,(newproof,newmetasenv, newty) = 
2035     Indexing.demodulation_goal 
2036       (metasenv,context,CicUniv.empty_ugraph) table initgoal 
2037   in
2038   if changed then
2039     begin
2040       let opengoal = Cic.Meta(maxm,irl) in
2041       let proofterm,_ = 
2042         Equality.build_goal_proof newproof opengoal ty [] in
2043         let extended_metasenv = (maxm,context,newty)::metasenv in
2044         let extended_status = 
2045           (curi,extended_metasenv,pbo,pty),goal in
2046         let (status,newgoals) = 
2047           ProofEngineTypes.apply_tactic 
2048             (PrimitiveTactics.apply_tac ~term:proofterm)
2049             extended_status in
2050         (status,maxm::newgoals)
2051     end
2052   else (* if newty = ty then *)
2053     raise (ProofEngineTypes.Fail (lazy "no progress"))
2054   (*else ProofEngineTypes.apply_tactic 
2055     (ReductionTactics.simpl_tac ~pattern) 
2056     initialstatus*)
2057 ;;
2058
2059 let demodulate_tac ~dbd ~pattern = 
2060   ProofEngineTypes.mk_tactic (demodulate_tac ~dbd ~pattern)
2061 ;;