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