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