]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_paramodulation/superposition.ml
c5db7a4e2ae8bc927c082bd1ceacfeee21afaba2
[helm.git] / helm / software / components / ng_paramodulation / superposition.ml
1 (*
2     ||M||  This file is part of HELM, an Hypertextual, Electronic        
3     ||A||  Library of Mathematics, developed at the Computer Science     
4     ||T||  Department, University of Bologna, Italy.                     
5     ||I||                                                                
6     ||T||  HELM is free software; you can redistribute it and/or         
7     ||A||  modify it under the terms of the GNU General Public License   
8     \   /  version 2 or (at your option) any later version.      
9      \ /   This software is distributed as is, NO WARRANTY.     
10       V_______________________________________________________________ *)
11
12 (* $Id: index.mli 9822 2009-06-03 15:37:06Z tassi $ *)
13
14 module Superposition (B : Orderings.Blob) = 
15   struct
16     module IDX = Index.Index(B)
17     module Unif = FoUnif.FoUnif(B)
18     module Subst = FoSubst 
19     module Order = B
20     module Utils = FoUtils.Utils(B)
21     module Pp = Pp.Pp(B)
22     module Clauses = Clauses.Clauses(B)
23     
24     exception Success of B.t Terms.bag * int * B.t Terms.clause
25
26     let debug s = prerr_endline (Lazy.force s);;
27     let debug _ = ();;
28     let enable = true;;
29
30     let rec list_first f = function
31       | [] -> None
32       | x::tl -> match f x with Some _ as x -> x | _ -> list_first f tl
33     ;;
34
35     let first_position pos ctx t f =
36       let inject_pos pos ctx = function
37         | None -> None
38         | Some (a,b,c,d) -> Some(ctx a,b,c,d,pos)
39       in
40       let rec aux pos ctx = function
41       | Terms.Leaf _ as t -> inject_pos pos ctx (f t)
42       | Terms.Var _ -> None
43       | Terms.Node l as t->
44           match f t with
45           | Some _ as x -> inject_pos pos ctx x
46           | None ->
47               let rec first pre post = function
48                 | [] -> None
49                 | t :: tl -> 
50                      let newctx = fun x -> ctx (Terms.Node (pre@[x]@post)) in
51                      match aux (List.length pre :: pos) newctx t with
52                      | Some _ as x -> x
53                      | None -> 
54                          if post = [] then None (* tl is also empty *)
55                          else first (pre @ [t]) (List.tl post) tl
56               in
57                 first [] (List.tl l) l 
58       in
59         aux pos ctx t
60     ;;
61                                      
62     let all_positions pos ctx t f =
63       let rec aux pos ctx = function
64       | Terms.Leaf _ as t -> f t pos ctx 
65       | Terms.Var _ -> []
66       | Terms.Node l as t-> 
67           let acc, _, _ = 
68             List.fold_left
69             (fun (acc,pre,post) t -> (* Invariant: pre @ [t] @ post = l *)
70                 let newctx = fun x -> ctx (Terms.Node (pre@[x]@post)) in
71                 let acc = aux (List.length pre :: pos) newctx t @ acc in
72                 if post = [] then acc, l, []
73                 else acc, pre @ [t], List.tl post)
74              (f t pos ctx, [], List.tl l) l
75           in
76            acc
77       in
78         aux pos ctx t
79     ;;
80
81     let parallel_positions bag pos ctx id lit t f =
82       let rec aux bag pos ctx id lit = function
83       | Terms.Leaf _ as t -> f bag t pos ctx id lit
84       | Terms.Var _ as t -> bag,t,id,lit
85       | Terms.Node (hd::l) as t->
86           let bag,t,id1,lit = f bag t pos ctx id lit in
87             if id = id1 then
88               let bag, l, _, id, lit = 
89                 List.fold_left
90                   (fun (bag,pre,post,id,lit) t ->
91                      let newctx = fun x -> ctx (Terms.Node (pre@[x]@post)) in
92                      let newpos = (List.length pre)::pos in
93                      let bag,newt,id,lit = aux bag newpos newctx id lit t in
94                        if post = [] then bag, pre@[newt], [], id,lit
95                        else bag, pre @ [newt], List.tl post, id, lit)
96                   (bag, [hd], List.tl l, id,lit) l
97               in
98                 bag, Terms.Node l, id, lit
99             else bag,t,id1,lit
100       | _ -> assert false
101       in
102         aux bag pos ctx id lit t
103     ;;
104
105     let visit bag pos ctx id lit t f =
106       let rec aux bag pos ctx id subst lit = function
107       | Terms.Leaf _ as t -> 
108           let  bag,subst,t,id,lit = f bag t pos ctx id lit
109           in assert (subst=[]); bag,t,id,lit
110       | Terms.Var i as t ->  
111           let t= Subst.apply_subst subst t in
112             bag,t,id,lit
113       | Terms.Node (hd::l) ->
114           let bag, l, _, id,lit = 
115             List.fold_left
116               (fun (bag,pre,post,id,lit) t ->
117                  let newctx = fun x -> ctx (Terms.Node (pre@[x]@post)) in
118                  let newpos = (List.length pre)::pos in
119                  let bag,newt,id,lit = aux bag newpos newctx id subst lit t in
120                    if post = [] then bag, pre@[newt], [], id, lit
121                    else bag, pre @ [newt], List.tl post, id, lit)
122               (bag, [hd], List.map (Subst.apply_subst subst) (List.tl l), id, lit) l
123           in
124           let bag,subst,t,id1,lit = f bag (Terms.Node l) pos ctx id lit
125           in
126             if id1 = id then (assert (subst=[]); bag,t,id,lit)
127             else aux bag pos ctx id1 subst lit t
128       | _ -> assert false
129       in
130         aux bag pos ctx id [] lit t
131     ;;
132
133     let build_clause ~fresh bag maxvar filter rule t subst id id2 pos dir clause_ctx =
134       let proof = Terms.Step(rule,id,id2,dir,pos,subst) in
135       let t = Subst.apply_subst subst t in
136       if filter subst then
137         let literal = 
138           match t with
139           | Terms.Node [ Terms.Leaf eq ; ty; l; r ] when B.eq B.eqP eq ->
140                let o = Order.compare_terms l r in
141                Terms.Equation (l, r, ty, o)
142           | t -> Terms.Predicate t
143         in
144         let nlit,plit = clause_ctx literal in
145         let cl = (0, nlit, plit, [], proof) in 
146         let vl = Clauses.vars_of_clause cl in
147         let cl,maxvar = 
148             if fresh then Clauses.fresh_clause ~subst maxvar (0, nlit, plit, vl, proof) 
149             else (0,nlit,plit,vl,proof),maxvar
150         in
151         let bag, cl = 
152           Terms.add_to_bag cl bag
153         in
154         debug (lazy (Pp.pp_clause cl));
155         Some (bag, maxvar, cl, literal)
156       else
157         ((*prerr_endline ("Filtering: " ^ Pp.pp_foterm t);*)None)
158     ;;
159     let prof_build_clause = HExtlib.profile ~enable "build_clause";;
160     let build_clause ~fresh bag maxvar filter rule t subst id id2 pos x =
161       prof_build_clause.HExtlib.profile
162           (build_clause ~fresh bag maxvar filter rule t subst id id2 pos) x
163     ;;
164       
165     
166     (* ============ simplification ================= *)
167     let prof_demod_u = HExtlib.profile ~enable "demod.unify";;
168     let prof_demod_r = HExtlib.profile ~enable "demod.retrieve_generalizations";;
169     let prof_demod_o = HExtlib.profile ~enable "demod.compare_terms";;
170     let prof_demod_s = HExtlib.profile ~enable "demod.apply_subst";;
171
172     let demod table varlist subterm =
173       let cands = 
174         prof_demod_r.HExtlib.profile 
175          (IDX.DT.retrieve_generalizations table) subterm 
176       in
177       list_first
178         (fun (dir, is_pos, pos, (id,nlit,plit,vl,_)) ->
179           match nlit,plit with
180            | [], [(lit,_)] ->
181               (match lit with
182               | Terms.Predicate _ -> assert false
183               | Terms.Equation (l,r,_,o) ->
184                   let side, newside = if dir=Terms.Left2Right then l,r else r,l in
185                   try 
186                     let subst =
187                       prof_demod_u.HExtlib.profile 
188                         (Unif.unification (* (varlist@vl) *) varlist subterm) side 
189                     in 
190                     let side = 
191                       prof_demod_s.HExtlib.profile 
192                         (Subst.apply_subst subst) side 
193                     in
194                     let newside = 
195                       prof_demod_s.HExtlib.profile 
196                         (Subst.apply_subst subst) newside 
197                     in
198                     if o = Terms.Incomparable || o = Terms.Invertible then
199                       let o = 
200                         prof_demod_o.HExtlib.profile 
201                          (Order.compare_terms newside) side in
202                       (* Riazanov, pp. 45 (ii) *)
203                       if o = Terms.Lt then
204                         Some (newside, subst, id, dir)
205                       else 
206                         ((*prerr_endline ("Filtering: " ^ 
207                            Pp.pp_foterm side ^ " =(< || =)" ^ 
208                            Pp.pp_foterm newside ^ " coming from " ^ 
209                            Pp.pp_clause uc );*)None)
210                     else
211                       Some (newside, subst, id, dir)
212                   with FoUnif.UnificationFailure _ -> None)
213           |  _ -> None)
214               (IDX.ClauseSet.elements cands)
215     ;;
216     let prof_demod = HExtlib.profile ~enable "demod";;
217     let demod table varlist x =
218       prof_demod.HExtlib.profile (demod table varlist) x
219     ;;
220
221     let mydemod table varlist subterm =
222       let cands = 
223         prof_demod_r.HExtlib.profile 
224          (IDX.DT.retrieve_generalizations table) subterm 
225       in
226       list_first
227         (fun (dir, is_pos, pos, (id,nlit,plit,vl,_)) ->
228          match (nlit,plit) with
229           | [],[(lit,_)] ->
230            (match lit with
231            | Terms.Predicate _ -> assert false
232            | Terms.Equation (l,r,_,o) ->
233                let side, newside = if dir=Terms.Left2Right then l,r else r,l in
234                try 
235                  let subst =
236                    prof_demod_u.HExtlib.profile 
237                      (Unif.unification (* (varlist@vl) *) varlist subterm) side 
238                  in 
239                  let iside = 
240                    prof_demod_s.HExtlib.profile 
241                      (Subst.apply_subst subst) side 
242                  in
243                  let inewside = 
244                    prof_demod_s.HExtlib.profile 
245                      (Subst.apply_subst subst) newside 
246                  in
247                  if o = Terms.Incomparable || o = Terms.Invertible then
248                    let o = 
249                      prof_demod_o.HExtlib.profile 
250                       (Order.compare_terms inewside) iside in
251                    (* Riazanov, pp. 45 (ii) *)
252                    if o = Terms.Lt then
253                      Some (newside, subst, id, dir)
254                    else 
255                      ((*prerr_endline ("Filtering: " ^ 
256                         Pp.pp_foterm side ^ " =(< || =)" ^ 
257                         Pp.pp_foterm newside ^ " coming from " ^ 
258                         Pp.pp_unit_clause uc );*)None)
259                  else
260                    Some (newside, subst, id, dir)
261                with FoUnif.UnificationFailure _ -> None)
262           | _ -> assert false)
263         (IDX.ClauseSet.elements cands)
264     ;;
265
266     let ctx_demod table vl clause_ctx bag t pos ctx id lit =
267       match mydemod table vl t with
268         | None -> (bag,[],t,id,lit)
269         | Some (newside, subst, id2, dir) ->
270             let inewside = Subst.apply_subst subst newside in
271             match build_clause ~fresh:false bag 0 (fun _ -> true)
272               Terms.Demodulation (ctx inewside) subst id id2 pos dir clause_ctx
273             with
274               | None -> assert false
275               | Some (bag,_,(id,_,_,_,_),lit) ->
276                     (bag,subst,newside,id,lit)
277     ;;
278       
279     let rec demodulate bag (id,nlit,plit,vl,proof) table =
280       let rec demod_lit ~jump_to_right bag id lit clause_ctx =
281        (match lit with
282       | Terms.Predicate t -> assert false
283       | Terms.Equation (l,r,ty,_) -> assert false
284           (*let bag,l,id1,lit = 
285             visit bag [2]
286             (fun x -> Terms.Node [ Terms.Leaf B.eqP; ty; x; r ]) id lit l
287             (ctx_demod table vl clause_ctx)
288           in 
289           let bag,_,id2,lit = 
290             visit bag [3]
291               (fun x -> Terms.Node [ Terms.Leaf B.eqP; ty; l; x ]) id1 lit r
292               (ctx_demod table vl clause_ctx)
293           in
294           let cl,_,_ = Terms.get_from_bag id2 bag in
295             bag,id2,cl *) )
296       in
297      let nlit,_,bag,id = if nlit = [] then nlit,[],bag,id
298        else List.fold_left
299        (fun (pre,post,bag,id) (lit,sel) ->
300           let bag, id, lit =
301               demod_lit ~jump_to_right:false bag id lit (fun l -> pre@[l,sel]@post,plit)
302           in
303              if post=[] then pre@[(lit,sel)],[],bag,id
304              else pre@[(lit,sel)],List.tl post,bag,id)
305        ([],List.tl nlit, bag, id) nlit
306       in
307       let _,_,bag,id = if plit = [] then plit,[],bag,id
308        else List.fold_left
309        (fun (pre,post,bag,id) (lit,sel) ->
310           let bag, id, lit = 
311               demod_lit ~jump_to_right:false bag id lit (fun l -> nlit,pre@[l,sel]@post)
312           in
313              if post=[] then pre@[(lit,sel)],[],bag,id
314              else pre@[(lit,sel)],List.tl post,bag,id)
315        ([],List.tl plit, bag, id) plit
316       in
317        let cl,_,_ = Terms.get_from_bag id bag in
318         bag,cl
319     ;;
320
321     let parallel_demod table vl clause_ctx bag t pos ctx id lit =
322       match demod table vl t with
323         | None -> (bag,t,id,lit)
324         | Some (newside, subst, id2, dir) ->
325             match build_clause ~fresh:false bag 0 (fun _ -> true)
326               Terms.Demodulation (ctx newside) subst id id2 pos dir clause_ctx
327             with
328               | None -> assert false
329               | Some (bag,_,(id,_,_,_,_),lit) ->
330                     (bag,newside,id,lit)
331     ;;
332
333     let demodulate_once ~jump_to_right bag id literal vl table clause_ctx =
334       match literal with
335       | Terms.Predicate t -> assert false
336       | Terms.Equation (l,r,ty,_) as lit ->
337           let bag,l,id1,lit = if jump_to_right then (bag,l,id,lit) else
338             parallel_positions bag [2]
339               (fun x -> Terms.Node [ Terms.Leaf B.eqP; ty; x; r ]) id lit l
340               (parallel_demod table vl clause_ctx)
341           in
342           let jump_to_right = id1 = id in
343           let bag,r,id2,lit =
344             parallel_positions bag [3]
345               (fun x -> Terms.Node [ Terms.Leaf B.eqP; ty; l; x ]) id1 lit r
346               (parallel_demod table vl clause_ctx)
347           in
348             if id = id2 then None
349             else
350               Some ((bag,id2,lit),jump_to_right)
351     ;;
352
353     let rec demodulate_old bag (id,nlit,plit,vl,proof) table =
354       let rec demod_lit ~jump_to_right bag id lit clause_ctx =
355          match demodulate_once ~jump_to_right bag id lit vl table clause_ctx with
356          | None -> bag, id, lit
357          | Some ((bag, id, lit),jump) ->
358              demod_lit ~jump_to_right:jump bag id lit clause_ctx
359       in
360       (*match nlit,plit with
361       |[],[lit,_] ->
362         let bag, id, lit = demod_lit ~jump_to_right:false bag id lit (fun l -> nlit, [l,true])
363         in
364         let cl,_,_ = Terms.get_from_bag id bag in
365         bag,cl
366       |[lit,_],[] ->
367         let bag, id, lit = demod_lit ~jump_to_right:false bag id lit (fun l -> [l,true],[])
368         in
369         let cl,_,_ = Terms.get_from_bag id bag in
370         bag,cl
371       |_ -> assert false*)
372       let nlit,_,bag,id = if nlit = [] then nlit,[],bag,id
373        else List.fold_left
374        (fun (pre,post,bag,id) (lit,sel) ->
375           let bag, id, lit =
376               demod_lit ~jump_to_right:false bag id lit (fun l -> pre@[l,sel]@post,plit)
377           in
378              if post=[] then pre@[(lit,sel)],[],bag,id
379              else pre@[(lit,sel)],List.tl post,bag,id)
380        ([],List.tl nlit, bag, id) nlit
381       in
382       let _,_,bag,id = if plit = [] then plit,[],bag,id
383        else List.fold_left
384        (fun (pre,post,bag,id) (lit,sel) ->
385           let bag, id, lit = 
386               demod_lit ~jump_to_right:false bag id lit (fun l -> nlit,pre@[l,sel]@post)
387           in
388              if post=[] then pre@[(lit,sel)],[],bag,id
389              else pre@[(lit,sel)],List.tl post,bag,id)
390        ([],List.tl plit, bag, id) plit
391       in
392        let cl,_,_ = Terms.get_from_bag id bag in
393         bag,cl
394     ;;
395
396     let prof_demodulate = HExtlib.profile ~enable "demodulate";;
397     let demodulate bag clause x =
398       prof_demodulate.HExtlib.profile (demodulate bag clause) x
399     ;;
400
401     (* move away *)
402     let is_identity_clause ~unify = function
403       | _, [], [Terms.Equation (_,_,_,Terms.Eq),_], _, _ -> true
404       | _, [], [Terms.Equation (l,r,_,_),_], vl, _ when unify ->
405           (try ignore(Unif.unification (* vl *) [] l r); true
406           with FoUnif.UnificationFailure _ -> false)
407       | _ -> false
408     ;;
409
410     let is_goal_trivial = function
411       | _, [Terms.Equation (_,_,_,Terms.Eq),_], [], _, _ -> true
412       | _, [Terms.Equation (l,r,_,_),_], [], vl, _ ->
413           (try ignore(Unif.unification (* vl *) [] l r); true
414           with FoUnif.UnificationFailure _ -> false)
415       | _ -> false
416
417     let fold_build_new_clause bag maxvar id rule filter res clause_ctx =
418       debug (lazy (string_of_int (List.length res)));
419       let (bag, maxvar), res =
420        HExtlib.filter_map_acc 
421          (fun (bag, maxvar) (t,subst,id2,pos,dir) ->
422            match build_clause ~fresh:true bag maxvar filter 
423                   rule t subst id id2 pos dir clause_ctx with
424             | None -> None
425             | Some (bag,maxvar,res,_) -> Some ((bag,maxvar),res))
426          (bag, maxvar) res
427       in
428        bag, maxvar, res
429     ;;
430
431     (* Tries to rewrite an equality to identity, using unit equalities in table *)    
432     let rewrite_eq ~unify l r ty vl table =
433       let retrieve = if unify then IDX.DT.retrieve_unifiables
434       else IDX.DT.retrieve_generalizations in
435       let lcands = retrieve table l in
436       let rcands = retrieve table r in
437       let f b c = 
438         let id, dir, l, r, vl = 
439           match c with
440             | (d,_,_, (id,[],[Terms.Equation (l,r,ty,_),_],vl,_))-> id, d, l, r, vl
441             | (d,_,_, (id,[Terms.Equation (l,r,ty,_),_],[],vl,_))-> id, d, l, r, vl
442             |_ -> assert false 
443         in 
444         let reverse = (dir = Terms.Left2Right) = b in
445         let l, r, proof_rewrite_dir = if reverse then l,r,Terms.Left2Right
446         else r,l, Terms.Right2Left in
447           (id,proof_rewrite_dir,Terms.Node [ Terms.Leaf B.eqP; ty; l; r ], vl)
448       in
449       let cands1 = List.map (f true) (IDX.ClauseSet.elements lcands) in
450       let cands2 = List.map (f false) (IDX.ClauseSet.elements rcands) in
451       let t = Terms.Node [ Terms.Leaf B.eqP; ty; l; r ] in
452       let locked_vars = if unify then [] else vl in
453       let rec aux = function
454         | [] -> None
455         | (id2,dir,c,vl1)::tl ->
456             try
457               let subst = Unif.unification (* (vl@vl1) *) locked_vars c t in
458               Some (id2, dir, subst)
459             with FoUnif.UnificationFailure _ -> aux tl
460       in
461         aux (cands1 @ cands2)
462     ;;
463
464     let is_subsumed ~unify bag maxvar (id, nlit, plit, vl, _) table =
465       match nlit,plit with
466       |  [Terms.Equation (l,r,ty,_) ,_],[] 
467       | [],[Terms.Equation (l,r,ty,_) ,_]-> 
468           (match rewrite_eq ~unify l r ty vl table with
469             | None -> None
470             | Some (id2, dir, subst) ->
471                 let id_t = Terms.Node [ Terms.Leaf B.eqP; ty; r; r ] in
472                   build_clause ~fresh:true bag maxvar (fun _ -> true)
473                   Terms.Superposition id_t subst id id2 [2] dir (fun l -> [],[l,true]))
474      | _ -> None (* TODO : implement subsumption for clauses *)
475     ;;
476     let prof_is_subsumed = HExtlib.profile ~enable "is_subsumed";;
477     let is_subsumed ~unify bag maxvar c x =
478       prof_is_subsumed.HExtlib.profile (is_subsumed ~unify bag maxvar c) x
479     ;;
480     (* id refers to a clause proving contextl l = contextr r *)
481
482     let rec deep_eq ~unify l r ty pos contextl contextr table acc =
483       match acc with 
484       | None -> None
485       | Some(bag,maxvar,(id,nlit,plit,vl,p as cl),subst) -> 
486           let l = Subst.apply_subst subst l in 
487           let r = Subst.apply_subst subst r in 
488             try 
489               let subst1 = Unif.unification (* vl *) [] l r in
490               let lit = 
491                 match nlit,plit with
492                   | [Terms.Equation (l,r,ty,o),_],[] -> 
493                      Terms.Equation (FoSubst.apply_subst subst1 l,
494                        FoSubst.apply_subst subst1 r, ty, o)
495                   | _ -> debug (lazy (Pp.pp_clause cl));assert false
496               in
497                 Some(bag,maxvar,(id,[lit,true],[],vl,p),Subst.concat subst1 subst)
498             with FoUnif.UnificationFailure _ -> 
499               match rewrite_eq ~unify l r ty vl table with
500               | Some (id2, dir, subst1) ->
501                   let newsubst = Subst.concat subst1 subst in
502                   let id_t = 
503                     FoSubst.apply_subst newsubst
504                       (Terms.Node[Terms.Leaf B.eqP;ty;contextl r;contextr r]) 
505                   in
506                     (match 
507                       build_clause ~fresh:true bag maxvar (fun _ -> true)
508                         Terms.Superposition id_t 
509                         subst1 id id2 (pos@[2]) dir (fun l -> [l,true],[])
510                     with
511                     | Some (bag, maxvar, c, _) -> 
512                         Some(bag,maxvar,c,newsubst)
513                     | None -> assert false)
514               | None ->
515                   match l,r with 
516                   | Terms.Node (a::la), Terms.Node (b::lb) when 
517                       a = b && List.length la = List.length lb ->
518                       let acc,_,_,_ =
519                         List.fold_left2 
520                           (fun (acc,pre,postl,postr) a b -> 
521                              let newcl = 
522                               fun x -> contextl(Terms.Node (pre@(x::postl))) in
523                              let newcr = 
524                               fun x -> contextr(Terms.Node (pre@(x::postr))) in
525                              let newpos = List.length pre::pos in
526                              let footail l =
527                                if l = [] then [] else List.tl l in
528                                (deep_eq ~unify a b ty 
529                                  newpos newcl newcr table acc,pre@[b],
530                                  footail postl, footail postr))
531                           (acc,[a],List.tl la,List.tl lb) la lb
532                       in acc
533                   | _,_ -> None
534     ;;
535     let prof_deep_eq = HExtlib.profile ~enable "deep_eq";;
536     let deep_eq ~unify l r ty pos contextl contextr table x =
537       prof_deep_eq.HExtlib.profile (deep_eq ~unify l r ty pos contextl contextr table) x
538     ;;
539
540     let rec orphan_murder bag acc i =
541       match Terms.get_from_bag i bag with
542         | (_,_,_,_,Terms.Exact _),discarded,_ -> (discarded,acc)
543         | (_,_,_,_,Terms.Step (_,i1,i2,_,_,_)),true,_ -> (true,acc)
544         | (_,_,_,_,Terms.Step (_,i1,i2,_,_,_)),false,_ ->
545             if (List.mem i acc) then (false,acc)
546             else match orphan_murder bag acc i1 with
547               | (true,acc) -> (true,acc)
548               | (false,acc) ->
549                   let (res,acc) = orphan_murder bag acc i2 in
550                   if res then res,acc else res,i::acc
551     ;;
552
553     let orphan_murder bag actives cl =
554       let (id,_,_,_,_) = cl in
555       let actives = List.map (fun (i,_,_,_,_) -> i) actives in
556       let (res,_) = orphan_murder bag actives id in
557         if res then debug (lazy "Orphan murdered"); res
558     ;;
559     let prof_orphan_murder = HExtlib.profile ~enable "orphan_murder";;
560     let orphan_murder bag actives x =
561       prof_orphan_murder.HExtlib.profile (orphan_murder bag actives) x
562     ;;
563
564     (* demodulate and check for subsumption *)
565     let simplify table maxvar bag clause = 
566       if is_identity_clause ~unify:false clause then bag,None
567       (* else if orphan_murder bag actives clause then bag,None *)
568       else let bag, clause = demodulate bag clause table in
569       if is_identity_clause ~unify:false clause then bag,None
570       else
571         match is_subsumed ~unify:false bag maxvar clause table with
572           | None -> bag, Some clause
573           | Some _ -> bag, None
574     ;;
575
576     let simplify table maxvar bag clause =
577       match simplify table maxvar bag clause with
578         | bag, None ->
579             let (id,_,_,_,_) = clause in
580             let (_,_,iter) = Terms.get_from_bag id bag in
581             Terms.replace_in_bag (clause,true,iter) bag, None
582         | bag, Some clause -> bag, Some clause
583     (*let (id,_,_,_) = clause in
584             if orphan_murder bag clause then
585               Terms.M.add id (clause,true) bag, Some clause
586             else bag, Some clause*)
587     ;;
588     let prof_simplify = HExtlib.profile ~enable "simplify";;
589     let simplify table maxvar bag x =
590       prof_simplify.HExtlib.profile (simplify table maxvar bag ) x
591     ;;
592
593     let one_pass_simplification new_clause (alist,atable) bag maxvar =
594       match simplify atable maxvar bag new_clause with
595         | bag,None -> bag,None (* new_clause has been discarded *)
596         | bag,(Some clause) ->
597             let ctable = IDX.index_clause IDX.DT.empty clause in
598             let bag, alist, atable = 
599               List.fold_left 
600                 (fun (bag, alist, atable) c ->
601                    match simplify ctable maxvar bag c with
602                      |bag,None -> (bag,alist,atable)
603                         (* an active clause as been discarded *)
604                      |bag,Some c1 ->
605                         bag, c :: alist, IDX.index_clause atable c)
606                 (bag,[],IDX.DT.empty) alist
607             in
608               bag, Some (clause, (alist,atable))
609     ;;
610     let prof_one_pass_simplification = HExtlib.profile ~enable "one_pass_simplification";;
611     let one_pass_simplification new_clause t bag x =
612       prof_one_pass_simplification.HExtlib.profile (one_pass_simplification new_clause t bag ) x
613     ;;
614
615     let simplification_step ~new_cl cl (alist,atable) bag maxvar new_clause =
616       let atable1 =
617         if new_cl then atable else
618         IDX.index_clause atable cl
619       in
620         (* Simplification of new_clause with :      *
621          * - actives and cl if new_clause is not cl *
622          * - only actives otherwise                 *)
623         match
624           simplify atable1 maxvar bag new_clause with
625           | bag,None -> bag,(Some cl, None) (* new_clause has been discarded *)
626           | bag,Some clause ->
627               (* Simplification of each active clause with clause *
628                * which is the simplified form of new_clause       *)
629               let ctable = IDX.index_clause IDX.DT.empty clause in
630               let bag, newa, alist, atable = 
631                 List.fold_left 
632                   (fun (bag, newa, alist, atable) c ->
633                      match simplify ctable maxvar bag c with
634                        |bag,None -> (bag, newa, alist, atable)
635                           (* an active clause as been discarded *)
636                        |bag,Some c1 ->
637                             if (c1 == c) then 
638                               bag, newa, c :: alist,
639                             IDX.index_clause atable c
640                             else
641                               bag, c1 :: newa, alist, atable)                  
642                   (bag,[],[],IDX.DT.empty) alist
643               in
644                 if new_cl then
645                   bag, (Some cl, Some (clause, (alist,atable), newa))
646                 else
647                   (* if new_clause is not cl, we simplify cl with clause *)
648                   match simplify ctable maxvar bag cl with
649                     | bag,None ->
650                         (* cl has been discarded *)
651                         bag,(None, Some (clause, (alist,atable), newa))
652                     | bag,Some cl1 ->
653                         bag,(Some cl1, Some (clause, (alist,atable), newa))
654     ;;
655     let prof_simplification_step = HExtlib.profile ~enable "simplification_step";;
656     let simplification_step ~new_cl cl (alist,atable) bag maxvar x =
657       prof_simplification_step.HExtlib.profile (simplification_step ~new_cl cl (alist,atable) bag maxvar) x
658     ;;
659
660     let keep_simplified cl (alist,atable) bag maxvar =
661       let rec keep_simplified_aux ~new_cl cl (alist,atable) bag newc =
662         if new_cl then
663           match simplification_step ~new_cl cl (alist,atable) bag maxvar cl with
664             | _,(None, _) -> assert false
665             | bag,(Some _, None) -> bag,None
666             | bag,(Some _, Some (clause, (alist,atable), newa)) ->
667                 keep_simplified_aux ~new_cl:(cl!=clause) clause (alist,atable)
668                   bag (newa@newc)
669         else
670           match newc with
671             | [] -> bag, Some (cl, (alist,atable))
672             | hd::tl ->
673                 match simplification_step ~new_cl cl
674                   (alist,atable) bag maxvar hd with
675                   | _,(None,None) -> assert false
676                   | bag,(Some _,None) ->
677                       keep_simplified_aux ~new_cl cl (alist,atable) bag tl
678                   | bag,(None, Some _) -> bag,None
679                   | bag,(Some cl1, Some (clause, (alist,atable), newa)) ->
680                       let alist,atable =
681                         (clause::alist, IDX.index_clause atable clause)
682                       in
683                         keep_simplified_aux ~new_cl:(cl!=cl1) cl1 (alist,atable)
684                           bag (newa@tl)
685       in
686         keep_simplified_aux ~new_cl:true cl (alist,atable) bag []
687     ;;
688     let prof_keep_simplified = HExtlib.profile ~enable "keep_simplified";;
689     let keep_simplified cl t bag x =
690       prof_keep_simplified.HExtlib.profile (keep_simplified cl t bag) x
691     ;;
692
693     (* this is like simplify but raises Success *)
694     let simplify_goal ~no_demod maxvar table bag g_actives clause = 
695       let bag, clause = 
696         if no_demod then bag, clause else demodulate bag clause table 
697       in
698       if List.exists (Clauses.are_alpha_eq_cl clause) g_actives then None else
699       if (is_goal_trivial clause)
700       then raise (Success (bag, maxvar, clause))
701       else   
702         let (id,nlit,plit,vl,_) = clause in 
703         if vl = [] then Some (bag,clause)
704         else
705          let l,r,ty = 
706            match nlit,plit with
707              | [Terms.Equation(l,r,ty,_),_],[] -> l,r,ty
708              | _ -> assert false 
709          in
710          match deep_eq ~unify:true l r ty [] (fun x -> x) (fun x -> x) 
711            table (Some(bag,maxvar,clause,Subst.id_subst)) with
712          | None -> Some (bag,clause)
713          | Some (bag,maxvar,cl,subst) -> 
714              prerr_endline "Goal subsumed";
715              raise (Success (bag,maxvar,cl))
716 (*
717       else match is_subsumed ~unify:true bag maxvar clause table with
718         | None -> Some (bag, clause)
719         | Some ((bag,maxvar),c) -> 
720             prerr_endline "Goal subsumed";
721             raise (Success (bag,maxvar,c))
722 *) 
723     ;;
724
725     let prof_simplify_goal = HExtlib.profile ~enable "simplify_goal";;
726     let  simplify_goal ~no_demod maxvar table bag g_actives x =
727       prof_simplify_goal.HExtlib.profile ( simplify_goal ~no_demod maxvar table bag g_actives) x
728     ;;
729
730     (* =================== inference ===================== *)
731
732     (* this is OK for both the sup_left and sup_right inference steps *)
733     let superposition table varlist is_pos subterm pos context =
734       let cands = IDX.DT.retrieve_unifiables table subterm in
735       HExtlib.filter_map
736         (fun (dir, is_cand_pos, _, (id,nlit,plit,vl,_ (*as uc*))) ->
737            match nlit,plit with
738            | [],[Terms.Equation (l,r,_,o),_] ->
739                (let side, newside = if dir=Terms.Left2Right then l,r else r,l in
740                debug (lazy (Pp.pp_foterm subterm));
741                debug (lazy (Pp.pp_foterm side));
742                try 
743                  let subst = 
744                    Unif.unification (* (varlist@vl)*)  [] subterm side 
745                  in 
746                  if o = Terms.Incomparable || o = Terms.Invertible then
747                    let side = Subst.apply_subst subst side in
748                    let newside = Subst.apply_subst subst newside in
749                    let o = Order.compare_terms side newside in
750                    (* XXX: check Riazanov p. 33 (iii) *)
751                    if o <> Terms.Lt && o <> Terms.Eq then  
752                      Some (context newside, subst, id, pos, dir)
753                    else 
754                      (debug (lazy "Filtering out..."); None)
755                  else
756                    Some (context newside, subst, id, pos, dir)
757                with FoUnif.UnificationFailure _ -> None)
758             | _ -> assert false)
759         (IDX.ClauseSet.elements cands)
760     ;;
761
762     (* Superposes selected equation with equalities in table *)
763     let superposition_with_table bag maxvar id vl lit is_pos clause_ctx table =
764       match lit with 
765       | Terms.Equation (l,r,ty,Terms.Lt) ->
766           fold_build_new_clause bag maxvar id Terms.Superposition
767             (fun _ -> true)
768             (all_positions [3] 
769               (fun x -> Terms.Node [ Terms.Leaf B.eqP; ty; l; x ])
770               r (superposition table vl is_pos)) clause_ctx
771       | Terms.Equation (l,r,ty,Terms.Invertible)
772       | Terms.Equation (l,r,ty,Terms.Gt) ->
773           fold_build_new_clause bag maxvar id Terms.Superposition
774             (fun _ -> true)
775             (all_positions [2] 
776               (fun x -> Terms.Node [ Terms.Leaf B.eqP; ty; x; r ])
777               l (superposition table vl is_pos)) clause_ctx
778       | Terms.Equation (l,r,ty,Terms.Incomparable) ->
779           let filtering avoid subst = (* Riazanov: p.33 condition (iv) *)
780             let l = Subst.apply_subst subst l in
781             let r = Subst.apply_subst subst r in
782             let o = Order.compare_terms l r in
783             o <> avoid && o <> Terms.Eq
784           in
785           let bag, maxvar,r_terms =
786             fold_build_new_clause bag maxvar id Terms.Superposition
787               (filtering Terms.Gt)
788               (all_positions [3] 
789                  (fun x -> Terms.Node [ Terms.Leaf B.eqP; ty; l; x ])
790                  r (superposition table vl is_pos)) clause_ctx
791           in
792           let bag, maxvar, l_terms =
793             fold_build_new_clause bag maxvar id Terms.Superposition
794               (filtering Terms.Lt)
795               (all_positions [2] 
796                  (fun x -> Terms.Node [ Terms.Leaf B.eqP; ty; x; r ])
797                  l (superposition table vl is_pos)) clause_ctx
798           in
799             bag, maxvar, r_terms @ l_terms
800       | _ -> assert false
801     ;;
802
803     let superpose_literal id vl table is_pos (bag,maxvar,pre,post,acc) (lit,sel) =
804       let clause_ctx =
805          if is_pos then fun l -> [],pre@[l,true]@post
806          else fun l -> pre@[l,true]@post,[]
807       in
808       let bag, maxvar, newc =
809         superposition_with_table bag maxvar id vl lit is_pos clause_ctx table
810       in
811          if post = [] then bag,maxvar,pre@[lit,sel],[],newc@acc
812          else bag,maxvar,pre@[lit,sel],List.tl post,newc@acc
813     ;;
814
815
816     (* the current equation is normal w.r.t. demodulation with atable
817      * (and is not the identity) *)
818     let infer_right bag maxvar current (alist,atable) = 
819       (* We demodulate actives clause with current until all *
820        * active clauses are reduced w.r.t each other         *)
821       (* let bag, (alist,atable) = keep_simplified (alist,atable) bag [current] in *)
822       let ctable = IDX.index_clause IDX.DT.empty current in
823       (* let bag, (alist, atable) = 
824         let bag, alist = 
825           HExtlib.filter_map_acc (simplify ctable) bag alist
826         in
827         bag, (alist, List.fold_left IDX.index_clause IDX.DT.empty alist)
828       in*)
829         debug (lazy "Simplified active clauses with fact");
830       (* We superpose active clauses with current *)
831       let bag, maxvar, new_clauses =
832         List.fold_left 
833           (fun (bag, maxvar, acc) (id,nlit,plit,vl,_) ->
834              let bag, maxvar, _, _, acc =
835               if nlit = [] then bag,maxvar,[],[],acc
836               else List.fold_left
837                  (superpose_literal id vl ctable false) (bag,maxvar,[],List.tl nlit,acc) nlit
838              in
839               let bag, maxvar, _, _, acc =
840                if plit = [] then bag,maxvar,[],[],acc
841                else List.fold_left
842                  (superpose_literal id vl ctable true) (bag,maxvar,[],List.tl plit,acc) plit
843              in            
844              bag, maxvar, acc)
845           (bag, maxvar, []) alist
846       in
847         debug (lazy "First superpositions");
848         (* We add current to active clauses so that it can be *
849          * superposed with itself                             *)
850       let alist, atable = 
851         current :: alist, IDX.index_clause atable current
852       in
853         debug (lazy "Indexed");
854       let fresh_current, maxvar = Clauses.fresh_clause maxvar current in
855         (* We need to put fresh_current into the bag so that all *
856          * variables clauses refer to are known.                 *)
857       let bag, (id,nlit,plit,vl,_) = Terms.add_to_bag fresh_current bag in
858         (* We superpose current with active clauses *)
859       let bag, maxvar, _, _, additional_new_clauses =
860          if nlit = [] then bag,maxvar,[],[],[]
861          else List.fold_left
862          (superpose_literal id vl atable false) (bag,maxvar,[],List.tl nlit,[]) nlit
863       in
864       let bag, maxvar, _, _, additional_new_clauses =
865          if plit = [] then bag,maxvar,[],[],[]
866          else List.fold_left
867           (superpose_literal id vl atable true) (bag,maxvar,[],List.tl plit,additional_new_clauses) plit
868       in 
869         debug (lazy "Another superposition");
870         let new_clauses = new_clauses@additional_new_clauses in
871         debug (lazy (Printf.sprintf "Demodulating %d clauses"
872                  (List.length new_clauses)));
873       let bag, new_clauses = 
874         HExtlib.filter_map_monad (simplify atable maxvar) bag new_clauses
875       in
876         debug (lazy "Demodulated new clauses");
877       bag, maxvar, (alist, atable), new_clauses
878     ;;
879
880     let prof_ir = HExtlib.profile ~enable "infer_right";;
881     let infer_right bag maxvar current t = 
882       prof_ir.HExtlib.profile (infer_right bag maxvar current) t
883     ;;
884
885     let infer_left bag maxvar goal (_alist, atable) =
886         (* We superpose the goal with active clauses *)
887      if (match goal with (_,_,_,[],_) -> true | _ -> false) then bag, maxvar, []
888      else
889       let (id,nlit,vl) =
890          match goal with
891            | (id,nlit,[],vl,_) -> id,nlit,vl
892            | _ -> assert false
893       in
894       let bag, maxvar, _, _, new_goals = 
895         List.fold_left (superpose_literal id vl atable false)
896             (bag,maxvar,[],List.tl nlit,[]) nlit
897       in
898         debug (lazy (string_of_int (List.length new_goals) ^ " new goals"));
899         (* We simplify the new goals with active clauses *)
900       let bag, new_goals = 
901         List.fold_left
902          (fun (bag, acc) g -> 
903             match simplify_goal ~no_demod:false maxvar atable bag [] g with
904               | None -> assert false
905               | Some (bag,g) -> bag,g::acc)
906          (bag, []) new_goals
907       in
908         debug (lazy "Simplified new goals with active clauses");
909       bag, maxvar, List.rev new_goals
910     ;;
911
912     let prof_il = HExtlib.profile ~enable "infer_left";;
913     let infer_left bag maxvar goal t = 
914       prof_il.HExtlib.profile (infer_left bag maxvar goal) t
915     ;;
916
917   end