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