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