]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/paramodulation/saturation.ml
Added the computation of max_weight for equations in proofs.
[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 let _profiler = <:profiler<_profiler>>;;
27
28 (* $Id$ *)
29
30 (* set to false to disable paramodulation inside auto_tac *)
31
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.proof * int * Subst.substitution * Cic.metasenv
75 type result =
76   | ParamodulationFailure of string
77   | ParamodulationSuccess of new_proof
78 ;;
79
80 (* type goal = Equality.goal_proof * Cic.metasenv * Cic.term;; *)
81
82 type theorem = Cic.term * Cic.term * Cic.metasenv;;
83
84 let symbols_of_equality equality = 
85   let (_, _, (_, left, right, _), _,_) = Equality.open_equality equality in
86   let m1 = Utils.symbols_of_term left in
87   let m = 
88     Utils.TermMap.fold
89       (fun k v res ->
90          try
91            let c = Utils.TermMap.find k res in
92            Utils.TermMap.add k (c+v) res
93          with Not_found ->
94            Utils.TermMap.add k v res)
95       (Utils.symbols_of_term right) m1
96   in
97   m
98 ;;
99
100 (* griggio *)
101 module OrderedEquality = struct 
102   type t = Equality.equality
103
104   let compare eq1 eq2 =
105     match Equality.meta_convertibility_eq eq1 eq2 with
106     | true -> 0
107     | false -> 
108         let w1, _, (ty,left, right, _), m1,_ = Equality.open_equality eq1 in
109         let w2, _, (ty',left', right', _), m2,_ = Equality.open_equality eq2 in
110         match Pervasives.compare w1 w2 with
111         | 0 -> 
112             let res = (List.length m1) - (List.length m2) in 
113             if res <> 0 then res else 
114               Equality.compare eq1 eq2
115         | res -> res 
116 end 
117
118 module EqualitySet = Set.Make(OrderedEquality);;
119
120 exception Empty_list;;
121
122 type passives = Equality.equality list * EqualitySet.t;;
123 type actives = Equality.equality list * Indexing.Index.t;;
124
125 (* initializes the passive set of equalities 
126  * XXX I think EqualitySet.elements should be ok (to eliminate duplicates)
127  *)
128 let make_passive pos =
129   let set =
130     List.fold_left (fun s e -> EqualitySet.add e s) EqualitySet.empty pos
131   in
132   (*EqualitySet.elements*) pos, set
133 ;;
134
135 let make_active () = [], Indexing.empty ;;
136 let size_of_passive (passive_list, _) = List.length passive_list;;
137 let size_of_active (active_list, _) = List.length active_list;;
138 let passive_is_empty = function
139   | [], s when EqualitySet.is_empty s -> true
140   | [], s -> assert false (* the set and the list should be in sync *)
141   | _ -> false
142 ;;
143
144 type goals = Equality.goal list * Equality.goal list
145
146 let no_more_passive_goals g = match g with | _,[] -> true | _ -> false;;
147   
148
149 let age_factor = 0.01;;
150
151 (**
152    selects one equality from passive. The selection strategy is a combination
153    of weight, age and goal-similarity
154 *)
155
156 let rec select env g passive =
157   processed_clauses := !processed_clauses + 1;
158 (*
159   let goal =
160     match (List.rev goals) with goal::_ -> goal | _ -> assert false
161   in
162 *)
163   let pos_list, pos_set = passive in
164   let remove eq l = List.filter (fun e -> Equality.compare e eq <> 0) l in
165   if !weight_age_ratio > 0 then
166     weight_age_counter := !weight_age_counter - 1;
167   match !weight_age_counter with
168   | 0 -> (
169       weight_age_counter := !weight_age_ratio;
170       let skip_giant pos_list pos_set =
171         match pos_list with
172           | (hd:EqualitySet.elt)::tl ->
173               let w,_,_,_,_ = Equality.open_equality hd in
174                 if w < 30 then
175                   hd, (tl, EqualitySet.remove hd pos_set)
176                 else
177                   (prerr_endline 
178                     ("+++ skipping giant of size "^string_of_int w^" +++");
179                   select env g (tl@[hd],pos_set))
180           | _ -> assert false
181                    in
182                     skip_giant pos_list pos_set)
183
184 (*
185       let rec skip_giant pos_list pos_set =
186         match pos_list with
187           | (hd:EqualitySet.elt)::tl ->
188               let w,_,_,_,_ = Equality.open_equality hd in
189               let pos_set = EqualitySet.remove hd pos_set in
190                 if w < 30 then
191                   hd, (tl, pos_set)
192                 else
193                   (prerr_endline 
194                     ("+++ skipping giant of size "^string_of_int w^" +++");
195                   skip_giant tl pos_set)
196           | _ -> assert false
197       in        
198   skip_giant pos_list pos_set)
199
200 *)
201 (*
202   | _ when (!symbols_counter > 0) -> 
203      (symbols_counter := !symbols_counter - 1;
204       let cardinality map =
205         Utils.TermMap.fold (fun k v res -> res + v) map 0
206       in
207       let symbols =
208         let _, _, term = goal in
209         Utils.symbols_of_term term
210       in
211       let card = cardinality symbols in
212       let foldfun k v (r1, r2) = 
213         if Utils.TermMap.mem k symbols then
214           let c = Utils.TermMap.find k symbols in
215           let c1 = abs (c - v) in
216           let c2 = v - c1 in
217           r1 + c2, r2 + c1
218         else
219           r1, r2 + v
220       in
221       let f equality (i, e) =
222         let common, others =
223           Utils.TermMap.fold foldfun (symbols_of_equality equality) (0, 0)
224         in
225         let c = others + (abs (common - card)) in
226         if c < i then (c, equality)
227         else (i, e)
228       in
229       let e1 = EqualitySet.min_elt pos_set in
230       let initial =
231         let common, others = 
232           Utils.TermMap.fold foldfun (symbols_of_equality e1) (0, 0)
233         in
234         (others + (abs (common - card))), e1
235       in
236       let _, current = EqualitySet.fold f pos_set initial in
237         current,
238       (remove current pos_list, EqualitySet.remove current pos_set))
239 *)
240   | _ ->
241       symbols_counter := !symbols_ratio;
242       let my_min e1 e2 =
243         let w1,_,_,_,_ = Equality.open_equality e1 in
244         let w2,_,_,_,_ = Equality.open_equality e2 in
245         if w1 < w2 then e1 else e2
246       in
247       let rec my_min_elt min = function
248         | [] -> min
249         | hd::tl -> my_min_elt (my_min hd min) tl
250       in
251 (*     let current = EqualitySet.min_elt pos_set in  *)
252        let current = my_min_elt (List.hd pos_list) (List.tl pos_list) in 
253        current,(remove current pos_list, EqualitySet.remove current pos_set)
254 ;;
255
256
257 let filter_dependent passive id =
258   let pos_list, pos_set = passive in
259   let passive,no_pruned =
260     List.fold_right
261       (fun eq ((list,set),no) ->
262          if Equality.depend eq id then
263            (list, EqualitySet.remove eq set), no + 1
264          else 
265            (eq::list, set), no)
266       pos_list (([],pos_set),0)
267   in
268   if no_pruned > 0 then
269     prerr_endline ("+++ pruning "^ string_of_int no_pruned ^" passives +++");  
270   passive
271 ;;
272
273
274 (* adds to passive a list of equalities new_pos *)
275 let add_to_passive passive new_pos preferred =
276   let pos_list, pos_set = passive in
277   let ok set equality = not (EqualitySet.mem equality set) in
278   let pos = List.filter (ok pos_set) new_pos in
279   let add set equalities =
280     List.fold_left (fun s e -> EqualitySet.add e s) set equalities
281   in
282   let pos_head, pos_tail =
283     List.partition 
284       (fun e -> List.exists (fun x -> Equality.compare x e = 0) preferred)  
285       pos 
286   in
287   assert(pos_head = []);
288   pos_head @ pos_list @ pos_tail, add pos_set pos
289 ;;
290
291 (* TODO *)
292 (* removes from passive equalities that are estimated impossible to activate
293    within the current time limit *)
294 let prune_passive howmany (active, _) passive =
295   let (pl, ps), tbl = passive in
296   let howmany = float_of_int howmany
297   and ratio = float_of_int !weight_age_ratio in
298   let round v =
299     let t = ceil v in 
300     int_of_float (if t -. v < 0.5 then t else v)
301   in
302   let in_weight = round (howmany *. ratio /. (ratio +. 1.))
303   and in_age = round (howmany /. (ratio +. 1.)) in 
304   Utils.debug_print
305     (lazy (Printf.sprintf "in_weight: %d, in_age: %d\n" in_weight in_age));
306   let counter = ref !symbols_ratio in
307   let rec pickw w ps =
308     if w > 0 then
309       if !counter > 0 then
310         let _ =
311           counter := !counter - 1;
312           if !counter = 0 then counter := !symbols_ratio in
313         let e = EqualitySet.min_elt ps in
314         let ps' = pickw (w-1) (EqualitySet.remove e ps) in
315           EqualitySet.add e ps'
316       else
317         let e = EqualitySet.min_elt ps in
318         let ps' = pickw (w-1) (EqualitySet.remove e ps) in
319         EqualitySet.add e ps'        
320     else
321       EqualitySet.empty
322   in
323   let ps = pickw in_weight ps in
324   let rec picka w s l =
325     if w > 0 then
326       match l with
327       | [] -> w, s, []
328       | hd::tl when not (EqualitySet.mem hd s) ->
329           let w, s, l = picka (w-1) s tl in
330           w, EqualitySet.add hd s, hd::l
331       | hd::tl ->
332           let w, s, l = picka w s tl in
333           w, s, hd::l
334     else
335       0, s, l
336   in
337   let _, ps, pl = picka in_age ps pl in
338   if not (EqualitySet.is_empty ps) then
339     maximal_retained_equality := Some (EqualitySet.max_elt ps); 
340   let tbl =
341     EqualitySet.fold
342       (fun e tbl -> Indexing.index tbl e) ps Indexing.empty
343   in
344   (pl, ps), tbl  
345 ;;
346
347
348 (** inference of new equalities between current and some in active *)
349 let infer eq_uri env current (active_list, active_table) =
350   let (_,c,_) = env in 
351   if Utils.debug_metas then
352     (ignore(Indexing.check_target c current "infer1");
353      ignore(List.map (function current -> Indexing.check_target c current "infer2") active_list)); 
354   let new_pos = 
355       let maxm, copy_of_current = Equality.fix_metas !maxmeta current in
356         maxmeta := maxm;
357       let active_table =  Indexing.index active_table copy_of_current in
358       let _ = <:start<current contro active>> in
359       let maxm, res =
360         Indexing.superposition_right eq_uri !maxmeta env active_table current 
361       in
362       let _ = <:stop<current contro active>> in
363       if Utils.debug_metas then
364         ignore(List.map 
365                  (function current -> 
366                     Indexing.check_target c current "sup0") res);
367       maxmeta := maxm;
368       let rec infer_positive table = function
369         | [] -> []
370         | equality::tl ->
371             let maxm, res =
372               Indexing.superposition_right 
373                 ~subterms_only:true eq_uri !maxmeta env table equality 
374             in
375               maxmeta := maxm;
376               if Utils.debug_metas then
377                 ignore
378                   (List.map 
379                      (function current -> 
380                         Indexing.check_target c current "sup2") res);
381               let pos = infer_positive table tl in
382               res @ pos
383       in
384 (*
385       let maxm, copy_of_current = Equality.fix_metas !maxmeta current in
386         maxmeta := maxm;
387 *)
388       let curr_table = Indexing.index Indexing.empty current in
389       let _ = <:start<active contro current>> in
390       let pos = infer_positive curr_table ((*copy_of_current::*)active_list) in
391       let _ = <:stop<active contro current>> in
392       if Utils.debug_metas then 
393         ignore(List.map 
394                  (function current -> 
395                     Indexing.check_target c current "sup3") pos);
396       res @ pos
397   in
398   derived_clauses := !derived_clauses + (List.length new_pos);
399   match !maximal_retained_equality with
400     | None -> new_pos
401     | Some eq ->
402       ignore(assert false);
403       (* if we have a maximal_retained_equality, we can discard all equalities
404          "greater" than it, as they will never be reached...  An equality is
405          greater than maximal_retained_equality if it is bigger
406          wrt. OrderedEquality.compare and it is less similar than
407          maximal_retained_equality to the current goal *)
408         List.filter (fun e -> OrderedEquality.compare e eq <= 0) new_pos
409 ;;
410
411 let check_for_deep_subsumption env active_table eq =
412   let _,_,(eq_ty, left, right, order),metas,id = Equality.open_equality eq in
413   let check_subsumed deep l r = 
414     let eqtmp = 
415       Equality.mk_tmp_equality(0,(eq_ty,l,r,Utils.Incomparable),metas)in
416     match Indexing.subsumption env active_table eqtmp with
417     | None -> false
418     | Some _ -> true        
419   in 
420   let rec aux b (ok_so_far, subsumption_used) t1 t2  = 
421     match t1,t2 with
422       | t1, t2 when not ok_so_far -> ok_so_far, subsumption_used
423       | t1, t2 when subsumption_used -> t1 = t2, subsumption_used
424       | Cic.Appl (h1::l),Cic.Appl (h2::l') ->
425           let rc = check_subsumed b t1 t2 in 
426             if rc then 
427               true, true
428             else if h1 = h2 then
429               (try 
430                  List.fold_left2 
431                    (fun (ok_so_far, subsumption_used) t t' -> 
432                       aux true (ok_so_far, subsumption_used) t t')
433                    (ok_so_far, subsumption_used) l l'
434                with Invalid_argument _ -> false,subsumption_used)
435             else
436               false, subsumption_used
437     | _ -> false, subsumption_used 
438   in
439   fst (aux false (true,false) left right)
440 ;;
441
442 (** simplifies current using active and passive *)
443 let forward_simplify eq_uri env current (active_list, active_table) =
444   let _, context, _ = env in
445   let demodulate table current = 
446     let newmeta, newcurrent =
447       Indexing.demodulation_equality eq_uri !maxmeta env table current
448     in
449     maxmeta := newmeta;
450     if Equality.is_identity env newcurrent then None else Some newcurrent
451   in
452   let rec demod current =
453     if Utils.debug_metas then
454       ignore (Indexing.check_target context current "demod0");
455     let res = demodulate active_table current in
456       if Utils.debug_metas then
457         ignore ((function None -> () | Some x -> 
458                    ignore (Indexing.check_target context x "demod1");()) res);
459     res
460   in 
461   let res = demod current in
462   match res with
463   | None -> None
464   | Some c ->
465       if Indexing.in_index active_table c ||
466          check_for_deep_subsumption env active_table c 
467       then
468         None
469       else 
470         res
471 ;;
472
473 (** simplifies new using active and passive *)
474 let forward_simplify_new eq_uri env new_pos active =
475   if Utils.debug_metas then
476     begin
477       let m,c,u = env in
478         ignore(List.map 
479         (fun current -> Indexing.check_target c current "forward new pos") 
480       new_pos;)
481     end;
482   let active_list, active_table = active in
483   let demodulate table target =
484     let newmeta, newtarget =
485       Indexing.demodulation_equality eq_uri !maxmeta env table target 
486     in
487     maxmeta := newmeta;
488     newtarget
489   in
490   (* we could also demodulate using passive. Currently we don't *)
491   let new_pos = List.map (demodulate active_table) new_pos in
492   let new_pos_set =
493     List.fold_left
494       (fun s e ->
495          if not (Equality.is_identity env e) then
496            EqualitySet.add e s
497          else s)
498       EqualitySet.empty new_pos
499   in
500   let new_pos = EqualitySet.elements new_pos_set in
501
502   let subs e = Indexing.subsumption env active_table e = None in
503   let is_duplicate e = not (Indexing.in_index active_table e) in
504   List.filter subs (List.filter is_duplicate new_pos)
505 ;;
506
507
508 (** simplifies a goal with equalities in active and passive *)  
509 let rec simplify_goal env goal (active_list, active_table) =
510   let demodulate table goal = Indexing.demodulation_goal env table goal in
511   let changed, goal = demodulate active_table goal in
512   changed,
513   if not changed then 
514     goal 
515   else 
516     snd (simplify_goal env goal (active_list, active_table)) 
517 ;;
518
519
520 let simplify_goals env goals active =
521   let a_goals, p_goals = goals in
522   let p_goals = List.map (fun g -> snd (simplify_goal env g active)) p_goals in
523   let a_goals = List.map (fun g -> snd (simplify_goal env g active)) a_goals in
524   a_goals, p_goals
525 ;;
526
527
528 (** simplifies active usign new *)
529 let backward_simplify_active eq_uri env new_pos new_table min_weight active =
530   let active_list, active_table = active in
531   let active_list, newa, pruned = 
532     List.fold_right
533       (fun equality (res, newn,pruned) ->
534          let ew, _, _, _,id = Equality.open_equality equality in
535          if ew < min_weight then
536            equality::res, newn,pruned
537          else
538            match 
539              forward_simplify eq_uri env equality (new_pos, new_table) 
540            with
541            | None -> res, newn, id::pruned
542            | Some e ->
543                if Equality.compare equality e = 0 then
544                  e::res, newn, pruned
545                else 
546                  res, e::newn, pruned)
547       active_list ([], [],[])
548   in
549   let find eq1 where =
550     List.exists (Equality.meta_convertibility_eq eq1) where
551   in
552   let id_of_eq eq = 
553     let _, _, _, _,id = Equality.open_equality eq in id
554   in
555   let ((active1,pruned),tbl), newa =
556     List.fold_right
557       (fun eq ((res,pruned), tbl) ->
558          if List.mem eq res then
559            (res, (id_of_eq eq)::pruned),tbl 
560          else if (Equality.is_identity env eq) || (find eq res) then (
561            (res, (id_of_eq eq)::pruned),tbl
562          ) 
563          else
564            (eq::res,pruned), Indexing.index tbl eq)
565       active_list (([],pruned), Indexing.empty),
566     List.fold_right
567       (fun eq p ->
568          if (Equality.is_identity env eq) then p
569          else eq::p)
570       newa []
571   in
572   match newa with
573   | [] -> (active1,tbl), None, pruned 
574   | _ -> (active1,tbl), Some newa, pruned
575 ;;
576
577
578 (** simplifies passive using new *)
579 let backward_simplify_passive eq_uri env new_pos new_table min_weight passive =
580   let (pl, ps), passive_table = passive in
581   let f equality (resl, ress, newn) =
582     let ew, _, _, _ , _ = Equality.open_equality equality in
583     if ew < min_weight then
584       equality::resl, ress, newn
585     else
586       match 
587         forward_simplify eq_uri env equality (new_pos, new_table) 
588       with
589       | None -> resl, EqualitySet.remove equality ress, newn
590       | Some e ->
591           if equality = e then
592             equality::resl, ress, newn
593           else
594             let ress = EqualitySet.remove equality ress in
595               resl, ress, e::newn
596   in
597   let pl, ps, newp = List.fold_right f pl ([], ps, []) in
598   let passive_table =
599     List.fold_left
600       (fun tbl e -> Indexing.index tbl e) Indexing.empty pl
601   in
602   match newp with
603   | [] -> ((pl, ps), passive_table), None
604   |  _ -> ((pl, ps), passive_table), Some (newp)
605 ;;
606
607 let build_table equations =
608     List.fold_left
609       (fun (l, t, w) e ->
610          let ew, _, _, _ , _ = Equality.open_equality e in
611          e::l, Indexing.index t e, min ew w)
612       ([], Indexing.empty, 1000000) equations
613 ;;
614   
615
616 let backward_simplify eq_uri env new' active =
617   let new_pos, new_table, min_weight = build_table new' in
618   let active, newa, pruned =
619     backward_simplify_active eq_uri env new_pos new_table min_weight active 
620   in
621   active, newa, None, pruned
622 ;;
623
624 let close eq_uri env new' given =
625   let new_pos, new_table, min_weight =
626     List.fold_left
627       (fun (l, t, w) e ->
628          let ew, _, _, _ , _ = Equality.open_equality e in
629          e::l, Indexing.index t e, min ew w)
630       ([], Indexing.empty, 1000000) (snd new')
631   in
632   List.fold_left
633     (fun p c ->
634        let pos = infer eq_uri env c (new_pos,new_table) in
635          pos@p)
636     [] given 
637 ;;
638
639 let is_commutative_law eq =
640   let w, proof, (eq_ty, left, right, order), metas , _ = 
641     Equality.open_equality eq 
642   in
643     match left,right with
644         Cic.Appl[f1;Cic.Meta _ as a1;Cic.Meta _ as b1], 
645         Cic.Appl[f2;Cic.Meta _ as a2;Cic.Meta _ as b2] ->
646           f1 = f2 && a1 = b2 && a2 = b1
647       | _ -> false
648 ;;
649
650 let prova eq_uri env new' active = 
651   let given = List.filter is_commutative_law (fst active) in
652   let _ =
653     Utils.debug_print
654       (lazy
655          (Printf.sprintf "symmetric:\n%s\n"
656             (String.concat "\n"
657                (List.map
658                   (fun e -> Equality.string_of_equality ~env e)
659                    given)))) in
660     close eq_uri env new' given
661 ;;
662
663 (* returns an estimation of how many equalities in passive can be activated
664    within the current time limit *)
665 let get_selection_estimate () =
666   elapsed_time := (Unix.gettimeofday ()) -. !start_time;
667   (*   !processed_clauses * (int_of_float (!time_limit /. !elapsed_time)) *)
668   int_of_float (
669     ceil ((float_of_int !processed_clauses) *.
670             ((!time_limit (* *. 2. *)) /. !elapsed_time -. 1.)))
671 ;;
672
673
674 (** initializes the set of goals *)
675 let make_goals goal =
676   let active = []
677   and passive = [0, [goal]] in
678   active, passive
679 ;;
680
681 let make_goal_set goal = 
682   ([],[goal]) 
683 ;;
684
685 (** initializes the set of theorems *)
686 let make_theorems theorems =
687   theorems, []
688 ;;
689
690
691 let activate_goal (active, passive) =
692   if active = [] then
693     match passive with
694     | goal_conj::tl -> true, (goal_conj::active, tl)
695     | [] -> false, (active, passive)
696   else  
697     true, (active,passive)
698 ;;
699
700
701 let activate_theorem (active, passive) =
702   match passive with
703   | theorem::tl -> true, (theorem::active, tl)
704   | [] -> false, (active, passive)
705 ;;
706
707
708
709 let simplify_theorems env theorems ?passive (active_list, active_table) =
710   let pl, passive_table =
711     match passive with
712     | None -> [], None
713     | Some ((pn, _), (pp, _), pt) -> pn @ pp, Some pt
714   in
715   let a_theorems, p_theorems = theorems in
716   let demodulate table theorem =
717     let newmeta, newthm =
718       Indexing.demodulation_theorem !maxmeta env table theorem in
719     maxmeta := newmeta;
720     theorem != newthm, newthm
721   in
722   let foldfun table (a, p) theorem =
723     let changed, theorem = demodulate table theorem in
724     if changed then (a, theorem::p) else (theorem::a, p)
725   in
726   let mapfun table theorem = snd (demodulate table theorem) in
727   match passive_table with
728   | None ->
729       let p_theorems = List.map (mapfun active_table) p_theorems in
730       List.fold_left (foldfun active_table) ([], p_theorems) a_theorems
731   | Some passive_table ->
732       let p_theorems = List.map (mapfun active_table) p_theorems in
733       let p_theorems, a_theorems =
734         List.fold_left (foldfun active_table) ([], p_theorems) a_theorems in
735       let p_theorems = List.map (mapfun passive_table) p_theorems in
736       List.fold_left (foldfun passive_table) ([], p_theorems) a_theorems
737 ;;
738
739
740 let rec simpl eq_uri env e others others_simpl =
741   let active = others @ others_simpl in
742   let tbl =
743     List.fold_left
744       (fun t e -> Indexing.index t e)
745       Indexing.empty active
746   in
747   let res = forward_simplify eq_uri env e (active, tbl) in
748     match others with
749       | hd::tl -> (
750           match res with
751             | None -> simpl eq_uri env hd tl others_simpl
752             | Some e -> simpl eq_uri env hd tl (e::others_simpl)
753         )
754       | [] -> (
755           match res with
756             | None -> others_simpl
757             | Some e -> e::others_simpl
758         )
759 ;;
760
761 let simplify_equalities eq_uri env equalities =
762   Utils.debug_print
763     (lazy 
764        (Printf.sprintf "equalities:\n%s\n"
765           (String.concat "\n"
766              (List.map Equality.string_of_equality equalities))));
767   Utils.debug_print (lazy "SIMPLYFYING EQUALITIES...");
768   match equalities with
769     | [] -> []
770     | hd::tl ->
771         let res =
772           List.rev (simpl eq_uri env hd tl [])
773         in
774           Utils.debug_print
775             (lazy
776                (Printf.sprintf "equalities AFTER:\n%s\n"
777                   (String.concat "\n"
778                      (List.map Equality.string_of_equality res))));
779           res
780 ;;
781
782 let print_goals goals = 
783   (String.concat "\n"
784      (List.map
785         (fun (d, gl) ->
786            let gl' =
787              List.map
788                (fun (p, _, t) ->
789                   (* (string_of_proof p) ^ ", " ^ *) (CicPp.ppterm t)) gl
790            in
791            Printf.sprintf "%d: %s" d (String.concat "; " gl')) goals))
792 ;;
793               
794 let pp_goal_set msg goals names = 
795   let active_goals, passive_goals = goals in
796   prerr_endline ("////" ^ msg);
797   prerr_endline ("ACTIVE G: " ^
798     (String.concat "\n " (List.map (fun (_,_,g) -> CicPp.pp g names)
799     active_goals)));
800   prerr_endline ("PASSIVE G: " ^
801     (String.concat "\n " (List.map (fun (_,_,g) -> CicPp.pp g names)
802     passive_goals)))
803 ;;
804
805 let check_if_goal_is_subsumed ((_,ctx,_) as env) table (goalproof,menv,ty) =
806   let names = Utils.names_of_context ctx in
807   match ty with
808   | Cic.Appl[Cic.MutInd(uri,_,_);eq_ty;left;right] 
809     when LibraryObjects.is_eq_URI uri ->
810       (let goal_equation = 
811          Equality.mk_equality
812            (0,Equality.Exact (Cic.Implicit None),(eq_ty,left,right,Utils.Eq),menv) 
813       in
814 (*      match Indexing.subsumption env table goal_equation with*)
815        match Indexing.unification env table goal_equation with 
816         | Some (subst, equality, swapped ) ->
817             prerr_endline 
818               ("GOAL SUBSUMED IS: " ^ Equality.string_of_equality goal_equation ~env);
819             prerr_endline 
820               ("GOAL IS SUBSUMED BY: " ^ Equality.string_of_equality equality ~env);
821             prerr_endline ("SUBST:" ^ Subst.ppsubst ~names subst);
822             let (_,p,(ty,l,r,_),m,id) = Equality.open_equality equality in
823             let cicmenv = Subst.apply_subst_metasenv subst (m @ menv) in
824             let p =
825               if swapped then
826                 Equality.symmetric eq_ty l id uri m
827               else
828                 p
829             in
830             Some (goalproof, p, id, subst, cicmenv)
831         | None -> None)
832   | _ -> None
833 ;;
834
835 let check_if_goal_is_identity env = function
836   | (goalproof,m,Cic.Appl[Cic.MutInd(uri,_,ens);eq_ty;left;right]) 
837     when left = right && LibraryObjects.is_eq_URI uri ->
838       let reflproof = Equality.Exact (Equality.refl_proof uri eq_ty left) in
839       Some (goalproof, reflproof, 0, Subst.empty_subst,m)
840   | (goalproof,m,Cic.Appl[Cic.MutInd(uri,_,ens);eq_ty;left;right]) 
841     when LibraryObjects.is_eq_URI uri ->
842     (let _,context,_ = env in
843     try 
844      let s,m,_ = 
845        Inference.unification m m context left right CicUniv.empty_ugraph 
846      in
847       let reflproof = Equality.Exact (Equality.refl_proof uri eq_ty left) in
848       let m = Subst.apply_subst_metasenv s m in
849       Some (goalproof, reflproof, 0, s,m)
850     with _ -> None)
851   | _ -> None
852 ;;                              
853     
854 let rec check goal = function
855   | [] -> None
856   | f::tl ->
857       match f goal with
858       | None -> check goal tl
859       | (Some p) as ok  -> ok
860 ;;
861   
862 let simplify_goal_set env goals active = 
863   let active_goals, passive_goals = goals in 
864   let find (_,_,g) where =
865     List.exists (fun (_,_,g1) -> Equality.meta_convertibility g g1) where
866   in
867     (* prova:tengo le passive semplificate 
868   let passive_goals = 
869     List.map (fun g -> snd (simplify_goal env g active)) passive_goals 
870   in *)
871     List.fold_left
872       (fun (acc_a,acc_p) goal -> 
873         match simplify_goal env goal active with 
874         | changed, g -> 
875             if changed then 
876               if find g acc_p then acc_a,acc_p else acc_a,g::acc_p
877             else
878               if find g acc_a then acc_a,acc_p else g::acc_a,acc_p)
879       ([],passive_goals) active_goals
880 ;;
881
882 let check_if_goals_set_is_solved env active goals =
883   let active_goals, passive_goals = goals in
884   List.fold_left 
885     (fun proof goal ->
886       match proof with
887       | Some p -> proof
888       | None -> 
889           check goal [
890             check_if_goal_is_identity env;
891             check_if_goal_is_subsumed env (snd active)])
892 (* provare active and passive?*)
893     None active_goals
894 ;;
895
896 let infer_goal_set env active goals = 
897   let active_goals, passive_goals = goals in
898   let rec aux = function
899     | [] -> active_goals, []
900     | hd::tl ->
901         let changed,selected = simplify_goal env hd active in
902         if changed then
903           prerr_endline ("--------------- goal semplificato");
904         let (_,_,t1) = selected in
905         let already_in = 
906           List.exists (fun (_,_,t) -> Equality.meta_convertibility t t1) 
907               active_goals
908         in
909         if already_in then 
910              aux tl
911           else
912             let passive_goals = tl in
913             let new_passive_goals =
914               if Utils.metas_of_term t1 = [] then passive_goals
915               else 
916                 let newmaxmeta,new' = 
917                    Indexing.superposition_left env (snd active) selected
918                    !maxmeta 
919                 in
920                 maxmeta := newmaxmeta;
921                 passive_goals @ new'
922             in
923             selected::active_goals, new_passive_goals
924   in 
925   aux passive_goals
926 ;;
927
928 let infer_goal_set_with_current env current goals active = 
929   let active_goals, passive_goals = 
930     simplify_goal_set env goals active
931   in
932   let l,table,_  = build_table [current] in
933   active_goals, 
934   List.fold_left 
935     (fun acc g ->
936       let newmaxmeta, new' = Indexing.superposition_left env table g !maxmeta in
937       maxmeta := newmaxmeta;
938       acc @ new')
939     passive_goals active_goals
940 ;;
941
942 let ids_of_goal g = 
943   let p,_,_ = g in
944   let ids = List.map (fun _,_,i,_,_ -> i) p in
945   ids
946 ;;
947
948 let ids_of_goal_set (ga,gp) =
949   List.flatten (List.map ids_of_goal ga) @
950   List.flatten (List.map ids_of_goal gp)
951 ;;
952
953 let size_of_goal_set_a (l,_) = List.length l;;
954 let size_of_goal_set_p (_,l) = List.length l;;
955       
956 let pp_goals label goals context = 
957   let names = Utils.names_of_context context in
958   List.iter                 
959     (fun _,_,g -> 
960       prerr_endline 
961         (Printf.sprintf  "Current goal: %s = %s\n" label (CicPp.pp g names))) 
962     (fst goals);
963   List.iter                 
964     (fun _,_,g -> 
965       prerr_endline 
966         (Printf.sprintf  "PASSIVE goal: %s = %s\n" label (CicPp.pp g names))) 
967       (snd goals);
968 ;;
969
970 (** given-clause algorithm with full reduction strategy: NEW implementation *)
971 (* here goals is a set of goals in OR *)
972 let given_clause 
973   eq_uri ((_,context,_) as env) goals theorems passive active max_iterations max_time
974
975   let initial_time = Unix.gettimeofday () in
976   let iterations_left iterno = 
977     let now = Unix.gettimeofday () in
978     let time_left = max_time -. now in
979     let time_spent_until_now = now -. initial_time in
980     let iteration_medium_cost = 
981       time_spent_until_now /. (float_of_int iterno)
982     in
983     let iterations_left = time_left /. iteration_medium_cost in
984     int_of_float iterations_left 
985   in
986   let rec step goals theorems passive active iterno =
987     if iterno > max_iterations then
988       (ParamodulationFailure "No more iterations to spend")
989     else if Unix.gettimeofday () > max_time then
990       (ParamodulationFailure "No more time to spend")
991     else
992 (*
993       let _ = prerr_endline "simpl goal with active" in
994       let _ = <:start<simplify goal set active>> in
995       let goals = simplify_goal_set env goals passive active in 
996       let _ = <:stop<simplify goal set active>> in
997 *)
998       let _ = 
999         prerr_endline 
1000          (Printf.sprintf "%d #ACTIVES: %d #PASSIVES: %d #GOALSET: %d(%d)\n"
1001            iterno (size_of_active active) (size_of_passive passive)
1002            (size_of_goal_set_a goals) (size_of_goal_set_p goals)) 
1003       in
1004       (* PRUNING OF PASSIVE THAT WILL NEVER BE PROCESSED *) 
1005       let passive =
1006         let selection_estimate = iterations_left iterno in
1007         let kept = size_of_passive passive in
1008         if kept > selection_estimate then 
1009           begin
1010             (*Printf.eprintf "Too many passive equalities: pruning...";
1011             prune_passive selection_estimate active*) passive
1012           end
1013         else
1014           passive
1015       in
1016       kept_clauses := (size_of_passive passive) + (size_of_active active);
1017       let goals = infer_goal_set env active goals 
1018       in
1019       match check_if_goals_set_is_solved env active goals with
1020       | Some p -> 
1021           prerr_endline 
1022             (Printf.sprintf "Found a proof in: %f\n" 
1023               (Unix.gettimeofday() -. initial_time));
1024           ParamodulationSuccess p
1025       | None -> 
1026           (* SELECTION *)
1027           if passive_is_empty passive then
1028             if no_more_passive_goals goals then 
1029               ParamodulationFailure "No more passive equations/goals"
1030               (*maybe this is a success! *)
1031             else
1032               step goals theorems passive active (iterno+1)
1033           else
1034             begin
1035               (* COLLECTION OF GARBAGED EQUALITIES *)
1036               if iterno mod 40 = 0 then
1037                 begin
1038                   let active = List.map Equality.id_of (fst active) in
1039                   let passive = List.map Equality.id_of (fst passive) in
1040                   let goal = ids_of_goal_set goals in
1041                   Equality.collect active passive goal
1042                 end;
1043               let current, passive = select env goals passive in
1044               (* SIMPLIFICATION OF CURRENT *)
1045               prerr_endline
1046                     ("Selected : " ^ 
1047                       Equality.string_of_equality ~env  current);
1048               let res = 
1049                 forward_simplify eq_uri env current active 
1050               in
1051               match res with
1052               | None -> step goals theorems passive active (iterno+1)
1053               | Some current ->
1054 (*
1055                   prerr_endline 
1056                     ("Selected simpl: " ^ 
1057                       Equality.string_of_equality ~env  current);
1058 *)
1059                   (* GENERATION OF NEW EQUATIONS *)
1060                   prerr_endline "infer";
1061                   let new' = infer eq_uri env current active in
1062                   prerr_endline "infer goal";
1063 (*
1064       match check_if_goals_set_is_solved env active goals with
1065       | Some p -> 
1066           prerr_endline 
1067             (Printf.sprintf "Found a proof in: %f\n" 
1068               (Unix.gettimeofday() -. initial_time));
1069           ParamodulationSuccess p
1070       | None -> 
1071 *)
1072                   let active = 
1073                       let al, tbl = active in
1074                       al @ [current], Indexing.index tbl current
1075                   in
1076                   let goals = 
1077                     infer_goal_set_with_current env current goals active 
1078                   in
1079                   (* FORWARD AND BACKWARD SIMPLIFICATION *)
1080                   prerr_endline "fwd/back simpl";
1081                   let rec simplify new' active passive head =
1082                     let new' = 
1083                       forward_simplify_new eq_uri env new' active 
1084                     in
1085                     let active, newa, retained, pruned =
1086                       backward_simplify eq_uri env new' active 
1087                     in
1088                     let passive = 
1089                       List.fold_left filter_dependent passive pruned 
1090                     in
1091                     match newa, retained with
1092                     | None, None -> active, passive, new', head
1093                     | Some p, None 
1094                     | None, Some p -> simplify (new' @ p) active passive head
1095                     | Some p, Some rp -> 
1096                         simplify (new' @ p @ rp) active passive (head @ p)
1097                   in
1098                   let active, passive, new', head = 
1099                     simplify new' active passive []
1100                   in
1101                   prerr_endline "simpl goal with new";
1102                   let goals = 
1103                     let a,b,_ = build_table new' in
1104                     let _ = <:start<simplify_goal_set new>> in
1105                     let rc = simplify_goal_set env goals (a,b) in
1106                     let _ = <:stop<simplify_goal_set new>> in
1107                     rc
1108                   in
1109                   let passive = add_to_passive passive new' head in
1110                   step goals theorems passive active (iterno+1)
1111             end
1112   in
1113     step goals theorems passive active 1
1114 ;;
1115
1116 let rec saturate_equations eq_uri env goal accept_fun passive active =
1117   elapsed_time := Unix.gettimeofday () -. !start_time;
1118   if !elapsed_time > !time_limit then
1119     (active, passive)
1120   else
1121     let current, passive = select env ([goal],[]) passive in
1122     let res = forward_simplify eq_uri env current active in
1123     match res with
1124     | None ->
1125         saturate_equations eq_uri env goal accept_fun passive active
1126     | Some current ->
1127         Utils.debug_print (lazy (Printf.sprintf "selected: %s"
1128                              (Equality.string_of_equality ~env current)));
1129         let new' = infer eq_uri env current active in
1130         let active =
1131           if Equality.is_identity env current then active
1132           else
1133             let al, tbl = active in
1134             al @ [current], Indexing.index tbl current
1135         in
1136         (* alla fine new' contiene anche le attive semplificate!
1137          * quindi le aggiungo alle passive insieme alle new *)
1138         let rec simplify new' active passive =
1139           let new' = forward_simplify_new eq_uri env new' active in
1140           let active, newa, retained, pruned =
1141             backward_simplify eq_uri env new' active in
1142           let passive = 
1143             List.fold_left filter_dependent passive pruned in
1144           match newa, retained with
1145           | None, None -> active, passive, new'
1146           | Some p, None
1147           | None, Some p -> simplify (new' @ p) active passive
1148           | Some p, Some rp -> simplify (new' @ p @ rp) active passive
1149         in
1150         let active, passive, new' = simplify new' active passive in
1151         let _ =
1152           Utils.debug_print
1153             (lazy
1154                (Printf.sprintf "active:\n%s\n"
1155                   (String.concat "\n"
1156                      (List.map
1157                          (fun e -> Equality.string_of_equality ~env e)
1158                          (fst active)))))
1159         in
1160         let _ =
1161           Utils.debug_print
1162             (lazy
1163                (Printf.sprintf "new':\n%s\n"
1164                   (String.concat "\n"
1165                      (List.map
1166                          (fun e -> "Negative " ^
1167                             (Equality.string_of_equality ~env e)) new'))))
1168         in
1169         let new' = List.filter accept_fun new' in
1170         let passive = add_to_passive passive new' [] in
1171         saturate_equations eq_uri env goal accept_fun passive active
1172 ;;
1173   
1174 let default_depth = !maxdepth
1175 and default_width = !maxwidth;;
1176
1177 let reset_refs () =
1178   maxmeta := 0;
1179   symbols_counter := 0;
1180   weight_age_counter := !weight_age_ratio;
1181   processed_clauses := 0;
1182   start_time := 0.;
1183   elapsed_time := 0.;
1184   maximal_retained_equality := None;
1185   infer_time := 0.;
1186   forward_simpl_time := 0.;
1187   forward_simpl_new_time := 0.;
1188   backward_simpl_time := 0.;
1189   passive_maintainance_time := 0.;
1190   derived_clauses := 0;
1191   kept_clauses := 0;
1192   Equality.reset ();
1193 ;;
1194
1195 let eq_of_goal = function
1196   | Cic.Appl [Cic.MutInd(uri,0,_);_;_;_] when LibraryObjects.is_eq_URI uri ->
1197       uri
1198   | _ -> raise (ProofEngineTypes.Fail (lazy ("The goal is not an equality ")))
1199 ;;
1200
1201 let eq_and_ty_of_goal = function
1202   | Cic.Appl [Cic.MutInd(uri,0,_);t;_;_] when LibraryObjects.is_eq_URI uri ->
1203       uri,t
1204   | _ -> raise (ProofEngineTypes.Fail (lazy ("The goal is not an equality ")))
1205 ;;
1206
1207 let saturate 
1208     caso_strano 
1209     dbd ?(full=false) ?(depth=default_depth) ?(width=default_width) status = 
1210   let module C = Cic in
1211   reset_refs ();
1212   Indexing.init_index ();
1213   maxdepth := depth;
1214   maxwidth := width;
1215 (*  CicUnification.unif_ty := false;*)
1216   let proof, goalno = status in
1217   let uri, metasenv, meta_proof, term_to_prove = proof in
1218   let _, context, type_of_goal = CicUtil.lookup_meta goalno metasenv in
1219   let eq_uri = eq_of_goal type_of_goal in 
1220   let cleaned_goal = Utils.remove_local_context type_of_goal in
1221   Utils.set_goal_symbols cleaned_goal;
1222   let names = Utils.names_of_context context in
1223   let eq_indexes, equalities, maxm = Inference.find_equalities context proof in
1224   let ugraph = CicUniv.empty_ugraph in
1225   let env = (metasenv, context, ugraph) in 
1226   let goal = [], List.filter (fun (i,_,_)->i<>goalno) metasenv, cleaned_goal in
1227   let res, time =
1228     let t1 = Unix.gettimeofday () in
1229     let lib_eq_uris, library_equalities, maxm =
1230       Inference.find_library_equalities caso_strano dbd context (proof, goalno) (maxm+2)
1231     in
1232     let library_equalities = List.map snd library_equalities in
1233     let t2 = Unix.gettimeofday () in
1234     maxmeta := maxm+2;
1235     let equalities = 
1236       simplify_equalities eq_uri env (equalities@library_equalities) 
1237     in 
1238     Utils.debug_print
1239       (lazy
1240          (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)));
1241     let t1 = Unix.gettimeofday () in
1242     let theorems =
1243       if full then
1244         let thms = Inference.find_library_theorems dbd env (proof, goalno) lib_eq_uris in
1245         let context_hyp = Inference.find_context_hypotheses env eq_indexes in
1246         context_hyp @ thms, []
1247       else
1248         let refl_equal = LibraryObjects.eq_refl_URI ~eq:eq_uri in
1249         let t = CicUtil.term_of_uri refl_equal in
1250         let ty, _ = CicTypeChecker.type_of_aux' [] [] t CicUniv.empty_ugraph in
1251         [(t, ty, [])], []
1252     in
1253     let t2 = Unix.gettimeofday () in
1254     let _ =
1255       Utils.debug_print
1256         (lazy
1257            (Printf.sprintf
1258               "Theorems:\n-------------------------------------\n%s\n"
1259               (String.concat "\n"
1260                  (List.map
1261                     (fun (t, ty, _) ->
1262                        Printf.sprintf
1263                          "Term: %s, type: %s"
1264                          (CicPp.ppterm t) (CicPp.ppterm ty))
1265                     (fst theorems)))));
1266       Utils.debug_print
1267         (lazy
1268            (Printf.sprintf "Time to retrieve theorems: %.9f\n" (t2 -. t1)));
1269     in
1270     let active = make_active () in
1271     let passive = make_passive equalities in
1272     let start = Unix.gettimeofday () in
1273     let res =
1274 (*
1275       let goals = make_goals goal in
1276       given_clause_fullred dbd env goals theorems passive active
1277 *)
1278       let goals = make_goal_set goal in
1279       let max_iterations = 10000 in
1280       let max_time = Unix.gettimeofday () +.  600. (* minutes *) in
1281       given_clause 
1282         eq_uri env goals theorems passive active max_iterations max_time 
1283     in
1284     let finish = Unix.gettimeofday () in
1285     (res, finish -. start)
1286   in
1287   match res with
1288   | ParamodulationFailure s ->
1289       raise (ProofEngineTypes.Fail (lazy ("NO proof found: " ^ s)))
1290   | ParamodulationSuccess 
1291     (goalproof,newproof,subsumption_id,subsumption_subst, proof_menv) ->
1292       prerr_endline "OK, found a proof!";
1293       prerr_endline 
1294         (Equality.pp_proof names goalproof newproof subsumption_subst
1295           subsumption_id type_of_goal);
1296       prerr_endline "ENDOFPROOFS___";
1297       prerr_endline ("max weight: " ^ 
1298         (string_of_int (Equality.max_weight goalproof newproof)));
1299       (* generation of the CIC proof *)
1300       let side_effects = 
1301         List.filter (fun i -> i <> goalno)
1302           (ProofEngineHelpers.compare_metasenvs 
1303             ~newmetasenv:metasenv ~oldmetasenv:proof_menv)
1304       in
1305       let goal_proof, side_effects_t = 
1306         let initial = Equality.add_subst subsumption_subst newproof in
1307         Equality.build_goal_proof 
1308           eq_uri goalproof initial type_of_goal side_effects
1309           context proof_menv
1310       in
1311       prerr_endline ("PROOF: " ^ CicPp.pp goal_proof names);
1312       let goal_proof = Subst.apply_subst subsumption_subst goal_proof in
1313       let metas_still_open_in_proof = Utils.metas_of_term goal_proof in
1314 (*prerr_endline (CicPp.pp goal_proof names);*)
1315       (* ?? *)
1316       let goal_proof = (* Subst.apply_subst subsumption_subst *) goal_proof in
1317       let side_effects_t = 
1318         List.map (Subst.apply_subst subsumption_subst) side_effects_t
1319       in
1320       (* replacing fake mets with real ones *)
1321       prerr_endline "replacing metas...";
1322       let irl=CicMkImplicit.identity_relocation_list_for_metavariable context in
1323       let goal_proof_menv, what, with_what,free_meta = 
1324         List.fold_left 
1325           (fun (acc1,acc2,acc3,uniq) (i,_,ty) -> 
1326              match uniq with
1327                | Some m -> 
1328                    acc1, (Cic.Meta(i,[]))::acc2, m::acc3, uniq
1329                | None ->
1330                    [i,context,ty], (Cic.Meta(i,[]))::acc2, 
1331                    (Cic.Meta(i,irl)) ::acc3,Some (Cic.Meta(i,irl))) 
1332           ([],[],[],None) 
1333           (List.filter 
1334            (fun (i,_,_) -> List.mem i metas_still_open_in_proof) 
1335            proof_menv)
1336       in
1337       let replace where = 
1338         (* we need this fake equality since the metas of the hypothesis may be
1339          * with a real local context *)
1340         ProofEngineReduction.replace_lifting 
1341           ~equality:(fun x y -> 
1342             match x,y with Cic.Meta(i,_),Cic.Meta(j,_) -> i=j | _-> false)
1343           ~what ~with_what ~where
1344       in
1345       let goal_proof = replace goal_proof in
1346         (* ok per le meta libere... ma per quelle che c'erano e sono rimaste? 
1347          * what mi pare buono, sostituisce solo le meta farlocche *)
1348       let side_effects_t = List.map replace side_effects_t in
1349       let free_metas = 
1350         List.filter (fun i -> i <> goalno)
1351           (ProofEngineHelpers.compare_metasenvs 
1352             ~oldmetasenv:metasenv ~newmetasenv:goal_proof_menv)
1353       in
1354 prerr_endline ("freemetas: " ^ String.concat "," (List.map string_of_int free_metas) );
1355       (* check/refine/... build the new proof *)
1356       let replaced_goal = 
1357         ProofEngineReduction.replace
1358           ~what:side_effects ~with_what:side_effects_t
1359           ~equality:(fun i t -> match t with Cic.Meta(j,_)->j=i|_->false)
1360           ~where:type_of_goal
1361       in
1362       let subst_side_effects,real_menv,_ = 
1363         let fail t s = raise (ProofEngineTypes.Fail (lazy (t^Lazy.force s))) in
1364         let free_metas_menv = 
1365           List.map (fun i -> CicUtil.lookup_meta i goal_proof_menv) free_metas
1366         in
1367         try
1368           CicUnification.fo_unif_subst [] context (metasenv @ free_metas_menv)
1369            replaced_goal type_of_goal CicUniv.empty_ugraph
1370         with
1371         | CicUnification.UnificationFailure s
1372         | CicUnification.Uncertain s 
1373         | CicUnification.AssertFailure s -> 
1374             fail "Maybe the local context of metas in the goal was not an IRL" s
1375       in
1376       let final_subst = 
1377         (goalno,(context,goal_proof,type_of_goal))::subst_side_effects
1378       in
1379 prerr_endline ("MENVreal_menv: " ^ CicMetaSubst.ppmetasenv [] real_menv);
1380       let _ = 
1381         try
1382           CicTypeChecker.type_of_aux' real_menv context goal_proof
1383             CicUniv.empty_ugraph
1384         with 
1385         | CicUtil.Meta_not_found _ 
1386         | CicTypeChecker.TypeCheckerFailure _ 
1387         | CicTypeChecker.AssertFailure _ 
1388         | Invalid_argument "list_fold_left2" as exn ->
1389             prerr_endline "THE PROOF DOES NOT TYPECHECK!";
1390             prerr_endline (CicPp.pp goal_proof names); 
1391             prerr_endline "THE PROOF DOES NOT TYPECHECK!";
1392             raise exn
1393       in
1394       let proof, real_metasenv = 
1395         ProofEngineHelpers.subst_meta_and_metasenv_in_proof
1396           proof goalno (CicMetaSubst.apply_subst final_subst) real_menv
1397       in
1398       let open_goals = 
1399         match free_meta with Some(Cic.Meta(m,_)) when m<>goalno ->[m] | _ ->[] 
1400       in
1401       Printf.eprintf 
1402         "GOALS APERTI: %s\nMETASENV PRIMA:\n%s\nMETASENV DOPO:\n%s\n" 
1403           (String.concat ", " (List.map string_of_int open_goals))
1404           (CicMetaSubst.ppmetasenv [] metasenv)
1405           (CicMetaSubst.ppmetasenv [] real_metasenv);
1406       prerr_endline (Printf.sprintf "\nTIME NEEDED: %8.2f" time);
1407       proof, open_goals
1408 ;;
1409
1410 let main _ _ _ _ _ = () ;;
1411
1412 let retrieve_and_print dbd term metasenv ugraph = 
1413   let module C = Cic in
1414   let module T = CicTypeChecker in
1415   let module PET = ProofEngineTypes in
1416   let module PP = CicPp in
1417   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1418   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1419   let proof, goals = status in
1420   let goal' = List.nth goals 0 in
1421   let uri, metasenv, meta_proof, term_to_prove = proof in
1422   let _, context, type_of_goal = CicUtil.lookup_meta goal' metasenv in
1423   let eq_uri = eq_of_goal type_of_goal in 
1424   let eq_indexes, equalities, maxm = Inference.find_equalities context proof in
1425   let ugraph = CicUniv.empty_ugraph in
1426   let env = (metasenv, context, ugraph) in
1427   let t1 = Unix.gettimeofday () in
1428   let lib_eq_uris, library_equalities, maxm =
1429     Inference.find_library_equalities false dbd context (proof, goal') (maxm+2) in
1430   let t2 = Unix.gettimeofday () in
1431   maxmeta := maxm+2;
1432   let equalities = (* equalities @ *) library_equalities in
1433   Utils.debug_print
1434      (lazy
1435         (Printf.sprintf "\n\nequalities:\n%s\n"
1436            (String.concat "\n"
1437               (List.map 
1438           (fun (u, e) ->
1439 (*                  Printf.sprintf "%s: %s" *)
1440                    (UriManager.string_of_uri u)
1441 (*                    (string_of_equality e) *)
1442                      )
1443           equalities))));
1444   Utils.debug_print (lazy "RETR: SIMPLYFYING EQUALITIES...");
1445   let rec simpl e others others_simpl =
1446     let (u, e) = e in
1447     let active = (others @ others_simpl) in
1448     let tbl =
1449       List.fold_left
1450         (fun t (_, e) -> Indexing.index t e)
1451         Indexing.empty active
1452     in
1453     let res = forward_simplify eq_uri env e (active, tbl) in
1454     match others with
1455         | hd::tl -> (
1456             match res with
1457               | None -> simpl hd tl others_simpl
1458               | Some e -> simpl hd tl ((u, e)::others_simpl)
1459           )
1460         | [] -> (
1461             match res with
1462               | None -> others_simpl
1463               | Some e -> (u, e)::others_simpl
1464           ) 
1465   in
1466   let _equalities =
1467     match equalities with
1468       | [] -> []
1469       | hd::tl ->
1470           let others = tl in (* List.map (fun e -> (Utils.Positive, e)) tl in *)
1471           let res =
1472             List.rev (simpl (*(Positive,*) hd others [])
1473           in
1474             Utils.debug_print
1475               (lazy
1476                  (Printf.sprintf "\nequalities AFTER:\n%s\n"
1477                     (String.concat "\n"
1478                        (List.map
1479                           (fun (u, e) ->
1480                              Printf.sprintf "%s: %s"
1481                                (UriManager.string_of_uri u)
1482                                (Equality.string_of_equality e)
1483                           )
1484                           res))));
1485             res in
1486     Utils.debug_print
1487       (lazy
1488          (Printf.sprintf "Time to retrieve equalities: %.9f\n" (t2 -. t1)))
1489 ;;
1490
1491
1492 let main_demod_equalities dbd term metasenv ugraph =
1493   let module C = Cic in
1494   let module T = CicTypeChecker in
1495   let module PET = ProofEngineTypes in
1496   let module PP = CicPp in
1497   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1498   let status = PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1499   let proof, goals = status in
1500   let goal' = List.nth goals 0 in
1501   let _, metasenv, meta_proof, _ = proof in
1502   let _, context, goal = CicUtil.lookup_meta goal' metasenv in
1503   let eq_uri = eq_of_goal goal in 
1504   let eq_indexes, equalities, maxm = Inference.find_equalities context proof in
1505   let lib_eq_uris, library_equalities, maxm =
1506     Inference.find_library_equalities false dbd context (proof, goal') (maxm+2)
1507   in
1508   let library_equalities = List.map snd library_equalities in
1509   maxmeta := maxm+2; (* TODO ugly!! *)
1510   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
1511   let new_meta_goal, metasenv, type_of_goal =
1512     let _, context, ty = CicUtil.lookup_meta goal' metasenv in
1513     Utils.debug_print
1514       (lazy
1515          (Printf.sprintf "\n\nTRYING TO INFER EQUALITIES MATCHING: %s\n\n"
1516             (CicPp.ppterm ty)));
1517     Cic.Meta (maxm+1, irl),
1518     (maxm+1, context, ty)::metasenv,
1519     ty
1520   in
1521   let env = (metasenv, context, ugraph) in
1522   (*try*)
1523     let goal = [], [], goal 
1524     in
1525     let equalities = 
1526       simplify_equalities eq_uri env (equalities@library_equalities) 
1527     in
1528     let active = make_active () in
1529     let passive = make_passive equalities in
1530     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
1531     Printf.printf "\nmetasenv:\n%s\n" (Utils.print_metasenv metasenv);
1532     Printf.printf "\nequalities:\n%s\n"
1533       (String.concat "\n"
1534          (List.map
1535             (Equality.string_of_equality ~env) equalities));
1536     print_endline "--------------------------------------------------";
1537     print_endline "GO!";
1538     start_time := Unix.gettimeofday ();
1539     if !time_limit < 1. then time_limit := 60.;    
1540     let ra, rp =
1541       saturate_equations eq_uri env goal (fun e -> true) passive active
1542     in
1543
1544     let initial =
1545       List.fold_left (fun s e -> EqualitySet.add e s)
1546         EqualitySet.empty equalities
1547     in
1548     let addfun s e = 
1549       if not (EqualitySet.mem e initial) then EqualitySet.add e s else s
1550     in
1551
1552     let passive =
1553       match rp with
1554       | p, _ ->
1555           EqualitySet.elements (List.fold_left addfun EqualitySet.empty p)
1556     in
1557     let active =
1558       let l = fst ra in
1559       EqualitySet.elements (List.fold_left addfun EqualitySet.empty l)
1560     in
1561     Printf.printf "\n\nRESULTS:\nActive:\n%s\n\nPassive:\n%s\n"
1562        (String.concat "\n" (List.map (Equality.string_of_equality ~env) active)) 
1563      (*  (String.concat "\n"
1564          (List.map (fun e -> CicPp.ppterm (term_of_equality e)) active)) *)
1565 (*       (String.concat "\n" (List.map (string_of_equality ~env) passive)); *)
1566       (String.concat "\n"
1567          (List.map 
1568            (fun e -> CicPp.ppterm (Equality.term_of_equality eq_uri e)) 
1569           passive));
1570     print_newline ();
1571 (*
1572   with e ->
1573     Utils.debug_print (lazy ("EXCEPTION: " ^ (Printexc.to_string e)))
1574 *)
1575 ;;
1576
1577 let demodulate_tac ~dbd ((proof,goal)(*s initialstatus*)) = 
1578   let curi,metasenv,pbo,pty = proof in
1579   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
1580   let eq_uri = eq_of_goal ty in 
1581   let eq_indexes, equalities, maxm = 
1582     Inference.find_equalities context proof 
1583   in
1584   let lib_eq_uris, library_equalities, maxm =
1585     Inference.find_library_equalities false dbd context (proof, goal) (maxm+2) in
1586   if library_equalities = [] then prerr_endline "VUOTA!!!";
1587   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
1588   let library_equalities = List.map snd library_equalities in
1589   let initgoal = [], [], ty in
1590   let env = (metasenv, context, CicUniv.empty_ugraph) in
1591   let equalities = 
1592     simplify_equalities eq_uri env (equalities@library_equalities) 
1593   in   
1594   let table = 
1595     List.fold_left 
1596       (fun tbl eq -> Indexing.index tbl eq) 
1597       Indexing.empty equalities 
1598   in
1599   let changed,(newproof,newmetasenv, newty) = 
1600     Indexing.demodulation_goal 
1601       (metasenv,context,CicUniv.empty_ugraph) table initgoal 
1602   in
1603   if changed then
1604     begin
1605       let opengoal = Equality.Exact (Cic.Meta(maxm,irl)) in
1606       let proofterm,_ = 
1607         Equality.build_goal_proof 
1608           eq_uri newproof opengoal ty [] context metasenv
1609       in
1610         let extended_metasenv = (maxm,context,newty)::metasenv in
1611         let extended_status = 
1612           (curi,extended_metasenv,pbo,pty),goal in
1613         let (status,newgoals) = 
1614           ProofEngineTypes.apply_tactic 
1615             (PrimitiveTactics.apply_tac ~term:proofterm)
1616             extended_status in
1617         (status,maxm::newgoals)
1618     end
1619   else (* if newty = ty then *)
1620     raise (ProofEngineTypes.Fail (lazy "no progress"))
1621   (*else ProofEngineTypes.apply_tactic 
1622     (ReductionTactics.simpl_tac
1623       ~pattern:(ProofEngineTypes.conclusion_pattern None)) initialstatus*)
1624 ;;
1625
1626 let demodulate_tac ~dbd = ProofEngineTypes.mk_tactic (demodulate_tac ~dbd);;
1627
1628 let rec find_in_ctx i name = function
1629   | [] -> raise (ProofEngineTypes.Fail (lazy ("Hypothesis not found: " ^ name)))
1630   | Some (Cic.Name name', _)::tl when name = name' -> i
1631   | _::tl -> find_in_ctx (i+1) name tl
1632 ;;
1633
1634 let rec position_of i x = function
1635   | [] -> assert false
1636   | j::tl when j <> x -> position_of (i+1) x tl
1637   | _ -> i
1638 ;;
1639
1640 (* Syntax: 
1641  *   auto superposition target = NAME 
1642  *     [table = NAME_LIST] [demod_table = NAME_LIST] [subterms_only]
1643  *
1644  *  - if table is omitted no superposition will be performed
1645  *  - if demod_table is omitted no demodulation will be prformed
1646  *  - subterms_only is passed to Indexing.superposition_right
1647  *
1648  *  lists are coded using _ (example: H_H1_H2)
1649  *)
1650
1651 let superposition_tac ~target ~table ~subterms_only ~demod_table status = 
1652   reset_refs();
1653   Indexing.init_index ();
1654   let proof,goalno = status in 
1655   let curi,metasenv,pbo,pty = proof in
1656   let metano,context,ty = CicUtil.lookup_meta goalno metasenv in
1657   let eq_uri,tty = eq_and_ty_of_goal ty in
1658   let env = (metasenv, context, CicUniv.empty_ugraph) in
1659   let names = Utils.names_of_context context in
1660   let eq_index, equalities, maxm = Inference.find_equalities context proof in
1661   let eq_what = 
1662     let what = find_in_ctx 1 target context in
1663     List.nth equalities (position_of 0 what eq_index)
1664   in
1665   let eq_other = 
1666     if table <> "" then
1667       let other = 
1668         let others = Str.split (Str.regexp "_") table in 
1669         List.map (fun other -> find_in_ctx 1 other context) others 
1670       in
1671       List.map 
1672         (fun other -> List.nth equalities (position_of 0 other eq_index)) 
1673         other 
1674     else
1675       []
1676   in
1677   let index = List.fold_left Indexing.index Indexing.empty eq_other in
1678   let maxm, eql = 
1679     if table = "" then maxm,[eq_what] else 
1680     Indexing.superposition_right 
1681       ~subterms_only eq_uri maxm env index eq_what
1682   in
1683   prerr_endline ("Superposition right:");
1684   prerr_endline ("\n eq: " ^ Equality.string_of_equality eq_what ~env);
1685   prerr_endline ("\n table: ");
1686   List.iter (fun e -> prerr_endline ("  " ^ Equality.string_of_equality e ~env)) eq_other;
1687   prerr_endline ("\n result: ");
1688   List.iter (fun e -> prerr_endline (Equality.string_of_equality e ~env)) eql;
1689   prerr_endline ("\n result (cut&paste): ");
1690   List.iter 
1691     (fun e -> 
1692       let t = Equality.term_of_equality eq_uri e in
1693       prerr_endline (CicPp.pp t names)) 
1694   eql;
1695   prerr_endline ("\n result proofs: ");
1696   List.iter (fun e -> 
1697     prerr_endline (let _,p,_,_,_ = Equality.open_equality e in
1698     let s = match p with Equality.Exact _ -> Subst.empty_subst | Equality.Step (s,_) -> s in
1699     Subst.ppsubst s ^ "\n" ^ 
1700     CicPp.pp (Equality.build_proof_term eq_uri [] 0 p) names)) eql;
1701   if demod_table <> "" then
1702     begin
1703       let eql = 
1704         if eql = [] then [eq_what] else eql
1705       in
1706       let demod = 
1707         let demod = Str.split (Str.regexp "_") demod_table in 
1708         List.map (fun other -> find_in_ctx 1 other context) demod 
1709       in
1710       let eq_demod = 
1711         List.map 
1712           (fun demod -> List.nth equalities (position_of 0 demod eq_index)) 
1713           demod 
1714       in
1715       let table = List.fold_left Indexing.index Indexing.empty eq_demod in
1716       let maxm,eql = 
1717         List.fold_left 
1718           (fun (maxm,acc) e -> 
1719             let maxm,eq = 
1720               Indexing.demodulation_equality eq_uri maxm env table e
1721             in
1722             maxm,eq::acc) 
1723           (maxm,[]) eql
1724       in
1725       let eql = List.rev eql in
1726       prerr_endline ("\n result [demod]: ");
1727       List.iter 
1728         (fun e -> prerr_endline (Equality.string_of_equality e ~env)) eql;
1729       prerr_endline ("\n result [demod] (cut&paste): ");
1730       List.iter 
1731         (fun e -> 
1732           let t = Equality.term_of_equality eq_uri e in
1733           prerr_endline (CicPp.pp t names)) 
1734       eql;
1735     end;
1736   proof,[goalno]
1737 ;;
1738
1739 let get_stats () = 
1740   <:show<Saturation.>> ^ Indexing.get_stats () ^ Inference.get_stats () ^
1741   Equality.get_stats ()
1742 ;;
1743