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