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