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