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