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