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