]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/paramodulation/saturation.ml
1) variables occurring only in proofs anre not relocated
[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 * 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             let (_,p,(ty,l,r,_),m,id) = Equality.open_equality equality in
958             let cicmenv = Subst.apply_subst_metasenv subst (m @ menv) in
959             Some (goalproof, p, subst, cicmenv)
960         | None -> None)
961   | _ -> None
962 ;;
963
964 let counter = ref 0
965
966 (** given-clause algorithm with full reduction strategy *)
967 let rec given_clause_fullred dbd env goals theorems ~passive active =
968   let goals = simplify_goals env goals ~passive active in 
969   let _,context,_ = env in
970   let ok, (goals:
971     (Equality.goal_proof * Cic.metasenv * Cic.term) list * 
972     (Equality.goal_proof * Cic.metasenv * Cic.term) list) = activate_goal 
973     
974     (goals: 
975   (Equality.goal_proof * Cic.metasenv * Cic.term) list * 
976     (Equality.goal_proof * Cic.metasenv * Cic.term) list)
977   in
978 (*   let theorems = simplify_theorems env theorems ~passive active in *)
979   if ok then
980     let names = List.map (HExtlib.map_option (fun (name,_) -> name)) context in 
981     let _, _, t = List.hd (fst goals) in
982     let _ = prerr_endline ("goal activated = " ^ (CicPp.pp t names)) in
983 (*     let _ = *)
984 (*       debug_print *)
985 (*         (lazy *)
986 (*            (Printf.sprintf "\ngoals = \nactive\n%s\npassive\n%s\n" *)
987 (*               (print_goals (fst goals)) (print_goals (snd goals)))); *)
988 (*       let current = List.hd (fst goals) in *)
989 (*       let p, _, t = List.hd (snd current) in *)
990 (*       debug_print *)
991 (*         (lazy *)
992 (*            (Printf.sprintf "goal activated:\n%s\n%s\n" *)
993 (*               (CicPp.ppterm t) (string_of_proof p))); *)
994 (*     in *)
995     let ok, proof =
996       (* apply_goal_to_theorems dbd env theorems ~passive active goals in *)
997       let iseq uri = UriManager.eq uri (LibraryObjects.eq_URI ()) in
998       match fst goals with
999         | (goalproof,m,Cic.Appl[Cic.MutInd(uri,_,ens);eq_ty;left;right])::_ 
1000             when left = right && iseq uri -> 
1001             let reflproof = Equality.Exact (Equality.refl_proof eq_ty left) in
1002             true, Some (goalproof, reflproof, Subst.empty_subst,m)
1003         | goal::_ ->
1004             (match check_if_goal_is_subsumed env (snd active) goal with
1005             | None -> false,None
1006             | Some p ->
1007                 prerr_endline "Proof found by subsumption!";
1008                 true, Some p)
1009         | _ -> false, None
1010     in 
1011     if ok then
1012       ( prerr_endline "esco qui";
1013         (*
1014         let s = Printf.sprintf "actives:\n%s\n"
1015           (String.concat "\n"
1016              ((List.map
1017                  (fun (s, e) -> (string_of_sign s) ^ " " ^
1018                     (string_of_equality ~env e))
1019                  (fst active)))) in
1020         let sp = Printf.sprintf "passives:\n%s\n"
1021           (String.concat "\n"
1022              (List.map
1023                 (string_of_equality ~env)
1024                 (let x,y,_ = passive in (fst x)@(fst y)))) in
1025           prerr_endline s;
1026           prerr_endline sp; *)
1027         match proof with 
1028         | None -> assert false 
1029         | Some p ->  ParamodulationSuccess p)
1030     else
1031       given_clause_fullred_aux dbd env goals theorems passive active
1032   else
1033 (*     let ok', theorems = activate_theorem theorems in *)
1034 (*     if ok' then *)
1035 (*       let ok, goals = apply_theorem_to_goals env theorems active goals in *)
1036 (*       if ok then *)
1037 (*         let proof = *)
1038 (*           match (fst goals) with *)
1039 (*           | (_, [proof, _, _])::_ -> Some proof *)
1040 (*           | _ -> assert false *)
1041 (*         in *)
1042 (*         ParamodulationSuccess (proof, env) *)
1043 (*       else *)
1044 (*         given_clause_fullred_aux env goals theorems passive active *)
1045 (*     else *)
1046       if (passive_is_empty passive) then ParamodulationFailure ""
1047       else given_clause_fullred_aux dbd env goals theorems passive active
1048     
1049 and given_clause_fullred_aux dbd env goals theorems passive active =
1050   prerr_endline (string_of_int !counter ^ 
1051                  " MAXMETA: " ^ string_of_int !maxmeta ^ 
1052                  " #ACTIVES: " ^ string_of_int (size_of_active active) ^
1053                  " #PASSIVES: " ^ string_of_int (size_of_passive passive));
1054   incr counter;
1055 (*
1056     if !counter mod 10 = 0 then
1057     begin
1058       let size = HExtlib.estimate_size (passive,active) in
1059       let sizep = HExtlib.estimate_size (passive) in
1060       let sizea = HExtlib.estimate_size (active) in
1061       let (l1,s1),(l2,s2), t = passive in 
1062       let sizetbl = HExtlib.estimate_size t in
1063       let sizel = HExtlib.estimate_size (l1,l2) in
1064       let sizes = HExtlib.estimate_size (s1,s2) in
1065
1066       prerr_endline ("SIZE: " ^ string_of_int size);        
1067       prerr_endline ("SIZE P: " ^ string_of_int sizep);        
1068       prerr_endline ("SIZE A: " ^ string_of_int sizea);        
1069       prerr_endline ("SIZE TBL: " ^ string_of_int sizetbl ^ 
1070                        " SIZE L: " ^ string_of_int sizel ^ 
1071                        " SIZE S:" ^ string_of_int sizes);
1072     end;*)
1073 (*
1074   if (size_of_active active) mod 50 = 0 then
1075     (let s = Printf.sprintf "actives:\n%s\n"
1076       (String.concat "\n"
1077          ((List.map
1078              (fun (s, e) -> (string_of_sign s) ^ " " ^
1079                 (string_of_equality ~env e))
1080              (fst active)))) in
1081      let sp = Printf.sprintf "passives:\n%s\n"
1082       (String.concat "\n"
1083          (List.map
1084              (string_of_equality ~env)
1085              (let x,y,_ = passive in (fst x)@(fst y)))) in
1086       prerr_endline s;
1087       prerr_endline sp); *)
1088   let time1 = Unix.gettimeofday () in
1089   let (_,context,_) = env in
1090   let selection_estimate = get_selection_estimate () in
1091   let kept = size_of_passive passive in
1092   let passive =
1093     if !time_limit = 0. || !processed_clauses = 0 then
1094       passive
1095     else if !elapsed_time > !time_limit then (
1096       debug_print (lazy (Printf.sprintf "Time limit (%.2f) reached: %.2f\n"
1097                            !time_limit !elapsed_time));
1098       make_passive [] 
1099     ) else if kept > selection_estimate then (
1100       debug_print
1101         (lazy (Printf.sprintf ("Too many passive equalities: pruning..." ^^
1102                                  "(kept: %d, selection_estimate: %d)\n")
1103                  kept selection_estimate));
1104       prune_passive selection_estimate active passive
1105     ) else
1106       passive
1107   in
1108
1109   let time2 = Unix.gettimeofday () in
1110   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
1111   
1112   kept_clauses := (size_of_passive passive) + (size_of_active active);
1113   match passive_is_empty passive with
1114   | true -> ParamodulationFailure ""
1115       (* given_clause_fullred dbd env goals theorems passive active  *)     
1116   | false ->
1117       let current, passive = select env goals passive in
1118       prerr_endline 
1119         ("Selected = " ^ Equality.string_of_equality ~env current);
1120 (* ^ 
1121            (let w,p,(t,l,r,o),m = current in
1122            " size w: " ^ string_of_int (HExtlib.estimate_size w)^
1123            " size p: " ^ string_of_int (HExtlib.estimate_size p)^
1124            " size t: " ^ string_of_int (HExtlib.estimate_size t)^
1125            " size l: " ^ string_of_int (HExtlib.estimate_size l)^
1126            " size r: " ^ string_of_int (HExtlib.estimate_size r)^
1127            " size o: " ^ string_of_int (HExtlib.estimate_size o)^
1128            " size m: " ^ string_of_int (HExtlib.estimate_size m)^
1129            " size m-c: " ^ string_of_int 
1130              (HExtlib.estimate_size (List.map (fun (x,_,_) -> x) m)))) *)
1131       let time1 = Unix.gettimeofday () in
1132       let res = forward_simplify env (Positive, current) ~passive active in
1133       let time2 = Unix.gettimeofday () in
1134       forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
1135       match res with
1136       | None ->
1137           (* weight_age_counter := !weight_age_counter + 1; *)
1138           given_clause_fullred dbd env goals theorems passive active
1139       | Some current ->
1140 (*          prerr_endline (Printf.sprintf "selected simpl: %s"
1141                                (Equality.string_of_equality ~env current));*)
1142           let t1 = Unix.gettimeofday () in
1143           let new' = infer env current active in
1144           let _ =
1145             debug_print
1146               (lazy
1147                  (Printf.sprintf "new' (senza semplificare):\n%s\n"
1148                     (String.concat "\n"
1149                        (List.map
1150                           (fun e -> "Positive " ^
1151                              (Equality.string_of_equality ~env e)) new'))))
1152           in
1153           let t2 = Unix.gettimeofday () in
1154             infer_time := !infer_time +. (t2 -. t1);
1155             let active =
1156               if Equality.is_identity env current then active
1157               else
1158                 let al, tbl = active in
1159                   al @ [current], Indexing.index tbl current
1160             in
1161             let rec simplify new' active passive =
1162               let t1 = Unix.gettimeofday () in
1163               let new' = forward_simplify_new env new'~passive active in
1164               let t2 = Unix.gettimeofday () in
1165               forward_simpl_new_time :=
1166                 !forward_simpl_new_time +. (t2 -. t1);
1167               let t1 = Unix.gettimeofday () in
1168               let active, passive, newa, retained, pruned =
1169                 backward_simplify env new' ~passive  active in
1170               let passive = 
1171                 List.fold_left filter_dependent passive pruned in
1172               let t2 = Unix.gettimeofday () in
1173                 backward_simpl_time := !backward_simpl_time +. (t2 -. t1);
1174               match newa, retained with
1175               | None, None -> active, passive, new'
1176               | Some p, None
1177               | None, Some p ->
1178                   if Utils.debug_metas then
1179                     begin
1180                       List.iter 
1181                         (fun x->Indexing.check_target context x "simplify1")
1182                         p;
1183                     end;
1184                   simplify (new' @ p) active passive
1185               | Some p, Some rp ->
1186                   simplify (new' @ p @ rp) active passive
1187             in
1188             let active, passive, new' = simplify new' active passive in
1189             let goals = 
1190               let a,b,_ = build_table new' in
1191               simplify_goals env goals ~passive (a,b)
1192             in
1193               
1194 (* pessima prova 
1195             let new1 = prova env new' active in
1196             let new' = (fst new') @ (fst new1), (snd new') @ (snd new1) in
1197             let _ =
1198               match new1 with
1199               | neg, pos ->
1200                   debug_print
1201                     (lazy
1202                        (Printf.sprintf "new1:\n%s\n"
1203                           (String.concat "\n"
1204                              ((List.map
1205                                  (fun e -> "Negative " ^
1206                                     (string_of_equality ~env e)) neg) @
1207                                 (List.map
1208                                    (fun e -> "Positive " ^
1209                                       (string_of_equality ~env e)) pos)))))
1210             in
1211 end prova *)
1212             let k = size_of_passive passive in
1213             if k < (kept - 1) then
1214               processed_clauses := !processed_clauses + (kept - 1 - k);
1215             
1216             let _ =
1217               debug_print
1218                 (lazy
1219                    (Printf.sprintf "active:\n%s\n"
1220                       (String.concat "\n"
1221                          ((List.map
1222                              (fun e -> (Equality.string_of_equality ~env e))
1223                              (fst active))))))
1224             in
1225             let _ =
1226               debug_print
1227                 (lazy
1228                    (Printf.sprintf "new':\n%s\n"
1229                       (String.concat "\n"
1230                          ((List.map
1231                              (fun e -> "Negative " ^
1232                                 (Equality.string_of_equality ~env e)) new')))))
1233             in
1234             let passive = add_to_passive passive new' in
1235               given_clause_fullred dbd env goals theorems passive active
1236 ;;
1237
1238 (*
1239 let profiler0 = HExtlib.profile "P/Saturation.given_clause_fullred"
1240
1241 let given_clause_fullred dbd env goals theorems passive active =
1242   profiler0.HExtlib.profile 
1243     (given_clause_fullred dbd env goals theorems passive) active
1244 *)
1245
1246 let iseq uri = UriManager.eq uri (LibraryObjects.eq_URI ());;
1247
1248 let check_if_goal_is_identity env = function
1249   | (goalproof,m,Cic.Appl[Cic.MutInd(uri,_,ens);eq_ty;left;right]) 
1250     when left = right && iseq uri ->
1251       let reflproof = Equality.Exact (Equality.refl_proof eq_ty left) in
1252       Some (goalproof, reflproof,Subst.empty_subst,m)
1253   | _ -> None
1254 ;;                              
1255     
1256 let rec check goal = function
1257   | [] -> None
1258   | f::tl ->
1259       match f goal with
1260       | None -> check goal tl
1261       | (Some p) as ok  -> ok
1262 ;;
1263   
1264 let simplify_goal_set env goals passive active = 
1265   let active_goals, passive_goals = goals in 
1266   let find (_,_,g) where =
1267     List.exists (fun (_,_,g1) -> Equality.meta_convertibility g g1) where
1268   in
1269   let simplified =
1270     List.fold_left
1271       (fun acc goal -> 
1272         match simplify_goal env goal ~passive active with 
1273         | _, g -> if find g acc then acc else g::acc)
1274       [] active_goals
1275   in
1276   if List.length active_goals <>  List.length simplified then
1277     prerr_endline "SEMPLIFICANDO HO SCARTATO...";
1278   (simplified,passive_goals)
1279         (*
1280   HExtlib.list_uniq ~eq:(fun (_,_,t1) (_,_,t2) -> t1 = t2)
1281     (List.sort (fun (_,_,t1) (_,_,t2) -> compare t1 t1)
1282       ((*goals @*) simplified))
1283       *)
1284 ;;
1285
1286 let check_if_goals_set_is_solved env active goals =
1287   let active_goals, passive_goals = goals in 
1288   List.fold_left 
1289     (fun proof goal ->
1290       match proof with
1291       | Some p -> proof
1292       | None -> 
1293           check goal [
1294             check_if_goal_is_identity env;
1295             check_if_goal_is_subsumed env (snd active)])
1296     None active_goals
1297 ;;
1298
1299 let infer_goal_set env active goals = 
1300   let active_goals, passive_goals = goals in
1301   let rec aux = function
1302     | [] -> goals
1303     | ((_,_,t1) as hd)::tl when 
1304        not (List.exists 
1305              (fun (_,_,t) -> Equality.meta_convertibility t t1) 
1306              active_goals)
1307        -> 
1308         let selected = hd in
1309         let passive_goals = tl in
1310         let new' = Indexing.superposition_left env (snd active) selected in
1311         selected::active_goals, passive_goals @ new'
1312     | _::tl -> aux tl
1313   in 
1314   aux passive_goals
1315 ;;
1316
1317 let infer_goal_set_with_current env current goals = 
1318   let active_goals, passive_goals = goals in
1319   let _,table,_ = build_table [current] in
1320   active_goals,
1321   List.fold_left 
1322     (fun acc g ->
1323       let new' = Indexing.superposition_left env table g in
1324       acc @ new')
1325     passive_goals active_goals
1326 ;;
1327
1328
1329
1330 let size_of_goal_set_a (l,_) = List.length l;;
1331 let size_of_goal_set_p (_,l) = List.length l;;
1332
1333 (** given-clause algorithm with full reduction strategy: NEW implementation *)
1334 (* here goals is a set of goals in OR *)
1335 let given_clause 
1336   ((_,context,_) as env) goals theorems passive active max_iterations max_time
1337
1338   let initial_time = Unix.gettimeofday () in
1339   let iterations_left iterno = 
1340     let now = Unix.gettimeofday () in
1341     let time_left = max_time -. now in
1342     let time_spent_until_now = now -. initial_time in
1343     let iteration_medium_cost = 
1344       time_spent_until_now /. (float_of_int iterno)
1345     in
1346     let iterations_left = time_left /. iteration_medium_cost in
1347     int_of_float iterations_left 
1348   in
1349   let rec step goals theorems passive active iterno =
1350     if iterno > max_iterations then
1351       (ParamodulationFailure "No more iterations to spend")
1352     else if Unix.gettimeofday () > max_time then
1353       (ParamodulationFailure "No more time to spend")
1354     else
1355       let _ = prerr_endline "simpl goal with active" in
1356       let goals = simplify_goal_set env goals passive active in  
1357       match check_if_goals_set_is_solved env active goals with
1358       | Some p -> 
1359           prerr_endline 
1360             (Printf.sprintf "Found a proof in: %f\n" 
1361               (Unix.gettimeofday() -. initial_time));
1362 (*          assert false;*)
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               prerr_endline (Printf.sprintf  "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                   prerr_endline "infer";
1400                   let new' = infer env current active in
1401                   prerr_endline "infer goal";
1402                   let goals = infer_goal_set_with_current env current goals in
1403                   let active = 
1404                       let al, tbl = active in
1405                       al @ [current], Indexing.index tbl current
1406                   in
1407                   (* FORWARD AND BACKWARD SIMPLIFICATION *)
1408                   prerr_endline "fwd/back simpl";
1409                   let rec simplify new' active passive =
1410                     let new' = forward_simplify_new env new' ~passive active in
1411                     let active, passive, newa, retained, pruned =
1412                       backward_simplify env new' ~passive  active 
1413                     in
1414                     let passive = 
1415                       List.fold_left filter_dependent passive pruned 
1416                     in
1417                     match newa, retained with
1418                     | None, None -> active, passive, new'
1419                     | Some p, None 
1420                     | None, Some p -> simplify (new' @ p) active passive
1421                     | Some p, Some rp -> simplify (new' @ p @ rp) active passive
1422                   in
1423                   let active, passive, new' = simplify new' active passive in
1424                   prerr_endline "simpl goal with new";
1425                   let goals = 
1426                     let a,b,_ = build_table new' in
1427                     simplify_goal_set env goals passive (a,b)
1428                   in
1429                   let passive = add_to_passive passive new' in
1430                   step goals theorems passive active (iterno+1)
1431             end
1432   in
1433     step goals theorems passive active 1
1434 ;;
1435
1436 let rec saturate_equations env goal accept_fun passive active =
1437   elapsed_time := Unix.gettimeofday () -. !start_time;
1438   if !elapsed_time > !time_limit then
1439     (active, passive)
1440   else
1441     let current, passive = select env ([goal],[]) passive in
1442     let res = forward_simplify env (Positive, current) ~passive active in
1443     match res with
1444     | None ->
1445         saturate_equations env goal accept_fun passive active
1446     | Some current ->
1447         debug_print (lazy (Printf.sprintf "selected: %s"
1448                              (Equality.string_of_equality ~env current)));
1449         let new' = infer env current active in
1450         let active =
1451           if Equality.is_identity env current then active
1452           else
1453             let al, tbl = active in
1454             al @ [current], Indexing.index tbl current
1455         in
1456         let rec simplify new' active passive =
1457           let new' = forward_simplify_new env new' ~passive active in
1458           let active, passive, newa, retained, pruned =
1459             backward_simplify env new' ~passive active in
1460           let passive = 
1461             List.fold_left filter_dependent passive pruned in
1462           match newa, retained with
1463           | None, None -> active, passive, new'
1464           | Some p, None
1465           | None, Some p -> simplify (new' @ p) active passive
1466           | Some p, Some rp -> simplify (new' @ p @ rp) active passive
1467         in
1468         let active, passive, new' = simplify new' active passive in
1469         let _ =
1470           debug_print
1471             (lazy
1472                (Printf.sprintf "active:\n%s\n"
1473                   (String.concat "\n"
1474                      (List.map
1475                          (fun e -> Equality.string_of_equality ~env e)
1476                          (fst active)))))
1477         in
1478         let _ =
1479           debug_print
1480             (lazy
1481                (Printf.sprintf "new':\n%s\n"
1482                   (String.concat "\n"
1483                      (List.map
1484                          (fun e -> "Negative " ^
1485                             (Equality.string_of_equality ~env e)) new'))))
1486         in
1487         let new' = List.filter accept_fun new' in
1488         let passive = add_to_passive passive new' in
1489         saturate_equations env goal accept_fun passive active
1490 ;;
1491   
1492 let main dbd full term metasenv ugraph = ()
1493 (*
1494 let main dbd full term metasenv ugraph =
1495   let module C = Cic in
1496   let module T = CicTypeChecker in
1497   let module PET = ProofEngineTypes in
1498   let module PP = CicPp in
1499   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1500   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1501   let proof, goals = status in
1502   let goal' = List.nth goals 0 in
1503   let _, metasenv, meta_proof, _ = proof in
1504   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1505   let eq_indexes, equalities, maxm = find_equalities context proof in
1506   let lib_eq_uris, library_equalities, maxm =
1507
1508     find_library_equalities dbd context (proof, goal') (maxm+2)
1509   in
1510   let library_equalities = List.map snd library_equalities in
1511   maxmeta := maxm+2; (* TODO ugly!! *)
1512   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
1513   let new_meta_goal, metasenv, type_of_goal =
1514     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1515     debug_print
1516       (lazy
1517          (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n\n" (CicPp.ppterm ty)));
1518     Cic.Meta (maxm+1, irl),
1519     (maxm+1, context, ty)::metasenv,
1520     ty
1521   in
1522   let env = (metasenv, context, ugraph) in
1523   let t1 = Unix.gettimeofday () in
1524   let theorems =
1525     if full then
1526       let theorems = find_library_theorems dbd env (proof, goal') lib_eq_uris in
1527       let context_hyp = find_context_hypotheses env eq_indexes in
1528       context_hyp @ theorems, []
1529     else
1530       let refl_equal =
1531         let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
1532         UriManager.uri_of_string (us ^ "#xpointer(1/1/1)")
1533       in
1534       let t = CicUtil.term_of_uri refl_equal in
1535       let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
1536       [(t, ty, [])], []
1537   in
1538   let t2 = Unix.gettimeofday () in
1539   debug_print
1540     (lazy
1541        (Printf.sprintf "Time to retrieve theorems: %.9f\n" (t2 -. t1)));
1542   let _ =
1543     debug_print
1544       (lazy
1545          (Printf.sprintf
1546             "Theorems:\n-------------------------------------\n%s\n"
1547             (String.concat "\n"
1548                (List.map
1549                   (fun (t, ty, _) ->
1550                      Printf.sprintf
1551                        "Term: %s, type: %s" (CicPp.ppterm t) (CicPp.ppterm ty))
1552                   (fst theorems)))))
1553   in
1554   (*try*)
1555     let goal = 
1556       ([],Equality.BasicProof (Equality.empty_subst ,new_meta_goal)), [], goal 
1557     in
1558     let equalities = simplify_equalities env 
1559       (equalities@library_equalities) in 
1560     let active = make_active () in
1561     let passive = make_passive equalities in
1562     Printf.printf "\ncurrent goal: %s\n"
1563       (let _, _, g = goal in CicPp.ppterm g);
1564     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
1565     Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
1566     Printf.printf "\nequalities:\n%s\n"
1567       (String.concat "\n"
1568          (List.map
1569             (Equality.string_of_equality ~env) equalities));
1570 (*             (equalities @ library_equalities))); *)
1571       print_endline "--------------------------------------------------";
1572       let start = Unix.gettimeofday () in
1573       print_endline "GO!";
1574       start_time := Unix.gettimeofday ();
1575       let res =
1576         let goals = make_goals goal in
1577         (if !use_fullred then given_clause_fullred else given_clause_fullred)
1578           dbd env goals theorems passive active
1579       in
1580       let finish = Unix.gettimeofday () in
1581       let _ =
1582         match res with
1583         | ParamodulationFailure ->
1584             Printf.printf "NO proof found! :-(\n\n"
1585         | ParamodulationSuccess (Some ((cicproof,cicmenv),(proof, env))) ->
1586             Printf.printf "OK, found a proof!\n";
1587             let oldproof = Equation.build_proof_term proof in
1588             let newproof,_,newenv,_ = 
1589                 CicRefine.type_of_aux' 
1590                   cicmenv context cicproof CicUniv.empty_ugraph
1591             in
1592             (* REMEMBER: we have to instantiate meta_proof, we should use
1593                apply  the "apply" tactic to proof and status 
1594             *)
1595             let names = names_of_context context in
1596             prerr_endline "OLD PROOF";
1597             print_endline (PP.pp proof names);
1598             prerr_endline "NEW PROOF";
1599             print_endline (PP.pp newproof names);
1600             let newmetasenv =
1601               List.fold_left
1602                 (fun m eq -> 
1603                   let (_, _, _, menv,_) = Equality.open_equality eq in 
1604                   m @ menv) 
1605               metasenv equalities
1606             in
1607             let _ =
1608               (*try*)
1609                 let ty, ug =
1610                   CicTypeChecker.type_of_aux' newmetasenv context proof ugraph
1611                 in
1612                 print_endline (string_of_float (finish -. start));
1613                 Printf.printf
1614                   "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n\n"
1615                   (CicPp.pp type_of_goal names) (CicPp.pp ty names)
1616                   (string_of_bool
1617                      (fst (CicReduction.are_convertible
1618                              context type_of_goal ty ug)));
1619               (*with e ->
1620                 Printf.printf "\nEXCEPTION!!! %s\n" (Printexc.to_string e);
1621                 Printf.printf "MAXMETA USED: %d\n" !maxmeta;
1622                 print_endline (string_of_float (finish -. start));*)
1623             in
1624             ()
1625               
1626         | ParamodulationSuccess None ->
1627             Printf.printf "Success, but no proof?!?\n\n"
1628       in
1629         if Utils.time then
1630           begin
1631             prerr_endline 
1632               ((Printf.sprintf ("infer_time: %.9f\nforward_simpl_time: %.9f\n" ^^
1633                        "forward_simpl_new_time: %.9f\n" ^^
1634                        "backward_simpl_time: %.9f\n")
1635               !infer_time !forward_simpl_time !forward_simpl_new_time
1636               !backward_simpl_time) ^
1637               (Printf.sprintf "passive_maintainance_time: %.9f\n"
1638                  !passive_maintainance_time) ^
1639               (Printf.sprintf "    successful unification/matching time: %.9f\n"
1640                  !Indexing.match_unif_time_ok) ^
1641               (Printf.sprintf "    failed unification/matching time: %.9f\n"
1642                  !Indexing.match_unif_time_no) ^
1643               (Printf.sprintf "    indexing retrieval time: %.9f\n"
1644                  !Indexing.indexing_retrieval_time) ^
1645               (Printf.sprintf "    demodulate_term.build_newtarget_time: %.9f\n"
1646                  !Indexing.build_newtarget_time) ^
1647               (Printf.sprintf "derived %d clauses, kept %d clauses.\n"
1648                  !derived_clauses !kept_clauses)) 
1649             end
1650 (*
1651   with exc ->
1652     print_endline ("EXCEPTION: " ^ (Printexc.to_string exc));
1653     raise exc
1654 *)
1655 ;;
1656 *)
1657
1658 let default_depth = !maxdepth
1659 and default_width = !maxwidth;;
1660
1661 let reset_refs () =
1662   maxmeta := 0;
1663   symbols_counter := 0;
1664   weight_age_counter := !weight_age_ratio;
1665   processed_clauses := 0;
1666   start_time := 0.;
1667   elapsed_time := 0.;
1668   maximal_retained_equality := None;
1669   infer_time := 0.;
1670   forward_simpl_time := 0.;
1671   forward_simpl_new_time := 0.;
1672   backward_simpl_time := 0.;
1673   passive_maintainance_time := 0.;
1674   derived_clauses := 0;
1675   kept_clauses := 0;
1676   Equality.reset ();
1677 ;;
1678
1679 let saturate 
1680     dbd ?(full=false) ?(depth=default_depth) ?(width=default_width) status = 
1681   let module C = Cic in
1682   reset_refs ();
1683   Indexing.init_index ();
1684   counter := 0;
1685   maxdepth := depth;
1686   maxwidth := width;
1687 (*  CicUnification.unif_ty := false;*)
1688   let proof, goalno = status in
1689   let uri, metasenv, meta_proof, term_to_prove = proof in
1690   let _, context, type_of_goal = CicUtil.lookup_meta goalno metasenv in
1691   let names = names_of_context context in
1692   let eq_indexes, equalities, maxm = find_equalities context proof in
1693   let ugraph = CicUniv.empty_ugraph in
1694   let env = (metasenv, context, ugraph) in 
1695   let goal = [], List.filter (fun (i,_,_)->i<>goalno) metasenv, type_of_goal in
1696   let res, time =
1697     let t1 = Unix.gettimeofday () in
1698     let lib_eq_uris, library_equalities, maxm =
1699       find_library_equalities dbd context (proof, goalno) (maxm+2)
1700     in
1701     let library_equalities = List.map snd library_equalities in
1702     let t2 = Unix.gettimeofday () in
1703     maxmeta := maxm+2;
1704     let equalities = simplify_equalities env (equalities@library_equalities) in 
1705     debug_print
1706       (lazy
1707          (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)));
1708     let t1 = Unix.gettimeofday () in
1709     let theorems =
1710       if full then
1711         let thms = find_library_theorems dbd env (proof, goalno) lib_eq_uris in
1712         let context_hyp = find_context_hypotheses env eq_indexes in
1713         context_hyp @ thms, []
1714       else
1715         let refl_equal =
1716           let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
1717           UriManager.uri_of_string (us ^ "#xpointer(1/1/1)")
1718         in
1719         let t = CicUtil.term_of_uri refl_equal in
1720         let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
1721         [(t, ty, [])], []
1722     in
1723     let t2 = Unix.gettimeofday () in
1724     let _ =
1725       debug_print
1726         (lazy
1727            (Printf.sprintf
1728               "Theorems:\n-------------------------------------\n%s\n"
1729               (String.concat "\n"
1730                  (List.map
1731                     (fun (t, ty, _) ->
1732                        Printf.sprintf
1733                          "Term: %s, type: %s"
1734                          (CicPp.ppterm t) (CicPp.ppterm ty))
1735                     (fst theorems)))));
1736       debug_print
1737         (lazy
1738            (Printf.sprintf "Time to retrieve theorems: %.9f\n" (t2 -. t1)));
1739     in
1740     let active = make_active () in
1741     let passive = make_passive equalities in
1742     let start = Unix.gettimeofday () in
1743     let res =
1744 (*
1745       let goals = make_goals goal in
1746       given_clause_fullred dbd env goals theorems passive active
1747 *)
1748       let goals = make_goal_set goal in
1749       let max_iterations = 1000 in
1750       let max_time = Unix.gettimeofday () +.  120. (* minutes *) in
1751       given_clause env goals theorems passive active max_iterations max_time 
1752     in
1753     let finish = Unix.gettimeofday () in
1754     (res, finish -. start)
1755   in
1756   match res with
1757   | ParamodulationFailure s ->
1758       raise (ProofEngineTypes.Fail (lazy ("NO proof found: " ^ s)))
1759   | ParamodulationSuccess 
1760     (goalproof,newproof,subsumption_subst, proof_menv) ->
1761       prerr_endline "OK, found a proof!";
1762       prerr_endline (Equality.pp_proof names goalproof newproof);
1763       prerr_endline (CicMetaSubst.ppmetasenv [] proof_menv);
1764       prerr_endline "ENDOFPROOFS";
1765       (* generation of the CIC proof *)
1766       let side_effects = 
1767         List.filter (fun i -> i <> goalno)
1768           (ProofEngineHelpers.compare_metasenvs 
1769             ~newmetasenv:metasenv ~oldmetasenv:proof_menv)
1770       in
1771       let goal_proof, side_effects_t = 
1772         let initial = newproof in
1773         Equality.build_goal_proof goalproof initial type_of_goal side_effects
1774       in
1775 (*prerr_endline (CicPp.pp goal_proof names);*)
1776       let goal_proof = Subst.apply_subst subsumption_subst goal_proof in
1777       let side_effects_t = 
1778         List.map (Subst.apply_subst subsumption_subst) side_effects_t
1779       in
1780       (* replacing fake mets with real ones *)
1781       prerr_endline "replacing metas...";
1782       let irl=CicMkImplicit.identity_relocation_list_for_metavariable context in
1783       let goal_proof_menv, what, with_what,free_meta = 
1784         List.fold_left 
1785           (fun (acc1,acc2,acc3,uniq) (i,_,ty) -> 
1786              match uniq with
1787                | Some m -> 
1788                    acc1, (Cic.Meta(i,[]))::acc2, m::acc3, uniq
1789                | None ->
1790                    [i,context,ty], (Cic.Meta(i,[]))::acc2, 
1791                    (Cic.Meta(i,irl)) ::acc3,Some (Cic.Meta(i,irl))) 
1792           ([],[],[],None) proof_menv 
1793       in
1794 prerr_endline ("RIMPIAZZATO CON " ^ match free_meta with None -> "?" | Some m -> CicPp.ppterm m);
1795
1796       let replace where = 
1797         ProofEngineReduction.replace_lifting 
1798           ~equality:(=) ~what ~with_what ~where
1799       in
1800       let goal_proof = replace goal_proof in
1801         (* ok per le meta libere... ma per quelle che c'erano e sono rimaste? 
1802          * what mi pare buono, sostituisce solo le meta farlocche *)
1803       let side_effects_t = List.map replace side_effects_t in
1804       let free_metas = 
1805         List.filter (fun i -> i <> goalno)
1806           (ProofEngineHelpers.compare_metasenvs 
1807             ~oldmetasenv:metasenv ~newmetasenv:goal_proof_menv)
1808       in
1809 prerr_endline ("freemetas: " ^ String.concat "," (List.map string_of_int free_metas) );
1810       (* check/refine/... build the new proof *)
1811       let replaced_goal = 
1812         ProofEngineReduction.replace
1813           ~what:side_effects ~with_what:side_effects_t
1814           ~equality:(fun i t -> match t with Cic.Meta(j,_)->j=i|_->false)
1815           ~where:type_of_goal
1816       in
1817       let subst_side_effects,real_menv,_ = 
1818         let fail t s = raise (ProofEngineTypes.Fail (lazy (t^Lazy.force s))) in
1819         let free_metas_menv = 
1820           List.map (fun i -> CicUtil.lookup_meta i goal_proof_menv) free_metas
1821         in
1822         try
1823           CicUnification.fo_unif_subst [] context (metasenv @ free_metas_menv)
1824            replaced_goal type_of_goal CicUniv.empty_ugraph
1825         with
1826         | CicUnification.UnificationFailure s
1827         | CicUnification.Uncertain s 
1828         | CicUnification.AssertFailure s -> 
1829             fail "Maybe the local context of metas in the goal was not an IRL" s
1830       in
1831       let final_subst = 
1832         (goalno,(context,goal_proof,type_of_goal))::subst_side_effects
1833       in
1834 prerr_endline ("MENVreal_menv: " ^ CicMetaSubst.ppmetasenv [] real_menv);
1835       let _ = 
1836         try
1837           CicTypeChecker.type_of_aux' real_menv context goal_proof
1838             CicUniv.empty_ugraph
1839         with 
1840         | CicUtil.Meta_not_found _ 
1841         | CicTypeChecker.TypeCheckerFailure _ 
1842         | CicTypeChecker.AssertFailure _ 
1843         | Invalid_argument "list_fold_left2" as exn ->
1844             prerr_endline "THE PROOF DOES NOT TYPECHECK!";
1845 (*            prerr_endline (CicPp.pp goal_proof names); *)
1846             raise exn
1847       in
1848       let proof, real_metasenv = 
1849         ProofEngineHelpers.subst_meta_and_metasenv_in_proof
1850           proof goalno (CicMetaSubst.apply_subst final_subst) real_menv
1851       in
1852       let open_goals = 
1853         match free_meta with Some(Cic.Meta(m,_)) when m<>goalno ->[m] | _ ->[] 
1854       in
1855       Printf.eprintf 
1856         "GOALS APERTI: %s\nMETASENV PRIMA:\n%s\nMETASENV DOPO:\n%s\n" 
1857           (String.concat ", " (List.map string_of_int open_goals))
1858           (CicMetaSubst.ppmetasenv [] metasenv)
1859           (CicMetaSubst.ppmetasenv [] real_metasenv);
1860       prerr_endline (Printf.sprintf "\nTIME NEEDED: %8.2f" time);
1861       proof, open_goals
1862 ;;
1863
1864 let retrieve_and_print dbd term metasenv ugraph = 
1865   let module C = Cic in
1866   let module T = CicTypeChecker in
1867   let module PET = ProofEngineTypes in
1868   let module PP = CicPp in
1869   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1870   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1871   let proof, goals = status in
1872   let goal' = List.nth goals 0 in
1873   let uri, metasenv, meta_proof, term_to_prove = proof in
1874   let _, context, type_of_goal = CicUtil.lookup_meta goal' metasenv in
1875   let eq_indexes, equalities, maxm = find_equalities context proof in
1876   let ugraph = CicUniv.empty_ugraph in
1877   let env = (metasenv, context, ugraph) in
1878   let t1 = Unix.gettimeofday () in
1879   let lib_eq_uris, library_equalities, maxm =
1880     find_library_equalities dbd context (proof, goal') (maxm+2) in
1881   let t2 = Unix.gettimeofday () in
1882   maxmeta := maxm+2;
1883   let equalities = (* equalities @ *) library_equalities in
1884   debug_print
1885      (lazy
1886         (Printf.sprintf "\n\nequalities:\n%s\n"
1887            (String.concat "\n"
1888               (List.map 
1889           (fun (u, e) ->
1890 (*                  Printf.sprintf "%s: %s" *)
1891                    (UriManager.string_of_uri u)
1892 (*                    (string_of_equality e) *)
1893                      )
1894           equalities))));
1895   debug_print (lazy "RETR: SIMPLYFYING EQUALITIES...");
1896   let rec simpl e others others_simpl =
1897     let (u, e) = e in
1898     let active = List.map (fun (u, e) -> (Positive, e))
1899       (others @ others_simpl) in
1900     let tbl =
1901       List.fold_left
1902         (fun t (_, e) -> Indexing.index t e)
1903         Indexing.empty active
1904     in
1905     let res = forward_simplify env (Positive, e) (active, tbl) in
1906     match others with
1907         | hd::tl -> (
1908             match res with
1909               | None -> simpl hd tl others_simpl
1910               | Some e -> simpl hd tl ((u, e)::others_simpl)
1911           )
1912         | [] -> (
1913             match res with
1914               | None -> others_simpl
1915               | Some e -> (u, e)::others_simpl
1916           ) 
1917   in
1918   let _equalities =
1919     match equalities with
1920       | [] -> []
1921       | hd::tl ->
1922           let others = tl in (* List.map (fun e -> (Positive, e)) tl in *)
1923           let res =
1924             List.rev (simpl (*(Positive,*) hd others [])
1925           in
1926             debug_print
1927               (lazy
1928                  (Printf.sprintf "\nequalities AFTER:\n%s\n"
1929                     (String.concat "\n"
1930                        (List.map
1931                           (fun (u, e) ->
1932                              Printf.sprintf "%s: %s"
1933                                (UriManager.string_of_uri u)
1934                                (Equality.string_of_equality e)
1935                           )
1936                           res))));
1937             res in
1938     debug_print
1939       (lazy
1940          (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)))
1941 ;;
1942
1943
1944 let main_demod_equalities dbd term metasenv ugraph =
1945   let module C = Cic in
1946   let module T = CicTypeChecker in
1947   let module PET = ProofEngineTypes in
1948   let module PP = CicPp in
1949   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1950   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1951   let proof, goals = status in
1952   let goal' = List.nth goals 0 in
1953   let _, metasenv, meta_proof, _ = proof in
1954   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1955   let eq_indexes, equalities, maxm = find_equalities context proof in
1956   let lib_eq_uris, library_equalities, maxm =
1957     find_library_equalities dbd context (proof, goal') (maxm+2)
1958   in
1959   let library_equalities = List.map snd library_equalities in
1960   maxmeta := maxm+2; (* TODO ugly!! *)
1961   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
1962   let new_meta_goal, metasenv, type_of_goal =
1963     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1964     debug_print
1965       (lazy
1966          (Printf.sprintf "\n\nTRYING TO INFER EQUALITIES MATCHING: %s\n\n"
1967             (CicPp.ppterm ty)));
1968     Cic.Meta (maxm+1, irl),
1969     (maxm+1, context, ty)::metasenv,
1970     ty
1971   in
1972   let env = (metasenv, context, ugraph) in
1973   (*try*)
1974     let goal = [], [], goal 
1975     in
1976     let equalities = simplify_equalities env (equalities@library_equalities) in
1977     let active = make_active () in
1978     let passive = make_passive equalities in
1979     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
1980     Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
1981     Printf.printf "\nequalities:\n%s\n"
1982       (String.concat "\n"
1983          (List.map
1984             (Equality.string_of_equality ~env) equalities));
1985     print_endline "--------------------------------------------------";
1986     print_endline "GO!";
1987     start_time := Unix.gettimeofday ();
1988     if !time_limit < 1. then time_limit := 60.;    
1989     let ra, rp =
1990       saturate_equations env goal (fun e -> true) passive active
1991     in
1992
1993     let initial =
1994       List.fold_left (fun s e -> EqualitySet.add e s)
1995         EqualitySet.empty equalities
1996     in
1997     let addfun s e = 
1998       if not (EqualitySet.mem e initial) then EqualitySet.add e s else s
1999     in
2000
2001     let passive =
2002       match rp with
2003       | (p, _), _ ->
2004           EqualitySet.elements (List.fold_left addfun EqualitySet.empty p)
2005     in
2006     let active =
2007       let l = fst ra in
2008       EqualitySet.elements (List.fold_left addfun EqualitySet.empty l)
2009     in
2010     Printf.printf "\n\nRESULTS:\nActive:\n%s\n\nPassive:\n%s\n"
2011        (String.concat "\n" (List.map (Equality.string_of_equality ~env) active)) 
2012      (*  (String.concat "\n"
2013          (List.map (fun e -> CicPp.ppterm (term_of_equality e)) active)) *)
2014 (*       (String.concat "\n" (List.map (string_of_equality ~env) passive)); *)
2015       (String.concat "\n"
2016          (List.map (fun e -> CicPp.ppterm (Equality.term_of_equality e)) passive));
2017     print_newline ();
2018 (*
2019   with e ->
2020     debug_print (lazy ("EXCEPTION: " ^ (Printexc.to_string e)))
2021 *)
2022 ;;
2023
2024 let demodulate_tac ~dbd ~pattern ((proof,goal)(*s initialstatus*)) = 
2025   let module I = Inference in
2026   let curi,metasenv,pbo,pty = proof in
2027   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
2028   let eq_indexes, equalities, maxm = I.find_equalities context proof in
2029   let lib_eq_uris, library_equalities, maxm =
2030     I.find_library_equalities dbd context (proof, goal) (maxm+2) in
2031   if library_equalities = [] then prerr_endline "VUOTA!!!";
2032   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
2033   let library_equalities = List.map snd library_equalities in
2034   let initgoal = [], [], ty in
2035   let env = (metasenv, context, CicUniv.empty_ugraph) in
2036   let equalities = simplify_equalities env (equalities@library_equalities) in   
2037   let table = 
2038     List.fold_left 
2039       (fun tbl eq -> Indexing.index tbl eq) 
2040       Indexing.empty equalities 
2041   in
2042   let changed,(newproof,newmetasenv, newty) = 
2043     Indexing.demodulation_goal 
2044       (metasenv,context,CicUniv.empty_ugraph) table initgoal 
2045   in
2046   if changed then
2047     begin
2048       let opengoal = Equality.Exact (Cic.Meta(maxm,irl)) in
2049       let proofterm,_ = 
2050         Equality.build_goal_proof newproof opengoal ty [] in
2051         let extended_metasenv = (maxm,context,newty)::metasenv in
2052         let extended_status = 
2053           (curi,extended_metasenv,pbo,pty),goal in
2054         let (status,newgoals) = 
2055           ProofEngineTypes.apply_tactic 
2056             (PrimitiveTactics.apply_tac ~term:proofterm)
2057             extended_status in
2058         (status,maxm::newgoals)
2059     end
2060   else (* if newty = ty then *)
2061     raise (ProofEngineTypes.Fail (lazy "no progress"))
2062   (*else ProofEngineTypes.apply_tactic 
2063     (ReductionTactics.simpl_tac ~pattern) 
2064     initialstatus*)
2065 ;;
2066
2067 let demodulate_tac ~dbd ~pattern = 
2068   ProofEngineTypes.mk_tactic (demodulate_tac ~dbd ~pattern)
2069 ;;
2070
2071 let get_stats () = 
2072   <:show<Saturation.>> ^ Indexing.get_stats () ^ Inference.get_stats ();;
2073