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