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