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