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