]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/paramodulation/saturation.ml
args removed from equalities.
[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
32 (*
33 for debugging 
34 let check_equation env equation msg =
35   let w, proof, (eq_ty, left, right, order), metas = equation in
36   let metasenv, context, ugraph = env in
37   let metasenv' = metasenv @ metas in
38     try
39       CicTypeChecker.type_of_aux' metasenv' context left ugraph;
40       CicTypeChecker.type_of_aux' metasenv' context right ugraph;
41       ()
42     with 
43         CicUtil.Meta_not_found _ as exn ->
44           begin
45             prerr_endline msg; 
46             prerr_endline (CicPp.ppterm left);
47             prerr_endline (CicPp.ppterm right);
48             raise exn
49           end 
50 *)
51
52 (* set to false to disable paramodulation inside auto_tac *)
53 let connect_to_auto = true;;
54
55
56 (* profiling statistics... *)
57 let infer_time = ref 0.;;
58 let forward_simpl_time = ref 0.;;
59 let forward_simpl_new_time = ref 0.;;
60 let backward_simpl_time = ref 0.;;
61 let passive_maintainance_time = ref 0.;;
62
63 (* limited-resource-strategy related globals *)
64 let processed_clauses = ref 0;; (* number of equalities selected so far... *)
65 let time_limit = ref 0.;; (* in seconds, settable by the user... *)
66 let start_time = ref 0.;; (* time at which the execution started *)
67 let elapsed_time = ref 0.;;
68 (* let maximal_weight = ref None;; *)
69 let maximal_retained_equality = ref None;;
70
71 (* equality-selection related globals *)
72 let use_fullred = ref true;;
73 let weight_age_ratio = ref 4 (* 5 *);; (* settable by the user *)
74 let weight_age_counter = ref !weight_age_ratio ;;
75 let symbols_ratio = ref 0 (* 3 *);;
76 let symbols_counter = ref 0;;
77
78 (* non-recursive Knuth-Bendix term ordering by default *)
79 (* Utils.compare_terms := Utils.rpo;; *)
80 (* Utils.compare_terms := Utils.nonrec_kbo;; *)
81 (* Utils.compare_terms := Utils.ao;; *)
82
83 (* statistics... *)
84 let derived_clauses = ref 0;;
85 let kept_clauses = ref 0;;
86
87 (* index of the greatest Cic.Meta created - TODO: find a better way! *)
88 let maxmeta = ref 0;;
89
90 (* varbiables controlling the search-space *)
91 let maxdepth = ref 3;;
92 let maxwidth = ref 3;;
93
94
95 type result =
96   | ParamodulationFailure
97   | ParamodulationSuccess of Inference.proof option * environment
98 ;;
99
100 type goal = proof * Cic.metasenv * Cic.term;;
101
102 type theorem = Cic.term * Cic.term * Cic.metasenv;;
103
104 let symbols_of_equality (_, _, (_, left, right, _), _) =
105   let m1 = symbols_of_term left in
106   let m = 
107     TermMap.fold
108       (fun k v res ->
109          try
110            let c = TermMap.find k res in
111            TermMap.add k (c+v) res
112          with Not_found ->
113            TermMap.add k v res)
114       (symbols_of_term right) m1
115   in
116   m
117 ;;
118
119 (* griggio *)
120 module OrderedEquality = struct 
121   type t = Inference.equality
122
123   let compare eq1 eq2 =
124     match meta_convertibility_eq eq1 eq2 with
125     | true -> 0
126     | false ->
127         let w1, _, (ty, left, right, _), m1 = eq1
128         and w2, _, (ty', left', right', _), m2 = eq2 in
129         match Pervasives.compare w1 w2 with
130         | 0 -> 
131             let res = (List.length m1) - (List.length m2) in 
132             if res <> 0 then res else Pervasives.compare eq1 eq2
133         | res -> res 
134 end 
135
136 (*
137 module OrderedEquality = struct
138   type t = Inference.equality
139
140   let minor eq =
141     let w, _, (ty, left, right, o), _ = eq in
142       match o with
143          | Lt -> Some left
144          | Le -> assert false
145          | Gt -> Some right
146          | Ge -> assert false
147          | Eq 
148          | Incomparable -> None
149              
150   let compare eq1 eq2 =
151     let w1, _, (ty, left, right, o1), m1 = eq1
152     and w2, _, (ty', left', right', o2), m2 = eq2 in
153       match Pervasives.compare w1 w2 with
154         | 0 ->
155             (match minor eq1, minor eq2 with
156               | Some t1, Some t2 ->
157                   fst (Utils.weight_of_term t1) - fst (Utils.weight_of_term t2)
158               | Some _, None -> -1
159               | None, Some _ -> 1
160               | _,_ -> 
161                   (List.length m2) - (List.length m1) )
162         | res ->  res
163   
164   let compare eq1 eq2 =
165     match compare eq1 eq2 with
166         0 -> Pervasives.compare eq1 eq2
167       | res -> res 
168 end 
169 *)
170
171 module EqualitySet = Set.Make(OrderedEquality);;
172
173 exception Empty_list;;
174
175 let passive_is_empty = function
176   | ([], _), ([], _), _ -> true
177   | _ -> false
178 ;;
179
180
181 let size_of_passive ((_, ns), (_, ps), _) =
182   (EqualitySet.cardinal ns) + (EqualitySet.cardinal ps)
183 ;;
184
185
186 let size_of_active (active_list, _) =
187   List.length active_list
188 ;;
189
190 let age_factor = 0.01;;
191
192 let min_elt weight l =
193   fst
194   (match l with
195       [] -> raise Empty_list
196     | a::tl -> 
197         let wa = float_of_int (weight a) in
198         let x = ref 0. in
199         List.fold_left
200           (fun (current,w) arg ->
201             x:=!x +. 1.;
202             let w1 = weight arg in
203             let wa = (float_of_int w1) +. !x *. age_factor in
204             if wa < w then (arg,wa) else (current,w))
205           (a,wa) tl)
206 ;;
207
208 (* 
209 let compare eq1 eq2 =
210   let w1, _, (ty, left, right, _), m1, _ = eq1 in
211   let w2, _, (ty', left', right', _), m2, _ = eq2 in
212   match Pervasives.compare w1 w2 with
213     | 0 -> (List.length m1) - (List.length m2)
214     | res -> res
215 ;;
216 *)
217
218 (**
219    selects one equality from passive. The selection strategy is a combination
220    of weight, age and goal-similarity
221 *)
222 let rec select env goals passive (active, _) =
223   processed_clauses := !processed_clauses + 1;
224   let goal =
225     match (List.rev goals) with (_, goal::_)::_ -> goal | _ -> assert false
226   in
227   let (neg_list, neg_set), (pos_list, pos_set), passive_table = passive in
228   let remove eq l =
229     List.filter (fun e -> e <> eq) l
230   in
231   if !weight_age_ratio > 0 then
232     weight_age_counter := !weight_age_counter - 1;
233   match !weight_age_counter with
234   | 0 -> (
235       weight_age_counter := !weight_age_ratio;
236       match neg_list, pos_list with
237       | hd::tl, pos ->
238           (* Negatives aren't indexed, no need to remove them... *)
239           (Negative, hd),
240           ((tl, EqualitySet.remove hd neg_set), (pos, pos_set), passive_table)
241       | [], (hd:EqualitySet.elt)::tl ->
242           let w,_,_,_ = hd in
243           let passive_table =
244             Indexing.remove_index passive_table hd
245           in  (Positive, hd),
246           (([], neg_set), (tl, EqualitySet.remove hd pos_set), passive_table)
247       | _, _ -> assert false
248     )
249   | _ when (!symbols_counter > 0) && (EqualitySet.is_empty neg_set) -> 
250      (symbols_counter := !symbols_counter - 1;
251       let cardinality map =
252         TermMap.fold (fun k v res -> res + v) map 0
253       in
254       let symbols =
255         let _, _, term = goal in
256         symbols_of_term term
257       in
258       let card = cardinality symbols in
259       let foldfun k v (r1, r2) = 
260         if TermMap.mem k symbols then
261           let c = TermMap.find k symbols in
262           let c1 = abs (c - v) in
263           let c2 = v - c1 in
264           r1 + c2, r2 + c1
265         else
266           r1, r2 + v
267       in
268       let f equality (i, e) =
269         let common, others =
270           TermMap.fold foldfun (symbols_of_equality equality) (0, 0)
271         in
272         let c = others + (abs (common - card)) in
273         if c < i then (c, equality)
274         else (i, e)
275       in
276       let e1 = EqualitySet.min_elt pos_set in
277       let initial =
278         let common, others = 
279           TermMap.fold foldfun (symbols_of_equality e1) (0, 0)
280         in
281         (others + (abs (common - card))), e1
282       in
283       let _, current = EqualitySet.fold f pos_set initial in
284       let passive_table =
285         Indexing.remove_index passive_table current
286       in
287       (Positive, current),
288       (([], neg_set),
289        (remove current pos_list, EqualitySet.remove current pos_set),
290        passive_table)
291     )
292   | _ ->
293       symbols_counter := !symbols_ratio;
294       let set_selection set = EqualitySet.min_elt set in 
295       (* let set_selection l = min_elt (fun (w,_,_,_) -> w) l in *)
296       if EqualitySet.is_empty neg_set then
297         let current = set_selection pos_set in
298         let passive =
299           (neg_list, neg_set),
300           (remove current pos_list, EqualitySet.remove current pos_set),
301           Indexing.remove_index passive_table current
302         in
303         (Positive, current), passive
304       else
305         let current = set_selection neg_set in
306         let passive =
307           (remove current neg_list, EqualitySet.remove current neg_set),
308           (pos_list, pos_set),
309           passive_table
310         in
311         (Negative, current), passive
312 ;;
313
314
315 (* initializes the passive set of equalities *)
316 let make_passive neg pos =
317   let set_of equalities =
318     List.fold_left (fun s e -> EqualitySet.add e s) EqualitySet.empty equalities
319   in
320   let table =
321       List.fold_left (fun tbl e -> Indexing.index tbl e) Indexing.empty pos
322   in
323   (neg, set_of neg),
324   (pos, set_of pos),
325   table
326 ;;
327
328
329 let make_active () =
330   [], Indexing.empty
331 ;;
332
333
334 (* adds to passive a list of equalities: new_neg is a list of negative
335    equalities, new_pos a list of positive equalities *)
336 let add_to_passive passive (new_neg, new_pos) =
337   let (neg_list, neg_set), (pos_list, pos_set), table = passive in
338   let ok set equality = not (EqualitySet.mem equality set) in
339   let neg = List.filter (ok neg_set) new_neg
340   and pos = List.filter (ok pos_set) new_pos in
341   let table =
342     List.fold_left (fun tbl e -> Indexing.index tbl e) table pos
343   in
344   let add set equalities =
345     List.fold_left (fun s e -> EqualitySet.add e s) set equalities
346   in
347   (neg @ neg_list, add neg_set neg),
348   (pos_list @ pos, add pos_set pos),
349   table
350 ;;
351
352
353 (* removes from passive equalities that are estimated impossible to activate
354    within the current time limit *)
355 let prune_passive howmany (active, _) passive =
356   let (nl, ns), (pl, ps), tbl = passive in
357   let howmany = float_of_int howmany
358   and ratio = float_of_int !weight_age_ratio in
359   let round v =
360     let t = ceil v in 
361     int_of_float (if t -. v < 0.5 then t else v)
362   in
363   let in_weight = round (howmany *. ratio /. (ratio +. 1.))
364   and in_age = round (howmany /. (ratio +. 1.)) in 
365   debug_print
366     (lazy (Printf.sprintf "in_weight: %d, in_age: %d\n" in_weight in_age));
367   let symbols, card =
368     match active with
369     | (Negative, e)::_ ->
370         let symbols = symbols_of_equality e in
371         let card = TermMap.fold (fun k v res -> res + v) symbols 0 in
372         Some symbols, card
373     | _ -> None, 0
374   in
375   let counter = ref !symbols_ratio in
376   let rec pickw w ns ps =
377     if w > 0 then
378       if not (EqualitySet.is_empty ns) then
379         let e = EqualitySet.min_elt ns in
380         let ns', ps = pickw (w-1) (EqualitySet.remove e ns) ps in
381         EqualitySet.add e ns', ps
382       else if !counter > 0 then
383         let _ =
384           counter := !counter - 1;
385           if !counter = 0 then counter := !symbols_ratio
386         in
387         match symbols with
388         | None ->
389             let e = EqualitySet.min_elt ps in
390             let ns, ps' = pickw (w-1) ns (EqualitySet.remove e ps) in
391             ns, EqualitySet.add e ps'
392         | Some symbols ->
393             let foldfun k v (r1, r2) =
394               if TermMap.mem k symbols then
395                 let c = TermMap.find k symbols in
396                 let c1 = abs (c - v) in
397                 let c2 = v - c1 in
398                 r1 + c2, r2 + c1
399               else
400                 r1, r2 + v
401             in
402             let f equality (i, e) =
403               let common, others =
404                 TermMap.fold foldfun (symbols_of_equality equality) (0, 0)
405               in
406               let c = others + (abs (common - card)) in
407               if c < i then (c, equality)
408               else (i, e)
409             in
410             let e1 = EqualitySet.min_elt ps in
411             let initial =
412               let common, others = 
413                 TermMap.fold foldfun (symbols_of_equality e1) (0, 0)
414               in
415               (others + (abs (common - card))), e1
416             in
417             let _, e = EqualitySet.fold f ps initial in
418             let ns, ps' = pickw (w-1) ns (EqualitySet.remove e ps) in
419             ns, EqualitySet.add e ps'
420       else
421         let e = EqualitySet.min_elt ps in
422         let ns, ps' = pickw (w-1) ns (EqualitySet.remove e ps) in
423         ns, EqualitySet.add e ps'        
424     else
425       EqualitySet.empty, EqualitySet.empty
426   in
427   let ns, ps = pickw in_weight ns ps in
428   let rec picka w s l =
429     if w > 0 then
430       match l with
431       | [] -> w, s, []
432       | hd::tl when not (EqualitySet.mem hd s) ->
433           let w, s, l = picka (w-1) s tl in
434           w, EqualitySet.add hd s, hd::l
435       | hd::tl ->
436           let w, s, l = picka w s tl in
437           w, s, hd::l
438     else
439       0, s, l
440   in
441   let in_age, ns, nl = picka in_age ns nl in
442   let _, ps, pl = picka in_age ps pl in
443   if not (EqualitySet.is_empty ps) then
444     maximal_retained_equality := Some (EqualitySet.max_elt ps); 
445   let tbl =
446     EqualitySet.fold
447       (fun e tbl -> Indexing.index tbl e) ps Indexing.empty
448   in
449   (nl, ns), (pl, ps), tbl  
450 ;;
451
452
453 (** inference of new equalities between current and some in active *)
454 let infer env sign current (active_list, active_table) =
455   let (_,c,_) = env in 
456   if Utils.debug_metas then
457     (ignore(Indexing.check_target c current "infer1");
458      ignore(List.map (function (_,current) -> Indexing.check_target c current "infer2") active_list)); 
459   let new_neg, new_pos = 
460     match sign with
461     | Negative ->
462         let maxm, res = 
463           Indexing.superposition_left !maxmeta env active_table current in
464           if Utils.debug_metas then
465             ignore(List.map 
466                      (function current -> 
467                         Indexing.check_target c current "sup-1") res);
468         maxmeta := maxm;
469         res, [] 
470     | Positive ->
471         let maxm, res =
472           Indexing.superposition_right !maxmeta env active_table current in
473           if Utils.debug_metas then
474             ignore(List.map 
475                      (function current -> 
476                         Indexing.check_target c current "sup0") res);
477           maxmeta := maxm;
478         let rec infer_positive table = function
479           | [] -> [], []
480           | (Negative, equality)::tl ->
481               let maxm, res =
482                 Indexing.superposition_left !maxmeta env table equality in
483               maxmeta := maxm;
484               if Utils.debug_metas then 
485                 ignore(List.map 
486                          (function current -> 
487                             Indexing.check_target c current "supl") res);
488               let neg, pos = infer_positive table tl in
489               res @ neg, pos
490           | (Positive, equality)::tl ->
491               let maxm, res =
492                 Indexing.superposition_right !maxmeta env table equality in
493               maxmeta := maxm;
494                 if Utils.debug_metas then
495                   ignore
496                     (List.map 
497                        (function current -> 
498                           Indexing.check_target c current "sup2") res);
499               let neg, pos = infer_positive table tl in
500               neg, res @ pos
501         in
502         let maxm, copy_of_current = Inference.fix_metas !maxmeta current in
503         maxmeta := maxm;
504         let curr_table = Indexing.index Indexing.empty current in
505         let neg, pos = 
506           infer_positive curr_table ((sign,copy_of_current)::active_list) 
507         in
508           if Utils.debug_metas then 
509             ignore(List.map 
510                      (function current -> 
511                         Indexing.check_target c current "sup3") pos);
512         neg, res @ pos
513   in
514   derived_clauses := !derived_clauses + (List.length new_neg) +
515     (List.length new_pos);
516   match !maximal_retained_equality with
517   | None -> 
518       if Utils.debug_metas then 
519         (ignore(List.map 
520                  (function current -> 
521                     Indexing.check_target c current "sup4") new_pos);
522         ignore(List.map 
523                  (function current -> 
524                     Indexing.check_target c current "sup5") new_neg));
525       new_neg, new_pos
526   | Some eq ->
527       ignore(assert false);
528       (* if we have a maximal_retained_equality, we can discard all equalities
529          "greater" than it, as they will never be reached...  An equality is
530          greater than maximal_retained_equality if it is bigger
531          wrt. OrderedEquality.compare and it is less similar than
532          maximal_retained_equality to the current goal *)
533       let symbols, card =
534         match active_list with
535         | (Negative, e)::_ ->
536             let symbols = symbols_of_equality e in
537             let card = TermMap.fold (fun k v res -> res + v) symbols 0 in
538             Some symbols, card
539         | _ -> None, 0
540       in
541       let new_pos = 
542         match symbols with
543         | None ->
544             List.filter (fun e -> OrderedEquality.compare e eq <= 0) new_pos
545         | Some symbols ->
546             let filterfun e =
547               if OrderedEquality.compare e eq <= 0 then
548                 true
549               else
550                 let foldfun k v (r1, r2) =
551                   if TermMap.mem k symbols then
552                     let c = TermMap.find k symbols in
553                     let c1 = abs (c - v) in
554                     let c2 = v - c1 in
555                     r1 + c2, r2 + c1
556                   else
557                     r1, r2 + v
558                 in
559                 let initial =
560                   let common, others =
561                     TermMap.fold foldfun (symbols_of_equality eq) (0, 0) in
562                   others + (abs (common - card))
563                 in
564                 let common, others =
565                   TermMap.fold foldfun (symbols_of_equality e) (0, 0) in
566                 let c = others + (abs (common - card)) in
567                 if c < initial then true else false 
568             in
569             List.filter filterfun new_pos
570       in
571         new_neg, new_pos
572 ;;
573
574
575 let contains_empty env (negative, positive) =
576   let metasenv, context, ugraph = env in
577   try
578     let found =
579       List.find
580         (fun (w, proof, (ty, left, right, ordering), m) ->
581            fst (CicReduction.are_convertible context left right ugraph))
582         negative
583     in
584     true, Some found
585   with Not_found ->
586     false, None
587 ;;
588
589
590 (** simplifies current using active and passive *)
591 let forward_simplify env (sign, current) ?passive (active_list, active_table) =
592   let _, context, _ = env in
593   let pl, passive_table =
594     match passive with
595     | None -> [], None
596     | Some ((pn, _), (pp, _), pt) ->
597         let pn = List.map (fun e -> (Negative, e)) pn
598         and pp = List.map (fun e -> (Positive, e)) pp in
599         pn @ pp, Some pt
600   in
601   let all =  if pl = [] then active_list else active_list @ pl in 
602   
603   let demodulate table current = 
604     let newmeta, newcurrent =
605       Indexing.demodulation_equality !maxmeta env table sign current in
606     maxmeta := newmeta;
607     if is_identity env newcurrent then
608       if sign = Negative then Some (sign, newcurrent)
609       else (
610 (*      debug_print  *)
611 (*        (lazy *)
612 (*           (Printf.sprintf "\ncurrent was: %s\nnewcurrent is: %s\n" *)
613 (*              (string_of_equality current) *)
614 (*              (string_of_equality newcurrent))); *)
615 (*      debug_print *)
616 (*        (lazy *)
617 (*           (Printf.sprintf "active is: %s" *)
618 (*              (String.concat "\n"  *)
619 (*                 (List.map (fun (_, e) -> (string_of_equality e)) active_list)))); *)
620         None
621       )
622     else
623       Some (sign, newcurrent)
624   in
625   let res =
626     if Utils.debug_metas then
627       ignore (Indexing.check_target context current "demod0");
628     let res = demodulate active_table current in
629       if Utils.debug_metas then
630         ignore ((function None -> () | Some (_,x) -> 
631                    Indexing.check_target context x "demod1";()) res);
632     match res with
633     | None -> None
634     | Some (sign, newcurrent) ->
635         match passive_table with
636         | None -> res
637         | Some passive_table -> demodulate passive_table newcurrent
638   in
639   match res with
640   | None -> None
641   | Some (Negative, c) ->
642       let ok = not (
643         List.exists
644           (fun (s, eq) -> s = Negative && meta_convertibility_eq eq c)
645           all)
646       in
647       if ok then res else None
648   | Some (Positive, c) ->
649       if Indexing.in_index active_table c then
650         None
651       else
652         match passive_table with
653         | None -> 
654             if fst (Indexing.subsumption env active_table c) then
655               None
656             else
657               res
658         | Some passive_table ->
659             if Indexing.in_index passive_table c then None
660             else 
661               let r1, _ = Indexing.subsumption env active_table c in
662               if r1 then None else
663                 let r2, _ = Indexing.subsumption env passive_table c in 
664                 if r2 then None else res
665 ;;
666
667 type fs_time_info_t = {
668   mutable build_all: float;
669   mutable demodulate: float;
670   mutable subsumption: float;
671 };;
672
673 let fs_time_info = { build_all = 0.; demodulate = 0.; subsumption = 0. };;
674
675
676 (** simplifies new using active and passive *)
677 let forward_simplify_new env (new_neg, new_pos) ?passive active =
678   if Utils.debug_metas then
679     begin
680       let m,c,u = env in
681         ignore(List.map 
682                  (fun current -> 
683                     Indexing.check_target c current "forward new neg") new_neg);
684         ignore(List.map 
685         (fun current -> Indexing.check_target c current "forward new pos") 
686       new_pos;)
687     end;
688   let t1 = Unix.gettimeofday () in
689
690   let active_list, active_table = active in
691   let pl, passive_table =
692     match passive with
693     | None -> [], None
694     | Some ((pn, _), (pp, _), pt) ->
695         let pn = List.map (fun e -> (Negative, e)) pn
696         and pp = List.map (fun e -> (Positive, e)) pp in
697         pn @ pp, Some pt
698   in
699   
700   let t2 = Unix.gettimeofday () in
701   fs_time_info.build_all <- fs_time_info.build_all +. (t2 -. t1);
702   
703   let demodulate sign table target =
704     let newmeta, newtarget =
705       Indexing.demodulation_equality !maxmeta env table sign target in
706     maxmeta := newmeta;
707     newtarget
708   in
709   let t1 = Unix.gettimeofday () in
710
711   let new_neg, new_pos =
712     let new_neg = List.map (demodulate Negative active_table) new_neg
713     and new_pos = List.map (demodulate Positive active_table) new_pos in
714       new_neg,new_pos  
715 (* PROVA 
716     match passive_table with
717     | None -> new_neg, new_pos
718     | Some passive_table ->
719         List.map (demodulate Negative passive_table) new_neg,
720         List.map (demodulate Positive passive_table) new_pos *)
721   in
722
723   let t2 = Unix.gettimeofday () in
724   fs_time_info.demodulate <- fs_time_info.demodulate +. (t2 -. t1);
725
726   let new_pos_set =
727     List.fold_left
728       (fun s e ->
729          if not (Inference.is_identity env e) then
730            if EqualitySet.mem e s then s
731            else EqualitySet.add e s
732          else s)
733       EqualitySet.empty new_pos
734   in
735   let new_pos = EqualitySet.elements new_pos_set in
736
737   let subs =
738     match passive_table with
739     | None ->
740         (fun e -> not (fst (Indexing.subsumption env active_table e)))
741     | Some passive_table ->
742         (fun e -> not ((fst (Indexing.subsumption env active_table e)) ||
743                          (fst (Indexing.subsumption env passive_table e))))
744   in
745 (*   let t1 = Unix.gettimeofday () in *)
746 (*   let t2 = Unix.gettimeofday () in *)
747 (*   fs_time_info.subsumption <- fs_time_info.subsumption +. (t2 -. t1); *)
748   let is_duplicate =
749     match passive_table with
750     | None ->
751         (fun e -> not (Indexing.in_index active_table e))
752     | Some passive_table ->
753         (fun e ->
754            not ((Indexing.in_index active_table e) ||
755                   (Indexing.in_index passive_table e)))
756   in
757   new_neg, List.filter subs (List.filter is_duplicate new_pos)
758 ;;
759
760
761 (** simplifies active usign new *)
762 let backward_simplify_active env new_pos new_table min_weight active =
763   let active_list, active_table = active in
764   let active_list, newa = 
765     List.fold_right
766       (fun (s, equality) (res, newn) ->
767          let ew, _, _, _ = equality in
768          if ew < min_weight then
769            (s, equality)::res, newn
770          else
771            match forward_simplify env (s, equality) (new_pos, new_table) with
772            | None -> res, newn
773            | Some (s, e) ->
774                if equality = e then
775                  (s, e)::res, newn
776                else 
777                  res, (s, e)::newn)
778       active_list ([], [])
779   in
780   let find eq1 where =
781     List.exists (fun (s, e) -> meta_convertibility_eq eq1 e) where
782   in
783   let active, newa =
784     List.fold_right
785       (fun (s, eq) (res, tbl) ->
786          if List.mem (s, eq) res then
787            res, tbl
788          else if (is_identity env eq) || (find eq res) then (
789            res, tbl
790          ) 
791          else
792            (s, eq)::res, if s = Negative then tbl else Indexing.index tbl eq)
793       active_list ([], Indexing.empty),
794     List.fold_right
795       (fun (s, eq) (n, p) ->
796          if (s <> Negative) && (is_identity env eq) then (
797            (n, p)
798          ) else
799            if s = Negative then eq::n, p
800            else n, eq::p)
801       newa ([], [])
802   in
803   match newa with
804   | [], [] -> active, None
805   | _ -> active, Some newa
806 ;;
807
808
809 (** simplifies passive using new *)
810 let backward_simplify_passive env new_pos new_table min_weight passive =
811   let (nl, ns), (pl, ps), passive_table = passive in
812   let f sign equality (resl, ress, newn) =
813     let ew, _, _, _ = equality in
814     if ew < min_weight then
815       equality::resl, ress, newn
816     else
817       match forward_simplify env (sign, equality) (new_pos, new_table) with
818       | None -> resl, EqualitySet.remove equality ress, newn
819       | Some (s, e) ->
820           if equality = e then
821             equality::resl, ress, newn
822           else
823             let ress = EqualitySet.remove equality ress in
824             resl, ress, e::newn
825   in
826   let nl, ns, newn = List.fold_right (f Negative) nl ([], ns, [])
827   and pl, ps, newp = List.fold_right (f Positive) pl ([], ps, []) in
828   let passive_table =
829     List.fold_left
830       (fun tbl e -> Indexing.index tbl e) Indexing.empty pl
831   in
832   match newn, newp with
833   | [], [] -> ((nl, ns), (pl, ps), passive_table), None
834   | _, _ -> ((nl, ns), (pl, ps), passive_table), Some (newn, newp)
835 ;;
836
837
838 let backward_simplify env new' ?passive active =
839   let new_pos, new_table, min_weight =
840     List.fold_left
841       (fun (l, t, w) e ->
842          let ew, _, _, _ = e in
843          (Positive, e)::l, Indexing.index t e, min ew w)
844       ([], Indexing.empty, 1000000) (snd new')
845   in
846   let active, newa =
847     backward_simplify_active env new_pos new_table min_weight active in
848   match passive with
849   | None ->
850       active, (make_passive [] []), newa, None
851   | Some passive ->
852      active, passive, newa, None
853 (* prova
854       let passive, newp =
855         backward_simplify_passive env new_pos new_table min_weight passive in
856       active, passive, newa, newp *)
857 ;;
858
859
860 let close env new' given =
861   let new_pos, new_table, min_weight =
862     List.fold_left
863       (fun (l, t, w) e ->
864          let ew, _, _, _ = e in
865          (Positive, e)::l, Indexing.index t e, min ew w)
866       ([], Indexing.empty, 1000000) (snd new')
867   in
868   List.fold_left
869     (fun (n,p) (s,c) ->
870        let neg,pos = infer env s c (new_pos,new_table) in
871          neg@n,pos@p)
872     ([],[]) given 
873 ;;
874
875 let is_commutative_law eq =
876   let w, proof, (eq_ty, left, right, order), metas = snd eq in
877     match left,right with
878         Cic.Appl[f1;Cic.Meta _ as a1;Cic.Meta _ as b1], 
879         Cic.Appl[f2;Cic.Meta _ as a2;Cic.Meta _ as b2] ->
880           f1 = f2 && a1 = b2 && a2 = b1
881       | _ -> false
882 ;;
883
884 let prova env new' active = 
885   let given = List.filter is_commutative_law (fst active) in
886   let _ =
887     debug_print
888       (lazy
889          (Printf.sprintf "symmetric:\n%s\n"
890             (String.concat "\n"
891                ((List.map
892                    (fun (s, e) -> (string_of_sign s) ^ " " ^
893                       (string_of_equality ~env e))
894                    (given)))))) in
895     close env new' given
896 ;;
897
898 (* returns an estimation of how many equalities in passive can be activated
899    within the current time limit *)
900 let get_selection_estimate () =
901   elapsed_time := (Unix.gettimeofday ()) -. !start_time;
902   (*   !processed_clauses * (int_of_float (!time_limit /. !elapsed_time)) *)
903   int_of_float (
904     ceil ((float_of_int !processed_clauses) *.
905             ((!time_limit (* *. 2. *)) /. !elapsed_time -. 1.)))
906 ;;
907
908
909 (** initializes the set of goals *)
910 let make_goals goal =
911   let active = []
912   and passive = [0, [goal]] in
913   active, passive
914 ;;
915
916
917 (** initializes the set of theorems *)
918 let make_theorems theorems =
919   theorems, []
920 ;;
921
922
923 let activate_goal (active, passive) =
924   match passive with
925   | goal_conj::tl -> true, (goal_conj::active, tl)
926   | [] -> false, (active, passive)
927 ;;
928
929
930 let activate_theorem (active, passive) =
931   match passive with
932   | theorem::tl -> true, (theorem::active, tl)
933   | [] -> false, (active, passive)
934 ;;
935
936
937 (** simplifies a goal with equalities in active and passive *)  
938 let simplify_goal env goal ?passive (active_list, active_table) =
939   let pl, passive_table =
940     match passive with
941     | None -> [], None
942     | Some ((pn, _), (pp, _), pt) ->
943         let pn = List.map (fun e -> (Negative, e)) pn
944         and pp = List.map (fun e -> (Positive, e)) pp in
945         pn @ pp, Some pt
946   in
947
948   let demodulate table goal = 
949     let newmeta, newgoal =
950       Indexing.demodulation_goal !maxmeta env table goal in
951     maxmeta := newmeta;
952     goal != newgoal, newgoal
953   in
954   let changed, goal =
955     match passive_table with
956     | None -> demodulate active_table goal
957     | Some passive_table ->
958         let changed, goal = demodulate active_table goal in
959         let changed', goal = demodulate passive_table goal in
960         (changed || changed'), goal
961   in
962   changed, goal
963 ;;
964
965
966 let simplify_goals env goals ?passive active =
967   let a_goals, p_goals = goals in
968   let p_goals = 
969     List.map
970       (fun (d, gl) ->
971          let gl =
972            List.map (fun g -> snd (simplify_goal env g ?passive active)) gl in
973          d, gl)
974       p_goals
975   in
976   let goals =
977     List.fold_left
978       (fun (a, p) (d, gl) ->
979          let changed = ref false in
980          let gl =
981            List.map
982              (fun g ->
983                 let c, g = simplify_goal env g ?passive active in
984                 changed := !changed || c; g) gl in
985          if !changed then (a, (d, gl)::p) else ((d, gl)::a, p))
986       ([], p_goals) a_goals
987   in
988   goals
989 ;;
990
991
992 let simplify_theorems env theorems ?passive (active_list, active_table) =
993   let pl, passive_table =
994     match passive with
995     | None -> [], None
996     | Some ((pn, _), (pp, _), pt) ->
997         let pn = List.map (fun e -> (Negative, e)) pn
998         and pp = List.map (fun e -> (Positive, e)) pp in
999         pn @ pp, Some pt
1000   in
1001   let a_theorems, p_theorems = theorems in
1002   let demodulate table theorem =
1003     let newmeta, newthm =
1004       Indexing.demodulation_theorem !maxmeta env table theorem in
1005     maxmeta := newmeta;
1006     theorem != newthm, newthm
1007   in
1008   let foldfun table (a, p) theorem =
1009     let changed, theorem = demodulate table theorem in
1010     if changed then (a, theorem::p) else (theorem::a, p)
1011   in
1012   let mapfun table theorem = snd (demodulate table theorem) in
1013   match passive_table with
1014   | None ->
1015       let p_theorems = List.map (mapfun active_table) p_theorems in
1016       List.fold_left (foldfun active_table) ([], p_theorems) a_theorems
1017   | Some passive_table ->
1018       let p_theorems = List.map (mapfun active_table) p_theorems in
1019       let p_theorems, a_theorems =
1020         List.fold_left (foldfun active_table) ([], p_theorems) a_theorems in
1021       let p_theorems = List.map (mapfun passive_table) p_theorems in
1022       List.fold_left (foldfun passive_table) ([], p_theorems) a_theorems
1023 ;;
1024
1025
1026 let rec simpl env e others others_simpl =
1027   let active = others @ others_simpl in
1028   let tbl =
1029     List.fold_left
1030       (fun t (_, e) -> Indexing.index t e)
1031       Indexing.empty active
1032   in
1033   let res = forward_simplify env e (active, tbl) in
1034     match others with
1035       | hd::tl -> (
1036           match res with
1037             | None -> simpl env hd tl others_simpl
1038             | Some e -> simpl env hd tl (e::others_simpl)
1039         )
1040       | [] -> (
1041           match res with
1042             | None -> others_simpl
1043             | Some e -> e::others_simpl
1044         )
1045 ;;
1046
1047 let simplify_equalities env equalities =
1048   debug_print
1049     (lazy 
1050        (Printf.sprintf "equalities:\n%s\n"
1051           (String.concat "\n"
1052              (List.map string_of_equality equalities))));
1053   debug_print (lazy "SIMPLYFYING EQUALITIES...");
1054   match equalities with
1055     | [] -> []
1056     | hd::tl ->
1057         let others = List.map (fun e -> (Positive, e)) tl in
1058         let res =
1059           List.rev (List.map snd (simpl env (Positive, hd) others []))
1060         in
1061           debug_print
1062             (lazy
1063                (Printf.sprintf "equalities AFTER:\n%s\n"
1064                   (String.concat "\n"
1065                      (List.map string_of_equality res))));
1066           res
1067 ;;
1068
1069 (* applies equality to goal to see if the goal can be closed *)
1070 let apply_equality_to_goal env equality goal =
1071   let module C = Cic in
1072   let module HL = HelmLibraryObjects in
1073   let module I = Inference in
1074   let metasenv, context, ugraph = env in
1075   let _, proof, (ty, left, right, _), metas = equality in
1076   let eqterm =
1077     C.Appl [C.MutInd (LibraryObjects.eq_URI (), 0, []); ty; left; right] in
1078   let gproof, gmetas, gterm = goal in
1079 (*   debug_print *)
1080 (*     (lazy *)
1081 (*        (Printf.sprintf "APPLY EQUALITY TO GOAL: %s, %s" *)
1082 (*           (string_of_equality equality) (CicPp.ppterm gterm))); *)
1083   try
1084     let subst, metasenv', _ =
1085       let menv = metasenv @ metas @ gmetas in
1086       Inference.unification metas gmetas context eqterm gterm ugraph
1087     in
1088     let newproof =
1089       match proof with
1090       | I.BasicProof t -> I.BasicProof (CicMetaSubst.apply_subst subst t)
1091       | I.ProofBlock (s, uri, nt, t, pe, p) ->
1092           I.ProofBlock (subst @ s, uri, nt, t, pe, p)
1093       | _ -> assert false
1094     in
1095     let newgproof =
1096       let rec repl = function
1097         | I.ProofGoalBlock (_, gp) -> I.ProofGoalBlock (newproof, gp)
1098         | I.NoProof -> newproof
1099         | I.BasicProof p -> newproof
1100         | I.SubProof (t, i, p) -> I.SubProof (t, i, repl p)
1101         | _ -> assert false
1102       in
1103       repl gproof
1104     in
1105     true, subst, newgproof
1106   with CicUnification.UnificationFailure _ ->
1107     false, [], I.NoProof
1108 ;;
1109
1110
1111
1112 let new_meta metasenv =
1113   let m = CicMkImplicit.new_meta metasenv [] in
1114   incr maxmeta;
1115   while !maxmeta <= m do incr maxmeta done;
1116   !maxmeta
1117 ;;
1118
1119
1120 (* applies a theorem or an equality to goal, returning a list of subgoals or
1121    an indication of failure *)
1122 let apply_to_goal env theorems ?passive active goal =
1123   let metasenv, context, ugraph = env in
1124   let proof, metas, term = goal in
1125   (*   debug_print *)
1126   (*     (lazy *)
1127   (*        (Printf.sprintf "apply_to_goal with goal: %s" *)
1128   (*           (\* (string_of_proof proof)  *\)(CicPp.ppterm term))); *)
1129   let status =
1130     let irl =
1131       CicMkImplicit.identity_relocation_list_for_metavariable context in
1132     let proof', newmeta =
1133       let rec get_meta = function
1134         | SubProof (t, i, p) ->
1135             let t', i' = get_meta p in
1136             if i' = -1 then t, i else t', i'
1137         | ProofGoalBlock (_, p) -> get_meta p
1138         | _ -> Cic.Implicit None, -1
1139       in
1140       let p, m = get_meta proof in
1141       if m = -1 then
1142         let n = new_meta (metasenv @ metas) in
1143         Cic.Meta (n, irl), n
1144       else
1145         p, m
1146     in
1147     let metasenv = (newmeta, context, term)::metasenv @ metas in
1148     let bit = new_meta metasenv, context, term in 
1149     let metasenv' = bit::metasenv in
1150     ((None, metasenv', Cic.Meta (newmeta, irl), term), newmeta)
1151   in
1152   let rec aux = function
1153     | [] -> `No
1154     | (theorem, thmty, _)::tl ->
1155         try
1156           let subst, (newproof, newgoals) =
1157             PrimitiveTactics.apply_tac_verbose_with_subst ~term:theorem status
1158           in
1159           if newgoals = [] then
1160             let _, _, p, _ = newproof in
1161             let newp =
1162               let rec repl = function
1163                 | Inference.ProofGoalBlock (_, gp) ->
1164                     Inference.ProofGoalBlock (Inference.BasicProof p, gp)
1165                 | Inference.NoProof -> Inference.BasicProof p
1166                 | Inference.BasicProof _ -> Inference.BasicProof p
1167                 | Inference.SubProof (t, i, p2) ->
1168                     Inference.SubProof (t, i, repl p2)
1169                 | _ -> assert false
1170               in
1171               repl proof
1172             in
1173             let _, m = status in
1174             let subst = List.filter (fun (i, _) -> i = m) subst in
1175             `Ok (subst, [newp, metas, term])
1176           else
1177             let _, menv, p, _ = newproof in
1178             let irl =
1179               CicMkImplicit.identity_relocation_list_for_metavariable context
1180             in
1181             let goals =
1182               List.map
1183                 (fun i ->
1184                    let _, _, ty = CicUtil.lookup_meta i menv in
1185                    let p' =
1186                      let rec gp = function
1187                        | SubProof (t, i, p) ->
1188                            SubProof (t, i, gp p)
1189                        | ProofGoalBlock (sp1, sp2) ->
1190                            ProofGoalBlock (sp1, gp sp2)
1191                        | BasicProof _
1192                        | NoProof ->
1193                            SubProof (p, i, BasicProof (Cic.Meta (i, irl)))
1194                        | ProofSymBlock (s, sp) ->
1195                            ProofSymBlock (s, gp sp)
1196                        | ProofBlock (s, u, nt, t, pe, sp) ->
1197                            ProofBlock (s, u, nt, t, pe, gp sp)
1198                      in gp proof
1199                    in
1200                    (p', menv, ty))
1201                 newgoals
1202             in
1203             let goals =
1204               let weight t =
1205                 let w, m = weight_of_term t in
1206                 w + 2 * (List.length m)
1207               in
1208               List.sort
1209                 (fun (_, _, t1) (_, _, t2) ->
1210                    Pervasives.compare (weight t1) (weight t2))
1211                 goals
1212             in
1213             let best = aux tl in
1214             match best with
1215             | `Ok (_, _) -> best
1216             | `No -> `GoOn ([subst, goals])
1217             | `GoOn sl -> `GoOn ((subst, goals)::sl)
1218         with ProofEngineTypes.Fail msg ->
1219           aux tl
1220   in
1221   let r, s, l =
1222     if Inference.term_is_equality term then
1223       let rec appleq_a = function
1224         | [] -> false, [], []
1225         | (Positive, equality)::tl ->
1226             let ok, s, newproof = apply_equality_to_goal env equality goal in
1227             if ok then true, s, [newproof, metas, term] else appleq_a tl
1228         | _::tl -> appleq_a tl
1229       in
1230       let rec appleq_p = function
1231         | [] -> false, [], []
1232         | equality::tl ->
1233             let ok, s, newproof = apply_equality_to_goal env equality goal in
1234             if ok then true, s, [newproof, metas, term] else appleq_p tl
1235       in
1236       let al, _ = active in
1237       match passive with
1238       | None -> appleq_a al
1239       | Some (_, (pl, _), _) ->
1240           let r, s, l = appleq_a al in if r then r, s, l else appleq_p pl
1241     else
1242       false, [], []
1243   in
1244   if r = true then `Ok (s, l) else aux theorems
1245 ;;
1246
1247
1248 (* sorts a conjunction of goals in order to detect earlier if it is
1249    unsatisfiable. Non-predicate goals are placed at the end of the list *)
1250 let sort_goal_conj (metasenv, context, ugraph) (depth, gl) =
1251   let gl = 
1252     List.stable_sort
1253       (fun (_, e1, g1) (_, e2, g2) ->
1254          let ty1, _ =
1255            CicTypeChecker.type_of_aux' (e1 @ metasenv) context g1 ugraph 
1256          and ty2, _ =
1257            CicTypeChecker.type_of_aux' (e2 @ metasenv) context g2 ugraph
1258          in
1259          let prop1 =
1260            let b, _ =
1261              CicReduction.are_convertible context (Cic.Sort Cic.Prop) ty1 ugraph
1262            in
1263            if b then 0 else 1
1264          and prop2 =
1265            let b, _ =
1266              CicReduction.are_convertible context (Cic.Sort Cic.Prop) ty2 ugraph
1267            in
1268            if b then 0 else 1
1269          in
1270          if prop1 = 0 && prop2 = 0 then
1271            let e1 = if Inference.term_is_equality g1 then 0 else 1
1272            and e2 = if Inference.term_is_equality g2 then 0 else 1 in
1273            e1 - e2
1274          else
1275            prop1 - prop2)
1276       gl
1277   in
1278   (depth, gl)
1279 ;;
1280
1281
1282 let is_meta_closed goals =
1283   List.for_all (fun (_, _, g) -> CicUtil.is_meta_closed g) goals
1284 ;;
1285
1286
1287 (* applies a series of theorems/equalities to a conjunction of goals *)
1288 let rec apply_to_goal_conj env theorems ?passive active (depth, goals) =
1289   let aux (goal, r) tl =
1290     let propagate_subst subst (proof, metas, term) =
1291       let rec repl = function
1292         | NoProof -> NoProof 
1293         | BasicProof t ->
1294             BasicProof (CicMetaSubst.apply_subst subst t)
1295         | ProofGoalBlock (p, pb) ->
1296             let pb' = repl pb in
1297             ProofGoalBlock (p, pb')
1298         | SubProof (t, i, p) ->
1299             let t' = CicMetaSubst.apply_subst subst t in
1300             let p = repl p in
1301             SubProof (t', i, p)
1302         | ProofSymBlock (ens, p) -> ProofSymBlock (ens, repl p)
1303         | ProofBlock (s, u, nty, t, pe, p) ->
1304             ProofBlock (subst @ s, u, nty, t, pe, p)
1305       in (repl proof, metas, term)
1306     in
1307     (* let r = apply_to_goal env theorems ?passive active goal in *) (
1308       match r with
1309       | `No -> `No (depth, goals)
1310       | `GoOn sl ->
1311           let l =
1312             List.map
1313               (fun (s, gl) ->
1314                  let tl = List.map (propagate_subst s) tl in
1315                  sort_goal_conj env (depth+1, gl @ tl)) sl
1316           in
1317           `GoOn l
1318       | `Ok (subst, gl) ->
1319           if tl = [] then
1320             `Ok (depth, gl)
1321           else
1322             let p, _, _ = List.hd gl in
1323             let subproof =
1324               let rec repl = function
1325                 | SubProof (_, _, p) -> repl p
1326                 | ProofGoalBlock (p1, p2) ->
1327                     ProofGoalBlock (repl p1, repl p2)
1328                 | p -> p
1329               in
1330               build_proof_term (repl p)
1331             in
1332             let i = 
1333               let rec get_meta = function
1334                 | SubProof (_, i, p) ->
1335                     let i' = get_meta p in
1336                     if i' = -1 then i else i'
1337 (*                         max i (get_meta p) *)
1338                 | ProofGoalBlock (_, p) -> get_meta p
1339                 | _ -> -1
1340               in
1341               get_meta p
1342             in
1343             let subst =
1344               let _, (context, _, _) = List.hd subst in
1345               [i, (context, subproof, Cic.Implicit None)]
1346             in
1347             let tl = List.map (propagate_subst subst) tl in
1348             let conj = sort_goal_conj env (depth(* +1 *), tl) in
1349             `GoOn ([conj])
1350     )
1351   in
1352   if depth > !maxdepth || (List.length goals) > !maxwidth then 
1353     `No (depth, goals)
1354   else
1355     let rec search_best res = function
1356       | [] -> res
1357       | goal::tl ->
1358           let r = apply_to_goal env theorems ?passive active goal in
1359           match r with
1360           | `Ok _ -> (goal, r)
1361           | `No -> search_best res tl
1362           | `GoOn l ->
1363               let newres = 
1364                 match res with
1365                 | _, `Ok _ -> assert false
1366                 | _, `No -> goal, r
1367                 | _, `GoOn l2 ->
1368                     if (List.length l) < (List.length l2) then goal, r else res
1369               in
1370               search_best newres tl
1371     in
1372     let hd = List.hd goals in
1373     let res = hd, (apply_to_goal env theorems ?passive active hd) in
1374     let best =
1375       match res with
1376       | _, `Ok _ -> res
1377       | _, _ -> search_best res (List.tl goals)
1378     in
1379     let res = aux best (List.filter (fun g -> g != (fst best)) goals) in
1380     match res with
1381     | `GoOn ([conj]) when is_meta_closed (snd conj) &&
1382         (List.length (snd conj)) < (List.length goals)->
1383         apply_to_goal_conj env theorems ?passive active conj
1384     | _ -> res
1385 ;;
1386
1387
1388 (*
1389 module OrderedGoals = struct
1390   type t = int * (Inference.proof * Cic.metasenv * Cic.term) list
1391
1392   let compare g1 g2 =
1393     let d1, l1 = g1
1394     and d2, l2 = g2 in
1395     let r = d2 - d1 in
1396     if r <> 0 then r
1397     else let r = (List.length l1) - (List.length l2) in
1398     if r <> 0 then r
1399     else
1400       let res = ref 0 in
1401       let _ = 
1402         List.exists2
1403           (fun (_, _, t1) (_, _, t2) ->
1404              let r = Pervasives.compare t1 t2 in
1405              if r <> 0 then (
1406                res := r;
1407                true
1408              ) else
1409                false) l1 l2
1410       in !res
1411 end
1412
1413 module GoalsSet = Set.Make(OrderedGoals);;
1414
1415
1416 exception SearchSpaceOver;;
1417 *)
1418
1419
1420 (*
1421 let apply_to_goals env is_passive_empty theorems active goals =
1422   debug_print (lazy "\n\n\tapply_to_goals\n\n");
1423   let add_to set goals =
1424     List.fold_left (fun s g -> GoalsSet.add g s) set goals 
1425   in
1426   let rec aux set = function
1427     | [] ->
1428         debug_print (lazy "HERE!!!");
1429         if is_passive_empty then raise SearchSpaceOver else false, set
1430     | goals::tl ->
1431         let res = apply_to_goal_conj env theorems active goals in
1432         match res with
1433         | `Ok newgoals ->
1434             let _ =
1435               let d, p, t =
1436                 match newgoals with
1437                 | (d, (p, _, t)::_) -> d, p, t
1438                 | _ -> assert false
1439               in
1440               debug_print
1441                 (lazy
1442                    (Printf.sprintf "\nOK!!!!\ndepth: %d\nProof: %s\ngoal: %s\n"
1443                       d (string_of_proof p) (CicPp.ppterm t)))
1444             in
1445             true, GoalsSet.singleton newgoals
1446         | `GoOn newgoals ->
1447             let set' = add_to set (goals::tl) in
1448             let set' = add_to set' newgoals in
1449             false, set'
1450         | `No newgoals ->
1451             aux set tl
1452   in
1453   let n = List.length goals in
1454   let res, goals = aux (add_to GoalsSet.empty goals) goals in
1455   let goals = GoalsSet.elements goals in
1456   debug_print (lazy "\n\tapply_to_goals end\n");
1457   let m = List.length goals in
1458   if m = n && is_passive_empty then
1459     raise SearchSpaceOver
1460   else
1461     res, goals
1462 ;;
1463 *)
1464
1465
1466 (* sorts the list of passive goals to minimize the search for a proof (doesn't
1467    work that well yet...) *)
1468 let sort_passive_goals goals =
1469   List.stable_sort
1470     (fun (d1, l1) (d2, l2) ->
1471        let r1 = d2 - d1 
1472        and r2 = (List.length l1) - (List.length l2) in
1473        let foldfun ht (_, _, t) = 
1474          let _ = List.map (fun i -> Hashtbl.replace ht i 1) (metas_of_term t)
1475          in ht
1476        in
1477        let m1 = Hashtbl.length (List.fold_left foldfun (Hashtbl.create 3) l1)
1478        and m2 = Hashtbl.length (List.fold_left foldfun (Hashtbl.create 3) l2)
1479        in let r3 = m1 - m2 in
1480        if r3 <> 0 then r3
1481        else if r2 <> 0 then r2 
1482        else r1)
1483     (*          let _, _, g1 = List.hd l1 *)
1484 (*          and _, _, g2 = List.hd l2 in *)
1485 (*          let e1 = if Inference.term_is_equality g1 then 0 else 1 *)
1486 (*          and e2 = if Inference.term_is_equality g2 then 0 else 1 *)
1487 (*          in let r4 = e1 - e2 in *)
1488 (*          if r4 <> 0 then r3 else r1) *)
1489     goals
1490 ;;
1491
1492
1493 let print_goals goals = 
1494   (String.concat "\n"
1495      (List.map
1496         (fun (d, gl) ->
1497            let gl' =
1498              List.map
1499                (fun (p, _, t) ->
1500                   (* (string_of_proof p) ^ ", " ^ *) (CicPp.ppterm t)) gl
1501            in
1502            Printf.sprintf "%d: %s" d (String.concat "; " gl')) goals))
1503 ;;
1504
1505
1506 (* tries to prove the first conjunction in goals with applications of
1507    theorems/equalities, returning new sub-goals or an indication of success *)
1508 let apply_goal_to_theorems dbd env theorems ?passive active goals =
1509   let theorems, _ = theorems in
1510   let a_goals, p_goals = goals in
1511   let goal = List.hd a_goals in
1512   let not_in_active gl =
1513     not
1514       (List.exists
1515          (fun (_, gl') ->
1516             if (List.length gl) = (List.length gl') then
1517               List.for_all2 (fun (_, _, g1) (_, _, g2) -> g1 = g2) gl gl'
1518             else
1519               false)
1520          a_goals)
1521   in
1522   let aux theorems =
1523     let res = apply_to_goal_conj env theorems ?passive active goal in
1524     match res with
1525     | `Ok newgoals ->
1526         true, ([newgoals], [])
1527     | `No _ ->
1528         false, (a_goals, p_goals)
1529     | `GoOn newgoals ->
1530         let newgoals =
1531           List.filter
1532             (fun (d, gl) ->
1533                (d <= !maxdepth) && (List.length gl) <= !maxwidth &&
1534                  not_in_active gl)
1535             newgoals in
1536         let p_goals = newgoals @ p_goals in
1537         let p_goals = sort_passive_goals p_goals in
1538         false, (a_goals, p_goals)
1539   in
1540   aux theorems
1541 ;;
1542
1543
1544 let apply_theorem_to_goals env theorems active goals =
1545   let a_goals, p_goals = goals in
1546   let theorem = List.hd (fst theorems) in
1547   let theorems = [theorem] in
1548   let rec aux p = function
1549     | [] -> false, ([], p)
1550     | goal::tl ->
1551         let res = apply_to_goal_conj env theorems active goal in
1552         match res with
1553         | `Ok newgoals -> true, ([newgoals], [])
1554         | `No _ -> aux p tl
1555         | `GoOn newgoals -> aux (newgoals @ p) tl
1556   in
1557   let ok, (a, p) = aux p_goals a_goals in
1558   if ok then
1559     ok, (a, p)
1560   else
1561     let p_goals =
1562       List.stable_sort
1563         (fun (d1, l1) (d2, l2) ->
1564            let r = d2 - d1 in
1565            if r <> 0 then r
1566            else let r = (List.length l1) - (List.length l2) in
1567            if r <> 0 then r
1568            else
1569              let res = ref 0 in
1570              let _ = 
1571                List.exists2
1572                  (fun (_, _, t1) (_, _, t2) ->
1573                     let r = Pervasives.compare t1 t2 in
1574                     if r <> 0 then (res := r; true) else false) l1 l2
1575              in !res)
1576         p
1577     in
1578     ok, (a_goals, p_goals)
1579 ;;
1580
1581
1582 (* given-clause algorithm with lazy reduction strategy *)
1583 let rec given_clause dbd env goals theorems passive active =
1584   let _,context,_ = env in 
1585   let goals = simplify_goals env goals active in
1586   let ok, goals = activate_goal goals in
1587   (*   let theorems = simplify_theorems env theorems active in *)
1588   if ok then
1589     let ok, goals = apply_goal_to_theorems dbd env theorems active goals in
1590     if ok then
1591       let proof =
1592         match (fst goals) with
1593         | (_, [proof, _, _])::_ -> Some proof
1594         | _ -> assert false
1595       in
1596       ParamodulationSuccess (proof, env)
1597     else
1598       given_clause_aux dbd env goals theorems passive active
1599   else
1600 (*     let ok', theorems = activate_theorem theorems in *)
1601     let ok', theorems = false, theorems in
1602     if ok' then
1603       let ok, goals = apply_theorem_to_goals env theorems active goals in
1604       if ok then
1605         let proof =
1606           match (fst goals) with
1607           | (_, [proof, _, _])::_ -> Some proof
1608           | _ -> assert false
1609         in
1610         ParamodulationSuccess (proof, env)
1611       else
1612         given_clause_aux dbd env goals theorems passive active
1613     else
1614       if (passive_is_empty passive) then ParamodulationFailure
1615       else given_clause_aux dbd env goals theorems passive active
1616
1617 and given_clause_aux dbd env goals theorems passive active = 
1618   let _,context,_ = env in
1619   let time1 = Unix.gettimeofday () in
1620  
1621   let selection_estimate = get_selection_estimate () in
1622   let kept = size_of_passive passive in
1623   let passive =
1624     if !time_limit = 0. || !processed_clauses = 0 then
1625       passive
1626     else if !elapsed_time > !time_limit then (
1627       debug_print (lazy (Printf.sprintf "Time limit (%.2f) reached: %.2f\n"
1628                            !time_limit !elapsed_time));
1629       make_passive [] []
1630     ) else if kept > selection_estimate then (
1631       debug_print
1632         (lazy (Printf.sprintf ("Too many passive equalities: pruning..." ^^
1633                                  "(kept: %d, selection_estimate: %d)\n")
1634                  kept selection_estimate));
1635       prune_passive selection_estimate active passive
1636     ) else
1637       passive
1638   in
1639
1640   let time2 = Unix.gettimeofday () in
1641   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
1642
1643   kept_clauses := (size_of_passive passive) + (size_of_active active);
1644   match passive_is_empty passive with
1645   | true -> (* ParamodulationFailure *)
1646       given_clause dbd env goals theorems passive active
1647   | false ->
1648       let (sign, current), passive = select env (fst goals) passive active in
1649       let names = List.map (HExtlib.map_option (fun (name,_) -> name)) context in 
1650       prerr_endline ("Selected = " ^ 
1651                        (CicPp.pp (Inference.term_of_equality current) names));
1652       let time1 = Unix.gettimeofday () in
1653       let res = forward_simplify env (sign, current) ~passive active in
1654       let time2 = Unix.gettimeofday () in
1655       forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
1656       match res with
1657       | None ->
1658           given_clause dbd env goals theorems passive active
1659       | Some (sign, current) ->
1660           if (sign = Negative) && (is_identity env current) then (
1661             debug_print
1662               (lazy (Printf.sprintf "OK!!! %s %s" (string_of_sign sign)
1663                        (string_of_equality ~env current)));
1664             let _, proof, _, _ = current in
1665             ParamodulationSuccess (Some proof, env)
1666           ) else (           
1667             debug_print
1668               (lazy "\n================================================");
1669             debug_print (lazy (Printf.sprintf "selected: %s %s"
1670                                  (string_of_sign sign)
1671                                  (string_of_equality ~env current)));
1672
1673             let t1 = Unix.gettimeofday () in
1674             let new' = infer env sign current active in
1675             let t2 = Unix.gettimeofday () in
1676             infer_time := !infer_time +. (t2 -. t1);
1677             
1678             let res, goal' = contains_empty env new' in
1679             if res then
1680               let proof =
1681                 match goal' with
1682                 | Some goal -> let _, proof, _, _ = goal in Some proof
1683                 | None -> None
1684               in
1685               ParamodulationSuccess (proof, env)
1686             else 
1687               let t1 = Unix.gettimeofday () in
1688               let new' = forward_simplify_new env new' active in
1689               let t2 = Unix.gettimeofday () in
1690               let _ =
1691                 forward_simpl_new_time :=
1692                   !forward_simpl_new_time +. (t2 -. t1)
1693               in
1694               let active =
1695                 match sign with
1696                 | Negative -> active
1697                 | Positive ->
1698                     let t1 = Unix.gettimeofday () in
1699                     let active, _, newa, _ =
1700                       backward_simplify env ([], [current]) active
1701                     in
1702                     let t2 = Unix.gettimeofday () in
1703                     backward_simpl_time :=
1704                       !backward_simpl_time +. (t2 -. t1);
1705                     match newa with
1706                     | None -> active
1707                     | Some (n, p) ->
1708                         let al, tbl = active in
1709                         let nn = List.map (fun e -> Negative, e) n in
1710                         let pp, tbl =
1711                           List.fold_right
1712                             (fun e (l, t) ->
1713                                (Positive, e)::l,
1714                                Indexing.index tbl e)
1715                             p ([], tbl)
1716                         in
1717                         nn @ al @ pp, tbl
1718               in
1719               match contains_empty env new' with
1720               | false, _ -> 
1721                   let active =
1722                     let al, tbl = active in
1723                     match sign with
1724                     | Negative -> (sign, current)::al, tbl
1725                     | Positive ->
1726                         al @ [(sign, current)], Indexing.index tbl current
1727                   in
1728                   let passive = add_to_passive passive new' in
1729                   given_clause dbd env goals theorems passive active
1730               | true, goal ->
1731                   let proof =
1732                     match goal with
1733                     | Some goal ->
1734                         let _, proof, _, _ = goal in Some proof
1735                     | None -> None
1736                   in
1737                   ParamodulationSuccess (proof, env)
1738           )
1739 ;;
1740
1741
1742 (** given-clause algorithm with full reduction strategy *)
1743 let rec given_clause_fullred dbd env goals theorems passive active =
1744   let goals = simplify_goals env goals ~passive active in 
1745   let _,context,_ = env in
1746   let ok, goals = activate_goal goals in
1747 (*   let theorems = simplify_theorems env theorems ~passive active in *)
1748   if ok then
1749     let names = List.map (HExtlib.map_option (fun (name,_) -> name)) context in 
1750     let _, _, t = List.hd (snd (List.hd (fst goals))) in
1751     let _ = prerr_endline ("goal activated = " ^ (CicPp.pp t names)) in
1752 (*     let _ = *)
1753 (*       debug_print *)
1754 (*         (lazy *)
1755 (*            (Printf.sprintf "\ngoals = \nactive\n%s\npassive\n%s\n" *)
1756 (*               (print_goals (fst goals)) (print_goals (snd goals)))); *)
1757 (*       let current = List.hd (fst goals) in *)
1758 (*       let p, _, t = List.hd (snd current) in *)
1759 (*       debug_print *)
1760 (*         (lazy *)
1761 (*            (Printf.sprintf "goal activated:\n%s\n%s\n" *)
1762 (*               (CicPp.ppterm t) (string_of_proof p))); *)
1763 (*     in *)
1764     let ok, goals =
1765       apply_goal_to_theorems dbd env theorems ~passive active goals
1766     in
1767     if ok then
1768       let proof =
1769         match (fst goals) with
1770         | (_, [proof, _, _])::_ -> Some proof
1771         | _ -> assert false
1772       in
1773       ( prerr_endline "esco qui";
1774         (*
1775         let s = Printf.sprintf "actives:\n%s\n"
1776           (String.concat "\n"
1777              ((List.map
1778                  (fun (s, e) -> (string_of_sign s) ^ " " ^
1779                     (string_of_equality ~env e))
1780                  (fst active)))) in
1781         let sp = Printf.sprintf "passives:\n%s\n"
1782           (String.concat "\n"
1783              (List.map
1784                 (string_of_equality ~env)
1785                 (let x,y,_ = passive in (fst x)@(fst y)))) in
1786           prerr_endline s;
1787           prerr_endline sp; *)
1788       ParamodulationSuccess (proof, env))
1789     else
1790       given_clause_fullred_aux dbd env goals theorems passive active
1791   else
1792 (*     let ok', theorems = activate_theorem theorems in *)
1793 (*     if ok' then *)
1794 (*       let ok, goals = apply_theorem_to_goals env theorems active goals in *)
1795 (*       if ok then *)
1796 (*         let proof = *)
1797 (*           match (fst goals) with *)
1798 (*           | (_, [proof, _, _])::_ -> Some proof *)
1799 (*           | _ -> assert false *)
1800 (*         in *)
1801 (*         ParamodulationSuccess (proof, env) *)
1802 (*       else *)
1803 (*         given_clause_fullred_aux env goals theorems passive active *)
1804 (*     else *)
1805       if (passive_is_empty passive) then ParamodulationFailure
1806       else given_clause_fullred_aux dbd env goals theorems passive active
1807     
1808 and given_clause_fullred_aux dbd env goals theorems passive active =
1809   prerr_endline ("MAXMETA: " ^ string_of_int !maxmeta ^ 
1810                  " LOCALMAX: " ^ string_of_int !Indexing.local_max ^
1811                  " #ACTIVES: " ^ string_of_int (size_of_active active) ^
1812                  " #PASSIVES: " ^ string_of_int (size_of_passive passive));
1813 (*
1814   if (size_of_active active) mod 50 = 0 then
1815     (let s = Printf.sprintf "actives:\n%s\n"
1816       (String.concat "\n"
1817          ((List.map
1818              (fun (s, e) -> (string_of_sign s) ^ " " ^
1819                 (string_of_equality ~env e))
1820              (fst active)))) in
1821      let sp = Printf.sprintf "passives:\n%s\n"
1822       (String.concat "\n"
1823          (List.map
1824              (string_of_equality ~env)
1825              (let x,y,_ = passive in (fst x)@(fst y)))) in
1826       prerr_endline s;
1827       prerr_endline sp); *)
1828   let time1 = Unix.gettimeofday () in
1829   let (_,context,_) = env in
1830   let selection_estimate = get_selection_estimate () in
1831   let kept = size_of_passive passive in
1832   let passive =
1833     if !time_limit = 0. || !processed_clauses = 0 then
1834       passive
1835     else if !elapsed_time > !time_limit then (
1836       debug_print (lazy (Printf.sprintf "Time limit (%.2f) reached: %.2f\n"
1837                            !time_limit !elapsed_time));
1838       make_passive [] []
1839     ) else if kept > selection_estimate then (
1840       debug_print
1841         (lazy (Printf.sprintf ("Too many passive equalities: pruning..." ^^
1842                                  "(kept: %d, selection_estimate: %d)\n")
1843                  kept selection_estimate));
1844       prune_passive selection_estimate active passive
1845     ) else
1846       passive
1847   in
1848
1849   let time2 = Unix.gettimeofday () in
1850   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
1851   
1852   kept_clauses := (size_of_passive passive) + (size_of_active active);
1853   match passive_is_empty passive with
1854   | true -> (* ParamodulationFailure *)
1855       given_clause_fullred dbd env goals theorems passive active        
1856   | false ->
1857       let (sign, current), passive = select env (fst goals) passive active in
1858       let names = List.map (HExtlib.map_option (fun (name,_) -> name)) context in 
1859       prerr_endline ("Selected = " ^ (string_of_sign sign) ^ " " ^ 
1860                      string_of_equality ~env current);
1861                   (* (CicPp.pp (Inference.term_of_equality current) names));*)
1862       let time1 = Unix.gettimeofday () in
1863       let res = forward_simplify env (sign, current) ~passive active in
1864       let time2 = Unix.gettimeofday () in
1865       forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
1866       match res with
1867       | None ->
1868           (* weight_age_counter := !weight_age_counter + 1; *)
1869           given_clause_fullred dbd env goals theorems passive active
1870       | Some (sign, current) ->
1871           if (sign = Negative) && (is_identity env current) then (
1872             debug_print
1873               (lazy (Printf.sprintf "OK!!! %s %s" (string_of_sign sign)
1874                        (string_of_equality ~env current)));
1875             let _, proof, _, _ = current in 
1876             ParamodulationSuccess (Some proof, env)
1877           ) else (
1878             debug_print
1879               (lazy "\n================================================");
1880             debug_print (lazy (Printf.sprintf "selected: %s %s"
1881                                  (string_of_sign sign)
1882                                  (string_of_equality ~env current)));
1883
1884             let t1 = Unix.gettimeofday () in
1885             let new' = infer env sign current active in
1886             let _ =
1887               match new' with
1888               | neg, pos ->
1889                   debug_print
1890                     (lazy
1891                        (Printf.sprintf "new' (senza semplificare):\n%s\n"
1892                           (String.concat "\n"
1893                              ((List.map
1894                                  (fun e -> "Negative " ^
1895                                     (string_of_equality ~env e)) neg) @
1896                                 (List.map
1897                                    (fun e -> "Positive " ^
1898                                       (string_of_equality ~env e)) pos)))))
1899             in
1900             let t2 = Unix.gettimeofday () in
1901             infer_time := !infer_time +. (t2 -. t1);
1902             let active =
1903               if is_identity env current then active
1904               else
1905                 let al, tbl = active in
1906                 match sign with
1907                 | Negative -> (sign, current)::al, tbl
1908                 | Positive ->
1909                     al @ [(sign, current)], Indexing.index tbl current
1910             in
1911             let rec simplify new' active passive =
1912               let t1 = Unix.gettimeofday () in
1913               let new' = forward_simplify_new env new' ~passive active in
1914               let t2 = Unix.gettimeofday () in
1915               forward_simpl_new_time :=
1916                 !forward_simpl_new_time +. (t2 -. t1);
1917               let t1 = Unix.gettimeofday () in
1918               let active, passive, newa, retained =
1919                 backward_simplify env new' ~passive active in
1920               let t2 = Unix.gettimeofday () in
1921                 backward_simpl_time := !backward_simpl_time +. (t2 -. t1);
1922               match newa, retained with
1923               | None, None -> active, passive, new'
1924               | Some (n, p), None
1925               | None, Some (n, p) ->
1926                   let nn, np = new' in
1927                     if Utils.debug_metas then
1928                       ignore (
1929                         List.map (fun x -> Indexing.check_target context x "simplify1")n;
1930                         List.map (fun x -> Indexing.check_target context x "simplify2")p);
1931                   simplify (nn @ n, np @ p) active passive
1932               | Some (n, p), Some (rn, rp) ->
1933                   let nn, np = new' in
1934                   simplify (nn @ n @ rn, np @ p @ rp) active passive
1935             in
1936             let active, passive, new' = simplify new' active passive in
1937 (* pessima prova 
1938             let new1 = prova env new' active in
1939             let new' = (fst new') @ (fst new1), (snd new') @ (snd new1) in
1940             let _ =
1941               match new1 with
1942               | neg, pos ->
1943                   debug_print
1944                     (lazy
1945                        (Printf.sprintf "new1:\n%s\n"
1946                           (String.concat "\n"
1947                              ((List.map
1948                                  (fun e -> "Negative " ^
1949                                     (string_of_equality ~env e)) neg) @
1950                                 (List.map
1951                                    (fun e -> "Positive " ^
1952                                       (string_of_equality ~env e)) pos)))))
1953             in
1954 end prova *)
1955             let k = size_of_passive passive in
1956             if k < (kept - 1) then
1957               processed_clauses := !processed_clauses + (kept - 1 - k);
1958             
1959             let _ =
1960               debug_print
1961                 (lazy
1962                    (Printf.sprintf "active:\n%s\n"
1963                       (String.concat "\n"
1964                          ((List.map
1965                              (fun (s, e) -> (string_of_sign s) ^ " " ^
1966                                 (string_of_equality ~env e))
1967                              (fst active))))))
1968             in
1969             let _ =
1970               match new' with
1971               | neg, pos ->
1972                   debug_print
1973                     (lazy
1974                        (Printf.sprintf "new':\n%s\n"
1975                           (String.concat "\n"
1976                              ((List.map
1977                                  (fun e -> "Negative " ^
1978                                     (string_of_equality ~env e)) neg) @
1979                                 (List.map
1980                                    (fun e -> "Positive " ^
1981                                       (string_of_equality ~env e)) pos)))))
1982             in
1983             match contains_empty env new' with
1984             | false, _ -> 
1985                 let passive = add_to_passive passive new' in
1986                 given_clause_fullred dbd env goals theorems passive active
1987             | true, goal ->
1988                 let proof =
1989                   match goal with
1990                   | Some goal -> let _, proof, _, _ = goal in Some proof
1991                   | None -> None
1992                 in
1993                 ParamodulationSuccess (proof, env)
1994           )
1995 ;;
1996
1997
1998 let rec saturate_equations env goal accept_fun passive active =
1999   elapsed_time := Unix.gettimeofday () -. !start_time;
2000   if !elapsed_time > !time_limit then
2001     (active, passive)
2002   else
2003     let (sign, current), passive = select env [1, [goal]] passive active in
2004     let res = forward_simplify env (sign, current) ~passive active in
2005     match res with
2006     | None ->
2007         saturate_equations env goal accept_fun passive active
2008     | Some (sign, current) ->
2009         assert (sign = Positive);
2010         debug_print
2011           (lazy "\n================================================");
2012         debug_print (lazy (Printf.sprintf "selected: %s %s"
2013                              (string_of_sign sign)
2014                              (string_of_equality ~env current)));
2015         let new' = infer env sign current active in
2016         let active =
2017           if is_identity env current then active
2018           else
2019             let al, tbl = active in
2020             al @ [(sign, current)], Indexing.index tbl current
2021         in
2022         let rec simplify new' active passive =
2023           let new' = forward_simplify_new env new' ~passive active in
2024           let active, passive, newa, retained =
2025             backward_simplify env new' ~passive active in
2026           match newa, retained with
2027           | None, None -> active, passive, new'
2028           | Some (n, p), None
2029           | None, Some (n, p) ->
2030               let nn, np = new' in
2031               simplify (nn @ n, np @ p) active passive
2032           | Some (n, p), Some (rn, rp) ->
2033               let nn, np = new' in
2034               simplify (nn @ n @ rn, np @ p @ rp) active passive
2035         in
2036         let active, passive, new' = simplify new' active passive in
2037         let _ =
2038           debug_print
2039             (lazy
2040                (Printf.sprintf "active:\n%s\n"
2041                   (String.concat "\n"
2042                      ((List.map
2043                          (fun (s, e) -> (string_of_sign s) ^ " " ^
2044                             (string_of_equality ~env e))
2045                          (fst active))))))
2046         in
2047         let _ =
2048           match new' with
2049           | neg, pos ->
2050               debug_print
2051                 (lazy
2052                    (Printf.sprintf "new':\n%s\n"
2053                       (String.concat "\n"
2054                          ((List.map
2055                              (fun e -> "Negative " ^
2056                                 (string_of_equality ~env e)) neg) @
2057                             (List.map
2058                                (fun e -> "Positive " ^
2059                                   (string_of_equality ~env e)) pos)))))
2060         in
2061         let new' = match new' with _, pos -> [], List.filter accept_fun pos in
2062         let passive = add_to_passive passive new' in
2063         saturate_equations env goal accept_fun passive active
2064 ;;
2065   
2066
2067
2068
2069 let main dbd full term metasenv ugraph =
2070   let module C = Cic in
2071   let module T = CicTypeChecker in
2072   let module PET = ProofEngineTypes in
2073   let module PP = CicPp in
2074   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
2075   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
2076   let proof, goals = status in
2077   let goal' = List.nth goals 0 in
2078   let _, metasenv, meta_proof, _ = proof in
2079   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
2080   let eq_indexes, equalities, maxm = find_equalities context proof in
2081   let lib_eq_uris, library_equalities, maxm =
2082
2083     find_library_equalities dbd context (proof, goal') (maxm+2)
2084   in
2085   let library_equalities = List.map snd library_equalities in
2086   maxmeta := maxm+2; (* TODO ugly!! *)
2087   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
2088   let new_meta_goal, metasenv, type_of_goal =
2089     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
2090     debug_print
2091       (lazy
2092          (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n\n" (CicPp.ppterm ty)));
2093     Cic.Meta (maxm+1, irl),
2094     (maxm+1, context, ty)::metasenv,
2095     ty
2096   in
2097   let env = (metasenv, context, ugraph) in
2098   let t1 = Unix.gettimeofday () in
2099   let theorems =
2100     if full then
2101       let theorems = find_library_theorems dbd env (proof, goal') lib_eq_uris in
2102       let context_hyp = find_context_hypotheses env eq_indexes in
2103       context_hyp @ theorems, []
2104     else
2105       let refl_equal =
2106         let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
2107         UriManager.uri_of_string (us ^ "#xpointer(1/1/1)")
2108       in
2109       let t = CicUtil.term_of_uri refl_equal in
2110       let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
2111       [(t, ty, [])], []
2112   in
2113   let t2 = Unix.gettimeofday () in
2114   debug_print
2115     (lazy
2116        (Printf.sprintf "Time to retrieve theorems: %.9f\n" (t2 -. t1)));
2117   let _ =
2118     debug_print
2119       (lazy
2120          (Printf.sprintf
2121             "Theorems:\n-------------------------------------\n%s\n"
2122             (String.concat "\n"
2123                (List.map
2124                   (fun (t, ty, _) ->
2125                      Printf.sprintf
2126                        "Term: %s, type: %s" (CicPp.ppterm t) (CicPp.ppterm ty))
2127                   (fst theorems)))))
2128   in
2129   (*try*)
2130     let goal = Inference.BasicProof new_meta_goal, [], goal in
2131     let equalities = simplify_equalities env 
2132       (equalities@library_equalities) in 
2133     let active = make_active () in
2134     let passive = make_passive [] equalities in
2135     Printf.printf "\ncurrent goal: %s\n"
2136       (let _, _, g = goal in CicPp.ppterm g);
2137     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
2138     Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
2139     Printf.printf "\nequalities:\n%s\n"
2140       (String.concat "\n"
2141          (List.map
2142             (string_of_equality ~env) equalities));
2143 (*             (equalities @ library_equalities))); *)
2144       print_endline "--------------------------------------------------";
2145       let start = Unix.gettimeofday () in
2146       print_endline "GO!";
2147       start_time := Unix.gettimeofday ();
2148       let res =
2149         let goals = make_goals goal in
2150         (if !use_fullred then given_clause_fullred else given_clause)
2151           dbd env goals theorems passive active
2152       in
2153       let finish = Unix.gettimeofday () in
2154       let _ =
2155         match res with
2156         | ParamodulationFailure ->
2157             Printf.printf "NO proof found! :-(\n\n"
2158         | ParamodulationSuccess (Some proof, env) ->
2159             let proof = Inference.build_proof_term proof in
2160             Printf.printf "OK, found a proof!\n";
2161             (* REMEMBER: we have to instantiate meta_proof, we should use
2162                apply  the "apply" tactic to proof and status 
2163             *)
2164             let names = names_of_context context in
2165             print_endline (PP.pp proof names);
2166             let newmetasenv =
2167               List.fold_left
2168                 (fun m (_, _, _, menv) -> m @ menv) metasenv equalities
2169             in
2170             let _ =
2171               (*try*)
2172                 let ty, ug =
2173                   CicTypeChecker.type_of_aux' newmetasenv context proof ugraph
2174                 in
2175                 print_endline (string_of_float (finish -. start));
2176                 Printf.printf
2177                   "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n\n"
2178                   (CicPp.pp type_of_goal names) (CicPp.pp ty names)
2179                   (string_of_bool
2180                      (fst (CicReduction.are_convertible
2181                              context type_of_goal ty ug)));
2182               (*with e ->
2183                 Printf.printf "\nEXCEPTION!!! %s\n" (Printexc.to_string e);
2184                 Printf.printf "MAXMETA USED: %d\n" !maxmeta;
2185                 print_endline (string_of_float (finish -. start));*)
2186             in
2187             ()
2188               
2189         | ParamodulationSuccess (None, env) ->
2190             Printf.printf "Success, but no proof?!?\n\n"
2191       in
2192         if Utils.time then
2193           begin
2194             prerr_endline 
2195               ((Printf.sprintf ("infer_time: %.9f\nforward_simpl_time: %.9f\n" ^^
2196                        "forward_simpl_new_time: %.9f\n" ^^
2197                        "backward_simpl_time: %.9f\n")
2198               !infer_time !forward_simpl_time !forward_simpl_new_time
2199               !backward_simpl_time) ^
2200               (Printf.sprintf "beta_expand_time: %.9f\n"
2201                  !Indexing.beta_expand_time) ^
2202               (Printf.sprintf "passive_maintainance_time: %.9f\n"
2203                  !passive_maintainance_time) ^
2204               (Printf.sprintf "    successful unification/matching time: %.9f\n"
2205                  !Indexing.match_unif_time_ok) ^
2206               (Printf.sprintf "    failed unification/matching time: %.9f\n"
2207                  !Indexing.match_unif_time_no) ^
2208               (Printf.sprintf "    indexing retrieval time: %.9f\n"
2209                  !Indexing.indexing_retrieval_time) ^
2210               (Printf.sprintf "    demodulate_term.build_newtarget_time: %.9f\n"
2211                  !Indexing.build_newtarget_time) ^
2212               (Printf.sprintf "derived %d clauses, kept %d clauses.\n"
2213                  !derived_clauses !kept_clauses)) 
2214             end
2215 (*
2216   with exc ->
2217     print_endline ("EXCEPTION: " ^ (Printexc.to_string exc));
2218     raise exc
2219 *)
2220 ;;
2221
2222
2223 let default_depth = !maxdepth
2224 and default_width = !maxwidth;;
2225
2226 let reset_refs () =
2227   maxmeta := 0;
2228   Indexing.local_max := 100;
2229   symbols_counter := 0;
2230   weight_age_counter := !weight_age_ratio;
2231   processed_clauses := 0;
2232   start_time := 0.;
2233   elapsed_time := 0.;
2234   maximal_retained_equality := None;
2235   infer_time := 0.;
2236   forward_simpl_time := 0.;
2237   forward_simpl_new_time := 0.;
2238   backward_simpl_time := 0.;
2239   passive_maintainance_time := 0.;
2240   derived_clauses := 0;
2241   kept_clauses := 0;
2242   Indexing.beta_expand_time := 0.;
2243   Inference.metas_of_proof_time := 0.;
2244 ;;
2245
2246 let saturate
2247     dbd ?(full=false) ?(depth=default_depth) ?(width=default_width) status = 
2248   let module C = Cic in
2249   reset_refs ();
2250   Indexing.init_index ();
2251   maxdepth := depth;
2252   maxwidth := width;
2253   let proof, goal = status in
2254   let goal' = goal in
2255   let uri, metasenv, meta_proof, term_to_prove = proof in
2256   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
2257   let eq_indexes, equalities, maxm = find_equalities context proof in
2258   let new_meta_goal, metasenv, type_of_goal =
2259     let irl =
2260       CicMkImplicit.identity_relocation_list_for_metavariable context in
2261     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
2262     debug_print
2263       (lazy (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n" (CicPp.ppterm ty)));
2264     Cic.Meta (maxm+1, irl),
2265     (maxm+1, context, ty)::metasenv,
2266     ty
2267   in
2268   let ugraph = CicUniv.empty_ugraph in
2269   let env = (metasenv, context, ugraph) in
2270   let goal = Inference.BasicProof new_meta_goal, [], goal in
2271   let res, time =
2272     let t1 = Unix.gettimeofday () in
2273     let lib_eq_uris, library_equalities, maxm =
2274       find_library_equalities dbd context (proof, goal') (maxm+2)
2275     in
2276     let library_equalities = List.map snd library_equalities in
2277     let t2 = Unix.gettimeofday () in
2278     maxmeta := maxm+2;
2279     let equalities = simplify_equalities env (equalities@library_equalities) in 
2280     debug_print
2281       (lazy
2282          (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)));
2283     let t1 = Unix.gettimeofday () in
2284     let theorems =
2285       if full then
2286         let thms = find_library_theorems dbd env (proof, goal') lib_eq_uris in
2287         let context_hyp = find_context_hypotheses env eq_indexes in
2288         context_hyp @ thms, []
2289       else
2290         let refl_equal =
2291           let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
2292           UriManager.uri_of_string (us ^ "#xpointer(1/1/1)")
2293         in
2294         let t = CicUtil.term_of_uri refl_equal in
2295         let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
2296         [(t, ty, [])], []
2297     in
2298     let t2 = Unix.gettimeofday () in
2299     let _ =
2300       debug_print
2301         (lazy
2302            (Printf.sprintf
2303               "Theorems:\n-------------------------------------\n%s\n"
2304               (String.concat "\n"
2305                  (List.map
2306                     (fun (t, ty, _) ->
2307                        Printf.sprintf
2308                          "Term: %s, type: %s"
2309                          (CicPp.ppterm t) (CicPp.ppterm ty))
2310                     (fst theorems)))));
2311       debug_print
2312         (lazy
2313            (Printf.sprintf "Time to retrieve theorems: %.9f\n" (t2 -. t1)));
2314     in
2315     let active = make_active () in
2316     let passive = make_passive [] equalities in
2317     let start = Unix.gettimeofday () in
2318     let res =
2319       let goals = make_goals goal in
2320       given_clause_fullred dbd env goals theorems passive active
2321     in
2322     let finish = Unix.gettimeofday () in
2323     (res, finish -. start)
2324   in
2325   match res with
2326   | ParamodulationSuccess (Some proof, env) ->
2327       debug_print (lazy "OK, found a proof!");
2328       let proof = Inference.build_proof_term proof in
2329       let names = names_of_context context in
2330       let newmetasenv =
2331         let i1 =
2332           match new_meta_goal with
2333           | C.Meta (i, _) -> i | _ -> assert false
2334         in
2335         List.filter (fun (i, _, _) -> i <> i1 && i <> goal') metasenv
2336       in
2337       let newstatus =
2338         try
2339           let ty, ug =
2340             CicTypeChecker.type_of_aux' newmetasenv context proof ugraph
2341           in
2342           debug_print (lazy (CicPp.pp proof [](* names *)));
2343           debug_print
2344             (lazy
2345                (Printf.sprintf
2346                   "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n"
2347                   (CicPp.pp type_of_goal names) (CicPp.pp ty names)
2348                   (string_of_bool
2349                      (fst (CicReduction.are_convertible
2350                              context type_of_goal ty ug)))));
2351           let equality_for_replace i t1 =
2352             match t1 with
2353             | C.Meta (n, _) -> n = i
2354             | _ -> false
2355           in
2356           let real_proof =
2357             ProofEngineReduction.replace
2358               ~equality:equality_for_replace
2359               ~what:[goal'] ~with_what:[proof]
2360               ~where:meta_proof
2361           in
2362           debug_print
2363             (lazy
2364                (Printf.sprintf "status:\n%s\n%s\n%s\n%s\n"
2365                   (match uri with Some uri -> UriManager.string_of_uri uri
2366                    | None -> "")
2367                   (print_metasenv newmetasenv)
2368                   (CicPp.pp real_proof [](* names *))
2369                   (CicPp.pp term_to_prove names)));
2370           ((uri, newmetasenv, real_proof, term_to_prove), [])
2371         with CicTypeChecker.TypeCheckerFailure _ ->
2372           debug_print (lazy "THE PROOF DOESN'T TYPECHECK!!!");
2373           debug_print (lazy (CicPp.pp proof names));
2374           raise (ProofEngineTypes.Fail
2375                   (lazy "Found a proof, but it doesn't typecheck"))
2376       in
2377       let tall = fs_time_info.build_all in
2378       let tdemodulate = fs_time_info.demodulate in
2379       let tsubsumption = fs_time_info.subsumption in
2380       if Utils.time then
2381         begin
2382           prerr_endline (
2383             (Printf.sprintf "\nTIME NEEDED: %.9f" time) ^
2384               (Printf.sprintf "\ntall: %.9f" tall) ^
2385               (Printf.sprintf "\ntdemod: %.9f" tdemodulate) ^
2386               (Printf.sprintf "\ntsubsumption: %.9f" tsubsumption) ^
2387               (Printf.sprintf "\ninfer_time: %.9f" !infer_time) ^
2388               (Printf.sprintf "\nbeta_expand_time: %.9f\n"
2389                  !Indexing.beta_expand_time) ^
2390               (Printf.sprintf "\nmetas_of_proof: %.9f\n"
2391                  !Inference.metas_of_proof_time) ^
2392               (Printf.sprintf "\nforward_simpl_times: %.9f" !forward_simpl_time) ^
2393               (Printf.sprintf "\nforward_simpl_new_times: %.9f" 
2394                  !forward_simpl_new_time) ^
2395               (Printf.sprintf "\nbackward_simpl_times: %.9f" !backward_simpl_time) ^
2396               (Printf.sprintf "\npassive_maintainance_time: %.9f" 
2397                  !passive_maintainance_time))
2398         end;
2399       newstatus          
2400   | _ ->
2401       raise (ProofEngineTypes.Fail (lazy "NO proof found"))
2402 ;;
2403
2404 (* dummy function called within matita to trigger linkage *)
2405 let init () = ();;
2406
2407
2408 let retrieve_and_print dbd term metasenv ugraph = 
2409   let module C = Cic in
2410   let module T = CicTypeChecker in
2411   let module PET = ProofEngineTypes in
2412   let module PP = CicPp in
2413   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
2414   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
2415   let proof, goals = status in
2416   let goal' = List.nth goals 0 in
2417   let uri, metasenv, meta_proof, term_to_prove = proof in
2418   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
2419   let eq_indexes, equalities, maxm = find_equalities context proof in
2420   let new_meta_goal, metasenv, type_of_goal =
2421     let irl =
2422       CicMkImplicit.identity_relocation_list_for_metavariable context in
2423     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
2424     debug_print
2425       (lazy (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n" (CicPp.ppterm ty)));
2426     Cic.Meta (maxm+1, irl),
2427     (maxm+1, context, ty)::metasenv,
2428     ty
2429   in
2430   let ugraph = CicUniv.empty_ugraph in
2431   let env = (metasenv, context, ugraph) in
2432   let t1 = Unix.gettimeofday () in
2433   let lib_eq_uris, library_equalities, maxm =
2434     find_library_equalities dbd context (proof, goal') (maxm+2) in
2435   let t2 = Unix.gettimeofday () in
2436   maxmeta := maxm+2;
2437   let equalities = (* equalities @ *) library_equalities in
2438   debug_print
2439      (lazy
2440         (Printf.sprintf "\n\nequalities:\n%s\n"
2441            (String.concat "\n"
2442               (List.map 
2443           (fun (u, e) ->
2444 (*               Printf.sprintf "%s: %s" *)
2445                    (UriManager.string_of_uri u)
2446 (*                 (string_of_equality e) *)
2447                      )
2448           equalities))));
2449   debug_print (lazy "RETR: SIMPLYFYING EQUALITIES...");
2450   let rec simpl e others others_simpl =
2451     let (u, e) = e in
2452     let active = List.map (fun (u, e) -> (Positive, e))
2453       (others @ others_simpl) in
2454     let tbl =
2455       List.fold_left
2456         (fun t (_, e) -> Indexing.index t e)
2457         Indexing.empty active
2458     in
2459     let res = forward_simplify env (Positive, e) (active, tbl) in
2460     match others with
2461         | hd::tl -> (
2462             match res with
2463               | None -> simpl hd tl others_simpl
2464               | Some e -> simpl hd tl ((u, (snd e))::others_simpl)
2465           )
2466         | [] -> (
2467             match res with
2468               | None -> others_simpl
2469               | Some e -> (u, (snd e))::others_simpl
2470           ) 
2471   in
2472   let _equalities =
2473     match equalities with
2474       | [] -> []
2475       | hd::tl ->
2476           let others = tl in (* List.map (fun e -> (Positive, e)) tl in *)
2477           let res =
2478             List.rev (simpl (*(Positive,*) hd others [])
2479           in
2480             debug_print
2481               (lazy
2482                  (Printf.sprintf "\nequalities AFTER:\n%s\n"
2483                     (String.concat "\n"
2484                        (List.map
2485                           (fun (u, e) ->
2486                              Printf.sprintf "%s: %s"
2487                                (UriManager.string_of_uri u)
2488                                (string_of_equality e)
2489                           )
2490                           res))));
2491             res in
2492     debug_print
2493       (lazy
2494          (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)))
2495 ;;
2496
2497
2498 let main_demod_equalities dbd term metasenv ugraph =
2499   let module C = Cic in
2500   let module T = CicTypeChecker in
2501   let module PET = ProofEngineTypes in
2502   let module PP = CicPp in
2503   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
2504   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
2505   let proof, goals = status in
2506   let goal' = List.nth goals 0 in
2507   let _, metasenv, meta_proof, _ = proof in
2508   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
2509   let eq_indexes, equalities, maxm = find_equalities context proof in
2510   let lib_eq_uris, library_equalities, maxm =
2511     find_library_equalities dbd context (proof, goal') (maxm+2)
2512   in
2513   let library_equalities = List.map snd library_equalities in
2514   maxmeta := maxm+2; (* TODO ugly!! *)
2515   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
2516   let new_meta_goal, metasenv, type_of_goal =
2517     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
2518     debug_print
2519       (lazy
2520          (Printf.sprintf "\n\nTRYING TO INFER EQUALITIES MATCHING: %s\n\n"
2521             (CicPp.ppterm ty)));
2522     Cic.Meta (maxm+1, irl),
2523     (maxm+1, context, ty)::metasenv,
2524     ty
2525   in
2526   let env = (metasenv, context, ugraph) in
2527   (*try*)
2528     let goal = Inference.BasicProof new_meta_goal, [], goal in
2529     let equalities = simplify_equalities env (equalities@library_equalities) in
2530     let active = make_active () in
2531     let passive = make_passive [] equalities in
2532     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
2533     Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
2534     Printf.printf "\nequalities:\n%s\n"
2535       (String.concat "\n"
2536          (List.map
2537             (string_of_equality ~env) equalities));
2538     print_endline "--------------------------------------------------";
2539     print_endline "GO!";
2540     start_time := Unix.gettimeofday ();
2541     if !time_limit < 1. then time_limit := 60.;    
2542     let ra, rp =
2543       saturate_equations env goal (fun e -> true) passive active
2544     in
2545
2546     let initial =
2547       List.fold_left (fun s e -> EqualitySet.add e s)
2548         EqualitySet.empty equalities
2549     in
2550     let addfun s e = 
2551       if not (EqualitySet.mem e initial) then EqualitySet.add e s else s
2552     in
2553
2554     let passive =
2555       match rp with
2556       | (n, _), (p, _), _ ->
2557           EqualitySet.elements (List.fold_left addfun EqualitySet.empty p)
2558     in
2559     let active =
2560       let l = List.map snd (fst ra) in
2561       EqualitySet.elements (List.fold_left addfun EqualitySet.empty l)
2562     in
2563     Printf.printf "\n\nRESULTS:\nActive:\n%s\n\nPassive:\n%s\n"
2564        (String.concat "\n" (List.map (string_of_equality ~env) active)) 
2565      (*  (String.concat "\n"
2566          (List.map (fun e -> CicPp.ppterm (term_of_equality e)) active)) *)
2567 (*       (String.concat "\n" (List.map (string_of_equality ~env) passive)); *)
2568       (String.concat "\n"
2569          (List.map (fun e -> CicPp.ppterm (term_of_equality e)) passive));
2570     print_newline ();
2571 (*
2572   with e ->
2573     debug_print (lazy ("EXCEPTION: " ^ (Printexc.to_string e)))
2574 *)
2575 ;;
2576
2577 let demodulate_tac ~dbd ~pattern ((proof,goal) as initialstatus) = 
2578   let module I = Inference in
2579   let curi,metasenv,pbo,pty = proof in
2580   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
2581   let eq_indexes, equalities, maxm = I.find_equalities context proof in
2582   let lib_eq_uris, library_equalities, maxm =
2583     I.find_library_equalities dbd context (proof, goal) (maxm+2) in
2584   if library_equalities = [] then prerr_endline "VUOTA!!!";
2585   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
2586   let library_equalities = List.map snd library_equalities in
2587   let goalterm = Cic.Meta (metano,irl) in
2588   let initgoal = Inference.BasicProof goalterm, [], ty in
2589   let env = (metasenv, context, CicUniv.empty_ugraph) in
2590   let equalities = simplify_equalities env (equalities@library_equalities) in   
2591   let table = 
2592     List.fold_left 
2593       (fun tbl eq -> Indexing.index tbl eq) 
2594       Indexing.empty equalities 
2595   in
2596   let newmeta,(newproof,newmetasenv, newty) = Indexing.demodulation_goal 
2597     maxm (metasenv,context,CicUniv.empty_ugraph) table initgoal 
2598   in
2599   if newmeta != maxm then
2600     begin
2601       let opengoal = Cic.Meta(maxm,irl) in
2602       let proofterm = 
2603         Inference.build_proof_term ~noproof:opengoal newproof in
2604         let extended_metasenv = (maxm,context,newty)::metasenv in
2605         let extended_status = 
2606           (curi,extended_metasenv,pbo,pty),goal in
2607         let (status,newgoals) = 
2608           ProofEngineTypes.apply_tactic 
2609             (PrimitiveTactics.apply_tac ~term:proofterm)
2610             extended_status in
2611         (status,maxm::newgoals)
2612     end
2613   else if newty = ty then
2614     raise (ProofEngineTypes.Fail (lazy "no progress"))
2615   else ProofEngineTypes.apply_tactic 
2616     (ReductionTactics.simpl_tac ~pattern) 
2617     initialstatus
2618 ;;
2619
2620 let demodulate_tac ~dbd ~pattern = 
2621   ProofEngineTypes.mk_tactic (demodulate_tac ~dbd ~pattern)
2622 ;;