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