]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/tactics/paramodulation/saturation.ml
6a700d868a30fd792279e13affc4e7a0b10ae2d6
[helm.git] / helm / ocaml / 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 (*
32 for debugging 
33 let check_equation env equation msg =
34   let w, proof, (eq_ty, left, right, order), metas, args = equation in
35   let metasenv, context, ugraph = env in
36   let metasenv' = metasenv @ metas in
37     try
38       CicTypeChecker.type_of_aux' metasenv' context left ugraph;
39       CicTypeChecker.type_of_aux' metasenv' context right ugraph;
40       ()
41     with 
42         CicUtil.Meta_not_found _ as exn ->
43           begin
44             prerr_endline msg; 
45             prerr_endline (CicPp.ppterm left);
46             prerr_endline (CicPp.ppterm right);
47             raise exn
48           end 
49 *)
50
51 (* set to false to disable paramodulation inside auto_tac *)
52 let connect_to_auto = true;;
53
54
55 (* profiling statistics... *)
56 let infer_time = ref 0.;;
57 let forward_simpl_time = ref 0.;;
58 let forward_simpl_new_time = ref 0.;;
59 let backward_simpl_time = ref 0.;;
60 let passive_maintainance_time = ref 0.;;
61
62 (* limited-resource-strategy related globals *)
63 let processed_clauses = ref 0;; (* number of equalities selected so far... *)
64 let time_limit = ref 0.;; (* in seconds, settable by the user... *)
65 let start_time = ref 0.;; (* time at which the execution started *)
66 let elapsed_time = ref 0.;;
67 (* let maximal_weight = ref None;; *)
68 let maximal_retained_equality = ref None;;
69
70 (* equality-selection related globals *)
71 let use_fullred = ref true;;
72 let weight_age_ratio = ref (* 5 *) 4;; (* settable by the user *)
73 let weight_age_counter = ref !weight_age_ratio;;
74 let symbols_ratio = ref (* 0 *) 3;;
75 let symbols_counter = ref 0;;
76
77 (* non-recursive Knuth-Bendix term ordering by default *)
78 (* Utils.compare_terms := Utils.rpo;; *)
79 (* Utils.compare_terms := Utils.nonrec_kbo;; *)
80 (* Utils.compare_terms := Utils.ao;; *)
81
82 (* statistics... *)
83 let derived_clauses = ref 0;;
84 let kept_clauses = ref 0;;
85
86 (* index of the greatest Cic.Meta created - TODO: find a better way! *)
87 let maxmeta = ref 0;;
88
89 (* varbiables controlling the search-space *)
90 let maxdepth = ref 3;;
91 let maxwidth = ref 3;;
92
93
94 type result =
95   | ParamodulationFailure
96   | ParamodulationSuccess of Inference.proof option * environment
97 ;;
98
99 type goal = proof * Cic.metasenv * Cic.term;;
100
101 type theorem = Cic.term * Cic.term * Cic.metasenv;;
102
103 let symbols_of_equality (_, _, (_, left, right, _), _, _) =
104   let m1 = symbols_of_term left in
105   let m = 
106     TermMap.fold
107       (fun k v res ->
108          try
109            let c = TermMap.find k res in
110            TermMap.add k (c+v) res
111          with Not_found ->
112            TermMap.add k v res)
113       (symbols_of_term right) m1
114   in
115   m
116 ;;
117
118 module OrderedEquality = struct
119   type t = Inference.equality
120
121   let compare eq1 eq2 =
122     match meta_convertibility_eq eq1 eq2 with
123     | true -> 0
124     | false ->
125         let w1, _, (ty, left, right, _), _, a = eq1
126         and w2, _, (ty', left', right', _), _, a' = eq2 in
127         match Pervasives.compare w1 w2 with
128         | 0 ->
129             let res = (List.length a) - (List.length a') in
130             if res <> 0 then res else (
131               try
132                 let res = Pervasives.compare (List.hd a) (List.hd a') in
133                 if res <> 0 then res else Pervasives.compare eq1 eq2
134               with Failure "hd" -> Pervasives.compare eq1 eq2
135             )
136         | res -> res
137 end
138
139 module EqualitySet = Set.Make(OrderedEquality);;
140
141
142 (**
143    selects one equality from passive. The selection strategy is a combination
144    of weight, age and goal-similarity
145 *)
146 let select env goals passive (active, _) =
147   processed_clauses := !processed_clauses + 1;
148   let goal =
149     match (List.rev goals) with (_, goal::_)::_ -> goal | _ -> assert false
150   in
151   let (neg_list, neg_set), (pos_list, pos_set), passive_table = passive in
152   let remove eq l =
153     List.filter (fun e -> e <> eq) l
154   in
155   if !weight_age_ratio > 0 then
156     weight_age_counter := !weight_age_counter - 1;
157   match !weight_age_counter with
158   | 0 -> (
159       weight_age_counter := !weight_age_ratio;
160       match neg_list, pos_list with
161       | hd::tl, pos ->
162           (* Negatives aren't indexed, no need to remove them... *)
163           (Negative, hd),
164           ((tl, EqualitySet.remove hd neg_set), (pos, pos_set), passive_table)
165       | [], (hd:EqualitySet.elt)::tl ->
166           let passive_table =
167             Indexing.remove_index passive_table hd
168           in
169           (Positive, hd),
170           (([], neg_set), (tl, EqualitySet.remove hd pos_set), passive_table)
171       | _, _ -> assert false
172     )
173   | _ when (!symbols_counter > 0) && (EqualitySet.is_empty neg_set) -> (
174       symbols_counter := !symbols_counter - 1;
175       let cardinality map =
176         TermMap.fold (fun k v res -> res + v) map 0
177       in
178       let symbols =
179         let _, _, term = goal in
180         symbols_of_term term
181       in
182       let card = cardinality symbols in
183       let foldfun k v (r1, r2) = 
184         if TermMap.mem k symbols then
185           let c = TermMap.find k symbols in
186           let c1 = abs (c - v) in
187           let c2 = v - c1 in
188           r1 + c2, r2 + c1
189         else
190           r1, r2 + v
191       in
192       let f equality (i, e) =
193         let common, others =
194           TermMap.fold foldfun (symbols_of_equality equality) (0, 0)
195         in
196         let c = others + (abs (common - card)) in
197         if c < i then (c, equality)
198         else (i, e)
199       in
200       let e1 = EqualitySet.min_elt pos_set in
201       let initial =
202         let common, others = 
203           TermMap.fold foldfun (symbols_of_equality e1) (0, 0)
204         in
205         (others + (abs (common - card))), e1
206       in
207       let _, current = EqualitySet.fold f pos_set initial in
208       let passive_table =
209         Indexing.remove_index passive_table current
210       in
211       (Positive, current),
212       (([], neg_set),
213        (remove current pos_list, EqualitySet.remove current pos_set),
214        passive_table)
215     )
216   | _ ->
217       symbols_counter := !symbols_ratio;
218       let set_selection set = EqualitySet.min_elt set in
219       if EqualitySet.is_empty neg_set then
220         let current = set_selection pos_set in
221         let passive =
222           (neg_list, neg_set),
223           (remove current pos_list, EqualitySet.remove current pos_set),
224           Indexing.remove_index passive_table current
225         in
226         (Positive, current), passive
227       else
228         let current = set_selection neg_set in
229         let passive =
230           (remove current neg_list, EqualitySet.remove current neg_set),
231           (pos_list, pos_set),
232           passive_table
233         in
234         (Negative, current), passive
235 ;;
236
237
238 (* initializes the passive set of equalities *)
239 let make_passive neg pos =
240   let set_of equalities =
241     List.fold_left (fun s e -> EqualitySet.add e s) EqualitySet.empty equalities
242   in
243   let table =
244       List.fold_left (fun tbl e -> Indexing.index tbl e) Indexing.empty pos
245   in
246   (neg, set_of neg),
247   (pos, set_of pos),
248   table
249 ;;
250
251
252 let make_active () =
253   [], Indexing.empty
254 ;;
255
256
257 (* adds to passive a list of equalities: new_neg is a list of negative
258    equalities, new_pos a list of positive equalities *)
259 let add_to_passive passive (new_neg, new_pos) =
260   let (neg_list, neg_set), (pos_list, pos_set), table = passive in
261   let ok set equality = not (EqualitySet.mem equality set) in
262   let neg = List.filter (ok neg_set) new_neg
263   and pos = List.filter (ok pos_set) new_pos in
264   let table =
265     List.fold_left (fun tbl e -> Indexing.index tbl e) table pos
266   in
267   let add set equalities =
268     List.fold_left (fun s e -> EqualitySet.add e s) set equalities
269   in
270   (neg @ neg_list, add neg_set neg),
271   (pos_list @ pos, add pos_set pos),
272   table
273 ;;
274
275
276 let passive_is_empty = function
277   | ([], _), ([], _), _ -> true
278   | _ -> false
279 ;;
280
281
282 let size_of_passive ((_, ns), (_, ps), _) =
283   (EqualitySet.cardinal ns) + (EqualitySet.cardinal ps)
284 ;;
285
286
287 let size_of_active (active_list, _) =
288   List.length active_list
289 ;;
290
291
292 (* removes from passive equalities that are estimated impossible to activate
293    within the current time limit *)
294 let prune_passive howmany (active, _) passive =
295   let (nl, ns), (pl, ps), tbl = passive in
296   let howmany = float_of_int howmany
297   and ratio = float_of_int !weight_age_ratio in
298   let round v =
299     let t = ceil v in 
300     int_of_float (if t -. v < 0.5 then t else v)
301   in
302   let in_weight = round (howmany *. ratio /. (ratio +. 1.))
303   and in_age = round (howmany /. (ratio +. 1.)) in 
304   debug_print
305     (lazy (Printf.sprintf "in_weight: %d, in_age: %d\n" in_weight in_age));
306   let symbols, card =
307     match active with
308     | (Negative, e)::_ ->
309         let symbols = symbols_of_equality e in
310         let card = TermMap.fold (fun k v res -> res + v) symbols 0 in
311         Some symbols, card
312     | _ -> None, 0
313   in
314   let counter = ref !symbols_ratio in
315   let rec pickw w ns ps =
316     if w > 0 then
317       if not (EqualitySet.is_empty ns) then
318         let e = EqualitySet.min_elt ns in
319         let ns', ps = pickw (w-1) (EqualitySet.remove e ns) ps in
320         EqualitySet.add e ns', ps
321       else if !counter > 0 then
322         let _ =
323           counter := !counter - 1;
324           if !counter = 0 then counter := !symbols_ratio
325         in
326         match symbols with
327         | None ->
328             let e = EqualitySet.min_elt ps in
329             let ns, ps' = pickw (w-1) ns (EqualitySet.remove e ps) in
330             ns, EqualitySet.add e ps'
331         | Some symbols ->
332             let foldfun k v (r1, r2) =
333               if TermMap.mem k symbols then
334                 let c = TermMap.find k symbols in
335                 let c1 = abs (c - v) in
336                 let c2 = v - c1 in
337                 r1 + c2, r2 + c1
338               else
339                 r1, r2 + v
340             in
341             let f equality (i, e) =
342               let common, others =
343                 TermMap.fold foldfun (symbols_of_equality equality) (0, 0)
344               in
345               let c = others + (abs (common - card)) in
346               if c < i then (c, equality)
347               else (i, e)
348             in
349             let e1 = EqualitySet.min_elt ps in
350             let initial =
351               let common, others = 
352                 TermMap.fold foldfun (symbols_of_equality e1) (0, 0)
353               in
354               (others + (abs (common - card))), e1
355             in
356             let _, e = EqualitySet.fold f ps initial in
357             let ns, ps' = pickw (w-1) ns (EqualitySet.remove e ps) in
358             ns, EqualitySet.add e ps'
359       else
360         let e = EqualitySet.min_elt ps in
361         let ns, ps' = pickw (w-1) ns (EqualitySet.remove e ps) in
362         ns, EqualitySet.add e ps'        
363     else
364       EqualitySet.empty, EqualitySet.empty
365   in
366   let ns, ps = pickw in_weight ns ps in
367   let rec picka w s l =
368     if w > 0 then
369       match l with
370       | [] -> w, s, []
371       | hd::tl when not (EqualitySet.mem hd s) ->
372           let w, s, l = picka (w-1) s tl in
373           w, EqualitySet.add hd s, hd::l
374       | hd::tl ->
375           let w, s, l = picka w s tl in
376           w, s, hd::l
377     else
378       0, s, l
379   in
380   let in_age, ns, nl = picka in_age ns nl in
381   let _, ps, pl = picka in_age ps pl in
382   if not (EqualitySet.is_empty ps) then
383     maximal_retained_equality := Some (EqualitySet.max_elt ps); 
384   let tbl =
385     EqualitySet.fold
386       (fun e tbl -> Indexing.index tbl e) ps Indexing.empty
387   in
388   (nl, ns), (pl, ps), tbl  
389 ;;
390
391
392 (** inference of new equalities between current and some in active *)
393 let infer env sign current (active_list, active_table) =
394   let new_neg, new_pos = 
395     match sign with
396     | Negative ->
397         let maxm, res = 
398           Indexing.superposition_left !maxmeta env active_table current in
399         maxmeta := maxm;
400         res, [] 
401     | Positive ->
402         let maxm, res =
403           Indexing.superposition_right !maxmeta env active_table current in
404         maxmeta := maxm;
405         let rec infer_positive table = function
406           | [] -> [], []
407           | (Negative, equality)::tl ->
408               let maxm, res =
409                 Indexing.superposition_left !maxmeta env table equality in
410               maxmeta := maxm;
411               let neg, pos = infer_positive table tl in
412               res @ neg, pos
413           | (Positive, equality)::tl ->
414               let maxm, res =
415                 Indexing.superposition_right !maxmeta env table equality in
416               maxmeta := maxm;
417               let neg, pos = infer_positive table tl in
418               neg, res @ pos
419         in
420         let curr_table = Indexing.index Indexing.empty current in
421         let neg, pos = infer_positive curr_table active_list in
422         neg, res @ pos
423   in
424   derived_clauses := !derived_clauses + (List.length new_neg) +
425     (List.length new_pos);
426   match !maximal_retained_equality with
427   | None -> new_neg, new_pos
428   | Some eq ->
429       (* if we have a maximal_retained_equality, we can discard all equalities
430          "greater" than it, as they will never be reached...  An equality is
431          greater than maximal_retained_equality if it is bigger
432          wrt. OrderedEquality.compare and it is less similar than
433          maximal_retained_equality to the current goal *)
434       let symbols, card =
435         match active_list with
436         | (Negative, e)::_ ->
437             let symbols = symbols_of_equality e in
438             let card = TermMap.fold (fun k v res -> res + v) symbols 0 in
439             Some symbols, card
440         | _ -> None, 0
441       in
442       let new_pos = 
443         match symbols with
444         | None ->
445             List.filter (fun e -> OrderedEquality.compare e eq <= 0) new_pos
446         | Some symbols ->
447             let filterfun e =
448               if OrderedEquality.compare e eq <= 0 then
449                 true
450               else
451                 let foldfun k v (r1, r2) =
452                   if TermMap.mem k symbols then
453                     let c = TermMap.find k symbols in
454                     let c1 = abs (c - v) in
455                     let c2 = v - c1 in
456                     r1 + c2, r2 + c1
457                   else
458                     r1, r2 + v
459                 in
460                 let initial =
461                   let common, others =
462                     TermMap.fold foldfun (symbols_of_equality eq) (0, 0) in
463                   others + (abs (common - card))
464                 in
465                 let common, others =
466                   TermMap.fold foldfun (symbols_of_equality e) (0, 0) in
467                 let c = others + (abs (common - card)) in
468                 if c < initial then true else false 
469             in
470             List.filter filterfun new_pos
471       in
472       new_neg, new_pos
473 ;;
474
475
476 let contains_empty env (negative, positive) =
477   let metasenv, context, ugraph = env in
478   try
479     let found =
480       List.find
481         (fun (w, proof, (ty, left, right, ordering), m, a) ->
482            fst (CicReduction.are_convertible context left right ugraph))
483         negative
484     in
485     true, Some found
486   with Not_found ->
487     false, None
488 ;;
489
490
491 (** simplifies current using active and passive *)
492 let forward_simplify env (sign, current) ?passive (active_list, active_table) =
493   let pl, passive_table =
494     match passive with
495     | None -> [], None
496     | Some ((pn, _), (pp, _), pt) ->
497         let pn = List.map (fun e -> (Negative, e)) pn
498         and pp = List.map (fun e -> (Positive, e)) pp in
499         pn @ pp, Some pt
500   in
501   let all = if pl = [] then active_list else active_list @ pl in
502   
503   let demodulate table current = 
504     let newmeta, newcurrent =
505       Indexing.demodulation_equality !maxmeta env table sign current in
506     maxmeta := newmeta;
507     if is_identity env newcurrent then
508       if sign = Negative then Some (sign, newcurrent)
509       else (
510 (*      debug_print  *)
511 (*        (lazy *)
512 (*           (Printf.sprintf "\ncurrent was: %s\nnewcurrent is: %s\n" *)
513 (*              (string_of_equality current) *)
514 (*              (string_of_equality newcurrent))); *)
515 (*      debug_print *)
516 (*        (lazy *)
517 (*           (Printf.sprintf "active is: %s" *)
518 (*              (String.concat "\n"  *)
519 (*                 (List.map (fun (_, e) -> (string_of_equality e)) active_list)))); *)
520         None
521       )
522     else
523       Some (sign, newcurrent)
524   in
525   let res =
526     let res = demodulate active_table current in
527     match res with
528     | None -> None
529     | Some (sign, newcurrent) ->
530         match passive_table with
531         | None -> res
532         | Some passive_table -> demodulate passive_table newcurrent
533   in
534   match res with
535   | None -> None
536   | Some (Negative, c) ->
537       let ok = not (
538         List.exists
539           (fun (s, eq) -> s = Negative && meta_convertibility_eq eq c)
540           all)
541       in
542       if ok then res else None
543   | Some (Positive, c) ->
544       if Indexing.in_index active_table c then
545         None
546       else
547         match passive_table with
548         | None -> 
549             if fst (Indexing.subsumption env active_table c) then
550               None
551             else
552               res
553         | Some passive_table ->
554             if Indexing.in_index passive_table c then None
555             else 
556               let r1, _ = Indexing.subsumption env active_table c in
557               if r1 then None else
558                 let r2, _ = Indexing.subsumption env passive_table c in 
559                 if r2 then None else res
560 ;;
561
562 type fs_time_info_t = {
563   mutable build_all: float;
564   mutable demodulate: float;
565   mutable subsumption: float;
566 };;
567
568 let fs_time_info = { build_all = 0.; demodulate = 0.; subsumption = 0. };;
569
570
571 (** simplifies new using active and passive *)
572 let forward_simplify_new env (new_neg, new_pos) ?passive active =
573   let t1 = Unix.gettimeofday () in
574
575   let active_list, active_table = active in
576   let pl, passive_table =
577     match passive with
578     | None -> [], None
579     | Some ((pn, _), (pp, _), pt) ->
580         let pn = List.map (fun e -> (Negative, e)) pn
581         and pp = List.map (fun e -> (Positive, e)) pp in
582         pn @ pp, Some pt
583   in
584   
585   let t2 = Unix.gettimeofday () in
586   fs_time_info.build_all <- fs_time_info.build_all +. (t2 -. t1);
587   
588   let demodulate sign table target =
589     let newmeta, newtarget =
590       Indexing.demodulation_equality !maxmeta env table sign target in
591     maxmeta := newmeta;
592     newtarget
593   in
594   let t1 = Unix.gettimeofday () in
595
596   let new_neg, new_pos =
597     let new_neg = List.map (demodulate Negative active_table) new_neg
598     and new_pos = List.map (demodulate Positive active_table) new_pos in
599       new_neg,new_pos
600
601 (* PROVA
602     match passive_table with
603     | None -> new_neg, new_pos
604     | Some passive_table ->
605         List.map (demodulate Negative passive_table) new_neg,
606         List.map (demodulate Positive passive_table) new_pos *)
607   in
608
609   let t2 = Unix.gettimeofday () in
610   fs_time_info.demodulate <- fs_time_info.demodulate +. (t2 -. t1);
611
612   let new_pos_set =
613     List.fold_left
614       (fun s e ->
615          if not (Inference.is_identity env e) then
616            if EqualitySet.mem e s then s
617            else EqualitySet.add e s
618          else s)
619       EqualitySet.empty new_pos
620   in
621   let new_pos = EqualitySet.elements new_pos_set in
622
623   let subs =
624     match passive_table with
625     | None ->
626         (fun e -> not (fst (Indexing.subsumption env active_table e)))
627     | Some passive_table ->
628         (fun e -> not ((fst (Indexing.subsumption env active_table e)) ||
629                          (fst (Indexing.subsumption env passive_table e))))
630   in
631 (*   let t1 = Unix.gettimeofday () in *)
632 (*   let t2 = Unix.gettimeofday () in *)
633 (*   fs_time_info.subsumption <- fs_time_info.subsumption +. (t2 -. t1); *)
634   let is_duplicate =
635     match passive_table with
636     | None ->
637         (fun e -> not (Indexing.in_index active_table e))
638     | Some passive_table ->
639         (fun e ->
640            not ((Indexing.in_index active_table e) ||
641                   (Indexing.in_index passive_table e)))
642   in
643   new_neg, List.filter subs (List.filter is_duplicate new_pos)
644 ;;
645
646
647 (** simplifies active usign new *)
648 let backward_simplify_active env new_pos new_table min_weight active =
649   let active_list, active_table = active in
650   let active_list, newa = 
651     List.fold_right
652       (fun (s, equality) (res, newn) ->
653          let ew, _, _, _, _ = equality in
654          if ew < min_weight then
655            (s, equality)::res, newn
656          else
657            match forward_simplify env (s, equality) (new_pos, new_table) with
658            | None -> res, newn
659            | Some (s, e) ->
660                if equality = e then
661                  (s, e)::res, newn
662                else 
663                  res, (s, e)::newn)
664       active_list ([], [])
665   in
666   let find eq1 where =
667     List.exists (fun (s, e) -> meta_convertibility_eq eq1 e) where
668   in
669   let active, newa =
670     List.fold_right
671       (fun (s, eq) (res, tbl) ->
672          if List.mem (s, eq) res then
673            res, tbl
674          else if (is_identity env eq) || (find eq res) then (
675            res, tbl
676          ) 
677          else
678            (s, eq)::res, if s = Negative then tbl else Indexing.index tbl eq)
679       active_list ([], Indexing.empty),
680     List.fold_right
681       (fun (s, eq) (n, p) ->
682          if (s <> Negative) && (is_identity env eq) then (
683            (n, p)
684          ) else
685            if s = Negative then eq::n, p
686            else n, eq::p)
687       newa ([], [])
688   in
689   match newa with
690   | [], [] -> active, None
691   | _ -> active, Some newa
692 ;;
693
694
695 (** simplifies passive using new *)
696 let backward_simplify_passive env new_pos new_table min_weight passive =
697   let (nl, ns), (pl, ps), passive_table = passive in
698   let f sign equality (resl, ress, newn) =
699     let ew, _, _, _, _ = equality in
700     if ew < min_weight then
701       equality::resl, ress, newn
702     else
703       match forward_simplify env (sign, equality) (new_pos, new_table) with
704       | None -> resl, EqualitySet.remove equality ress, newn
705       | Some (s, e) ->
706           if equality = e then
707             equality::resl, ress, newn
708           else
709             let ress = EqualitySet.remove equality ress in
710             resl, ress, e::newn
711   in
712   let nl, ns, newn = List.fold_right (f Negative) nl ([], ns, [])
713   and pl, ps, newp = List.fold_right (f Positive) pl ([], ps, []) in
714   let passive_table =
715     List.fold_left
716       (fun tbl e -> Indexing.index tbl e) Indexing.empty pl
717   in
718   match newn, newp with
719   | [], [] -> ((nl, ns), (pl, ps), passive_table), None
720   | _, _ -> ((nl, ns), (pl, ps), passive_table), Some (newn, newp)
721 ;;
722
723
724 let backward_simplify env new' ?passive active =
725   let new_pos, new_table, min_weight =
726     List.fold_left
727       (fun (l, t, w) e ->
728          let ew, _, _, _, _ = e in
729          (Positive, e)::l, Indexing.index t e, min ew w)
730       ([], Indexing.empty, 1000000) (snd new')
731   in
732   let active, newa =
733     backward_simplify_active env new_pos new_table min_weight active in
734   match passive with
735   | None ->
736       active, (make_passive [] []), newa, None
737   | Some passive ->
738       let passive, newp =
739         backward_simplify_passive env new_pos new_table min_weight passive in
740       active, passive, newa, newp
741 ;;
742
743
744 (* returns an estimation of how many equalities in passive can be activated
745    within the current time limit *)
746 let get_selection_estimate () =
747   elapsed_time := (Unix.gettimeofday ()) -. !start_time;
748   (*   !processed_clauses * (int_of_float (!time_limit /. !elapsed_time)) *)
749   int_of_float (
750     ceil ((float_of_int !processed_clauses) *.
751             ((!time_limit (* *. 2. *)) /. !elapsed_time -. 1.)))
752 ;;
753
754
755 (** initializes the set of goals *)
756 let make_goals goal =
757   let active = []
758   and passive = [0, [goal]] in
759   active, passive
760 ;;
761
762
763 (** initializes the set of theorems *)
764 let make_theorems theorems =
765   theorems, []
766 ;;
767
768
769 let activate_goal (active, passive) =
770   match passive with
771   | goal_conj::tl -> true, (goal_conj::active, tl)
772   | [] -> false, (active, passive)
773 ;;
774
775
776 let activate_theorem (active, passive) =
777   match passive with
778   | theorem::tl -> true, (theorem::active, tl)
779   | [] -> false, (active, passive)
780 ;;
781
782
783 (** simplifies a goal with equalities in active and passive *)  
784 let simplify_goal env goal ?passive (active_list, active_table) =
785   let pl, passive_table =
786     match passive with
787     | None -> [], None
788     | Some ((pn, _), (pp, _), pt) ->
789         let pn = List.map (fun e -> (Negative, e)) pn
790         and pp = List.map (fun e -> (Positive, e)) pp in
791         pn @ pp, Some pt
792   in
793
794   let demodulate table goal = 
795     let newmeta, newgoal =
796       Indexing.demodulation_goal !maxmeta env table goal in
797     maxmeta := newmeta;
798     goal != newgoal, newgoal
799   in
800   let changed, goal =
801     match passive_table with
802     | None -> demodulate active_table goal
803     | Some passive_table ->
804         let changed, goal = demodulate active_table goal in
805         let changed', goal = demodulate passive_table goal in
806         (changed || changed'), goal
807   in
808   changed, goal
809 ;;
810
811
812 let simplify_goals env goals ?passive active =
813   let a_goals, p_goals = goals in
814   let p_goals = 
815     List.map
816       (fun (d, gl) ->
817          let gl =
818            List.map (fun g -> snd (simplify_goal env g ?passive active)) gl in
819          d, gl)
820       p_goals
821   in
822   let goals =
823     List.fold_left
824       (fun (a, p) (d, gl) ->
825          let changed = ref false in
826          let gl =
827            List.map
828              (fun g ->
829                 let c, g = simplify_goal env g ?passive active in
830                 changed := !changed || c; g) gl in
831          if !changed then (a, (d, gl)::p) else ((d, gl)::a, p))
832       ([], p_goals) a_goals
833   in
834   goals
835 ;;
836
837
838 let simplify_theorems env theorems ?passive (active_list, active_table) =
839   let pl, passive_table =
840     match passive with
841     | None -> [], None
842     | Some ((pn, _), (pp, _), pt) ->
843         let pn = List.map (fun e -> (Negative, e)) pn
844         and pp = List.map (fun e -> (Positive, e)) pp in
845         pn @ pp, Some pt
846   in
847   let a_theorems, p_theorems = theorems in
848   let demodulate table theorem =
849     let newmeta, newthm =
850       Indexing.demodulation_theorem !maxmeta env table theorem in
851     maxmeta := newmeta;
852     theorem != newthm, newthm
853   in
854   let foldfun table (a, p) theorem =
855     let changed, theorem = demodulate table theorem in
856     if changed then (a, theorem::p) else (theorem::a, p)
857   in
858   let mapfun table theorem = snd (demodulate table theorem) in
859   match passive_table with
860   | None ->
861       let p_theorems = List.map (mapfun active_table) p_theorems in
862       List.fold_left (foldfun active_table) ([], p_theorems) a_theorems
863   | Some passive_table ->
864       let p_theorems = List.map (mapfun active_table) p_theorems in
865       let p_theorems, a_theorems =
866         List.fold_left (foldfun active_table) ([], p_theorems) a_theorems in
867       let p_theorems = List.map (mapfun passive_table) p_theorems in
868       List.fold_left (foldfun passive_table) ([], p_theorems) a_theorems
869 ;;
870
871
872 let rec simpl env e others others_simpl =
873   let active = others @ others_simpl in
874   let tbl =
875     List.fold_left
876       (fun t (_, e) -> Indexing.index t e)
877       Indexing.empty active
878   in
879   let res = forward_simplify env e (active, tbl) in
880     match others with
881       | hd::tl -> (
882           match res with
883             | None -> simpl env hd tl others_simpl
884             | Some e -> simpl env hd tl (e::others_simpl)
885         )
886       | [] -> (
887           match res with
888             | None -> others_simpl
889             | Some e -> e::others_simpl
890         )
891 ;;
892
893 let simplify_equalities env equalities =
894   debug_print
895     (lazy 
896        (Printf.sprintf "equalities:\n%s\n"
897           (String.concat "\n"
898              (List.map string_of_equality equalities))));
899   debug_print (lazy "SIMPLYFYING EQUALITIES...");
900   match equalities with
901     | [] -> []
902     | hd::tl ->
903         let others = List.map (fun e -> (Positive, e)) tl in
904         let res =
905           List.rev (List.map snd (simpl env (Positive, hd) others []))
906         in
907           debug_print
908             (lazy
909                (Printf.sprintf "equalities AFTER:\n%s\n"
910                   (String.concat "\n"
911                      (List.map string_of_equality res))));
912           res
913 ;;
914
915 (* applies equality to goal to see if the goal can be closed *)
916 let apply_equality_to_goal env equality goal =
917   let module C = Cic in
918   let module HL = HelmLibraryObjects in
919   let module I = Inference in
920   let metasenv, context, ugraph = env in
921   let _, proof, (ty, left, right, _), metas, args = equality in
922   let eqterm =
923     C.Appl [C.MutInd (LibraryObjects.eq_URI (), 0, []); ty; left; right] in
924   let gproof, gmetas, gterm = goal in
925 (*   debug_print *)
926 (*     (lazy *)
927 (*        (Printf.sprintf "APPLY EQUALITY TO GOAL: %s, %s" *)
928 (*           (string_of_equality equality) (CicPp.ppterm gterm))); *)
929   try
930     let subst, metasenv', _ =
931       let menv = metasenv @ metas @ gmetas in
932       Inference.unification menv context eqterm gterm ugraph
933     in
934     let newproof =
935       match proof with
936       | I.BasicProof t -> I.BasicProof (CicMetaSubst.apply_subst subst t)
937       | I.ProofBlock (s, uri, nt, t, pe, p) ->
938           I.ProofBlock (subst @ s, uri, nt, t, pe, p)
939       | _ -> assert false
940     in
941     let newgproof =
942       let rec repl = function
943         | I.ProofGoalBlock (_, gp) -> I.ProofGoalBlock (newproof, gp)
944         | I.NoProof -> newproof
945         | I.BasicProof p -> newproof
946         | I.SubProof (t, i, p) -> I.SubProof (t, i, repl p)
947         | _ -> assert false
948       in
949       repl gproof
950     in
951     true, subst, newgproof
952   with CicUnification.UnificationFailure _ ->
953     false, [], I.NoProof
954 ;;
955
956
957
958 let new_meta metasenv =
959   let m = CicMkImplicit.new_meta metasenv [] in
960   incr maxmeta;
961   while !maxmeta <= m do incr maxmeta done;
962   !maxmeta
963 ;;
964
965
966 (* applies a theorem or an equality to goal, returning a list of subgoals or
967    an indication of failure *)
968 let apply_to_goal env theorems ?passive active goal =
969   let metasenv, context, ugraph = env in
970   let proof, metas, term = goal in
971   (*   debug_print *)
972   (*     (lazy *)
973   (*        (Printf.sprintf "apply_to_goal with goal: %s" *)
974   (*           (\* (string_of_proof proof)  *\)(CicPp.ppterm term))); *)
975   let status =
976     let irl =
977       CicMkImplicit.identity_relocation_list_for_metavariable context in
978     let proof', newmeta =
979       let rec get_meta = function
980         | SubProof (t, i, p) ->
981             let t', i' = get_meta p in
982             if i' = -1 then t, i else t', i'
983         | ProofGoalBlock (_, p) -> get_meta p
984         | _ -> Cic.Implicit None, -1
985       in
986       let p, m = get_meta proof in
987       if m = -1 then
988         let n = new_meta (metasenv @ metas) in
989         Cic.Meta (n, irl), n
990       else
991         p, m
992     in
993     let metasenv = (newmeta, context, term)::metasenv @ metas in
994     let bit = new_meta metasenv, context, term in 
995     let metasenv' = bit::metasenv in
996     ((None, metasenv', Cic.Meta (newmeta, irl), term), newmeta)
997   in
998   let rec aux = function
999     | [] -> `No
1000     | (theorem, thmty, _)::tl ->
1001         try
1002           let subst, (newproof, newgoals) =
1003             PrimitiveTactics.apply_tac_verbose_with_subst ~term:theorem status
1004           in
1005           if newgoals = [] then
1006             let _, _, p, _ = newproof in
1007             let newp =
1008               let rec repl = function
1009                 | Inference.ProofGoalBlock (_, gp) ->
1010                     Inference.ProofGoalBlock (Inference.BasicProof p, gp)
1011                 | Inference.NoProof -> Inference.BasicProof p
1012                 | Inference.BasicProof _ -> Inference.BasicProof p
1013                 | Inference.SubProof (t, i, p2) ->
1014                     Inference.SubProof (t, i, repl p2)
1015                 | _ -> assert false
1016               in
1017               repl proof
1018             in
1019             let _, m = status in
1020             let subst = List.filter (fun (i, _) -> i = m) subst in
1021             `Ok (subst, [newp, metas, term])
1022           else
1023             let _, menv, p, _ = newproof in
1024             let irl =
1025               CicMkImplicit.identity_relocation_list_for_metavariable context
1026             in
1027             let goals =
1028               List.map
1029                 (fun i ->
1030                    let _, _, ty = CicUtil.lookup_meta i menv in
1031                    let p' =
1032                      let rec gp = function
1033                        | SubProof (t, i, p) ->
1034                            SubProof (t, i, gp p)
1035                        | ProofGoalBlock (sp1, sp2) ->
1036                            ProofGoalBlock (sp1, gp sp2)
1037                        | BasicProof _
1038                        | NoProof ->
1039                            SubProof (p, i, BasicProof (Cic.Meta (i, irl)))
1040                        | ProofSymBlock (s, sp) ->
1041                            ProofSymBlock (s, gp sp)
1042                        | ProofBlock (s, u, nt, t, pe, sp) ->
1043                            ProofBlock (s, u, nt, t, pe, gp sp)
1044                      in gp proof
1045                    in
1046                    (p', menv, ty))
1047                 newgoals
1048             in
1049             let goals =
1050               let weight t =
1051                 let w, m = weight_of_term t in
1052                 w + 2 * (List.length m)
1053               in
1054               List.sort
1055                 (fun (_, _, t1) (_, _, t2) ->
1056                    Pervasives.compare (weight t1) (weight t2))
1057                 goals
1058             in
1059             let best = aux tl in
1060             match best with
1061             | `Ok (_, _) -> best
1062             | `No -> `GoOn ([subst, goals])
1063             | `GoOn sl -> `GoOn ((subst, goals)::sl)
1064         with ProofEngineTypes.Fail msg ->
1065           aux tl
1066   in
1067   let r, s, l =
1068     if Inference.term_is_equality term then
1069       let rec appleq_a = function
1070         | [] -> false, [], []
1071         | (Positive, equality)::tl ->
1072             let ok, s, newproof = apply_equality_to_goal env equality goal in
1073             if ok then true, s, [newproof, metas, term] else appleq_a tl
1074         | _::tl -> appleq_a tl
1075       in
1076       let rec appleq_p = function
1077         | [] -> false, [], []
1078         | equality::tl ->
1079             let ok, s, newproof = apply_equality_to_goal env equality goal in
1080             if ok then true, s, [newproof, metas, term] else appleq_p tl
1081       in
1082       let al, _ = active in
1083       match passive with
1084       | None -> appleq_a al
1085       | Some (_, (pl, _), _) ->
1086           let r, s, l = appleq_a al in if r then r, s, l else appleq_p pl
1087     else
1088       false, [], []
1089   in
1090   if r = true then `Ok (s, l) else aux theorems
1091 ;;
1092
1093
1094 (* sorts a conjunction of goals in order to detect earlier if it is
1095    unsatisfiable. Non-predicate goals are placed at the end of the list *)
1096 let sort_goal_conj (metasenv, context, ugraph) (depth, gl) =
1097   let gl = 
1098     List.stable_sort
1099       (fun (_, e1, g1) (_, e2, g2) ->
1100          let ty1, _ =
1101            CicTypeChecker.type_of_aux' (e1 @ metasenv) context g1 ugraph 
1102          and ty2, _ =
1103            CicTypeChecker.type_of_aux' (e2 @ metasenv) context g2 ugraph
1104          in
1105          let prop1 =
1106            let b, _ =
1107              CicReduction.are_convertible context (Cic.Sort Cic.Prop) ty1 ugraph
1108            in
1109            if b then 0 else 1
1110          and prop2 =
1111            let b, _ =
1112              CicReduction.are_convertible context (Cic.Sort Cic.Prop) ty2 ugraph
1113            in
1114            if b then 0 else 1
1115          in
1116          if prop1 = 0 && prop2 = 0 then
1117            let e1 = if Inference.term_is_equality g1 then 0 else 1
1118            and e2 = if Inference.term_is_equality g2 then 0 else 1 in
1119            e1 - e2
1120          else
1121            prop1 - prop2)
1122       gl
1123   in
1124   (depth, gl)
1125 ;;
1126
1127
1128 let is_meta_closed goals =
1129   List.for_all (fun (_, _, g) -> CicUtil.is_meta_closed g) goals
1130 ;;
1131
1132
1133 (* applies a series of theorems/equalities to a conjunction of goals *)
1134 let rec apply_to_goal_conj env theorems ?passive active (depth, goals) =
1135   let aux (goal, r) tl =
1136     let propagate_subst subst (proof, metas, term) =
1137       let rec repl = function
1138         | NoProof -> NoProof 
1139         | BasicProof t ->
1140             BasicProof (CicMetaSubst.apply_subst subst t)
1141         | ProofGoalBlock (p, pb) ->
1142             let pb' = repl pb in
1143             ProofGoalBlock (p, pb')
1144         | SubProof (t, i, p) ->
1145             let t' = CicMetaSubst.apply_subst subst t in
1146             let p = repl p in
1147             SubProof (t', i, p)
1148         | ProofSymBlock (ens, p) -> ProofSymBlock (ens, repl p)
1149         | ProofBlock (s, u, nty, t, pe, p) ->
1150             ProofBlock (subst @ s, u, nty, t, pe, p)
1151       in (repl proof, metas, term)
1152     in
1153     (* let r = apply_to_goal env theorems ?passive active goal in *) (
1154       match r with
1155       | `No -> `No (depth, goals)
1156       | `GoOn sl ->
1157           let l =
1158             List.map
1159               (fun (s, gl) ->
1160                  let tl = List.map (propagate_subst s) tl in
1161                  sort_goal_conj env (depth+1, gl @ tl)) sl
1162           in
1163           `GoOn l
1164       | `Ok (subst, gl) ->
1165           if tl = [] then
1166             `Ok (depth, gl)
1167           else
1168             let p, _, _ = List.hd gl in
1169             let subproof =
1170               let rec repl = function
1171                 | SubProof (_, _, p) -> repl p
1172                 | ProofGoalBlock (p1, p2) ->
1173                     ProofGoalBlock (repl p1, repl p2)
1174                 | p -> p
1175               in
1176               build_proof_term (repl p)
1177             in
1178             let i = 
1179               let rec get_meta = function
1180                 | SubProof (_, i, p) ->
1181                     let i' = get_meta p in
1182                     if i' = -1 then i else i'
1183 (*                         max i (get_meta p) *)
1184                 | ProofGoalBlock (_, p) -> get_meta p
1185                 | _ -> -1
1186               in
1187               get_meta p
1188             in
1189             let subst =
1190               let _, (context, _, _) = List.hd subst in
1191               [i, (context, subproof, Cic.Implicit None)]
1192             in
1193             let tl = List.map (propagate_subst subst) tl in
1194             let conj = sort_goal_conj env (depth(* +1 *), tl) in
1195             `GoOn ([conj])
1196     )
1197   in
1198   if depth > !maxdepth || (List.length goals) > !maxwidth then 
1199     `No (depth, goals)
1200   else
1201     let rec search_best res = function
1202       | [] -> res
1203       | goal::tl ->
1204           let r = apply_to_goal env theorems ?passive active goal in
1205           match r with
1206           | `Ok _ -> (goal, r)
1207           | `No -> search_best res tl
1208           | `GoOn l ->
1209               let newres = 
1210                 match res with
1211                 | _, `Ok _ -> assert false
1212                 | _, `No -> goal, r
1213                 | _, `GoOn l2 ->
1214                     if (List.length l) < (List.length l2) then goal, r else res
1215               in
1216               search_best newres tl
1217     in
1218     let hd = List.hd goals in
1219     let res = hd, (apply_to_goal env theorems ?passive active hd) in
1220     let best =
1221       match res with
1222       | _, `Ok _ -> res
1223       | _, _ -> search_best res (List.tl goals)
1224     in
1225     let res = aux best (List.filter (fun g -> g != (fst best)) goals) in
1226     match res with
1227     | `GoOn ([conj]) when is_meta_closed (snd conj) &&
1228         (List.length (snd conj)) < (List.length goals)->
1229         apply_to_goal_conj env theorems ?passive active conj
1230     | _ -> res
1231 ;;
1232
1233
1234 (*
1235 module OrderedGoals = struct
1236   type t = int * (Inference.proof * Cic.metasenv * Cic.term) list
1237
1238   let compare g1 g2 =
1239     let d1, l1 = g1
1240     and d2, l2 = g2 in
1241     let r = d2 - d1 in
1242     if r <> 0 then r
1243     else let r = (List.length l1) - (List.length l2) in
1244     if r <> 0 then r
1245     else
1246       let res = ref 0 in
1247       let _ = 
1248         List.exists2
1249           (fun (_, _, t1) (_, _, t2) ->
1250              let r = Pervasives.compare t1 t2 in
1251              if r <> 0 then (
1252                res := r;
1253                true
1254              ) else
1255                false) l1 l2
1256       in !res
1257 end
1258
1259 module GoalsSet = Set.Make(OrderedGoals);;
1260
1261
1262 exception SearchSpaceOver;;
1263 *)
1264
1265
1266 (*
1267 let apply_to_goals env is_passive_empty theorems active goals =
1268   debug_print (lazy "\n\n\tapply_to_goals\n\n");
1269   let add_to set goals =
1270     List.fold_left (fun s g -> GoalsSet.add g s) set goals 
1271   in
1272   let rec aux set = function
1273     | [] ->
1274         debug_print (lazy "HERE!!!");
1275         if is_passive_empty then raise SearchSpaceOver else false, set
1276     | goals::tl ->
1277         let res = apply_to_goal_conj env theorems active goals in
1278         match res with
1279         | `Ok newgoals ->
1280             let _ =
1281               let d, p, t =
1282                 match newgoals with
1283                 | (d, (p, _, t)::_) -> d, p, t
1284                 | _ -> assert false
1285               in
1286               debug_print
1287                 (lazy
1288                    (Printf.sprintf "\nOK!!!!\ndepth: %d\nProof: %s\ngoal: %s\n"
1289                       d (string_of_proof p) (CicPp.ppterm t)))
1290             in
1291             true, GoalsSet.singleton newgoals
1292         | `GoOn newgoals ->
1293             let set' = add_to set (goals::tl) in
1294             let set' = add_to set' newgoals in
1295             false, set'
1296         | `No newgoals ->
1297             aux set tl
1298   in
1299   let n = List.length goals in
1300   let res, goals = aux (add_to GoalsSet.empty goals) goals in
1301   let goals = GoalsSet.elements goals in
1302   debug_print (lazy "\n\tapply_to_goals end\n");
1303   let m = List.length goals in
1304   if m = n && is_passive_empty then
1305     raise SearchSpaceOver
1306   else
1307     res, goals
1308 ;;
1309 *)
1310
1311
1312 (* sorts the list of passive goals to minimize the search for a proof (doesn't
1313    work that well yet...) *)
1314 let sort_passive_goals goals =
1315   List.stable_sort
1316     (fun (d1, l1) (d2, l2) ->
1317        let r1 = d2 - d1 
1318        and r2 = (List.length l1) - (List.length l2) in
1319        let foldfun ht (_, _, t) = 
1320          let _ = List.map (fun i -> Hashtbl.replace ht i 1) (metas_of_term t)
1321          in ht
1322        in
1323        let m1 = Hashtbl.length (List.fold_left foldfun (Hashtbl.create 3) l1)
1324        and m2 = Hashtbl.length (List.fold_left foldfun (Hashtbl.create 3) l2)
1325        in let r3 = m1 - m2 in
1326        if r3 <> 0 then r3
1327        else if r2 <> 0 then r2 
1328        else r1)
1329     (*          let _, _, g1 = List.hd l1 *)
1330 (*          and _, _, g2 = List.hd l2 in *)
1331 (*          let e1 = if Inference.term_is_equality g1 then 0 else 1 *)
1332 (*          and e2 = if Inference.term_is_equality g2 then 0 else 1 *)
1333 (*          in let r4 = e1 - e2 in *)
1334 (*          if r4 <> 0 then r3 else r1) *)
1335     goals
1336 ;;
1337
1338
1339 let print_goals goals = 
1340   (String.concat "\n"
1341      (List.map
1342         (fun (d, gl) ->
1343            let gl' =
1344              List.map
1345                (fun (p, _, t) ->
1346                   (* (string_of_proof p) ^ ", " ^ *) (CicPp.ppterm t)) gl
1347            in
1348            Printf.sprintf "%d: %s" d (String.concat "; " gl')) goals))
1349 ;;
1350
1351
1352 (* tries to prove the first conjunction in goals with applications of
1353    theorems/equalities, returning new sub-goals or an indication of success *)
1354 let apply_goal_to_theorems dbd env theorems ?passive active goals =
1355   let theorems, _ = theorems in
1356   let a_goals, p_goals = goals in
1357   let goal = List.hd a_goals in
1358   let not_in_active gl =
1359     not
1360       (List.exists
1361          (fun (_, gl') ->
1362             if (List.length gl) = (List.length gl') then
1363               List.for_all2 (fun (_, _, g1) (_, _, g2) -> g1 = g2) gl gl'
1364             else
1365               false)
1366          a_goals)
1367   in
1368   let aux theorems =
1369     let res = apply_to_goal_conj env theorems ?passive active goal in
1370     match res with
1371     | `Ok newgoals ->
1372         true, ([newgoals], [])
1373     | `No _ ->
1374         false, (a_goals, p_goals)
1375     | `GoOn newgoals ->
1376         let newgoals =
1377           List.filter
1378             (fun (d, gl) ->
1379                (d <= !maxdepth) && (List.length gl) <= !maxwidth &&
1380                  not_in_active gl)
1381             newgoals in
1382         let p_goals = newgoals @ p_goals in
1383         let p_goals = sort_passive_goals p_goals in
1384         false, (a_goals, p_goals)
1385   in
1386   aux theorems
1387 ;;
1388
1389
1390 let apply_theorem_to_goals env theorems active goals =
1391   let a_goals, p_goals = goals in
1392   let theorem = List.hd (fst theorems) in
1393   let theorems = [theorem] in
1394   let rec aux p = function
1395     | [] -> false, ([], p)
1396     | goal::tl ->
1397         let res = apply_to_goal_conj env theorems active goal in
1398         match res with
1399         | `Ok newgoals -> true, ([newgoals], [])
1400         | `No _ -> aux p tl
1401         | `GoOn newgoals -> aux (newgoals @ p) tl
1402   in
1403   let ok, (a, p) = aux p_goals a_goals in
1404   if ok then
1405     ok, (a, p)
1406   else
1407     let p_goals =
1408       List.stable_sort
1409         (fun (d1, l1) (d2, l2) ->
1410            let r = d2 - d1 in
1411            if r <> 0 then r
1412            else let r = (List.length l1) - (List.length l2) in
1413            if r <> 0 then r
1414            else
1415              let res = ref 0 in
1416              let _ = 
1417                List.exists2
1418                  (fun (_, _, t1) (_, _, t2) ->
1419                     let r = Pervasives.compare t1 t2 in
1420                     if r <> 0 then (res := r; true) else false) l1 l2
1421              in !res)
1422         p
1423     in
1424     ok, (a_goals, p_goals)
1425 ;;
1426
1427
1428 (* given-clause algorithm with lazy reduction strategy *)
1429 let rec given_clause dbd env goals theorems passive active =
1430   let goals = simplify_goals env goals active in
1431   let ok, goals = activate_goal goals in
1432   (*   let theorems = simplify_theorems env theorems active in *)
1433   if ok then
1434     let ok, goals = apply_goal_to_theorems dbd env theorems active goals in
1435     if ok then
1436       let proof =
1437         match (fst goals) with
1438         | (_, [proof, _, _])::_ -> Some proof
1439         | _ -> assert false
1440       in
1441       ParamodulationSuccess (proof, env)
1442     else
1443       given_clause_aux dbd env goals theorems passive active
1444   else
1445 (*     let ok', theorems = activate_theorem theorems in *)
1446     let ok', theorems = false, theorems in
1447     if ok' then
1448       let ok, goals = apply_theorem_to_goals env theorems active goals in
1449       if ok then
1450         let proof =
1451           match (fst goals) with
1452           | (_, [proof, _, _])::_ -> Some proof
1453           | _ -> assert false
1454         in
1455         ParamodulationSuccess (proof, env)
1456       else
1457         given_clause_aux dbd env goals theorems passive active
1458     else
1459       if (passive_is_empty passive) then ParamodulationFailure
1460       else given_clause_aux dbd env goals theorems passive active
1461
1462 and given_clause_aux dbd env goals theorems passive active = 
1463   let time1 = Unix.gettimeofday () in
1464
1465   let selection_estimate = get_selection_estimate () in
1466   let kept = size_of_passive passive in
1467   let passive =
1468     if !time_limit = 0. || !processed_clauses = 0 then
1469       passive
1470     else if !elapsed_time > !time_limit then (
1471       debug_print (lazy (Printf.sprintf "Time limit (%.2f) reached: %.2f\n"
1472                            !time_limit !elapsed_time));
1473       make_passive [] []
1474     ) else if kept > selection_estimate then (
1475       debug_print
1476         (lazy (Printf.sprintf ("Too many passive equalities: pruning..." ^^
1477                                  "(kept: %d, selection_estimate: %d)\n")
1478                  kept selection_estimate));
1479       prune_passive selection_estimate active passive
1480     ) else
1481       passive
1482   in
1483
1484   let time2 = Unix.gettimeofday () in
1485   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
1486
1487   kept_clauses := (size_of_passive passive) + (size_of_active active);
1488   match passive_is_empty passive with
1489   | true -> (* ParamodulationFailure *)
1490       given_clause dbd env goals theorems passive active
1491   | false ->
1492       let (sign, current), passive = select env (fst goals) passive active in
1493       let time1 = Unix.gettimeofday () in
1494       let res = forward_simplify env (sign, current) ~passive active in
1495       let time2 = Unix.gettimeofday () in
1496       forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
1497       match res with
1498       | None ->
1499           given_clause dbd env goals theorems passive active
1500       | Some (sign, current) ->
1501           if (sign = Negative) && (is_identity env current) then (
1502             debug_print
1503               (lazy (Printf.sprintf "OK!!! %s %s" (string_of_sign sign)
1504                        (string_of_equality ~env current)));
1505             let _, proof, _, _, _  = current in
1506             ParamodulationSuccess (Some proof, env)
1507           ) else (            
1508             debug_print
1509               (lazy "\n================================================");
1510             debug_print (lazy (Printf.sprintf "selected: %s %s"
1511                                  (string_of_sign sign)
1512                                  (string_of_equality ~env current)));
1513
1514             let t1 = Unix.gettimeofday () in
1515             let new' = infer env sign current active in
1516             let t2 = Unix.gettimeofday () in
1517             infer_time := !infer_time +. (t2 -. t1);
1518             
1519             let res, goal' = contains_empty env new' in
1520             if res then
1521               let proof =
1522                 match goal' with
1523                 | Some goal -> let _, proof, _, _, _ = goal in Some proof
1524                 | None -> None
1525               in
1526               ParamodulationSuccess (proof, env)
1527             else 
1528               let t1 = Unix.gettimeofday () in
1529               let new' = forward_simplify_new env new' active in
1530               let t2 = Unix.gettimeofday () in
1531               let _ =
1532                 forward_simpl_new_time :=
1533                   !forward_simpl_new_time +. (t2 -. t1)
1534               in
1535               let active =
1536                 match sign with
1537                 | Negative -> active
1538                 | Positive ->
1539                     let t1 = Unix.gettimeofday () in
1540                     let active, _, newa, _ =
1541                       backward_simplify env ([], [current]) active
1542                     in
1543                     let t2 = Unix.gettimeofday () in
1544                     backward_simpl_time :=
1545                       !backward_simpl_time +. (t2 -. t1);
1546                     match newa with
1547                     | None -> active
1548                     | Some (n, p) ->
1549                         let al, tbl = active in
1550                         let nn = List.map (fun e -> Negative, e) n in
1551                         let pp, tbl =
1552                           List.fold_right
1553                             (fun e (l, t) ->
1554                                (Positive, e)::l,
1555                                Indexing.index tbl e)
1556                             p ([], tbl)
1557                         in
1558                         nn @ al @ pp, tbl
1559               in
1560               match contains_empty env new' with
1561               | false, _ -> 
1562                   let active =
1563                     let al, tbl = active in
1564                     match sign with
1565                     | Negative -> (sign, current)::al, tbl
1566                     | Positive ->
1567                         al @ [(sign, current)], Indexing.index tbl current
1568                   in
1569                   let passive = add_to_passive passive new' in
1570                   given_clause dbd env goals theorems passive active
1571               | true, goal ->
1572                   let proof =
1573                     match goal with
1574                     | Some goal ->
1575                         let _, proof, _, _, _ = goal in Some proof
1576                     | None -> None
1577                   in
1578                   ParamodulationSuccess (proof, env)
1579           )
1580 ;;
1581
1582
1583 (** given-clause algorithm with full reduction strategy *)
1584 let rec given_clause_fullred dbd env goals theorems passive active =
1585   let goals = simplify_goals env goals ~passive active in
1586   let ok, goals = activate_goal goals in
1587 (*   let theorems = simplify_theorems env theorems ~passive active in *)
1588   if ok then
1589 (*     let _ = *)
1590 (*       debug_print *)
1591 (*         (lazy *)
1592 (*            (Printf.sprintf "\ngoals = \nactive\n%s\npassive\n%s\n" *)
1593 (*               (print_goals (fst goals)) (print_goals (snd goals)))); *)
1594 (*       let current = List.hd (fst goals) in *)
1595 (*       let p, _, t = List.hd (snd current) in *)
1596 (*       debug_print *)
1597 (*         (lazy *)
1598 (*            (Printf.sprintf "goal activated:\n%s\n%s\n" *)
1599 (*               (CicPp.ppterm t) (string_of_proof p))); *)
1600 (*     in *)
1601     let ok, goals =
1602       apply_goal_to_theorems dbd env theorems ~passive active goals
1603     in
1604     if ok then
1605       let proof =
1606         match (fst goals) with
1607         | (_, [proof, _, _])::_ -> Some proof
1608         | _ -> assert false
1609       in
1610       ParamodulationSuccess (proof, env)
1611     else
1612       given_clause_fullred_aux dbd env goals theorems passive active
1613   else
1614 (*     let ok', theorems = activate_theorem theorems in *)
1615 (*     if ok' then *)
1616 (*       let ok, goals = apply_theorem_to_goals env theorems active goals in *)
1617 (*       if ok then *)
1618 (*         let proof = *)
1619 (*           match (fst goals) with *)
1620 (*           | (_, [proof, _, _])::_ -> Some proof *)
1621 (*           | _ -> assert false *)
1622 (*         in *)
1623 (*         ParamodulationSuccess (proof, env) *)
1624 (*       else *)
1625 (*         given_clause_fullred_aux env goals theorems passive active *)
1626 (*     else *)
1627       if (passive_is_empty passive) then ParamodulationFailure
1628       else given_clause_fullred_aux dbd env goals theorems passive active
1629     
1630 and given_clause_fullred_aux dbd env goals theorems passive active =
1631   let time1 = Unix.gettimeofday () in
1632   
1633   let selection_estimate = get_selection_estimate () in
1634   let kept = size_of_passive passive in
1635   let passive =
1636     if !time_limit = 0. || !processed_clauses = 0 then
1637       passive
1638     else if !elapsed_time > !time_limit then (
1639       debug_print (lazy (Printf.sprintf "Time limit (%.2f) reached: %.2f\n"
1640                            !time_limit !elapsed_time));
1641       make_passive [] []
1642     ) else if kept > selection_estimate then (
1643       debug_print
1644         (lazy (Printf.sprintf ("Too many passive equalities: pruning..." ^^
1645                                  "(kept: %d, selection_estimate: %d)\n")
1646                  kept selection_estimate));
1647       prune_passive selection_estimate active passive
1648     ) else
1649       passive
1650   in
1651
1652   let time2 = Unix.gettimeofday () in
1653   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
1654   
1655   kept_clauses := (size_of_passive passive) + (size_of_active active);
1656   match passive_is_empty passive with
1657   | true -> (* ParamodulationFailure *)
1658       given_clause_fullred dbd env goals theorems passive active        
1659   | false ->
1660       let (sign, current), passive = select env (fst goals) passive active in
1661       let time1 = Unix.gettimeofday () in
1662       let res = forward_simplify env (sign, current) ~passive active in
1663       let time2 = Unix.gettimeofday () in
1664       forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
1665       match res with
1666       | None ->
1667           given_clause_fullred dbd env goals theorems passive active
1668       | Some (sign, current) ->
1669           if (sign = Negative) && (is_identity env current) then (
1670             debug_print
1671               (lazy (Printf.sprintf "OK!!! %s %s" (string_of_sign sign)
1672                        (string_of_equality ~env current)));
1673             let _, proof, _, _, _ = current in 
1674             ParamodulationSuccess (Some proof, env)
1675           ) else (
1676             debug_print
1677               (lazy "\n================================================");
1678             debug_print (lazy (Printf.sprintf "selected: %s %s"
1679                                  (string_of_sign sign)
1680                                  (string_of_equality ~env current)));
1681
1682             let t1 = Unix.gettimeofday () in
1683             let new' = infer env sign current active in
1684             let t2 = Unix.gettimeofday () in
1685             infer_time := !infer_time +. (t2 -. t1);
1686
1687             let active =
1688               if is_identity env current then active
1689               else
1690                 let al, tbl = active in
1691                 match sign with
1692                 | Negative -> (sign, current)::al, tbl
1693                 | Positive ->
1694                     al @ [(sign, current)], Indexing.index tbl current
1695             in
1696             let rec simplify new' active passive =
1697               let t1 = Unix.gettimeofday () in
1698               let new' = forward_simplify_new env new' ~passive active in
1699               let t2 = Unix.gettimeofday () in
1700               forward_simpl_new_time :=
1701                 !forward_simpl_new_time +. (t2 -. t1);
1702               let t1 = Unix.gettimeofday () in
1703               let active, passive, newa, retained =
1704                 backward_simplify env new' ~passive active in
1705               let t2 = Unix.gettimeofday () in
1706               backward_simpl_time := !backward_simpl_time +. (t2 -. t1);
1707               match newa, retained with
1708               | None, None -> active, passive, new'
1709               | Some (n, p), None
1710               | None, Some (n, p) ->
1711                   let nn, np = new' in
1712                   simplify (nn @ n, np @ p) active passive
1713               | Some (n, p), Some (rn, rp) ->
1714                   let nn, np = new' in
1715                   simplify (nn @ n @ rn, np @ p @ rp) active passive
1716             in
1717             let active, passive, new' = simplify new' active passive in
1718
1719             let k = size_of_passive passive in
1720             if k < (kept - 1) then
1721               processed_clauses := !processed_clauses + (kept - 1 - k);
1722             
1723             let _ =
1724               debug_print
1725                 (lazy
1726                    (Printf.sprintf "active:\n%s\n"
1727                       (String.concat "\n"
1728                          ((List.map
1729                              (fun (s, e) -> (string_of_sign s) ^ " " ^
1730                                 (string_of_equality ~env e))
1731                              (fst active))))))
1732             in
1733             let _ =
1734               match new' with
1735               | neg, pos ->
1736                   debug_print
1737                     (lazy
1738                        (Printf.sprintf "new':\n%s\n"
1739                           (String.concat "\n"
1740                              ((List.map
1741                                  (fun e -> "Negative " ^
1742                                     (string_of_equality ~env e)) neg) @
1743                                 (List.map
1744                                    (fun e -> "Positive " ^
1745                                       (string_of_equality ~env e)) pos)))))
1746             in
1747             match contains_empty env new' with
1748             | false, _ -> 
1749                 let passive = add_to_passive passive new' in
1750                 given_clause_fullred dbd env goals theorems passive active
1751             | true, goal ->
1752                 let proof =
1753                   match goal with
1754                   | Some goal -> let _, proof, _, _, _ = goal in Some proof
1755                   | None -> None
1756                 in
1757                 ParamodulationSuccess (proof, env)
1758           )
1759 ;;
1760
1761
1762 let rec saturate_equations env goal accept_fun passive active =
1763   elapsed_time := Unix.gettimeofday () -. !start_time;
1764   if !elapsed_time > !time_limit then
1765     (active, passive)
1766   else
1767     let (sign, current), passive = select env [1, [goal]] passive active in
1768     let res = forward_simplify env (sign, current) ~passive active in
1769     match res with
1770     | None ->
1771         saturate_equations env goal accept_fun passive active
1772     | Some (sign, current) ->
1773         assert (sign = Positive);
1774         debug_print
1775           (lazy "\n================================================");
1776         debug_print (lazy (Printf.sprintf "selected: %s %s"
1777                              (string_of_sign sign)
1778                              (string_of_equality ~env current)));
1779         let new' = infer env sign current active in
1780         let active =
1781           if is_identity env current then active
1782           else
1783             let al, tbl = active in
1784             al @ [(sign, current)], Indexing.index tbl current
1785         in
1786         let rec simplify new' active passive =
1787           let new' = forward_simplify_new env new' ~passive active in
1788           let active, passive, newa, retained =
1789             backward_simplify env new' ~passive active in
1790           match newa, retained with
1791           | None, None -> active, passive, new'
1792           | Some (n, p), None
1793           | None, Some (n, p) ->
1794               let nn, np = new' in
1795               simplify (nn @ n, np @ p) active passive
1796           | Some (n, p), Some (rn, rp) ->
1797               let nn, np = new' in
1798               simplify (nn @ n @ rn, np @ p @ rp) active passive
1799         in
1800         let active, passive, new' = simplify new' active passive in
1801         let _ =
1802           debug_print
1803             (lazy
1804                (Printf.sprintf "active:\n%s\n"
1805                   (String.concat "\n"
1806                      ((List.map
1807                          (fun (s, e) -> (string_of_sign s) ^ " " ^
1808                             (string_of_equality ~env e))
1809                          (fst active))))))
1810         in
1811         let _ =
1812           match new' with
1813           | neg, pos ->
1814               debug_print
1815                 (lazy
1816                    (Printf.sprintf "new':\n%s\n"
1817                       (String.concat "\n"
1818                          ((List.map
1819                              (fun e -> "Negative " ^
1820                                 (string_of_equality ~env e)) neg) @
1821                             (List.map
1822                                (fun e -> "Positive " ^
1823                                   (string_of_equality ~env e)) pos)))))
1824         in
1825         let new' = match new' with _, pos -> [], List.filter accept_fun pos in
1826         let passive = add_to_passive passive new' in
1827         saturate_equations env goal accept_fun passive active
1828 ;;
1829   
1830
1831
1832
1833 let main dbd full term metasenv ugraph =
1834   let module C = Cic in
1835   let module T = CicTypeChecker in
1836   let module PET = ProofEngineTypes in
1837   let module PP = CicPp in
1838   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1839   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1840   let proof, goals = status in
1841   let goal' = List.nth goals 0 in
1842   let _, metasenv, meta_proof, _ = proof in
1843   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1844   let eq_indexes, equalities, maxm = find_equalities context proof in
1845   let lib_eq_uris, library_equalities, maxm =
1846
1847     find_library_equalities dbd context (proof, goal') (maxm+2)
1848   in
1849   let library_equalities = List.map snd library_equalities in
1850   maxmeta := maxm+2; (* TODO ugly!! *)
1851   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
1852   let new_meta_goal, metasenv, type_of_goal =
1853     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1854     debug_print
1855       (lazy
1856          (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n\n" (CicPp.ppterm ty)));
1857     Cic.Meta (maxm+1, irl),
1858     (maxm+1, context, ty)::metasenv,
1859     ty
1860   in
1861   let env = (metasenv, context, ugraph) in
1862   let t1 = Unix.gettimeofday () in
1863   let theorems =
1864     if full then
1865       let theorems = find_library_theorems dbd env (proof, goal') lib_eq_uris in
1866       let context_hyp = find_context_hypotheses env eq_indexes in
1867       context_hyp @ theorems, []
1868     else
1869       let refl_equal =
1870         let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
1871         UriManager.uri_of_string (us ^ "#xpointer(1/1/1)")
1872       in
1873       let t = CicUtil.term_of_uri refl_equal in
1874       let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
1875       [(t, ty, [])], []
1876   in
1877   let t2 = Unix.gettimeofday () in
1878   debug_print
1879     (lazy
1880        (Printf.sprintf "Time to retrieve theorems: %.9f\n" (t2 -. t1)));
1881   let _ =
1882     debug_print
1883       (lazy
1884          (Printf.sprintf
1885             "Theorems:\n-------------------------------------\n%s\n"
1886             (String.concat "\n"
1887                (List.map
1888                   (fun (t, ty, _) ->
1889                      Printf.sprintf
1890                        "Term: %s, type: %s" (CicPp.ppterm t) (CicPp.ppterm ty))
1891                   (fst theorems)))))
1892   in
1893   (*try*)
1894     let goal = Inference.BasicProof new_meta_goal, [], goal in
1895     let equalities = simplify_equalities env (equalities@library_equalities) in
1896     let active = make_active () in
1897     let passive = make_passive [] equalities in
1898     Printf.printf "\ncurrent goal: %s\n"
1899       (let _, _, g = goal in CicPp.ppterm g);
1900     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
1901     Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
1902     Printf.printf "\nequalities:\n%s\n"
1903       (String.concat "\n"
1904          (List.map
1905             (string_of_equality ~env) equalities));
1906 (*             (equalities @ library_equalities))); *)
1907       print_endline "--------------------------------------------------";
1908       let start = Unix.gettimeofday () in
1909       print_endline "GO!";
1910       start_time := Unix.gettimeofday ();
1911       let res =
1912         let goals = make_goals goal in
1913         (if !use_fullred then given_clause_fullred else given_clause)
1914           dbd env goals theorems passive active
1915       in
1916       let finish = Unix.gettimeofday () in
1917       let _ =
1918         match res with
1919         | ParamodulationFailure ->
1920             Printf.printf "NO proof found! :-(\n\n"
1921         | ParamodulationSuccess (Some proof, env) ->
1922             let proof = Inference.build_proof_term proof in
1923             Printf.printf "OK, found a proof!\n";
1924             (* REMEMBER: we have to instantiate meta_proof, we should use
1925                apply  the "apply" tactic to proof and status 
1926             *)
1927             let names = names_of_context context in
1928             print_endline (PP.pp proof names);
1929             let newmetasenv =
1930               List.fold_left
1931                 (fun m (_, _, _, menv, _) -> m @ menv) metasenv equalities
1932             in
1933             let _ =
1934               (*try*)
1935                 let ty, ug =
1936                   CicTypeChecker.type_of_aux' newmetasenv context proof ugraph
1937                 in
1938                 print_endline (string_of_float (finish -. start));
1939                 Printf.printf
1940                   "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n\n"
1941                   (CicPp.pp type_of_goal names) (CicPp.pp ty names)
1942                   (string_of_bool
1943                      (fst (CicReduction.are_convertible
1944                              context type_of_goal ty ug)));
1945               (*with e ->
1946                 Printf.printf "\nEXCEPTION!!! %s\n" (Printexc.to_string e);
1947                 Printf.printf "MAXMETA USED: %d\n" !maxmeta;
1948                 print_endline (string_of_float (finish -. start));*)
1949             in
1950             ()
1951               
1952         | ParamodulationSuccess (None, env) ->
1953             Printf.printf "Success, but no proof?!?\n\n"
1954       in
1955       Printf.printf ("infer_time: %.9f\nforward_simpl_time: %.9f\n" ^^
1956                        "forward_simpl_new_time: %.9f\n" ^^
1957                        "backward_simpl_time: %.9f\n")
1958         !infer_time !forward_simpl_time !forward_simpl_new_time
1959         !backward_simpl_time;
1960       Printf.printf "passive_maintainance_time: %.9f\n"
1961         !passive_maintainance_time;
1962       Printf.printf "    successful unification/matching time: %.9f\n"
1963         !Indexing.match_unif_time_ok;
1964       Printf.printf "    failed unification/matching time: %.9f\n"
1965         !Indexing.match_unif_time_no;
1966       Printf.printf "    indexing retrieval time: %.9f\n"
1967         !Indexing.indexing_retrieval_time;
1968       Printf.printf "    demodulate_term.build_newtarget_time: %.9f\n"
1969         !Indexing.build_newtarget_time;
1970       Printf.printf "derived %d clauses, kept %d clauses.\n"
1971         !derived_clauses !kept_clauses;
1972 (*
1973   with exc ->
1974     print_endline ("EXCEPTION: " ^ (Printexc.to_string exc));
1975     raise exc
1976 *)
1977 ;;
1978
1979
1980 let default_depth = !maxdepth
1981 and default_width = !maxwidth;;
1982
1983 let reset_refs () =
1984   maxmeta := 0;
1985   symbols_counter := 0;
1986   weight_age_counter := !weight_age_ratio;
1987   processed_clauses := 0;
1988   start_time := 0.;
1989   elapsed_time := 0.;
1990   maximal_retained_equality := None;
1991   infer_time := 0.;
1992   forward_simpl_time := 0.;
1993   forward_simpl_new_time := 0.;
1994   backward_simpl_time := 0.;
1995   passive_maintainance_time := 0.;
1996   derived_clauses := 0;
1997   kept_clauses := 0;
1998 ;;
1999
2000 let saturate
2001     dbd ?(full=false) ?(depth=default_depth) ?(width=default_width) status = 
2002   let module C = Cic in
2003   reset_refs ();
2004   Indexing.init_index ();
2005   maxdepth := depth;
2006   maxwidth := width;
2007   let proof, goal = status in
2008   let goal' = goal in
2009   let uri, metasenv, meta_proof, term_to_prove = proof in
2010   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
2011   let eq_indexes, equalities, maxm = find_equalities context proof in
2012   let new_meta_goal, metasenv, type_of_goal =
2013     let irl =
2014       CicMkImplicit.identity_relocation_list_for_metavariable context in
2015     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
2016     debug_print
2017       (lazy (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n" (CicPp.ppterm ty)));
2018     Cic.Meta (maxm+1, irl),
2019     (maxm+1, context, ty)::metasenv,
2020     ty
2021   in
2022   let ugraph = CicUniv.empty_ugraph in
2023   let env = (metasenv, context, ugraph) in
2024   let goal = Inference.BasicProof new_meta_goal, [], goal in
2025   let res, time =
2026     let t1 = Unix.gettimeofday () in
2027     let lib_eq_uris, library_equalities, maxm =
2028       find_library_equalities dbd context (proof, goal') (maxm+2)
2029     in
2030     let library_equalities = List.map snd library_equalities in
2031     let t2 = Unix.gettimeofday () in
2032     maxmeta := maxm+2;
2033     let equalities = simplify_equalities env (equalities@library_equalities) in
2034     debug_print
2035       (lazy
2036          (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)));
2037     let t1 = Unix.gettimeofday () in
2038     let theorems =
2039       if full then
2040         let thms = find_library_theorems dbd env (proof, goal') lib_eq_uris in
2041         let context_hyp = find_context_hypotheses env eq_indexes in
2042         context_hyp @ thms, []
2043       else
2044         let refl_equal =
2045           let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
2046           UriManager.uri_of_string (us ^ "#xpointer(1/1/1)")
2047         in
2048         let t = CicUtil.term_of_uri refl_equal in
2049         let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
2050         [(t, ty, [])], []
2051     in
2052     let t2 = Unix.gettimeofday () in
2053     let _ =
2054       debug_print
2055         (lazy
2056            (Printf.sprintf
2057               "Theorems:\n-------------------------------------\n%s\n"
2058               (String.concat "\n"
2059                  (List.map
2060                     (fun (t, ty, _) ->
2061                        Printf.sprintf
2062                          "Term: %s, type: %s"
2063                          (CicPp.ppterm t) (CicPp.ppterm ty))
2064                     (fst theorems)))));
2065       debug_print
2066         (lazy
2067            (Printf.sprintf "Time to retrieve theorems: %.9f\n" (t2 -. t1)));
2068     in
2069     let active = make_active () in
2070     let passive = make_passive [] equalities in
2071     let start = Unix.gettimeofday () in
2072     let res =
2073       let goals = make_goals goal in
2074       given_clause_fullred dbd env goals theorems passive active
2075     in
2076     let finish = Unix.gettimeofday () in
2077     (res, finish -. start)
2078   in
2079   match res with
2080   | ParamodulationSuccess (Some proof, env) ->
2081       debug_print (lazy "OK, found a proof!");
2082       let proof = Inference.build_proof_term proof in
2083       let names = names_of_context context in
2084       let newmetasenv =
2085         let i1 =
2086           match new_meta_goal with
2087           | C.Meta (i, _) -> i | _ -> assert false
2088         in
2089         List.filter (fun (i, _, _) -> i <> i1 && i <> goal') metasenv
2090       in
2091       let newstatus =
2092         try
2093           let ty, ug =
2094             CicTypeChecker.type_of_aux' newmetasenv context proof ugraph
2095           in
2096           debug_print (lazy (CicPp.pp proof [](* names *)));
2097           debug_print
2098             (lazy
2099                (Printf.sprintf
2100                   "\nGOAL was: %s\nPROOF has type: %s\nconvertible?: %s\n"
2101                   (CicPp.pp type_of_goal names) (CicPp.pp ty names)
2102                   (string_of_bool
2103                      (fst (CicReduction.are_convertible
2104                              context type_of_goal ty ug)))));
2105           let equality_for_replace i t1 =
2106             match t1 with
2107             | C.Meta (n, _) -> n = i
2108             | _ -> false
2109           in
2110           let real_proof =
2111             ProofEngineReduction.replace
2112               ~equality:equality_for_replace
2113               ~what:[goal'] ~with_what:[proof]
2114               ~where:meta_proof
2115           in
2116           debug_print
2117             (lazy
2118                (Printf.sprintf "status:\n%s\n%s\n%s\n%s\n"
2119                   (match uri with Some uri -> UriManager.string_of_uri uri
2120                    | None -> "")
2121                   (print_metasenv newmetasenv)
2122                   (CicPp.pp real_proof [](* names *))
2123                   (CicPp.pp term_to_prove names)));
2124           ((uri, newmetasenv, real_proof, term_to_prove), [])
2125         with CicTypeChecker.TypeCheckerFailure _ ->
2126           debug_print (lazy "THE PROOF DOESN'T TYPECHECK!!!");
2127           debug_print (lazy (CicPp.pp proof names));
2128           raise (ProofEngineTypes.Fail
2129                   (lazy "Found a proof, but it doesn't typecheck"))
2130       in
2131       let tall = fs_time_info.build_all in
2132       let tdemodulate = fs_time_info.demodulate in
2133       let tsubsumption = fs_time_info.subsumption in
2134       debug_print (lazy (Printf.sprintf "\nTIME NEEDED: %.9f" time));
2135       debug_print (lazy (Printf.sprintf "\ntall: %.9f" tall));
2136       debug_print (lazy (Printf.sprintf "\ntdemod: %.9f" tdemodulate));
2137       debug_print (lazy (Printf.sprintf "\ntsubsumption: %.9f" tsubsumption));
2138       debug_print (lazy (Printf.sprintf "\ninfer_time: %.9f" !infer_time));
2139       debug_print (lazy (Printf.sprintf "\nforward_simpl_times: %.9f" !forward_simpl_time));
2140       debug_print (lazy (Printf.sprintf "\nforward_simpl_new_times: %.9f" !forward_simpl_new_time));
2141       debug_print (lazy (Printf.sprintf "\nbackward_simpl_times: %.9f" !backward_simpl_time));
2142       debug_print (lazy (Printf.sprintf "\npassive_maintainance_time: %.9f" !passive_maintainance_time));
2143       newstatus          
2144   | _ ->
2145       raise (ProofEngineTypes.Fail (lazy "NO proof found"))
2146 ;;
2147
2148 (* dummy function called within matita to trigger linkage *)
2149 let init () = ();;
2150
2151
2152 let retrieve_and_print dbd term metasenv ugraph = 
2153   let module C = Cic in
2154   let module T = CicTypeChecker in
2155   let module PET = ProofEngineTypes in
2156   let module PP = CicPp in
2157   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
2158   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
2159   let proof, goals = status in
2160   let goal' = List.nth goals 0 in
2161   let uri, metasenv, meta_proof, term_to_prove = proof in
2162   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
2163   let eq_indexes, equalities, maxm = find_equalities context proof in
2164   let new_meta_goal, metasenv, type_of_goal =
2165     let irl =
2166       CicMkImplicit.identity_relocation_list_for_metavariable context in
2167     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
2168     debug_print
2169       (lazy (Printf.sprintf "\n\nTIPO DEL GOAL: %s\n" (CicPp.ppterm ty)));
2170     Cic.Meta (maxm+1, irl),
2171     (maxm+1, context, ty)::metasenv,
2172     ty
2173   in
2174   let ugraph = CicUniv.empty_ugraph in
2175   let env = (metasenv, context, ugraph) in
2176   let t1 = Unix.gettimeofday () in
2177   let lib_eq_uris, library_equalities, maxm =
2178     find_library_equalities dbd context (proof, goal') (maxm+2) in
2179   let t2 = Unix.gettimeofday () in
2180   maxmeta := maxm+2;
2181   let equalities = (* equalities @ *) library_equalities in
2182   debug_print
2183      (lazy
2184         (Printf.sprintf "\n\nequalities:\n%s\n"
2185            (String.concat "\n"
2186               (List.map 
2187           (fun (u, e) ->
2188 (*               Printf.sprintf "%s: %s" *)
2189                    (UriManager.string_of_uri u)
2190 (*                 (string_of_equality e) *)
2191                      )
2192           equalities))));
2193   debug_print (lazy "SIMPLYFYING EQUALITIES...");
2194   let rec simpl e others others_simpl =
2195     let (u, e) = e in
2196     let active = List.map (fun (u, e) -> (Positive, e))
2197       (others @ others_simpl) in
2198     let tbl =
2199       List.fold_left
2200         (fun t (_, e) -> Indexing.index t e)
2201         Indexing.empty active
2202     in
2203     let res = forward_simplify env (Positive, e) (active, tbl) in
2204     match others with
2205         | hd::tl -> (
2206             match res with
2207               | None -> simpl hd tl others_simpl
2208               | Some e -> simpl hd tl ((u, (snd e))::others_simpl)
2209           )
2210         | [] -> (
2211             match res with
2212               | None -> others_simpl
2213               | Some e -> (u, (snd e))::others_simpl
2214           ) 
2215   in
2216   let _equalities =
2217     match equalities with
2218       | [] -> []
2219       | hd::tl ->
2220           let others = tl in (* List.map (fun e -> (Positive, e)) tl in *)
2221           let res =
2222             List.rev (simpl (*(Positive,*) hd others [])
2223           in
2224             debug_print
2225               (lazy
2226                  (Printf.sprintf "\nequalities AFTER:\n%s\n"
2227                     (String.concat "\n"
2228                        (List.map
2229                           (fun (u, e) ->
2230                              Printf.sprintf "%s: %s"
2231                                (UriManager.string_of_uri u)
2232                                (string_of_equality e)
2233                           )
2234                           res))));
2235             res in
2236     debug_print
2237       (lazy
2238          (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)))
2239 ;;
2240
2241
2242 let main_demod_equalities dbd term metasenv ugraph =
2243   let module C = Cic in
2244   let module T = CicTypeChecker in
2245   let module PET = ProofEngineTypes in
2246   let module PP = CicPp in
2247   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
2248   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
2249   let proof, goals = status in
2250   let goal' = List.nth goals 0 in
2251   let _, metasenv, meta_proof, _ = proof in
2252   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
2253   let eq_indexes, equalities, maxm = find_equalities context proof in
2254   let lib_eq_uris, library_equalities, maxm =
2255     find_library_equalities dbd context (proof, goal') (maxm+2)
2256   in
2257   let library_equalities = List.map snd library_equalities in
2258   maxmeta := maxm+2; (* TODO ugly!! *)
2259   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
2260   let new_meta_goal, metasenv, type_of_goal =
2261     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
2262     debug_print
2263       (lazy
2264          (Printf.sprintf "\n\nTRYING TO INFER EQUALITIES MATCHING: %s\n\n"
2265             (CicPp.ppterm ty)));
2266     Cic.Meta (maxm+1, irl),
2267     (maxm+1, context, ty)::metasenv,
2268     ty
2269   in
2270   let env = (metasenv, context, ugraph) in
2271   (*try*)
2272     let goal = Inference.BasicProof new_meta_goal, [], goal in
2273     let equalities = simplify_equalities env (equalities@library_equalities) in
2274     let active = make_active () in
2275     let passive = make_passive [] equalities in
2276     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
2277     Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
2278     Printf.printf "\nequalities:\n%s\n"
2279       (String.concat "\n"
2280          (List.map
2281             (string_of_equality ~env) equalities));
2282     print_endline "--------------------------------------------------";
2283     print_endline "GO!";
2284     start_time := Unix.gettimeofday ();
2285     if !time_limit < 1. then time_limit := 60.;    
2286     let ra, rp =
2287       saturate_equations env goal (fun e -> true) passive active
2288     in
2289
2290     let initial =
2291       List.fold_left (fun s e -> EqualitySet.add e s)
2292         EqualitySet.empty equalities
2293     in
2294     let addfun s e = 
2295       if not (EqualitySet.mem e initial) then EqualitySet.add e s else s
2296     in
2297
2298     let passive =
2299       match rp with
2300       | (n, _), (p, _), _ ->
2301           EqualitySet.elements (List.fold_left addfun EqualitySet.empty p)
2302     in
2303     let active =
2304       let l = List.map snd (fst ra) in
2305       EqualitySet.elements (List.fold_left addfun EqualitySet.empty l)
2306     in
2307     Printf.printf "\n\nRESULTS:\nActive:\n%s\n\nPassive:\n%s\n"
2308        (String.concat "\n" (List.map (string_of_equality ~env) active)) 
2309      (*  (String.concat "\n"
2310          (List.map (fun e -> CicPp.ppterm (term_of_equality e)) active)) *)
2311 (*       (String.concat "\n" (List.map (string_of_equality ~env) passive)); *)
2312       (String.concat "\n"
2313          (List.map (fun e -> CicPp.ppterm (term_of_equality e)) passive));
2314     print_newline ();
2315 (*
2316   with e ->
2317     debug_print (lazy ("EXCEPTION: " ^ (Printexc.to_string e)))
2318 *)
2319 ;;
2320
2321 let demodulate_tac ~dbd ~pattern ((proof,goal) as initialstatus) = 
2322   let module I = Inference in
2323   let curi,metasenv,pbo,pty = proof in
2324   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
2325   let eq_indexes, equalities, maxm = I.find_equalities context proof in
2326   let lib_eq_uris, library_equalities, maxm =
2327     I.find_library_equalities dbd context (proof, goal) (maxm+2) in
2328   if library_equalities = [] then prerr_endline "VUOTA!!!";
2329   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
2330   let library_equalities = List.map snd library_equalities in
2331   let goalterm = Cic.Meta (metano,irl) in
2332   let initgoal = Inference.BasicProof goalterm, [], ty in
2333   let env = (metasenv, context, CicUniv.empty_ugraph) in
2334   let equalities = simplify_equalities env (equalities@library_equalities) in  
2335   let table = 
2336     List.fold_left 
2337       (fun tbl eq -> Indexing.index tbl eq) 
2338       Indexing.empty equalities 
2339   in
2340   let newmeta,(newproof,newmetasenv, newty) = Indexing.demodulation_goal 
2341     maxm (metasenv,context,CicUniv.empty_ugraph) table initgoal 
2342   in
2343   if newmeta != maxm then
2344     begin
2345       let opengoal = Cic.Meta(maxm,irl) in
2346       let proofterm = 
2347         Inference.build_proof_term ~noproof:opengoal newproof in
2348         let extended_metasenv = (maxm,context,newty)::metasenv in
2349         let extended_status = 
2350           (curi,extended_metasenv,pbo,pty),goal in
2351         let (status,newgoals) = 
2352           ProofEngineTypes.apply_tactic 
2353             (PrimitiveTactics.apply_tac ~term:proofterm)
2354             extended_status in
2355         (status,maxm::newgoals)
2356     end
2357   else if newty = ty then
2358     raise (ProofEngineTypes.Fail (lazy "no progress"))
2359   else ProofEngineTypes.apply_tactic 
2360     (ReductionTactics.simpl_tac ~pattern) 
2361     initialstatus
2362 ;;
2363
2364 let demodulate_tac ~dbd ~pattern = 
2365   ProofEngineTypes.mk_tactic (demodulate_tac ~dbd ~pattern)
2366 ;;